cmSystemTools.cxx 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmSystemTools.h"
  4. #include "cmAlgorithms.h"
  5. #include "cmDuration.h"
  6. #include "cmProcessOutput.h"
  7. #include "cm_sys_stat.h"
  8. #include "cm_uv.h"
  9. #if defined(CMAKE_BUILD_WITH_CMAKE)
  10. # include "cmArchiveWrite.h"
  11. # include "cmLocale.h"
  12. # include "cm_libarchive.h"
  13. # ifndef __LA_INT64_T
  14. # define __LA_INT64_T la_int64_t
  15. # endif
  16. # ifndef __LA_SSIZE_T
  17. # define __LA_SSIZE_T la_ssize_t
  18. # endif
  19. #endif
  20. #if defined(CMAKE_BUILD_WITH_CMAKE)
  21. # include "cmCryptoHash.h"
  22. #endif
  23. #if defined(CMAKE_USE_ELF_PARSER)
  24. # include "cmELF.h"
  25. #endif
  26. #if defined(CMAKE_USE_MACH_PARSER)
  27. # include "cmMachO.h"
  28. #endif
  29. #include "cmsys/Directory.hxx"
  30. #include "cmsys/Encoding.hxx"
  31. #include "cmsys/FStream.hxx"
  32. #include "cmsys/RegularExpression.hxx"
  33. #include "cmsys/System.h"
  34. #include "cmsys/Terminal.h"
  35. #include <algorithm>
  36. #include <assert.h>
  37. #include <ctype.h>
  38. #include <errno.h>
  39. #include <iostream>
  40. #include <sstream>
  41. #include <stdio.h>
  42. #include <stdlib.h>
  43. #include <string.h>
  44. #include <time.h>
  45. #include <utility>
  46. #include <vector>
  47. #if defined(_WIN32)
  48. # include <windows.h>
  49. // include wincrypt.h after windows.h
  50. # include <wincrypt.h>
  51. # include <fcntl.h> /* _O_TEXT */
  52. #else
  53. # include <sys/time.h>
  54. # include <unistd.h>
  55. # include <utime.h>
  56. #endif
  57. #if defined(_WIN32) && \
  58. (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__MINGW32__))
  59. # include <io.h>
  60. #endif
  61. #if defined(__APPLE__)
  62. # include <mach-o/dyld.h>
  63. #endif
  64. #ifdef __QNX__
  65. # include <malloc.h> /* for malloc/free on QNX */
  66. #endif
  67. static bool cm_isspace(char c)
  68. {
  69. return ((c & 0x80) == 0) && isspace(c);
  70. }
  71. class cmSystemToolsFileTime
  72. {
  73. public:
  74. #if defined(_WIN32) && !defined(__CYGWIN__)
  75. FILETIME timeCreation;
  76. FILETIME timeLastAccess;
  77. FILETIME timeLastWrite;
  78. #else
  79. struct utimbuf timeBuf;
  80. #endif
  81. };
  82. #if !defined(HAVE_ENVIRON_NOT_REQUIRE_PROTOTYPE)
  83. // For GetEnvironmentVariables
  84. # if defined(_WIN32)
  85. extern __declspec(dllimport) char** environ;
  86. # else
  87. extern char** environ;
  88. # endif
  89. #endif
  90. #if defined(CMAKE_BUILD_WITH_CMAKE)
  91. static std::string cm_archive_entry_pathname(struct archive_entry* entry)
  92. {
  93. # if cmsys_STL_HAS_WSTRING
  94. return cmsys::Encoding::ToNarrow(archive_entry_pathname_w(entry));
  95. # else
  96. return archive_entry_pathname(entry);
  97. # endif
  98. }
  99. static int cm_archive_read_open_file(struct archive* a, const char* file,
  100. int block_size)
  101. {
  102. # if cmsys_STL_HAS_WSTRING
  103. std::wstring wfile = cmsys::Encoding::ToWide(file);
  104. return archive_read_open_filename_w(a, wfile.c_str(), block_size);
  105. # else
  106. return archive_read_open_filename(a, file, block_size);
  107. # endif
  108. }
  109. #endif
  110. #ifdef _WIN32
  111. class cmSystemToolsWindowsHandle
  112. {
  113. public:
  114. cmSystemToolsWindowsHandle(HANDLE h)
  115. : handle_(h)
  116. {
  117. }
  118. ~cmSystemToolsWindowsHandle()
  119. {
  120. if (this->handle_ != INVALID_HANDLE_VALUE) {
  121. CloseHandle(this->handle_);
  122. }
  123. }
  124. explicit operator bool() const
  125. {
  126. return this->handle_ != INVALID_HANDLE_VALUE;
  127. }
  128. bool operator!() const { return this->handle_ == INVALID_HANDLE_VALUE; }
  129. operator HANDLE() const { return this->handle_; }
  130. private:
  131. HANDLE handle_;
  132. };
  133. #elif defined(__APPLE__)
  134. # include <crt_externs.h>
  135. # define environ (*_NSGetEnviron())
  136. #endif
  137. bool cmSystemTools::s_RunCommandHideConsole = false;
  138. bool cmSystemTools::s_DisableRunCommandOutput = false;
  139. bool cmSystemTools::s_ErrorOccured = false;
  140. bool cmSystemTools::s_FatalErrorOccured = false;
  141. bool cmSystemTools::s_DisableMessages = false;
  142. bool cmSystemTools::s_ForceUnixPaths = false;
  143. cmSystemTools::MessageCallback cmSystemTools::s_MessageCallback;
  144. cmSystemTools::OutputCallback cmSystemTools::s_StdoutCallback;
  145. cmSystemTools::OutputCallback cmSystemTools::s_StderrCallback;
  146. cmSystemTools::InterruptCallback cmSystemTools::s_InterruptCallback;
  147. void* cmSystemTools::s_MessageCallbackClientData;
  148. void* cmSystemTools::s_StdoutCallbackClientData;
  149. void* cmSystemTools::s_StderrCallbackClientData;
  150. void* cmSystemTools::s_InterruptCallbackClientData;
  151. // replace replace with with as many times as it shows up in source.
  152. // write the result into source.
  153. #if defined(_WIN32) && !defined(__CYGWIN__)
  154. void cmSystemTools::ExpandRegistryValues(std::string& source, KeyWOW64 view)
  155. {
  156. // Regular expression to match anything inside [...] that begins in HKEY.
  157. // Note that there is a special rule for regular expressions to match a
  158. // close square-bracket inside a list delimited by square brackets.
  159. // The "[^]]" part of this expression will match any character except
  160. // a close square-bracket. The ']' character must be the first in the
  161. // list of characters inside the [^...] block of the expression.
  162. cmsys::RegularExpression regEntry("\\[(HKEY[^]]*)\\]");
  163. // check for black line or comment
  164. while (regEntry.find(source)) {
  165. // the arguments are the second match
  166. std::string key = regEntry.match(1);
  167. std::string val;
  168. if (ReadRegistryValue(key.c_str(), val, view)) {
  169. std::string reg = "[";
  170. reg += key + "]";
  171. cmSystemTools::ReplaceString(source, reg.c_str(), val.c_str());
  172. } else {
  173. std::string reg = "[";
  174. reg += key + "]";
  175. cmSystemTools::ReplaceString(source, reg.c_str(), "/registry");
  176. }
  177. }
  178. }
  179. #else
  180. void cmSystemTools::ExpandRegistryValues(std::string& source,
  181. KeyWOW64 /*unused*/)
  182. {
  183. cmsys::RegularExpression regEntry("\\[(HKEY[^]]*)\\]");
  184. while (regEntry.find(source)) {
  185. // the arguments are the second match
  186. std::string key = regEntry.match(1);
  187. std::string reg = "[";
  188. reg += key + "]";
  189. cmSystemTools::ReplaceString(source, reg.c_str(), "/registry");
  190. }
  191. }
  192. #endif
  193. std::string cmSystemTools::EscapeQuotes(const std::string& str)
  194. {
  195. std::string result;
  196. result.reserve(str.size());
  197. for (const char* ch = str.c_str(); *ch != '\0'; ++ch) {
  198. if (*ch == '"') {
  199. result += '\\';
  200. }
  201. result += *ch;
  202. }
  203. return result;
  204. }
  205. std::string cmSystemTools::HelpFileName(std::string name)
  206. {
  207. cmSystemTools::ReplaceString(name, "<", "");
  208. cmSystemTools::ReplaceString(name, ">", "");
  209. return name;
  210. }
  211. std::string cmSystemTools::TrimWhitespace(const std::string& s)
  212. {
  213. std::string::const_iterator start = s.begin();
  214. while (start != s.end() && cm_isspace(*start)) {
  215. ++start;
  216. }
  217. if (start == s.end()) {
  218. return "";
  219. }
  220. std::string::const_iterator stop = s.end() - 1;
  221. while (cm_isspace(*stop)) {
  222. --stop;
  223. }
  224. return std::string(start, stop + 1);
  225. }
  226. void cmSystemTools::Error(const char* m1, const char* m2, const char* m3,
  227. const char* m4)
  228. {
  229. std::string message = "CMake Error: ";
  230. if (m1) {
  231. message += m1;
  232. }
  233. if (m2) {
  234. message += m2;
  235. }
  236. if (m3) {
  237. message += m3;
  238. }
  239. if (m4) {
  240. message += m4;
  241. }
  242. cmSystemTools::s_ErrorOccured = true;
  243. cmSystemTools::Message(message.c_str(), "Error");
  244. }
  245. void cmSystemTools::SetInterruptCallback(InterruptCallback f, void* clientData)
  246. {
  247. s_InterruptCallback = f;
  248. s_InterruptCallbackClientData = clientData;
  249. }
  250. bool cmSystemTools::GetInterruptFlag()
  251. {
  252. if (s_InterruptCallback) {
  253. return (*s_InterruptCallback)(s_InterruptCallbackClientData);
  254. }
  255. return false;
  256. }
  257. void cmSystemTools::SetMessageCallback(MessageCallback f, void* clientData)
  258. {
  259. s_MessageCallback = f;
  260. s_MessageCallbackClientData = clientData;
  261. }
  262. void cmSystemTools::SetStdoutCallback(OutputCallback f, void* clientData)
  263. {
  264. s_StdoutCallback = f;
  265. s_StdoutCallbackClientData = clientData;
  266. }
  267. void cmSystemTools::SetStderrCallback(OutputCallback f, void* clientData)
  268. {
  269. s_StderrCallback = f;
  270. s_StderrCallbackClientData = clientData;
  271. }
  272. void cmSystemTools::Stderr(const std::string& s)
  273. {
  274. if (s_StderrCallback) {
  275. (*s_StderrCallback)(s.c_str(), s.length(), s_StderrCallbackClientData);
  276. } else {
  277. std::cerr << s << std::flush;
  278. }
  279. }
  280. void cmSystemTools::Stdout(const std::string& s)
  281. {
  282. if (s_StdoutCallback) {
  283. (*s_StdoutCallback)(s.c_str(), s.length(), s_StdoutCallbackClientData);
  284. } else {
  285. std::cout << s << std::flush;
  286. }
  287. }
  288. void cmSystemTools::Message(const char* m1, const char* title)
  289. {
  290. if (s_DisableMessages) {
  291. return;
  292. }
  293. if (s_MessageCallback) {
  294. (*s_MessageCallback)(m1, title, s_DisableMessages,
  295. s_MessageCallbackClientData);
  296. return;
  297. }
  298. std::cerr << m1 << std::endl << std::flush;
  299. }
  300. void cmSystemTools::ReportLastSystemError(const char* msg)
  301. {
  302. std::string m = msg;
  303. m += ": System Error: ";
  304. m += Superclass::GetLastSystemError();
  305. cmSystemTools::Error(m.c_str());
  306. }
  307. bool cmSystemTools::IsInternallyOn(const char* val)
  308. {
  309. if (!val) {
  310. return false;
  311. }
  312. std::string v = val;
  313. if (v.size() > 4) {
  314. return false;
  315. }
  316. for (char& c : v) {
  317. c = static_cast<char>(toupper(c));
  318. }
  319. return v == "I_ON";
  320. }
  321. bool cmSystemTools::IsOn(const char* val)
  322. {
  323. if (!val) {
  324. return false;
  325. }
  326. /* clang-format off */
  327. // "1"
  328. if (val[0] == '1' && val[1] == '\0') {
  329. return true;
  330. }
  331. // "ON"
  332. if ((val[0] == 'O' || val[0] == 'o') &&
  333. (val[1] == 'N' || val[1] == 'n') && val[2] == '\0') {
  334. return true;
  335. }
  336. // "Y", "YES"
  337. if ((val[0] == 'Y' || val[0] == 'y') && (val[1] == '\0' || (
  338. (val[1] == 'E' || val[1] == 'e') &&
  339. (val[2] == 'S' || val[2] == 's') && val[3] == '\0'))) {
  340. return true;
  341. }
  342. // "TRUE"
  343. if ((val[0] == 'T' || val[0] == 't') &&
  344. (val[1] == 'R' || val[1] == 'r') &&
  345. (val[2] == 'U' || val[2] == 'u') &&
  346. (val[3] == 'E' || val[3] == 'e') && val[4] == '\0') {
  347. return true;
  348. }
  349. /* clang-format on */
  350. return false;
  351. }
  352. bool cmSystemTools::IsOn(const std::string& val)
  353. {
  354. return cmSystemTools::IsOn(val.c_str());
  355. }
  356. bool cmSystemTools::IsNOTFOUND(const char* val)
  357. {
  358. if (strcmp(val, "NOTFOUND") == 0) {
  359. return true;
  360. }
  361. return cmHasLiteralSuffix(val, "-NOTFOUND");
  362. }
  363. bool cmSystemTools::IsOff(const char* val)
  364. {
  365. // ""
  366. if (!val || val[0] == '\0') {
  367. return true;
  368. }
  369. /* clang-format off */
  370. // "0"
  371. if (val[0] == '0' && val[1] == '\0') {
  372. return true;
  373. }
  374. // "OFF"
  375. if ((val[0] == 'O' || val[0] == 'o') &&
  376. (val[1] == 'F' || val[1] == 'f') &&
  377. (val[2] == 'F' || val[2] == 'f') && val[3] == '\0') {
  378. return true;
  379. }
  380. // "N", "NO"
  381. if ((val[0] == 'N' || val[0] == 'n') && (val[1] == '\0' || (
  382. (val[1] == 'O' || val[1] == 'o') && val[2] == '\0'))) {
  383. return true;
  384. }
  385. // "FALSE"
  386. if ((val[0] == 'F' || val[0] == 'f') &&
  387. (val[1] == 'A' || val[1] == 'a') &&
  388. (val[2] == 'L' || val[2] == 'l') &&
  389. (val[3] == 'S' || val[3] == 's') &&
  390. (val[4] == 'E' || val[4] == 'e') && val[5] == '\0') {
  391. return true;
  392. }
  393. // "IGNORE"
  394. if ((val[0] == 'I' || val[0] == 'i') &&
  395. (val[1] == 'G' || val[1] == 'g') &&
  396. (val[2] == 'N' || val[2] == 'n') &&
  397. (val[3] == 'O' || val[3] == 'o') &&
  398. (val[4] == 'R' || val[4] == 'r') &&
  399. (val[5] == 'E' || val[5] == 'e') && val[6] == '\0') {
  400. return true;
  401. }
  402. /* clang-format on */
  403. return cmSystemTools::IsNOTFOUND(val);
  404. }
  405. bool cmSystemTools::IsOff(const std::string& val)
  406. {
  407. return cmSystemTools::IsOff(val.c_str());
  408. }
  409. void cmSystemTools::ParseWindowsCommandLine(const char* command,
  410. std::vector<std::string>& args)
  411. {
  412. // See the MSDN document "Parsing C Command-Line Arguments" at
  413. // http://msdn2.microsoft.com/en-us/library/a1y7w461.aspx for rules
  414. // of parsing the windows command line.
  415. bool in_argument = false;
  416. bool in_quotes = false;
  417. int backslashes = 0;
  418. std::string arg;
  419. for (const char* c = command; *c; ++c) {
  420. if (*c == '\\') {
  421. ++backslashes;
  422. in_argument = true;
  423. } else if (*c == '"') {
  424. int backslash_pairs = backslashes >> 1;
  425. int backslash_escaped = backslashes & 1;
  426. arg.append(backslash_pairs, '\\');
  427. backslashes = 0;
  428. if (backslash_escaped) {
  429. /* An odd number of backslashes precede this quote.
  430. It is escaped. */
  431. arg.append(1, '"');
  432. } else {
  433. /* An even number of backslashes precede this quote.
  434. It is not escaped. */
  435. in_quotes = !in_quotes;
  436. }
  437. in_argument = true;
  438. } else {
  439. arg.append(backslashes, '\\');
  440. backslashes = 0;
  441. if (cm_isspace(*c)) {
  442. if (in_quotes) {
  443. arg.append(1, *c);
  444. } else if (in_argument) {
  445. args.push_back(arg);
  446. arg.clear();
  447. in_argument = false;
  448. }
  449. } else {
  450. in_argument = true;
  451. arg.append(1, *c);
  452. }
  453. }
  454. }
  455. arg.append(backslashes, '\\');
  456. if (in_argument) {
  457. args.push_back(arg);
  458. }
  459. }
  460. class cmSystemToolsArgV
  461. {
  462. char** ArgV;
  463. public:
  464. cmSystemToolsArgV(char** argv)
  465. : ArgV(argv)
  466. {
  467. }
  468. ~cmSystemToolsArgV()
  469. {
  470. for (char** arg = this->ArgV; arg && *arg; ++arg) {
  471. free(*arg);
  472. }
  473. free(this->ArgV);
  474. }
  475. void Store(std::vector<std::string>& args) const
  476. {
  477. for (char** arg = this->ArgV; arg && *arg; ++arg) {
  478. args.emplace_back(*arg);
  479. }
  480. }
  481. };
  482. void cmSystemTools::ParseUnixCommandLine(const char* command,
  483. std::vector<std::string>& args)
  484. {
  485. // Invoke the underlying parser.
  486. cmSystemToolsArgV argv = cmsysSystem_Parse_CommandForUnix(command, 0);
  487. argv.Store(args);
  488. }
  489. std::vector<std::string> cmSystemTools::HandleResponseFile(
  490. std::vector<std::string>::const_iterator argBeg,
  491. std::vector<std::string>::const_iterator argEnd)
  492. {
  493. std::vector<std::string> arg_full;
  494. for (std::vector<std::string>::const_iterator a = argBeg; a != argEnd; ++a) {
  495. std::string const& arg = *a;
  496. if (cmHasLiteralPrefix(arg, "@")) {
  497. cmsys::ifstream responseFile(arg.substr(1).c_str(), std::ios::in);
  498. if (!responseFile) {
  499. std::string error = "failed to open for reading (";
  500. error += cmSystemTools::GetLastSystemError();
  501. error += "):\n ";
  502. error += arg.substr(1);
  503. cmSystemTools::Error(error.c_str());
  504. } else {
  505. std::string line;
  506. cmSystemTools::GetLineFromStream(responseFile, line);
  507. std::vector<std::string> args2;
  508. #ifdef _WIN32
  509. cmSystemTools::ParseWindowsCommandLine(line.c_str(), args2);
  510. #else
  511. cmSystemTools::ParseUnixCommandLine(line.c_str(), args2);
  512. #endif
  513. arg_full.insert(arg_full.end(), args2.begin(), args2.end());
  514. }
  515. } else {
  516. arg_full.push_back(arg);
  517. }
  518. }
  519. return arg_full;
  520. }
  521. std::vector<std::string> cmSystemTools::ParseArguments(const char* command)
  522. {
  523. std::vector<std::string> args;
  524. std::string arg;
  525. bool win_path = false;
  526. if (command[0] && command[1] &&
  527. ((command[0] != '/' && command[1] == ':' && command[2] == '\\') ||
  528. (command[0] == '\"' && command[1] != '/' && command[2] == ':' &&
  529. command[3] == '\\') ||
  530. (command[0] == '\'' && command[1] != '/' && command[2] == ':' &&
  531. command[3] == '\\') ||
  532. (command[0] == '\\' && command[1] == '\\'))) {
  533. win_path = true;
  534. }
  535. // Split the command into an argv array.
  536. for (const char* c = command; *c;) {
  537. // Skip over whitespace.
  538. while (*c == ' ' || *c == '\t') {
  539. ++c;
  540. }
  541. arg.clear();
  542. if (*c == '"') {
  543. // Parse a quoted argument.
  544. ++c;
  545. while (*c && *c != '"') {
  546. arg.append(1, *c);
  547. ++c;
  548. }
  549. if (*c) {
  550. ++c;
  551. }
  552. args.push_back(arg);
  553. } else if (*c == '\'') {
  554. // Parse a quoted argument.
  555. ++c;
  556. while (*c && *c != '\'') {
  557. arg.append(1, *c);
  558. ++c;
  559. }
  560. if (*c) {
  561. ++c;
  562. }
  563. args.push_back(arg);
  564. } else if (*c) {
  565. // Parse an unquoted argument.
  566. while (*c && *c != ' ' && *c != '\t') {
  567. if (*c == '\\' && !win_path) {
  568. ++c;
  569. if (*c) {
  570. arg.append(1, *c);
  571. ++c;
  572. }
  573. } else {
  574. arg.append(1, *c);
  575. ++c;
  576. }
  577. }
  578. args.push_back(arg);
  579. }
  580. }
  581. return args;
  582. }
  583. bool cmSystemTools::SplitProgramFromArgs(std::string const& command,
  584. std::string& program,
  585. std::string& args)
  586. {
  587. const char* c = command.c_str();
  588. // Skip leading whitespace.
  589. while (isspace(static_cast<unsigned char>(*c))) {
  590. ++c;
  591. }
  592. // Parse one command-line element up to an unquoted space.
  593. bool in_escape = false;
  594. bool in_double = false;
  595. bool in_single = false;
  596. for (; *c; ++c) {
  597. if (in_single) {
  598. if (*c == '\'') {
  599. in_single = false;
  600. } else {
  601. program += *c;
  602. }
  603. } else if (in_escape) {
  604. in_escape = false;
  605. program += *c;
  606. } else if (*c == '\\') {
  607. in_escape = true;
  608. } else if (in_double) {
  609. if (*c == '"') {
  610. in_double = false;
  611. } else {
  612. program += *c;
  613. }
  614. } else if (*c == '"') {
  615. in_double = true;
  616. } else if (*c == '\'') {
  617. in_single = true;
  618. } else if (isspace(static_cast<unsigned char>(*c))) {
  619. break;
  620. } else {
  621. program += *c;
  622. }
  623. }
  624. // The remainder of the command line holds unparsed arguments.
  625. args = c;
  626. return !in_single && !in_escape && !in_double;
  627. }
  628. size_t cmSystemTools::CalculateCommandLineLengthLimit()
  629. {
  630. size_t sz =
  631. #ifdef _WIN32
  632. // There's a maximum of 65536 bytes and thus 32768 WCHARs on Windows
  633. // However, cmd.exe itself can only handle 8191 WCHARs and Ninja for
  634. // example uses it to spawn processes.
  635. size_t(8191);
  636. #elif defined(__linux)
  637. // MAX_ARG_STRLEN is the maximum length of a string permissible for
  638. // the execve() syscall on Linux. It's defined as (PAGE_SIZE * 32)
  639. // in Linux's binfmts.h
  640. static_cast<size_t>(sysconf(_SC_PAGESIZE) * 32);
  641. #else
  642. size_t(0);
  643. #endif
  644. #if defined(_SC_ARG_MAX)
  645. // ARG_MAX is the maximum size of the command and environment
  646. // that can be passed to the exec functions on UNIX.
  647. // The value in limits.h does not need to be present and may
  648. // depend upon runtime memory constraints, hence sysconf()
  649. // should be used to query it.
  650. long szArgMax = sysconf(_SC_ARG_MAX);
  651. // A return value of -1 signifies an undetermined limit, but
  652. // it does not imply an infinite limit, and thus is ignored.
  653. if (szArgMax != -1) {
  654. // We estimate the size of the environment block to be 1000.
  655. // This isn't accurate at all, but leaves some headroom.
  656. szArgMax = szArgMax < 1000 ? 0 : szArgMax - 1000;
  657. # if defined(_WIN32) || defined(__linux)
  658. sz = std::min(sz, static_cast<size_t>(szArgMax));
  659. # else
  660. sz = static_cast<size_t>(szArgMax);
  661. # endif
  662. }
  663. #endif
  664. return sz;
  665. }
  666. bool cmSystemTools::RunSingleCommand(std::vector<std::string> const& command,
  667. std::string* captureStdOut,
  668. std::string* captureStdErr, int* retVal,
  669. const char* dir, OutputOption outputflag,
  670. cmDuration timeout, Encoding encoding)
  671. {
  672. std::vector<const char*> argv;
  673. argv.reserve(command.size() + 1);
  674. for (std::string const& cmd : command) {
  675. argv.push_back(cmd.c_str());
  676. }
  677. argv.push_back(nullptr);
  678. cmsysProcess* cp = cmsysProcess_New();
  679. cmsysProcess_SetCommand(cp, &*argv.begin());
  680. cmsysProcess_SetWorkingDirectory(cp, dir);
  681. if (cmSystemTools::GetRunCommandHideConsole()) {
  682. cmsysProcess_SetOption(cp, cmsysProcess_Option_HideWindow, 1);
  683. }
  684. if (outputflag == OUTPUT_PASSTHROUGH) {
  685. cmsysProcess_SetPipeShared(cp, cmsysProcess_Pipe_STDOUT, 1);
  686. cmsysProcess_SetPipeShared(cp, cmsysProcess_Pipe_STDERR, 1);
  687. captureStdOut = nullptr;
  688. captureStdErr = nullptr;
  689. } else if (outputflag == OUTPUT_MERGE ||
  690. (captureStdErr && captureStdErr == captureStdOut)) {
  691. cmsysProcess_SetOption(cp, cmsysProcess_Option_MergeOutput, 1);
  692. captureStdErr = nullptr;
  693. }
  694. assert(!captureStdErr || captureStdErr != captureStdOut);
  695. cmsysProcess_SetTimeout(cp, timeout.count());
  696. cmsysProcess_Execute(cp);
  697. std::vector<char> tempStdOut;
  698. std::vector<char> tempStdErr;
  699. char* data;
  700. int length;
  701. int pipe;
  702. cmProcessOutput processOutput(encoding);
  703. std::string strdata;
  704. if (outputflag != OUTPUT_PASSTHROUGH &&
  705. (captureStdOut || captureStdErr || outputflag != OUTPUT_NONE)) {
  706. while ((pipe = cmsysProcess_WaitForData(cp, &data, &length, nullptr)) >
  707. 0) {
  708. // Translate NULL characters in the output into valid text.
  709. for (int i = 0; i < length; ++i) {
  710. if (data[i] == '\0') {
  711. data[i] = ' ';
  712. }
  713. }
  714. if (pipe == cmsysProcess_Pipe_STDOUT) {
  715. if (outputflag != OUTPUT_NONE) {
  716. processOutput.DecodeText(data, length, strdata, 1);
  717. cmSystemTools::Stdout(strdata);
  718. }
  719. if (captureStdOut) {
  720. tempStdOut.insert(tempStdOut.end(), data, data + length);
  721. }
  722. } else if (pipe == cmsysProcess_Pipe_STDERR) {
  723. if (outputflag != OUTPUT_NONE) {
  724. processOutput.DecodeText(data, length, strdata, 2);
  725. cmSystemTools::Stderr(strdata);
  726. }
  727. if (captureStdErr) {
  728. tempStdErr.insert(tempStdErr.end(), data, data + length);
  729. }
  730. }
  731. }
  732. if (outputflag != OUTPUT_NONE) {
  733. processOutput.DecodeText(std::string(), strdata, 1);
  734. if (!strdata.empty()) {
  735. cmSystemTools::Stdout(strdata);
  736. }
  737. processOutput.DecodeText(std::string(), strdata, 2);
  738. if (!strdata.empty()) {
  739. cmSystemTools::Stderr(strdata);
  740. }
  741. }
  742. }
  743. cmsysProcess_WaitForExit(cp, nullptr);
  744. if (captureStdOut) {
  745. captureStdOut->assign(tempStdOut.begin(), tempStdOut.end());
  746. processOutput.DecodeText(*captureStdOut, *captureStdOut);
  747. }
  748. if (captureStdErr) {
  749. captureStdErr->assign(tempStdErr.begin(), tempStdErr.end());
  750. processOutput.DecodeText(*captureStdErr, *captureStdErr);
  751. }
  752. bool result = true;
  753. if (cmsysProcess_GetState(cp) == cmsysProcess_State_Exited) {
  754. if (retVal) {
  755. *retVal = cmsysProcess_GetExitValue(cp);
  756. } else {
  757. if (cmsysProcess_GetExitValue(cp) != 0) {
  758. result = false;
  759. }
  760. }
  761. } else if (cmsysProcess_GetState(cp) == cmsysProcess_State_Exception) {
  762. const char* exception_str = cmsysProcess_GetExceptionString(cp);
  763. if (outputflag != OUTPUT_NONE) {
  764. std::cerr << exception_str << std::endl;
  765. }
  766. if (captureStdErr) {
  767. captureStdErr->append(exception_str, strlen(exception_str));
  768. } else if (captureStdOut) {
  769. captureStdOut->append(exception_str, strlen(exception_str));
  770. }
  771. result = false;
  772. } else if (cmsysProcess_GetState(cp) == cmsysProcess_State_Error) {
  773. const char* error_str = cmsysProcess_GetErrorString(cp);
  774. if (outputflag != OUTPUT_NONE) {
  775. std::cerr << error_str << std::endl;
  776. }
  777. if (captureStdErr) {
  778. captureStdErr->append(error_str, strlen(error_str));
  779. } else if (captureStdOut) {
  780. captureStdOut->append(error_str, strlen(error_str));
  781. }
  782. result = false;
  783. } else if (cmsysProcess_GetState(cp) == cmsysProcess_State_Expired) {
  784. const char* error_str = "Process terminated due to timeout\n";
  785. if (outputflag != OUTPUT_NONE) {
  786. std::cerr << error_str << std::endl;
  787. }
  788. if (captureStdErr) {
  789. captureStdErr->append(error_str, strlen(error_str));
  790. }
  791. result = false;
  792. }
  793. cmsysProcess_Delete(cp);
  794. return result;
  795. }
  796. bool cmSystemTools::RunSingleCommand(const char* command,
  797. std::string* captureStdOut,
  798. std::string* captureStdErr, int* retVal,
  799. const char* dir, OutputOption outputflag,
  800. cmDuration timeout)
  801. {
  802. if (s_DisableRunCommandOutput) {
  803. outputflag = OUTPUT_NONE;
  804. }
  805. std::vector<std::string> args = cmSystemTools::ParseArguments(command);
  806. if (args.empty()) {
  807. return false;
  808. }
  809. return cmSystemTools::RunSingleCommand(args, captureStdOut, captureStdErr,
  810. retVal, dir, outputflag, timeout);
  811. }
  812. std::string cmSystemTools::PrintSingleCommand(
  813. std::vector<std::string> const& command)
  814. {
  815. if (command.empty()) {
  816. return std::string();
  817. }
  818. return cmWrap('"', command, '"', " ");
  819. }
  820. bool cmSystemTools::DoesFileExistWithExtensions(
  821. const char* name, const std::vector<std::string>& headerExts)
  822. {
  823. std::string hname;
  824. for (std::string const& headerExt : headerExts) {
  825. hname = name;
  826. hname += ".";
  827. hname += headerExt;
  828. if (cmSystemTools::FileExists(hname)) {
  829. return true;
  830. }
  831. }
  832. return false;
  833. }
  834. std::string cmSystemTools::FileExistsInParentDirectories(const char* fname,
  835. const char* directory,
  836. const char* toplevel)
  837. {
  838. std::string file = fname;
  839. cmSystemTools::ConvertToUnixSlashes(file);
  840. std::string dir = directory;
  841. cmSystemTools::ConvertToUnixSlashes(dir);
  842. std::string prevDir;
  843. while (dir != prevDir) {
  844. std::string path = dir + "/" + file;
  845. if (cmSystemTools::FileExists(path)) {
  846. return path;
  847. }
  848. if (dir.size() < strlen(toplevel)) {
  849. break;
  850. }
  851. prevDir = dir;
  852. dir = cmSystemTools::GetParentDirectory(dir);
  853. }
  854. return "";
  855. }
  856. bool cmSystemTools::cmCopyFile(const char* source, const char* destination)
  857. {
  858. return Superclass::CopyFileAlways(source, destination);
  859. }
  860. bool cmSystemTools::CopyFileIfDifferent(const char* source,
  861. const char* destination)
  862. {
  863. return Superclass::CopyFileIfDifferent(source, destination);
  864. }
  865. #ifdef _WIN32
  866. cmSystemTools::WindowsFileRetry cmSystemTools::GetWindowsFileRetry()
  867. {
  868. static WindowsFileRetry retry = { 0, 0 };
  869. if (!retry.Count) {
  870. unsigned int data[2] = { 0, 0 };
  871. HKEY const keys[2] = { HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE };
  872. wchar_t const* const values[2] = { L"FilesystemRetryCount",
  873. L"FilesystemRetryDelay" };
  874. for (int k = 0; k < 2; ++k) {
  875. HKEY hKey;
  876. if (RegOpenKeyExW(keys[k], L"Software\\Kitware\\CMake\\Config", 0,
  877. KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS) {
  878. for (int v = 0; v < 2; ++v) {
  879. DWORD dwData, dwType, dwSize = 4;
  880. if (!data[v] &&
  881. RegQueryValueExW(hKey, values[v], 0, &dwType, (BYTE*)&dwData,
  882. &dwSize) == ERROR_SUCCESS &&
  883. dwType == REG_DWORD && dwSize == 4) {
  884. data[v] = static_cast<unsigned int>(dwData);
  885. }
  886. }
  887. RegCloseKey(hKey);
  888. }
  889. }
  890. retry.Count = data[0] ? data[0] : 5;
  891. retry.Delay = data[1] ? data[1] : 500;
  892. }
  893. return retry;
  894. }
  895. #endif
  896. std::string cmSystemTools::GetRealPathResolvingWindowsSubst(
  897. const std::string& path, std::string* errorMessage)
  898. {
  899. #ifdef _WIN32
  900. // uv_fs_realpath uses Windows Vista API so fallback to kwsys if not found
  901. std::string resolved_path;
  902. uv_fs_t req;
  903. int err = uv_fs_realpath(NULL, &req, path.c_str(), NULL);
  904. if (!err) {
  905. resolved_path = std::string((char*)req.ptr);
  906. cmSystemTools::ConvertToUnixSlashes(resolved_path);
  907. // Normalize to upper-case drive letter as GetActualCaseForPath does.
  908. if (resolved_path.size() > 1 && resolved_path[1] == ':') {
  909. resolved_path[0] = toupper(resolved_path[0]);
  910. }
  911. } else if (err == UV_ENOSYS) {
  912. resolved_path = cmsys::SystemTools::GetRealPath(path, errorMessage);
  913. } else if (errorMessage) {
  914. LPSTR message = NULL;
  915. DWORD size = FormatMessageA(
  916. FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
  917. FORMAT_MESSAGE_IGNORE_INSERTS,
  918. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&message, 0,
  919. NULL);
  920. *errorMessage = std::string(message, size);
  921. LocalFree(message);
  922. resolved_path = "";
  923. } else {
  924. resolved_path = path;
  925. }
  926. return resolved_path;
  927. #else
  928. return cmsys::SystemTools::GetRealPath(path, errorMessage);
  929. #endif
  930. }
  931. void cmSystemTools::InitializeLibUV()
  932. {
  933. #if defined(_WIN32)
  934. // Perform libuv one-time initialization now, and then un-do its
  935. // global _fmode setting so that using libuv does not change the
  936. // default file text/binary mode. See libuv issue 840.
  937. uv_loop_close(uv_default_loop());
  938. # ifdef _MSC_VER
  939. _set_fmode(_O_TEXT);
  940. # else
  941. _fmode = _O_TEXT;
  942. # endif
  943. #endif
  944. }
  945. bool cmSystemTools::RenameFile(const std::string& oldname,
  946. const std::string& newname)
  947. {
  948. #ifdef _WIN32
  949. # ifndef INVALID_FILE_ATTRIBUTES
  950. # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
  951. # endif
  952. /* Windows MoveFileEx may not replace read-only or in-use files. If it
  953. fails then remove the read-only attribute from any existing destination.
  954. Try multiple times since we may be racing against another process
  955. creating/opening the destination file just before our MoveFileEx. */
  956. WindowsFileRetry retry = cmSystemTools::GetWindowsFileRetry();
  957. while (
  958. !MoveFileExW(SystemTools::ConvertToWindowsExtendedPath(oldname).c_str(),
  959. SystemTools::ConvertToWindowsExtendedPath(newname).c_str(),
  960. MOVEFILE_REPLACE_EXISTING) &&
  961. --retry.Count) {
  962. DWORD last_error = GetLastError();
  963. // Try again only if failure was due to access/sharing permissions.
  964. if (last_error != ERROR_ACCESS_DENIED &&
  965. last_error != ERROR_SHARING_VIOLATION) {
  966. return false;
  967. }
  968. DWORD attrs = GetFileAttributesW(
  969. SystemTools::ConvertToWindowsExtendedPath(newname).c_str());
  970. if ((attrs != INVALID_FILE_ATTRIBUTES) &&
  971. (attrs & FILE_ATTRIBUTE_READONLY)) {
  972. // Remove the read-only attribute from the destination file.
  973. SetFileAttributesW(
  974. SystemTools::ConvertToWindowsExtendedPath(newname).c_str(),
  975. attrs & ~FILE_ATTRIBUTE_READONLY);
  976. } else {
  977. // The file may be temporarily in use so wait a bit.
  978. cmSystemTools::Delay(retry.Delay);
  979. }
  980. }
  981. return retry.Count > 0;
  982. #else
  983. /* On UNIX we have an OS-provided call to do this atomically. */
  984. return rename(oldname.c_str(), newname.c_str()) == 0;
  985. #endif
  986. }
  987. std::string cmSystemTools::ComputeFileHash(const std::string& source,
  988. cmCryptoHash::Algo algo)
  989. {
  990. #if defined(CMAKE_BUILD_WITH_CMAKE)
  991. cmCryptoHash hash(algo);
  992. return hash.HashFile(source);
  993. #else
  994. (void)source;
  995. cmSystemTools::Message("hashsum not supported in bootstrapping mode",
  996. "Error");
  997. return std::string();
  998. #endif
  999. }
  1000. std::string cmSystemTools::ComputeStringMD5(const std::string& input)
  1001. {
  1002. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1003. cmCryptoHash md5(cmCryptoHash::AlgoMD5);
  1004. return md5.HashString(input);
  1005. #else
  1006. (void)input;
  1007. cmSystemTools::Message("md5sum not supported in bootstrapping mode",
  1008. "Error");
  1009. return "";
  1010. #endif
  1011. }
  1012. std::string cmSystemTools::ComputeCertificateThumbprint(
  1013. const std::string& source)
  1014. {
  1015. std::string thumbprint;
  1016. #if defined(CMAKE_BUILD_WITH_CMAKE) && defined(_WIN32)
  1017. BYTE* certData = NULL;
  1018. CRYPT_INTEGER_BLOB cryptBlob;
  1019. HCERTSTORE certStore = NULL;
  1020. PCCERT_CONTEXT certContext = NULL;
  1021. HANDLE certFile = CreateFileW(
  1022. cmsys::Encoding::ToWide(source.c_str()).c_str(), GENERIC_READ,
  1023. FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  1024. if (certFile != INVALID_HANDLE_VALUE && certFile != NULL) {
  1025. DWORD fileSize = GetFileSize(certFile, NULL);
  1026. if (fileSize != INVALID_FILE_SIZE) {
  1027. certData = new BYTE[fileSize];
  1028. if (certData != NULL) {
  1029. DWORD dwRead = 0;
  1030. if (ReadFile(certFile, certData, fileSize, &dwRead, NULL)) {
  1031. cryptBlob.cbData = fileSize;
  1032. cryptBlob.pbData = certData;
  1033. // Verify that this is a valid cert
  1034. if (PFXIsPFXBlob(&cryptBlob)) {
  1035. // Open the certificate as a store
  1036. certStore = PFXImportCertStore(&cryptBlob, NULL, CRYPT_EXPORTABLE);
  1037. if (certStore != NULL) {
  1038. // There should only be 1 cert.
  1039. certContext =
  1040. CertEnumCertificatesInStore(certStore, certContext);
  1041. if (certContext != NULL) {
  1042. // The hash is 20 bytes
  1043. BYTE hashData[20];
  1044. DWORD hashLength = 20;
  1045. // Buffer to print the hash. Each byte takes 2 chars +
  1046. // terminating character
  1047. char hashPrint[41];
  1048. char* pHashPrint = hashPrint;
  1049. // Get the hash property from the certificate
  1050. if (CertGetCertificateContextProperty(
  1051. certContext, CERT_HASH_PROP_ID, hashData, &hashLength)) {
  1052. for (DWORD i = 0; i < hashLength; i++) {
  1053. // Convert each byte to hexadecimal
  1054. sprintf(pHashPrint, "%02X", hashData[i]);
  1055. pHashPrint += 2;
  1056. }
  1057. *pHashPrint = '\0';
  1058. thumbprint = hashPrint;
  1059. }
  1060. CertFreeCertificateContext(certContext);
  1061. }
  1062. CertCloseStore(certStore, 0);
  1063. }
  1064. }
  1065. }
  1066. delete[] certData;
  1067. }
  1068. }
  1069. CloseHandle(certFile);
  1070. }
  1071. #else
  1072. (void)source;
  1073. cmSystemTools::Message("ComputeCertificateThumbprint is not implemented",
  1074. "Error");
  1075. #endif
  1076. return thumbprint;
  1077. }
  1078. void cmSystemTools::Glob(const std::string& directory,
  1079. const std::string& regexp,
  1080. std::vector<std::string>& files)
  1081. {
  1082. cmsys::Directory d;
  1083. cmsys::RegularExpression reg(regexp.c_str());
  1084. if (d.Load(directory)) {
  1085. size_t numf;
  1086. unsigned int i;
  1087. numf = d.GetNumberOfFiles();
  1088. for (i = 0; i < numf; i++) {
  1089. std::string fname = d.GetFile(i);
  1090. if (reg.find(fname)) {
  1091. files.push_back(std::move(fname));
  1092. }
  1093. }
  1094. }
  1095. }
  1096. void cmSystemTools::GlobDirs(const std::string& path,
  1097. std::vector<std::string>& files)
  1098. {
  1099. std::string::size_type pos = path.find("/*");
  1100. if (pos == std::string::npos) {
  1101. files.push_back(path);
  1102. return;
  1103. }
  1104. std::string startPath = path.substr(0, pos);
  1105. std::string finishPath = path.substr(pos + 2);
  1106. cmsys::Directory d;
  1107. if (d.Load(startPath)) {
  1108. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i) {
  1109. if ((std::string(d.GetFile(i)) != ".") &&
  1110. (std::string(d.GetFile(i)) != "..")) {
  1111. std::string fname = startPath;
  1112. fname += "/";
  1113. fname += d.GetFile(i);
  1114. if (cmSystemTools::FileIsDirectory(fname)) {
  1115. fname += finishPath;
  1116. cmSystemTools::GlobDirs(fname, files);
  1117. }
  1118. }
  1119. }
  1120. }
  1121. }
  1122. void cmSystemTools::ExpandList(std::vector<std::string> const& arguments,
  1123. std::vector<std::string>& newargs)
  1124. {
  1125. std::vector<std::string>::const_iterator i;
  1126. for (i = arguments.begin(); i != arguments.end(); ++i) {
  1127. cmSystemTools::ExpandListArgument(*i, newargs);
  1128. }
  1129. }
  1130. void cmSystemTools::ExpandListArgument(const std::string& arg,
  1131. std::vector<std::string>& newargs,
  1132. bool emptyArgs)
  1133. {
  1134. // If argument is empty, it is an empty list.
  1135. if (!emptyArgs && arg.empty()) {
  1136. return;
  1137. }
  1138. // if there are no ; in the name then just copy the current string
  1139. if (arg.find(';') == std::string::npos) {
  1140. newargs.push_back(arg);
  1141. return;
  1142. }
  1143. std::string newArg;
  1144. const char* last = arg.c_str();
  1145. // Break the string at non-escaped semicolons not nested in [].
  1146. int squareNesting = 0;
  1147. for (const char* c = last; *c; ++c) {
  1148. switch (*c) {
  1149. case '\\': {
  1150. // We only want to allow escaping of semicolons. Other
  1151. // escapes should not be processed here.
  1152. const char* next = c + 1;
  1153. if (*next == ';') {
  1154. newArg.append(last, c - last);
  1155. // Skip over the escape character
  1156. last = c = next;
  1157. }
  1158. } break;
  1159. case '[': {
  1160. ++squareNesting;
  1161. } break;
  1162. case ']': {
  1163. --squareNesting;
  1164. } break;
  1165. case ';': {
  1166. // Break the string here if we are not nested inside square
  1167. // brackets.
  1168. if (squareNesting == 0) {
  1169. newArg.append(last, c - last);
  1170. // Skip over the semicolon
  1171. last = c + 1;
  1172. if (!newArg.empty() || emptyArgs) {
  1173. // Add the last argument if the string is not empty.
  1174. newargs.push_back(newArg);
  1175. newArg.clear();
  1176. }
  1177. }
  1178. } break;
  1179. default: {
  1180. // Just append this character.
  1181. } break;
  1182. }
  1183. }
  1184. newArg.append(last);
  1185. if (!newArg.empty() || emptyArgs) {
  1186. // Add the last argument if the string is not empty.
  1187. newargs.push_back(newArg);
  1188. }
  1189. }
  1190. bool cmSystemTools::SimpleGlob(const std::string& glob,
  1191. std::vector<std::string>& files,
  1192. int type /* = 0 */)
  1193. {
  1194. files.clear();
  1195. if (glob.back() != '*') {
  1196. return false;
  1197. }
  1198. std::string path = cmSystemTools::GetFilenamePath(glob);
  1199. std::string ppath = cmSystemTools::GetFilenameName(glob);
  1200. ppath = ppath.substr(0, ppath.size() - 1);
  1201. if (path.empty()) {
  1202. path = "/";
  1203. }
  1204. bool res = false;
  1205. cmsys::Directory d;
  1206. if (d.Load(path)) {
  1207. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i) {
  1208. if ((std::string(d.GetFile(i)) != ".") &&
  1209. (std::string(d.GetFile(i)) != "..")) {
  1210. std::string fname = path;
  1211. if (path.back() != '/') {
  1212. fname += "/";
  1213. }
  1214. fname += d.GetFile(i);
  1215. std::string sfname = d.GetFile(i);
  1216. if (type > 0 && cmSystemTools::FileIsDirectory(fname)) {
  1217. continue;
  1218. }
  1219. if (type < 0 && !cmSystemTools::FileIsDirectory(fname)) {
  1220. continue;
  1221. }
  1222. if (sfname.size() >= ppath.size() &&
  1223. sfname.substr(0, ppath.size()) == ppath) {
  1224. files.push_back(fname);
  1225. res = true;
  1226. }
  1227. }
  1228. }
  1229. }
  1230. return res;
  1231. }
  1232. cmSystemTools::FileFormat cmSystemTools::GetFileFormat(const char* cext)
  1233. {
  1234. if (!cext || *cext == 0) {
  1235. return cmSystemTools::NO_FILE_FORMAT;
  1236. }
  1237. // std::string ext = cmSystemTools::LowerCase(cext);
  1238. std::string ext = cext;
  1239. if (ext == "c" || ext == ".c" || ext == "m" || ext == ".m") {
  1240. return cmSystemTools::C_FILE_FORMAT;
  1241. }
  1242. if (ext == "C" || ext == ".C" || ext == "M" || ext == ".M" || ext == "c++" ||
  1243. ext == ".c++" || ext == "cc" || ext == ".cc" || ext == "cpp" ||
  1244. ext == ".cpp" || ext == "cxx" || ext == ".cxx" || ext == "mm" ||
  1245. ext == ".mm") {
  1246. return cmSystemTools::CXX_FILE_FORMAT;
  1247. }
  1248. if (ext == "f" || ext == ".f" || ext == "F" || ext == ".F" || ext == "f77" ||
  1249. ext == ".f77" || ext == "f90" || ext == ".f90" || ext == "for" ||
  1250. ext == ".for" || ext == "f95" || ext == ".f95") {
  1251. return cmSystemTools::FORTRAN_FILE_FORMAT;
  1252. }
  1253. if (ext == "java" || ext == ".java") {
  1254. return cmSystemTools::JAVA_FILE_FORMAT;
  1255. }
  1256. if (ext == "cu" || ext == ".cu") {
  1257. return cmSystemTools::CUDA_FILE_FORMAT;
  1258. }
  1259. if (ext == "H" || ext == ".H" || ext == "h" || ext == ".h" || ext == "h++" ||
  1260. ext == ".h++" || ext == "hm" || ext == ".hm" || ext == "hpp" ||
  1261. ext == ".hpp" || ext == "hxx" || ext == ".hxx" || ext == "in" ||
  1262. ext == ".in" || ext == "txx" || ext == ".txx") {
  1263. return cmSystemTools::HEADER_FILE_FORMAT;
  1264. }
  1265. if (ext == "rc" || ext == ".rc") {
  1266. return cmSystemTools::RESOURCE_FILE_FORMAT;
  1267. }
  1268. if (ext == "def" || ext == ".def") {
  1269. return cmSystemTools::DEFINITION_FILE_FORMAT;
  1270. }
  1271. if (ext == "lib" || ext == ".lib" || ext == "a" || ext == ".a") {
  1272. return cmSystemTools::STATIC_LIBRARY_FILE_FORMAT;
  1273. }
  1274. if (ext == "o" || ext == ".o" || ext == "obj" || ext == ".obj") {
  1275. return cmSystemTools::OBJECT_FILE_FORMAT;
  1276. }
  1277. #ifdef __APPLE__
  1278. if (ext == "dylib" || ext == ".dylib") {
  1279. return cmSystemTools::SHARED_LIBRARY_FILE_FORMAT;
  1280. }
  1281. if (ext == "so" || ext == ".so" || ext == "bundle" || ext == ".bundle") {
  1282. return cmSystemTools::MODULE_FILE_FORMAT;
  1283. }
  1284. #else // __APPLE__
  1285. if (ext == "so" || ext == ".so" || ext == "sl" || ext == ".sl" ||
  1286. ext == "dll" || ext == ".dll") {
  1287. return cmSystemTools::SHARED_LIBRARY_FILE_FORMAT;
  1288. }
  1289. #endif // __APPLE__
  1290. return cmSystemTools::UNKNOWN_FILE_FORMAT;
  1291. }
  1292. bool cmSystemTools::Split(const char* s, std::vector<std::string>& l)
  1293. {
  1294. std::vector<std::string> temp;
  1295. bool res = Superclass::Split(s, temp);
  1296. l.insert(l.end(), temp.begin(), temp.end());
  1297. return res;
  1298. }
  1299. std::string cmSystemTools::ConvertToOutputPath(std::string const& path)
  1300. {
  1301. #if defined(_WIN32) && !defined(__CYGWIN__)
  1302. if (s_ForceUnixPaths) {
  1303. return cmSystemTools::ConvertToUnixOutputPath(path);
  1304. }
  1305. return cmSystemTools::ConvertToWindowsOutputPath(path);
  1306. #else
  1307. return cmSystemTools::ConvertToUnixOutputPath(path);
  1308. #endif
  1309. }
  1310. void cmSystemTools::ConvertToOutputSlashes(std::string& path)
  1311. {
  1312. #if defined(_WIN32) && !defined(__CYGWIN__)
  1313. if (!s_ForceUnixPaths) {
  1314. // Convert to windows slashes.
  1315. std::string::size_type pos = 0;
  1316. while ((pos = path.find('/', pos)) != std::string::npos) {
  1317. path[pos++] = '\\';
  1318. }
  1319. }
  1320. #else
  1321. static_cast<void>(path);
  1322. #endif
  1323. }
  1324. std::string cmSystemTools::ConvertToRunCommandPath(const char* path)
  1325. {
  1326. #if defined(_WIN32) && !defined(__CYGWIN__)
  1327. return cmSystemTools::ConvertToWindowsOutputPath(path);
  1328. #else
  1329. return cmSystemTools::ConvertToUnixOutputPath(path);
  1330. #endif
  1331. }
  1332. // compute the relative path from here to there
  1333. std::string cmSystemTools::RelativePath(std::string const& local,
  1334. std::string const& remote)
  1335. {
  1336. if (!cmSystemTools::FileIsFullPath(local)) {
  1337. cmSystemTools::Error("RelativePath must be passed a full path to local: ",
  1338. local.c_str());
  1339. }
  1340. if (!cmSystemTools::FileIsFullPath(remote)) {
  1341. cmSystemTools::Error("RelativePath must be passed a full path to remote: ",
  1342. remote.c_str());
  1343. }
  1344. return cmsys::SystemTools::RelativePath(local, remote);
  1345. }
  1346. std::string cmSystemTools::ForceToRelativePath(std::string const& local_path,
  1347. std::string const& remote_path)
  1348. {
  1349. // The paths should never be quoted.
  1350. assert(local_path.front() != '\"');
  1351. assert(remote_path.front() != '\"');
  1352. // The local path should never have a trailing slash.
  1353. assert(local_path.empty() || local_path.back() != '/');
  1354. // If the path is already relative then just return the path.
  1355. if (!cmSystemTools::FileIsFullPath(remote_path)) {
  1356. return remote_path;
  1357. }
  1358. // Identify the longest shared path component between the remote
  1359. // path and the local path.
  1360. std::vector<std::string> local;
  1361. cmSystemTools::SplitPath(local_path, local);
  1362. std::vector<std::string> remote;
  1363. cmSystemTools::SplitPath(remote_path, remote);
  1364. unsigned int common = 0;
  1365. while (common < remote.size() && common < local.size() &&
  1366. cmSystemTools::ComparePath(remote[common], local[common])) {
  1367. ++common;
  1368. }
  1369. // If no part of the path is in common then return the full path.
  1370. if (common == 0) {
  1371. return remote_path;
  1372. }
  1373. // If the entire path is in common then just return a ".".
  1374. if (common == remote.size() && common == local.size()) {
  1375. return ".";
  1376. }
  1377. // If the entire path is in common except for a trailing slash then
  1378. // just return a "./".
  1379. if (common + 1 == remote.size() && remote[common].empty() &&
  1380. common == local.size()) {
  1381. return "./";
  1382. }
  1383. // Construct the relative path.
  1384. std::string relative;
  1385. // First add enough ../ to get up to the level of the shared portion
  1386. // of the path. Leave off the trailing slash. Note that the last
  1387. // component of local will never be empty because local should never
  1388. // have a trailing slash.
  1389. for (unsigned int i = common; i < local.size(); ++i) {
  1390. relative += "..";
  1391. if (i < local.size() - 1) {
  1392. relative += "/";
  1393. }
  1394. }
  1395. // Now add the portion of the destination path that is not included
  1396. // in the shared portion of the path. Add a slash the first time
  1397. // only if there was already something in the path. If there was a
  1398. // trailing slash in the input then the last iteration of the loop
  1399. // will add a slash followed by an empty string which will preserve
  1400. // the trailing slash in the output.
  1401. if (!relative.empty() && !remote.empty()) {
  1402. relative += "/";
  1403. }
  1404. relative += cmJoin(cmMakeRange(remote).advance(common), "/");
  1405. // Finally return the path.
  1406. return relative;
  1407. }
  1408. std::string cmSystemTools::CollapseCombinedPath(std::string const& dir,
  1409. std::string const& file)
  1410. {
  1411. if (dir.empty() || dir == ".") {
  1412. return file;
  1413. }
  1414. std::vector<std::string> dirComponents;
  1415. std::vector<std::string> fileComponents;
  1416. cmSystemTools::SplitPath(dir, dirComponents);
  1417. cmSystemTools::SplitPath(file, fileComponents);
  1418. if (fileComponents.empty()) {
  1419. return dir;
  1420. }
  1421. if (!fileComponents[0].empty()) {
  1422. // File is not a relative path.
  1423. return file;
  1424. }
  1425. std::vector<std::string>::iterator i = fileComponents.begin() + 1;
  1426. while (i != fileComponents.end() && *i == ".." && dirComponents.size() > 1) {
  1427. ++i; // Remove ".." file component.
  1428. dirComponents.pop_back(); // Remove last dir component.
  1429. }
  1430. dirComponents.insert(dirComponents.end(), i, fileComponents.end());
  1431. return cmSystemTools::JoinPath(dirComponents);
  1432. }
  1433. #ifdef CMAKE_BUILD_WITH_CMAKE
  1434. bool cmSystemTools::UnsetEnv(const char* value)
  1435. {
  1436. # if !defined(HAVE_UNSETENV)
  1437. std::string var = value;
  1438. var += "=";
  1439. return cmSystemTools::PutEnv(var.c_str());
  1440. # else
  1441. unsetenv(value);
  1442. return true;
  1443. # endif
  1444. }
  1445. std::vector<std::string> cmSystemTools::GetEnvironmentVariables()
  1446. {
  1447. std::vector<std::string> env;
  1448. int cc;
  1449. for (cc = 0; environ[cc]; ++cc) {
  1450. env.emplace_back(environ[cc]);
  1451. }
  1452. return env;
  1453. }
  1454. void cmSystemTools::AppendEnv(std::vector<std::string> const& env)
  1455. {
  1456. for (std::string const& eit : env) {
  1457. cmSystemTools::PutEnv(eit);
  1458. }
  1459. }
  1460. cmSystemTools::SaveRestoreEnvironment::SaveRestoreEnvironment()
  1461. {
  1462. this->Env = cmSystemTools::GetEnvironmentVariables();
  1463. }
  1464. cmSystemTools::SaveRestoreEnvironment::~SaveRestoreEnvironment()
  1465. {
  1466. // First clear everything in the current environment:
  1467. std::vector<std::string> currentEnv = GetEnvironmentVariables();
  1468. for (std::string var : currentEnv) {
  1469. std::string::size_type pos = var.find('=');
  1470. if (pos != std::string::npos) {
  1471. var = var.substr(0, pos);
  1472. }
  1473. cmSystemTools::UnsetEnv(var.c_str());
  1474. }
  1475. // Then put back each entry from the original environment:
  1476. cmSystemTools::AppendEnv(this->Env);
  1477. }
  1478. #endif
  1479. void cmSystemTools::EnableVSConsoleOutput()
  1480. {
  1481. #ifdef _WIN32
  1482. // Visual Studio tools like devenv may not
  1483. // display output to the console unless this environment variable is
  1484. // set. We need it to capture the output of these build tools.
  1485. // Note for future work that one could pass "/out \\.\pipe\NAME" to
  1486. // either of these executables where NAME is created with
  1487. // CreateNamedPipe. This would bypass the internal buffering of the
  1488. // output and allow it to be captured on the fly.
  1489. cmSystemTools::PutEnv("vsconsoleoutput=1");
  1490. # ifdef CMAKE_BUILD_WITH_CMAKE
  1491. // VS sets an environment variable to tell MS tools like "cl" to report
  1492. // output through a backdoor pipe instead of stdout/stderr. Unset the
  1493. // environment variable to close this backdoor for any path of process
  1494. // invocations that passes through CMake so we can capture the output.
  1495. cmSystemTools::UnsetEnv("VS_UNICODE_OUTPUT");
  1496. # endif
  1497. #endif
  1498. }
  1499. bool cmSystemTools::IsPathToFramework(const char* path)
  1500. {
  1501. return (cmSystemTools::FileIsFullPath(path) &&
  1502. cmHasLiteralSuffix(path, ".framework"));
  1503. }
  1504. bool cmSystemTools::CreateTar(const char* outFileName,
  1505. const std::vector<std::string>& files,
  1506. cmTarCompression compressType, bool verbose,
  1507. std::string const& mtime,
  1508. std::string const& format)
  1509. {
  1510. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1511. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1512. cmsys::ofstream fout(outFileName, std::ios::out | std::ios::binary);
  1513. if (!fout) {
  1514. std::string e = "Cannot open output file \"";
  1515. e += outFileName;
  1516. e += "\": ";
  1517. e += cmSystemTools::GetLastSystemError();
  1518. cmSystemTools::Error(e.c_str());
  1519. return false;
  1520. }
  1521. cmArchiveWrite::Compress compress = cmArchiveWrite::CompressNone;
  1522. switch (compressType) {
  1523. case TarCompressGZip:
  1524. compress = cmArchiveWrite::CompressGZip;
  1525. break;
  1526. case TarCompressBZip2:
  1527. compress = cmArchiveWrite::CompressBZip2;
  1528. break;
  1529. case TarCompressXZ:
  1530. compress = cmArchiveWrite::CompressXZ;
  1531. break;
  1532. case TarCompressNone:
  1533. compress = cmArchiveWrite::CompressNone;
  1534. break;
  1535. }
  1536. cmArchiveWrite a(fout, compress, format.empty() ? "paxr" : format);
  1537. a.SetMTime(mtime);
  1538. a.SetVerbose(verbose);
  1539. for (auto path : files) {
  1540. if (cmSystemTools::FileIsFullPath(path)) {
  1541. // Get the relative path to the file.
  1542. path = cmSystemTools::RelativePath(cwd, path);
  1543. }
  1544. if (!a.Add(path)) {
  1545. break;
  1546. }
  1547. }
  1548. if (!a) {
  1549. cmSystemTools::Error(a.GetError().c_str());
  1550. return false;
  1551. }
  1552. return true;
  1553. #else
  1554. (void)outFileName;
  1555. (void)files;
  1556. (void)verbose;
  1557. return false;
  1558. #endif
  1559. }
  1560. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1561. namespace {
  1562. # define BSDTAR_FILESIZE_PRINTF "%lu"
  1563. # define BSDTAR_FILESIZE_TYPE unsigned long
  1564. void list_item_verbose(FILE* out, struct archive_entry* entry)
  1565. {
  1566. char tmp[100];
  1567. size_t w;
  1568. const char* p;
  1569. const char* fmt;
  1570. time_t tim;
  1571. static time_t now;
  1572. size_t u_width = 6;
  1573. size_t gs_width = 13;
  1574. /*
  1575. * We avoid collecting the entire list in memory at once by
  1576. * listing things as we see them. However, that also means we can't
  1577. * just pre-compute the field widths. Instead, we start with guesses
  1578. * and just widen them as necessary. These numbers are completely
  1579. * arbitrary.
  1580. */
  1581. if (!now) {
  1582. time(&now);
  1583. }
  1584. fprintf(out, "%s %d ", archive_entry_strmode(entry),
  1585. archive_entry_nlink(entry));
  1586. /* Use uname if it's present, else uid. */
  1587. p = archive_entry_uname(entry);
  1588. if ((p == nullptr) || (*p == '\0')) {
  1589. sprintf(tmp, "%lu ", static_cast<unsigned long>(archive_entry_uid(entry)));
  1590. p = tmp;
  1591. }
  1592. w = strlen(p);
  1593. if (w > u_width) {
  1594. u_width = w;
  1595. }
  1596. fprintf(out, "%-*s ", static_cast<int>(u_width), p);
  1597. /* Use gname if it's present, else gid. */
  1598. p = archive_entry_gname(entry);
  1599. if (p != nullptr && p[0] != '\0') {
  1600. fprintf(out, "%s", p);
  1601. w = strlen(p);
  1602. } else {
  1603. sprintf(tmp, "%lu", static_cast<unsigned long>(archive_entry_gid(entry)));
  1604. w = strlen(tmp);
  1605. fprintf(out, "%s", tmp);
  1606. }
  1607. /*
  1608. * Print device number or file size, right-aligned so as to make
  1609. * total width of group and devnum/filesize fields be gs_width.
  1610. * If gs_width is too small, grow it.
  1611. */
  1612. if (archive_entry_filetype(entry) == AE_IFCHR ||
  1613. archive_entry_filetype(entry) == AE_IFBLK) {
  1614. unsigned long rdevmajor = archive_entry_rdevmajor(entry);
  1615. unsigned long rdevminor = archive_entry_rdevminor(entry);
  1616. sprintf(tmp, "%lu,%lu", rdevmajor, rdevminor);
  1617. } else {
  1618. /*
  1619. * Note the use of platform-dependent macros to format
  1620. * the filesize here. We need the format string and the
  1621. * corresponding type for the cast.
  1622. */
  1623. sprintf(tmp, BSDTAR_FILESIZE_PRINTF,
  1624. static_cast<BSDTAR_FILESIZE_TYPE>(archive_entry_size(entry)));
  1625. }
  1626. if (w + strlen(tmp) >= gs_width) {
  1627. gs_width = w + strlen(tmp) + 1;
  1628. }
  1629. fprintf(out, "%*s", static_cast<int>(gs_width - w), tmp);
  1630. /* Format the time using 'ls -l' conventions. */
  1631. tim = archive_entry_mtime(entry);
  1632. # define HALF_YEAR ((time_t)365 * 86400 / 2)
  1633. # if defined(_WIN32) && !defined(__CYGWIN__)
  1634. /* Windows' strftime function does not support %e format. */
  1635. # define DAY_FMT "%d"
  1636. # else
  1637. # define DAY_FMT "%e" /* Day number without leading zeros */
  1638. # endif
  1639. if (tim < now - HALF_YEAR || tim > now + HALF_YEAR) {
  1640. fmt = DAY_FMT " %b %Y";
  1641. } else {
  1642. fmt = DAY_FMT " %b %H:%M";
  1643. }
  1644. strftime(tmp, sizeof(tmp), fmt, localtime(&tim));
  1645. fprintf(out, " %s ", tmp);
  1646. fprintf(out, "%s", cm_archive_entry_pathname(entry).c_str());
  1647. /* Extra information for links. */
  1648. if (archive_entry_hardlink(entry)) /* Hard link */
  1649. {
  1650. fprintf(out, " link to %s", archive_entry_hardlink(entry));
  1651. } else if (archive_entry_symlink(entry)) /* Symbolic link */
  1652. {
  1653. fprintf(out, " -> %s", archive_entry_symlink(entry));
  1654. }
  1655. fflush(out);
  1656. }
  1657. bool la_diagnostic(struct archive* ar, __LA_SSIZE_T r)
  1658. {
  1659. // See archive.h definition of ARCHIVE_OK for return values.
  1660. if (r >= ARCHIVE_OK) {
  1661. return true;
  1662. }
  1663. if (r >= ARCHIVE_WARN) {
  1664. const char* warn = archive_error_string(ar);
  1665. if (!warn) {
  1666. warn = "unknown warning";
  1667. }
  1668. std::cerr << "cmake -E tar: warning: " << warn << '\n';
  1669. return true;
  1670. }
  1671. // Error.
  1672. const char* err = archive_error_string(ar);
  1673. if (!err) {
  1674. err = "unknown error";
  1675. }
  1676. std::cerr << "cmake -E tar: error: " << err << '\n';
  1677. return false;
  1678. }
  1679. // Return 'true' on success
  1680. bool copy_data(struct archive* ar, struct archive* aw)
  1681. {
  1682. long r;
  1683. const void* buff;
  1684. size_t size;
  1685. # if defined(ARCHIVE_VERSION_NUMBER) && ARCHIVE_VERSION_NUMBER >= 3000000
  1686. __LA_INT64_T offset;
  1687. # else
  1688. off_t offset;
  1689. # endif
  1690. for (;;) {
  1691. // See archive.h definition of ARCHIVE_OK for return values.
  1692. r = archive_read_data_block(ar, &buff, &size, &offset);
  1693. if (r == ARCHIVE_EOF) {
  1694. return true;
  1695. }
  1696. if (!la_diagnostic(ar, r)) {
  1697. return false;
  1698. }
  1699. // See archive.h definition of ARCHIVE_OK for return values.
  1700. __LA_SSIZE_T const w = archive_write_data_block(aw, buff, size, offset);
  1701. if (!la_diagnostic(ar, w)) {
  1702. return false;
  1703. }
  1704. }
  1705. # if !defined(__clang__) && !defined(__HP_aCC)
  1706. return false; /* this should not happen but it quiets some compilers */
  1707. # endif
  1708. }
  1709. bool extract_tar(const char* outFileName, bool verbose, bool extract)
  1710. {
  1711. cmLocaleRAII localeRAII;
  1712. static_cast<void>(localeRAII);
  1713. struct archive* a = archive_read_new();
  1714. struct archive* ext = archive_write_disk_new();
  1715. archive_read_support_filter_all(a);
  1716. archive_read_support_format_all(a);
  1717. struct archive_entry* entry;
  1718. int r = cm_archive_read_open_file(a, outFileName, 10240);
  1719. if (r) {
  1720. cmSystemTools::Error("Problem with archive_read_open_file(): ",
  1721. archive_error_string(a));
  1722. archive_write_free(ext);
  1723. archive_read_close(a);
  1724. return false;
  1725. }
  1726. for (;;) {
  1727. r = archive_read_next_header(a, &entry);
  1728. if (r == ARCHIVE_EOF) {
  1729. break;
  1730. }
  1731. if (r != ARCHIVE_OK) {
  1732. cmSystemTools::Error("Problem with archive_read_next_header(): ",
  1733. archive_error_string(a));
  1734. break;
  1735. }
  1736. if (verbose) {
  1737. if (extract) {
  1738. cmSystemTools::Stdout("x ");
  1739. cmSystemTools::Stdout(cm_archive_entry_pathname(entry));
  1740. } else {
  1741. list_item_verbose(stdout, entry);
  1742. }
  1743. cmSystemTools::Stdout("\n");
  1744. } else if (!extract) {
  1745. cmSystemTools::Stdout(cm_archive_entry_pathname(entry));
  1746. cmSystemTools::Stdout("\n");
  1747. }
  1748. if (extract) {
  1749. r = archive_write_disk_set_options(ext, ARCHIVE_EXTRACT_TIME);
  1750. if (r != ARCHIVE_OK) {
  1751. cmSystemTools::Error("Problem with archive_write_disk_set_options(): ",
  1752. archive_error_string(ext));
  1753. break;
  1754. }
  1755. r = archive_write_header(ext, entry);
  1756. if (r == ARCHIVE_OK) {
  1757. if (!copy_data(a, ext)) {
  1758. break;
  1759. }
  1760. r = archive_write_finish_entry(ext);
  1761. if (r != ARCHIVE_OK) {
  1762. cmSystemTools::Error("Problem with archive_write_finish_entry(): ",
  1763. archive_error_string(ext));
  1764. break;
  1765. }
  1766. }
  1767. # ifdef _WIN32
  1768. else if (const char* linktext = archive_entry_symlink(entry)) {
  1769. std::cerr << "cmake -E tar: warning: skipping symbolic link \""
  1770. << cm_archive_entry_pathname(entry) << "\" -> \"" << linktext
  1771. << "\"." << std::endl;
  1772. }
  1773. # endif
  1774. else {
  1775. cmSystemTools::Error("Problem with archive_write_header(): ",
  1776. archive_error_string(ext));
  1777. cmSystemTools::Error("Current file: ",
  1778. cm_archive_entry_pathname(entry).c_str());
  1779. break;
  1780. }
  1781. }
  1782. }
  1783. archive_write_free(ext);
  1784. archive_read_close(a);
  1785. archive_read_free(a);
  1786. return r == ARCHIVE_EOF || r == ARCHIVE_OK;
  1787. }
  1788. }
  1789. #endif
  1790. bool cmSystemTools::ExtractTar(const char* outFileName, bool verbose)
  1791. {
  1792. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1793. return extract_tar(outFileName, verbose, true);
  1794. #else
  1795. (void)outFileName;
  1796. (void)verbose;
  1797. return false;
  1798. #endif
  1799. }
  1800. bool cmSystemTools::ListTar(const char* outFileName, bool verbose)
  1801. {
  1802. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1803. return extract_tar(outFileName, verbose, false);
  1804. #else
  1805. (void)outFileName;
  1806. (void)verbose;
  1807. return false;
  1808. #endif
  1809. }
  1810. int cmSystemTools::WaitForLine(cmsysProcess* process, std::string& line,
  1811. cmDuration timeout, std::vector<char>& out,
  1812. std::vector<char>& err)
  1813. {
  1814. line.clear();
  1815. std::vector<char>::iterator outiter = out.begin();
  1816. std::vector<char>::iterator erriter = err.begin();
  1817. cmProcessOutput processOutput;
  1818. std::string strdata;
  1819. while (true) {
  1820. // Check for a newline in stdout.
  1821. for (; outiter != out.end(); ++outiter) {
  1822. if ((*outiter == '\r') && ((outiter + 1) == out.end())) {
  1823. break;
  1824. }
  1825. if (*outiter == '\n' || *outiter == '\0') {
  1826. std::vector<char>::size_type length = outiter - out.begin();
  1827. if (length > 1 && *(outiter - 1) == '\r') {
  1828. --length;
  1829. }
  1830. if (length > 0) {
  1831. line.append(&out[0], length);
  1832. }
  1833. out.erase(out.begin(), outiter + 1);
  1834. return cmsysProcess_Pipe_STDOUT;
  1835. }
  1836. }
  1837. // Check for a newline in stderr.
  1838. for (; erriter != err.end(); ++erriter) {
  1839. if ((*erriter == '\r') && ((erriter + 1) == err.end())) {
  1840. break;
  1841. }
  1842. if (*erriter == '\n' || *erriter == '\0') {
  1843. std::vector<char>::size_type length = erriter - err.begin();
  1844. if (length > 1 && *(erriter - 1) == '\r') {
  1845. --length;
  1846. }
  1847. if (length > 0) {
  1848. line.append(&err[0], length);
  1849. }
  1850. err.erase(err.begin(), erriter + 1);
  1851. return cmsysProcess_Pipe_STDERR;
  1852. }
  1853. }
  1854. // No newlines found. Wait for more data from the process.
  1855. int length;
  1856. char* data;
  1857. double timeoutAsDbl = timeout.count();
  1858. int pipe =
  1859. cmsysProcess_WaitForData(process, &data, &length, &timeoutAsDbl);
  1860. if (pipe == cmsysProcess_Pipe_Timeout) {
  1861. // Timeout has been exceeded.
  1862. return pipe;
  1863. }
  1864. if (pipe == cmsysProcess_Pipe_STDOUT) {
  1865. processOutput.DecodeText(data, length, strdata, 1);
  1866. // Append to the stdout buffer.
  1867. std::vector<char>::size_type size = out.size();
  1868. out.insert(out.end(), strdata.begin(), strdata.end());
  1869. outiter = out.begin() + size;
  1870. } else if (pipe == cmsysProcess_Pipe_STDERR) {
  1871. processOutput.DecodeText(data, length, strdata, 2);
  1872. // Append to the stderr buffer.
  1873. std::vector<char>::size_type size = err.size();
  1874. err.insert(err.end(), strdata.begin(), strdata.end());
  1875. erriter = err.begin() + size;
  1876. } else if (pipe == cmsysProcess_Pipe_None) {
  1877. // Both stdout and stderr pipes have broken. Return leftover data.
  1878. processOutput.DecodeText(std::string(), strdata, 1);
  1879. if (!strdata.empty()) {
  1880. std::vector<char>::size_type size = out.size();
  1881. out.insert(out.end(), strdata.begin(), strdata.end());
  1882. outiter = out.begin() + size;
  1883. }
  1884. processOutput.DecodeText(std::string(), strdata, 2);
  1885. if (!strdata.empty()) {
  1886. std::vector<char>::size_type size = err.size();
  1887. err.insert(err.end(), strdata.begin(), strdata.end());
  1888. erriter = err.begin() + size;
  1889. }
  1890. if (!out.empty()) {
  1891. line.append(&out[0], outiter - out.begin());
  1892. out.erase(out.begin(), out.end());
  1893. return cmsysProcess_Pipe_STDOUT;
  1894. }
  1895. if (!err.empty()) {
  1896. line.append(&err[0], erriter - err.begin());
  1897. err.erase(err.begin(), err.end());
  1898. return cmsysProcess_Pipe_STDERR;
  1899. }
  1900. return cmsysProcess_Pipe_None;
  1901. }
  1902. }
  1903. }
  1904. void cmSystemTools::DoNotInheritStdPipes()
  1905. {
  1906. #ifdef _WIN32
  1907. // Check to see if we are attached to a console
  1908. // if so, then do not stop the inherited pipes
  1909. // or stdout and stderr will not show up in dos
  1910. // shell windows
  1911. CONSOLE_SCREEN_BUFFER_INFO hOutInfo;
  1912. HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
  1913. if (GetConsoleScreenBufferInfo(hOut, &hOutInfo)) {
  1914. return;
  1915. }
  1916. {
  1917. HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
  1918. DuplicateHandle(GetCurrentProcess(), out, GetCurrentProcess(), &out, 0,
  1919. FALSE, DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
  1920. SetStdHandle(STD_OUTPUT_HANDLE, out);
  1921. }
  1922. {
  1923. HANDLE out = GetStdHandle(STD_ERROR_HANDLE);
  1924. DuplicateHandle(GetCurrentProcess(), out, GetCurrentProcess(), &out, 0,
  1925. FALSE, DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
  1926. SetStdHandle(STD_ERROR_HANDLE, out);
  1927. }
  1928. #endif
  1929. }
  1930. bool cmSystemTools::CopyFileTime(const char* fromFile, const char* toFile)
  1931. {
  1932. #if defined(_WIN32) && !defined(__CYGWIN__)
  1933. cmSystemToolsWindowsHandle hFrom = CreateFileW(
  1934. SystemTools::ConvertToWindowsExtendedPath(fromFile).c_str(), GENERIC_READ,
  1935. FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
  1936. cmSystemToolsWindowsHandle hTo = CreateFileW(
  1937. SystemTools::ConvertToWindowsExtendedPath(toFile).c_str(),
  1938. FILE_WRITE_ATTRIBUTES, 0, 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
  1939. if (!hFrom || !hTo) {
  1940. return false;
  1941. }
  1942. FILETIME timeCreation;
  1943. FILETIME timeLastAccess;
  1944. FILETIME timeLastWrite;
  1945. if (!GetFileTime(hFrom, &timeCreation, &timeLastAccess, &timeLastWrite)) {
  1946. return false;
  1947. }
  1948. return SetFileTime(hTo, &timeCreation, &timeLastAccess, &timeLastWrite) != 0;
  1949. #else
  1950. struct stat fromStat;
  1951. if (stat(fromFile, &fromStat) < 0) {
  1952. return false;
  1953. }
  1954. struct utimbuf buf;
  1955. buf.actime = fromStat.st_atime;
  1956. buf.modtime = fromStat.st_mtime;
  1957. return utime(toFile, &buf) >= 0;
  1958. #endif
  1959. }
  1960. cmSystemToolsFileTime* cmSystemTools::FileTimeNew()
  1961. {
  1962. return new cmSystemToolsFileTime;
  1963. }
  1964. void cmSystemTools::FileTimeDelete(cmSystemToolsFileTime* t)
  1965. {
  1966. delete t;
  1967. }
  1968. bool cmSystemTools::FileTimeGet(const char* fname, cmSystemToolsFileTime* t)
  1969. {
  1970. #if defined(_WIN32) && !defined(__CYGWIN__)
  1971. cmSystemToolsWindowsHandle h = CreateFileW(
  1972. SystemTools::ConvertToWindowsExtendedPath(fname).c_str(), GENERIC_READ,
  1973. FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
  1974. if (!h) {
  1975. return false;
  1976. }
  1977. if (!GetFileTime(h, &t->timeCreation, &t->timeLastAccess,
  1978. &t->timeLastWrite)) {
  1979. return false;
  1980. }
  1981. #else
  1982. struct stat st;
  1983. if (stat(fname, &st) < 0) {
  1984. return false;
  1985. }
  1986. t->timeBuf.actime = st.st_atime;
  1987. t->timeBuf.modtime = st.st_mtime;
  1988. #endif
  1989. return true;
  1990. }
  1991. bool cmSystemTools::FileTimeSet(const char* fname, cmSystemToolsFileTime* t)
  1992. {
  1993. #if defined(_WIN32) && !defined(__CYGWIN__)
  1994. cmSystemToolsWindowsHandle h = CreateFileW(
  1995. SystemTools::ConvertToWindowsExtendedPath(fname).c_str(),
  1996. FILE_WRITE_ATTRIBUTES, 0, 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
  1997. if (!h) {
  1998. return false;
  1999. }
  2000. return SetFileTime(h, &t->timeCreation, &t->timeLastAccess,
  2001. &t->timeLastWrite) != 0;
  2002. #else
  2003. return utime(fname, &t->timeBuf) >= 0;
  2004. #endif
  2005. }
  2006. #ifdef _WIN32
  2007. # ifndef CRYPT_SILENT
  2008. # define CRYPT_SILENT 0x40 /* Not defined by VS 6 version of header. */
  2009. # endif
  2010. static int WinCryptRandom(void* data, size_t size)
  2011. {
  2012. int result = 0;
  2013. HCRYPTPROV hProvider = 0;
  2014. if (CryptAcquireContextW(&hProvider, 0, 0, PROV_RSA_FULL,
  2015. CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) {
  2016. result = CryptGenRandom(hProvider, (DWORD)size, (BYTE*)data) ? 1 : 0;
  2017. CryptReleaseContext(hProvider, 0);
  2018. }
  2019. return result;
  2020. }
  2021. #endif
  2022. unsigned int cmSystemTools::RandomSeed()
  2023. {
  2024. #if defined(_WIN32) && !defined(__CYGWIN__)
  2025. unsigned int seed = 0;
  2026. // Try using a real random source.
  2027. if (WinCryptRandom(&seed, sizeof(seed))) {
  2028. return seed;
  2029. }
  2030. // Fall back to the time and pid.
  2031. FILETIME ft;
  2032. GetSystemTimeAsFileTime(&ft);
  2033. unsigned int t1 = static_cast<unsigned int>(ft.dwHighDateTime);
  2034. unsigned int t2 = static_cast<unsigned int>(ft.dwLowDateTime);
  2035. unsigned int pid = static_cast<unsigned int>(GetCurrentProcessId());
  2036. return t1 ^ t2 ^ pid;
  2037. #else
  2038. union
  2039. {
  2040. unsigned int integer;
  2041. char bytes[sizeof(unsigned int)];
  2042. } seed;
  2043. // Try using a real random source.
  2044. cmsys::ifstream fin;
  2045. fin.rdbuf()->pubsetbuf(nullptr, 0); // Unbuffered read.
  2046. fin.open("/dev/urandom");
  2047. if (fin.good() && fin.read(seed.bytes, sizeof(seed)) &&
  2048. fin.gcount() == sizeof(seed)) {
  2049. return seed.integer;
  2050. }
  2051. // Fall back to the time and pid.
  2052. struct timeval t;
  2053. gettimeofday(&t, nullptr);
  2054. unsigned int pid = static_cast<unsigned int>(getpid());
  2055. unsigned int tv_sec = static_cast<unsigned int>(t.tv_sec);
  2056. unsigned int tv_usec = static_cast<unsigned int>(t.tv_usec);
  2057. // Since tv_usec never fills more than 11 bits we shift it to fill
  2058. // in the slow-changing high-order bits of tv_sec.
  2059. return tv_sec ^ (tv_usec << 21) ^ pid;
  2060. #endif
  2061. }
  2062. static std::string cmSystemToolsCMakeCommand;
  2063. static std::string cmSystemToolsCTestCommand;
  2064. static std::string cmSystemToolsCPackCommand;
  2065. static std::string cmSystemToolsCMakeCursesCommand;
  2066. static std::string cmSystemToolsCMakeGUICommand;
  2067. static std::string cmSystemToolsCMClDepsCommand;
  2068. static std::string cmSystemToolsCMakeRoot;
  2069. void cmSystemTools::FindCMakeResources(const char* argv0)
  2070. {
  2071. std::string exe_dir;
  2072. #if defined(_WIN32) && !defined(__CYGWIN__)
  2073. (void)argv0; // ignore this on windows
  2074. wchar_t modulepath[_MAX_PATH];
  2075. ::GetModuleFileNameW(NULL, modulepath, sizeof(modulepath));
  2076. std::string path = cmsys::Encoding::ToNarrow(modulepath);
  2077. std::string realPath =
  2078. cmSystemTools::GetRealPathResolvingWindowsSubst(path, NULL);
  2079. if (realPath.empty()) {
  2080. realPath = path;
  2081. }
  2082. exe_dir = cmSystemTools::GetFilenamePath(realPath);
  2083. #elif defined(__APPLE__)
  2084. (void)argv0; // ignore this on OS X
  2085. # define CM_EXE_PATH_LOCAL_SIZE 16384
  2086. char exe_path_local[CM_EXE_PATH_LOCAL_SIZE];
  2087. # if defined(MAC_OS_X_VERSION_10_3) && !defined(MAC_OS_X_VERSION_10_4)
  2088. unsigned long exe_path_size = CM_EXE_PATH_LOCAL_SIZE;
  2089. # else
  2090. uint32_t exe_path_size = CM_EXE_PATH_LOCAL_SIZE;
  2091. # endif
  2092. # undef CM_EXE_PATH_LOCAL_SIZE
  2093. char* exe_path = exe_path_local;
  2094. if (_NSGetExecutablePath(exe_path, &exe_path_size) < 0) {
  2095. exe_path = static_cast<char*>(malloc(exe_path_size));
  2096. _NSGetExecutablePath(exe_path, &exe_path_size);
  2097. }
  2098. exe_dir =
  2099. cmSystemTools::GetFilenamePath(cmSystemTools::GetRealPath(exe_path));
  2100. if (exe_path != exe_path_local) {
  2101. free(exe_path);
  2102. }
  2103. if (cmSystemTools::GetFilenameName(exe_dir) == "MacOS") {
  2104. // The executable is inside an application bundle.
  2105. // Look for ..<CMAKE_BIN_DIR> (install tree) and then fall back to
  2106. // ../../../bin (build tree).
  2107. exe_dir = cmSystemTools::GetFilenamePath(exe_dir);
  2108. if (cmSystemTools::FileExists(exe_dir + CMAKE_BIN_DIR "/cmake")) {
  2109. exe_dir += CMAKE_BIN_DIR;
  2110. } else {
  2111. exe_dir = cmSystemTools::GetFilenamePath(exe_dir);
  2112. exe_dir = cmSystemTools::GetFilenamePath(exe_dir);
  2113. }
  2114. }
  2115. #else
  2116. std::string errorMsg;
  2117. std::string exe;
  2118. if (cmSystemTools::FindProgramPath(argv0, exe, errorMsg)) {
  2119. // remove symlinks
  2120. exe = cmSystemTools::GetRealPath(exe);
  2121. exe_dir = cmSystemTools::GetFilenamePath(exe);
  2122. } else {
  2123. // ???
  2124. }
  2125. #endif
  2126. exe_dir = cmSystemTools::GetActualCaseForPath(exe_dir);
  2127. cmSystemToolsCMakeCommand = exe_dir;
  2128. cmSystemToolsCMakeCommand += "/cmake";
  2129. cmSystemToolsCMakeCommand += cmSystemTools::GetExecutableExtension();
  2130. #ifndef CMAKE_BUILD_WITH_CMAKE
  2131. // The bootstrap cmake does not provide the other tools,
  2132. // so use the directory where they are about to be built.
  2133. exe_dir = CMAKE_BOOTSTRAP_BINARY_DIR "/bin";
  2134. #endif
  2135. cmSystemToolsCTestCommand = exe_dir;
  2136. cmSystemToolsCTestCommand += "/ctest";
  2137. cmSystemToolsCTestCommand += cmSystemTools::GetExecutableExtension();
  2138. cmSystemToolsCPackCommand = exe_dir;
  2139. cmSystemToolsCPackCommand += "/cpack";
  2140. cmSystemToolsCPackCommand += cmSystemTools::GetExecutableExtension();
  2141. cmSystemToolsCMakeGUICommand = exe_dir;
  2142. cmSystemToolsCMakeGUICommand += "/cmake-gui";
  2143. cmSystemToolsCMakeGUICommand += cmSystemTools::GetExecutableExtension();
  2144. if (!cmSystemTools::FileExists(cmSystemToolsCMakeGUICommand)) {
  2145. cmSystemToolsCMakeGUICommand.clear();
  2146. }
  2147. cmSystemToolsCMakeCursesCommand = exe_dir;
  2148. cmSystemToolsCMakeCursesCommand += "/ccmake";
  2149. cmSystemToolsCMakeCursesCommand += cmSystemTools::GetExecutableExtension();
  2150. if (!cmSystemTools::FileExists(cmSystemToolsCMakeCursesCommand)) {
  2151. cmSystemToolsCMakeCursesCommand.clear();
  2152. }
  2153. cmSystemToolsCMClDepsCommand = exe_dir;
  2154. cmSystemToolsCMClDepsCommand += "/cmcldeps";
  2155. cmSystemToolsCMClDepsCommand += cmSystemTools::GetExecutableExtension();
  2156. if (!cmSystemTools::FileExists(cmSystemToolsCMClDepsCommand)) {
  2157. cmSystemToolsCMClDepsCommand.clear();
  2158. }
  2159. #ifdef CMAKE_BUILD_WITH_CMAKE
  2160. // Install tree has
  2161. // - "<prefix><CMAKE_BIN_DIR>/cmake"
  2162. // - "<prefix><CMAKE_DATA_DIR>"
  2163. if (cmHasSuffix(exe_dir, CMAKE_BIN_DIR)) {
  2164. std::string const prefix =
  2165. exe_dir.substr(0, exe_dir.size() - strlen(CMAKE_BIN_DIR));
  2166. cmSystemToolsCMakeRoot = prefix + CMAKE_DATA_DIR;
  2167. }
  2168. if (cmSystemToolsCMakeRoot.empty() ||
  2169. !cmSystemTools::FileExists(
  2170. (cmSystemToolsCMakeRoot + "/Modules/CMake.cmake"))) {
  2171. // Build tree has "<build>/bin[/<config>]/cmake" and
  2172. // "<build>/CMakeFiles/CMakeSourceDir.txt".
  2173. std::string dir = cmSystemTools::GetFilenamePath(exe_dir);
  2174. std::string src_dir_txt = dir + "/CMakeFiles/CMakeSourceDir.txt";
  2175. cmsys::ifstream fin(src_dir_txt.c_str());
  2176. std::string src_dir;
  2177. if (fin && cmSystemTools::GetLineFromStream(fin, src_dir) &&
  2178. cmSystemTools::FileIsDirectory(src_dir)) {
  2179. cmSystemToolsCMakeRoot = src_dir;
  2180. } else {
  2181. dir = cmSystemTools::GetFilenamePath(dir);
  2182. src_dir_txt = dir + "/CMakeFiles/CMakeSourceDir.txt";
  2183. cmsys::ifstream fin2(src_dir_txt.c_str());
  2184. if (fin2 && cmSystemTools::GetLineFromStream(fin2, src_dir) &&
  2185. cmSystemTools::FileIsDirectory(src_dir)) {
  2186. cmSystemToolsCMakeRoot = src_dir;
  2187. }
  2188. }
  2189. }
  2190. #else
  2191. // Bootstrap build knows its source.
  2192. cmSystemToolsCMakeRoot = CMAKE_BOOTSTRAP_SOURCE_DIR;
  2193. #endif
  2194. }
  2195. std::string const& cmSystemTools::GetCMakeCommand()
  2196. {
  2197. return cmSystemToolsCMakeCommand;
  2198. }
  2199. std::string const& cmSystemTools::GetCTestCommand()
  2200. {
  2201. return cmSystemToolsCTestCommand;
  2202. }
  2203. std::string const& cmSystemTools::GetCPackCommand()
  2204. {
  2205. return cmSystemToolsCPackCommand;
  2206. }
  2207. std::string const& cmSystemTools::GetCMakeCursesCommand()
  2208. {
  2209. return cmSystemToolsCMakeCursesCommand;
  2210. }
  2211. std::string const& cmSystemTools::GetCMakeGUICommand()
  2212. {
  2213. return cmSystemToolsCMakeGUICommand;
  2214. }
  2215. std::string const& cmSystemTools::GetCMClDepsCommand()
  2216. {
  2217. return cmSystemToolsCMClDepsCommand;
  2218. }
  2219. std::string const& cmSystemTools::GetCMakeRoot()
  2220. {
  2221. return cmSystemToolsCMakeRoot;
  2222. }
  2223. void cmSystemTools::MakefileColorEcho(int color, const char* message,
  2224. bool newline, bool enabled)
  2225. {
  2226. // On some platforms (an MSYS prompt) cmsysTerminal may not be able
  2227. // to determine whether the stream is displayed on a tty. In this
  2228. // case it assumes no unless we tell it otherwise. Since we want
  2229. // color messages to be displayed for users we will assume yes.
  2230. // However, we can test for some situations when the answer is most
  2231. // likely no.
  2232. int assumeTTY = cmsysTerminal_Color_AssumeTTY;
  2233. if (cmSystemTools::HasEnv("DART_TEST_FROM_DART") ||
  2234. cmSystemTools::HasEnv("DASHBOARD_TEST_FROM_CTEST") ||
  2235. cmSystemTools::HasEnv("CTEST_INTERACTIVE_DEBUG_MODE")) {
  2236. // Avoid printing color escapes during dashboard builds.
  2237. assumeTTY = 0;
  2238. }
  2239. if (enabled && color != cmsysTerminal_Color_Normal) {
  2240. // Print with color. Delay the newline until later so that
  2241. // all color restore sequences appear before it.
  2242. cmsysTerminal_cfprintf(color | assumeTTY, stdout, "%s", message);
  2243. } else {
  2244. // Color is disabled. Print without color.
  2245. fprintf(stdout, "%s", message);
  2246. }
  2247. if (newline) {
  2248. fprintf(stdout, "\n");
  2249. }
  2250. }
  2251. bool cmSystemTools::GuessLibrarySOName(std::string const& fullPath,
  2252. std::string& soname)
  2253. {
  2254. // For ELF shared libraries use a real parser to get the correct
  2255. // soname.
  2256. #if defined(CMAKE_USE_ELF_PARSER)
  2257. cmELF elf(fullPath.c_str());
  2258. if (elf) {
  2259. return elf.GetSOName(soname);
  2260. }
  2261. #endif
  2262. // If the file is not a symlink we have no guess for its soname.
  2263. if (!cmSystemTools::FileIsSymlink(fullPath)) {
  2264. return false;
  2265. }
  2266. if (!cmSystemTools::ReadSymlink(fullPath, soname)) {
  2267. return false;
  2268. }
  2269. // If the symlink has a path component we have no guess for the soname.
  2270. if (!cmSystemTools::GetFilenamePath(soname).empty()) {
  2271. return false;
  2272. }
  2273. // If the symlink points at an extended version of the same name
  2274. // assume it is the soname.
  2275. std::string name = cmSystemTools::GetFilenameName(fullPath);
  2276. return soname.length() > name.length() &&
  2277. soname.compare(0, name.length(), name) == 0;
  2278. }
  2279. bool cmSystemTools::GuessLibraryInstallName(std::string const& fullPath,
  2280. std::string& soname)
  2281. {
  2282. #if defined(CMAKE_USE_MACH_PARSER)
  2283. cmMachO macho(fullPath.c_str());
  2284. if (macho) {
  2285. return macho.GetInstallName(soname);
  2286. }
  2287. #else
  2288. (void)fullPath;
  2289. (void)soname;
  2290. #endif
  2291. return false;
  2292. }
  2293. #if defined(CMAKE_USE_ELF_PARSER)
  2294. std::string::size_type cmSystemToolsFindRPath(std::string const& have,
  2295. std::string const& want)
  2296. {
  2297. std::string::size_type pos = 0;
  2298. while (pos < have.size()) {
  2299. // Look for an occurrence of the string.
  2300. std::string::size_type const beg = have.find(want, pos);
  2301. if (beg == std::string::npos) {
  2302. return std::string::npos;
  2303. }
  2304. // Make sure it is separated from preceding entries.
  2305. if (beg > 0 && have[beg - 1] != ':') {
  2306. pos = beg + 1;
  2307. continue;
  2308. }
  2309. // Make sure it is separated from following entries.
  2310. std::string::size_type const end = beg + want.size();
  2311. if (end < have.size() && have[end] != ':') {
  2312. pos = beg + 1;
  2313. continue;
  2314. }
  2315. // Return the position of the path portion.
  2316. return beg;
  2317. }
  2318. // The desired rpath was not found.
  2319. return std::string::npos;
  2320. }
  2321. #endif
  2322. #if defined(CMAKE_USE_ELF_PARSER)
  2323. struct cmSystemToolsRPathInfo
  2324. {
  2325. unsigned long Position;
  2326. unsigned long Size;
  2327. std::string Name;
  2328. std::string Value;
  2329. };
  2330. #endif
  2331. #if defined(CMAKE_USE_ELF_PARSER)
  2332. bool cmSystemTools::ChangeRPath(std::string const& file,
  2333. std::string const& oldRPath,
  2334. std::string const& newRPath, std::string* emsg,
  2335. bool* changed)
  2336. {
  2337. if (changed) {
  2338. *changed = false;
  2339. }
  2340. int rp_count = 0;
  2341. bool remove_rpath = true;
  2342. cmSystemToolsRPathInfo rp[2];
  2343. {
  2344. // Parse the ELF binary.
  2345. cmELF elf(file.c_str());
  2346. // Get the RPATH and RUNPATH entries from it.
  2347. int se_count = 0;
  2348. cmELF::StringEntry const* se[2] = { nullptr, nullptr };
  2349. const char* se_name[2] = { nullptr, nullptr };
  2350. if (cmELF::StringEntry const* se_rpath = elf.GetRPath()) {
  2351. se[se_count] = se_rpath;
  2352. se_name[se_count] = "RPATH";
  2353. ++se_count;
  2354. }
  2355. if (cmELF::StringEntry const* se_runpath = elf.GetRunPath()) {
  2356. se[se_count] = se_runpath;
  2357. se_name[se_count] = "RUNPATH";
  2358. ++se_count;
  2359. }
  2360. if (se_count == 0) {
  2361. if (newRPath.empty()) {
  2362. // The new rpath is empty and there is no rpath anyway so it is
  2363. // okay.
  2364. return true;
  2365. }
  2366. if (emsg) {
  2367. *emsg = "No valid ELF RPATH or RUNPATH entry exists in the file; ";
  2368. *emsg += elf.GetErrorMessage();
  2369. }
  2370. return false;
  2371. }
  2372. for (int i = 0; i < se_count; ++i) {
  2373. // If both RPATH and RUNPATH refer to the same string literal it
  2374. // needs to be changed only once.
  2375. if (rp_count && rp[0].Position == se[i]->Position) {
  2376. continue;
  2377. }
  2378. // Make sure the current rpath contains the old rpath.
  2379. std::string::size_type pos =
  2380. cmSystemToolsFindRPath(se[i]->Value, oldRPath);
  2381. if (pos == std::string::npos) {
  2382. // If it contains the new rpath instead then it is okay.
  2383. if (cmSystemToolsFindRPath(se[i]->Value, newRPath) !=
  2384. std::string::npos) {
  2385. remove_rpath = false;
  2386. continue;
  2387. }
  2388. if (emsg) {
  2389. std::ostringstream e;
  2390. /* clang-format off */
  2391. e << "The current " << se_name[i] << " is:\n"
  2392. << " " << se[i]->Value << "\n"
  2393. << "which does not contain:\n"
  2394. << " " << oldRPath << "\n"
  2395. << "as was expected.";
  2396. /* clang-format on */
  2397. *emsg = e.str();
  2398. }
  2399. return false;
  2400. }
  2401. // Store information about the entry in the file.
  2402. rp[rp_count].Position = se[i]->Position;
  2403. rp[rp_count].Size = se[i]->Size;
  2404. rp[rp_count].Name = se_name[i];
  2405. std::string::size_type prefix_len = pos;
  2406. // If oldRPath was at the end of the file's RPath, and newRPath is empty,
  2407. // we should remove the unnecessary ':' at the end.
  2408. if (newRPath.empty() && pos > 0 && se[i]->Value[pos - 1] == ':' &&
  2409. pos + oldRPath.length() == se[i]->Value.length()) {
  2410. prefix_len--;
  2411. }
  2412. // Construct the new value which preserves the part of the path
  2413. // not being changed.
  2414. rp[rp_count].Value = se[i]->Value.substr(0, prefix_len);
  2415. rp[rp_count].Value += newRPath;
  2416. rp[rp_count].Value += se[i]->Value.substr(pos + oldRPath.length());
  2417. if (!rp[rp_count].Value.empty()) {
  2418. remove_rpath = false;
  2419. }
  2420. // Make sure there is enough room to store the new rpath and at
  2421. // least one null terminator.
  2422. if (rp[rp_count].Size < rp[rp_count].Value.length() + 1) {
  2423. if (emsg) {
  2424. *emsg = "The replacement path is too long for the ";
  2425. *emsg += se_name[i];
  2426. *emsg += " entry.";
  2427. }
  2428. return false;
  2429. }
  2430. // This entry is ready for update.
  2431. ++rp_count;
  2432. }
  2433. }
  2434. // If no runtime path needs to be changed, we are done.
  2435. if (rp_count == 0) {
  2436. return true;
  2437. }
  2438. // If the resulting rpath is empty, just remove the entire entry instead.
  2439. if (remove_rpath) {
  2440. return cmSystemTools::RemoveRPath(file, emsg, changed);
  2441. }
  2442. {
  2443. // Open the file for update.
  2444. cmsys::ofstream f(file.c_str(),
  2445. std::ios::in | std::ios::out | std::ios::binary);
  2446. if (!f) {
  2447. if (emsg) {
  2448. *emsg = "Error opening file for update.";
  2449. }
  2450. return false;
  2451. }
  2452. // Store the new RPATH and RUNPATH strings.
  2453. for (int i = 0; i < rp_count; ++i) {
  2454. // Seek to the RPATH position.
  2455. if (!f.seekp(rp[i].Position)) {
  2456. if (emsg) {
  2457. *emsg = "Error seeking to ";
  2458. *emsg += rp[i].Name;
  2459. *emsg += " position.";
  2460. }
  2461. return false;
  2462. }
  2463. // Write the new rpath. Follow it with enough null terminators to
  2464. // fill the string table entry.
  2465. f << rp[i].Value;
  2466. for (unsigned long j = rp[i].Value.length(); j < rp[i].Size; ++j) {
  2467. f << '\0';
  2468. }
  2469. // Make sure it wrote correctly.
  2470. if (!f) {
  2471. if (emsg) {
  2472. *emsg = "Error writing the new ";
  2473. *emsg += rp[i].Name;
  2474. *emsg += " string to the file.";
  2475. }
  2476. return false;
  2477. }
  2478. }
  2479. }
  2480. // Everything was updated successfully.
  2481. if (changed) {
  2482. *changed = true;
  2483. }
  2484. return true;
  2485. }
  2486. #else
  2487. bool cmSystemTools::ChangeRPath(std::string const& /*file*/,
  2488. std::string const& /*oldRPath*/,
  2489. std::string const& /*newRPath*/,
  2490. std::string* /*emsg*/, bool* /*changed*/)
  2491. {
  2492. return false;
  2493. }
  2494. #endif
  2495. bool cmSystemTools::VersionCompare(cmSystemTools::CompareOp op,
  2496. const char* lhss, const char* rhss)
  2497. {
  2498. const char* endl = lhss;
  2499. const char* endr = rhss;
  2500. unsigned long lhs, rhs;
  2501. while (((*endl >= '0') && (*endl <= '9')) ||
  2502. ((*endr >= '0') && (*endr <= '9'))) {
  2503. // Do component-wise comparison.
  2504. lhs = strtoul(endl, const_cast<char**>(&endl), 10);
  2505. rhs = strtoul(endr, const_cast<char**>(&endr), 10);
  2506. if (lhs < rhs) {
  2507. // lhs < rhs, so true if operation is LESS
  2508. return (op & cmSystemTools::OP_LESS) != 0;
  2509. }
  2510. if (lhs > rhs) {
  2511. // lhs > rhs, so true if operation is GREATER
  2512. return (op & cmSystemTools::OP_GREATER) != 0;
  2513. }
  2514. if (*endr == '.') {
  2515. endr++;
  2516. }
  2517. if (*endl == '.') {
  2518. endl++;
  2519. }
  2520. }
  2521. // lhs == rhs, so true if operation is EQUAL
  2522. return (op & cmSystemTools::OP_EQUAL) != 0;
  2523. }
  2524. bool cmSystemTools::VersionCompareEqual(std::string const& lhs,
  2525. std::string const& rhs)
  2526. {
  2527. return cmSystemTools::VersionCompare(cmSystemTools::OP_EQUAL, lhs.c_str(),
  2528. rhs.c_str());
  2529. }
  2530. bool cmSystemTools::VersionCompareGreater(std::string const& lhs,
  2531. std::string const& rhs)
  2532. {
  2533. return cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER, lhs.c_str(),
  2534. rhs.c_str());
  2535. }
  2536. bool cmSystemTools::VersionCompareGreaterEq(std::string const& lhs,
  2537. std::string const& rhs)
  2538. {
  2539. return cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER_EQUAL,
  2540. lhs.c_str(), rhs.c_str());
  2541. }
  2542. static size_t cm_strverscmp_find_first_difference_or_end(const char* lhs,
  2543. const char* rhs)
  2544. {
  2545. size_t i = 0;
  2546. /* Step forward until we find a difference or both strings end together.
  2547. The difference may lie on the null-terminator of one string. */
  2548. while (lhs[i] == rhs[i] && lhs[i] != 0) {
  2549. ++i;
  2550. }
  2551. return i;
  2552. }
  2553. static size_t cm_strverscmp_find_digits_begin(const char* s, size_t i)
  2554. {
  2555. /* Step back until we are not preceded by a digit. */
  2556. while (i > 0 && isdigit(s[i - 1])) {
  2557. --i;
  2558. }
  2559. return i;
  2560. }
  2561. static size_t cm_strverscmp_find_digits_end(const char* s, size_t i)
  2562. {
  2563. /* Step forward over digits. */
  2564. while (isdigit(s[i])) {
  2565. ++i;
  2566. }
  2567. return i;
  2568. }
  2569. static size_t cm_strverscmp_count_leading_zeros(const char* s, size_t b)
  2570. {
  2571. size_t i = b;
  2572. /* Step forward over zeros that are followed by another digit. */
  2573. while (s[i] == '0' && isdigit(s[i + 1])) {
  2574. ++i;
  2575. }
  2576. return i - b;
  2577. }
  2578. static int cm_strverscmp(const char* lhs, const char* rhs)
  2579. {
  2580. size_t const i = cm_strverscmp_find_first_difference_or_end(lhs, rhs);
  2581. if (lhs[i] != rhs[i]) {
  2582. /* The strings differ starting at 'i'. Check for a digit sequence. */
  2583. size_t const b = cm_strverscmp_find_digits_begin(lhs, i);
  2584. if (b != i || (isdigit(lhs[i]) && isdigit(rhs[i]))) {
  2585. /* A digit sequence starts at 'b', preceding or at 'i'. */
  2586. /* Look for leading zeros, implying a leading decimal point. */
  2587. size_t const lhs_zeros = cm_strverscmp_count_leading_zeros(lhs, b);
  2588. size_t const rhs_zeros = cm_strverscmp_count_leading_zeros(rhs, b);
  2589. if (lhs_zeros != rhs_zeros) {
  2590. /* The side with more leading zeros orders first. */
  2591. return rhs_zeros > lhs_zeros ? 1 : -1;
  2592. }
  2593. if (lhs_zeros == 0) {
  2594. /* No leading zeros; compare digit sequence lengths. */
  2595. size_t const lhs_end = cm_strverscmp_find_digits_end(lhs, i);
  2596. size_t const rhs_end = cm_strverscmp_find_digits_end(rhs, i);
  2597. if (lhs_end != rhs_end) {
  2598. /* The side with fewer digits orders first. */
  2599. return lhs_end > rhs_end ? 1 : -1;
  2600. }
  2601. }
  2602. }
  2603. }
  2604. /* Ordering was not decided by digit sequence lengths; compare bytes. */
  2605. return lhs[i] - rhs[i];
  2606. }
  2607. int cmSystemTools::strverscmp(std::string const& lhs, std::string const& rhs)
  2608. {
  2609. return cm_strverscmp(lhs.c_str(), rhs.c_str());
  2610. }
  2611. #if defined(CMAKE_USE_ELF_PARSER)
  2612. bool cmSystemTools::RemoveRPath(std::string const& file, std::string* emsg,
  2613. bool* removed)
  2614. {
  2615. if (removed) {
  2616. *removed = false;
  2617. }
  2618. int zeroCount = 0;
  2619. unsigned long zeroPosition[2] = { 0, 0 };
  2620. unsigned long zeroSize[2] = { 0, 0 };
  2621. unsigned long bytesBegin = 0;
  2622. std::vector<char> bytes;
  2623. {
  2624. // Parse the ELF binary.
  2625. cmELF elf(file.c_str());
  2626. // Get the RPATH and RUNPATH entries from it and sort them by index
  2627. // in the dynamic section header.
  2628. int se_count = 0;
  2629. cmELF::StringEntry const* se[2] = { nullptr, nullptr };
  2630. if (cmELF::StringEntry const* se_rpath = elf.GetRPath()) {
  2631. se[se_count++] = se_rpath;
  2632. }
  2633. if (cmELF::StringEntry const* se_runpath = elf.GetRunPath()) {
  2634. se[se_count++] = se_runpath;
  2635. }
  2636. if (se_count == 0) {
  2637. // There is no RPATH or RUNPATH anyway.
  2638. return true;
  2639. }
  2640. if (se_count == 2 && se[1]->IndexInSection < se[0]->IndexInSection) {
  2641. std::swap(se[0], se[1]);
  2642. }
  2643. // Obtain a copy of the dynamic entries
  2644. cmELF::DynamicEntryList dentries = elf.GetDynamicEntries();
  2645. if (dentries.empty()) {
  2646. // This should happen only for invalid ELF files where a DT_NULL
  2647. // appears before the end of the table.
  2648. if (emsg) {
  2649. *emsg = "DYNAMIC section contains a DT_NULL before the end.";
  2650. }
  2651. return false;
  2652. }
  2653. // Save information about the string entries to be zeroed.
  2654. zeroCount = se_count;
  2655. for (int i = 0; i < se_count; ++i) {
  2656. zeroPosition[i] = se[i]->Position;
  2657. zeroSize[i] = se[i]->Size;
  2658. }
  2659. // Get size of one DYNAMIC entry
  2660. unsigned long const sizeof_dentry =
  2661. elf.GetDynamicEntryPosition(1) - elf.GetDynamicEntryPosition(0);
  2662. // Adjust the entry list as necessary to remove the run path
  2663. unsigned long entriesErased = 0;
  2664. for (cmELF::DynamicEntryList::iterator it = dentries.begin();
  2665. it != dentries.end();) {
  2666. if (it->first == cmELF::TagRPath || it->first == cmELF::TagRunPath) {
  2667. it = dentries.erase(it);
  2668. entriesErased++;
  2669. continue;
  2670. }
  2671. if (cmELF::TagMipsRldMapRel != 0 &&
  2672. it->first == cmELF::TagMipsRldMapRel) {
  2673. // Background: debuggers need to know the "linker map" which contains
  2674. // the addresses each dynamic object is loaded at. Most arches use
  2675. // the DT_DEBUG tag which the dynamic linker writes to (directly) and
  2676. // contain the location of the linker map, however on MIPS the
  2677. // .dynamic section is always read-only so this is not possible. MIPS
  2678. // objects instead contain a DT_MIPS_RLD_MAP tag which contains the
  2679. // address where the dynamic linker will write to (an indirect
  2680. // version of DT_DEBUG). Since this doesn't work when using PIE, a
  2681. // relative equivalent was created - DT_MIPS_RLD_MAP_REL. Since this
  2682. // version contains a relative offset, moving it changes the
  2683. // calculated address. This may cause the dynamic linker to write
  2684. // into memory it should not be changing.
  2685. //
  2686. // To fix this, we adjust the value of DT_MIPS_RLD_MAP_REL here. If
  2687. // we move it up by n bytes, we add n bytes to the value of this tag.
  2688. it->second += entriesErased * sizeof_dentry;
  2689. }
  2690. it++;
  2691. }
  2692. // Encode new entries list
  2693. bytes = elf.EncodeDynamicEntries(dentries);
  2694. bytesBegin = elf.GetDynamicEntryPosition(0);
  2695. }
  2696. // Open the file for update.
  2697. cmsys::ofstream f(file.c_str(),
  2698. std::ios::in | std::ios::out | std::ios::binary);
  2699. if (!f) {
  2700. if (emsg) {
  2701. *emsg = "Error opening file for update.";
  2702. }
  2703. return false;
  2704. }
  2705. // Write the new DYNAMIC table header.
  2706. if (!f.seekp(bytesBegin)) {
  2707. if (emsg) {
  2708. *emsg = "Error seeking to DYNAMIC table header for RPATH.";
  2709. }
  2710. return false;
  2711. }
  2712. if (!f.write(&bytes[0], bytes.size())) {
  2713. if (emsg) {
  2714. *emsg = "Error replacing DYNAMIC table header.";
  2715. }
  2716. return false;
  2717. }
  2718. // Fill the RPATH and RUNPATH strings with zero bytes.
  2719. for (int i = 0; i < zeroCount; ++i) {
  2720. if (!f.seekp(zeroPosition[i])) {
  2721. if (emsg) {
  2722. *emsg = "Error seeking to RPATH position.";
  2723. }
  2724. return false;
  2725. }
  2726. for (unsigned long j = 0; j < zeroSize[i]; ++j) {
  2727. f << '\0';
  2728. }
  2729. if (!f) {
  2730. if (emsg) {
  2731. *emsg = "Error writing the empty rpath string to the file.";
  2732. }
  2733. return false;
  2734. }
  2735. }
  2736. // Everything was updated successfully.
  2737. if (removed) {
  2738. *removed = true;
  2739. }
  2740. return true;
  2741. }
  2742. #else
  2743. bool cmSystemTools::RemoveRPath(std::string const& /*file*/,
  2744. std::string* /*emsg*/, bool* /*removed*/)
  2745. {
  2746. return false;
  2747. }
  2748. #endif
  2749. bool cmSystemTools::CheckRPath(std::string const& file,
  2750. std::string const& newRPath)
  2751. {
  2752. #if defined(CMAKE_USE_ELF_PARSER)
  2753. // Parse the ELF binary.
  2754. cmELF elf(file.c_str());
  2755. // Get the RPATH or RUNPATH entry from it.
  2756. cmELF::StringEntry const* se = elf.GetRPath();
  2757. if (!se) {
  2758. se = elf.GetRunPath();
  2759. }
  2760. // Make sure the current rpath contains the new rpath.
  2761. if (newRPath.empty()) {
  2762. if (!se) {
  2763. return true;
  2764. }
  2765. } else {
  2766. if (se &&
  2767. cmSystemToolsFindRPath(se->Value, newRPath) != std::string::npos) {
  2768. return true;
  2769. }
  2770. }
  2771. return false;
  2772. #else
  2773. (void)file;
  2774. (void)newRPath;
  2775. return false;
  2776. #endif
  2777. }
  2778. bool cmSystemTools::RepeatedRemoveDirectory(const char* dir)
  2779. {
  2780. // Windows sometimes locks files temporarily so try a few times.
  2781. for (int i = 0; i < 10; ++i) {
  2782. if (cmSystemTools::RemoveADirectory(dir)) {
  2783. return true;
  2784. }
  2785. cmSystemTools::Delay(100);
  2786. }
  2787. return false;
  2788. }
  2789. std::vector<std::string> cmSystemTools::tokenize(const std::string& str,
  2790. const std::string& sep)
  2791. {
  2792. std::vector<std::string> tokens;
  2793. std::string::size_type tokend = 0;
  2794. do {
  2795. std::string::size_type tokstart = str.find_first_not_of(sep, tokend);
  2796. if (tokstart == std::string::npos) {
  2797. break; // no more tokens
  2798. }
  2799. tokend = str.find_first_of(sep, tokstart);
  2800. if (tokend == std::string::npos) {
  2801. tokens.push_back(str.substr(tokstart));
  2802. } else {
  2803. tokens.push_back(str.substr(tokstart, tokend - tokstart));
  2804. }
  2805. } while (tokend != std::string::npos);
  2806. if (tokens.empty()) {
  2807. tokens.emplace_back();
  2808. }
  2809. return tokens;
  2810. }
  2811. bool cmSystemTools::StringToLong(const char* str, long* value)
  2812. {
  2813. errno = 0;
  2814. char* endp;
  2815. *value = strtol(str, &endp, 10);
  2816. return (*endp == '\0') && (endp != str) && (errno == 0);
  2817. }
  2818. bool cmSystemTools::StringToULong(const char* str, unsigned long* value)
  2819. {
  2820. errno = 0;
  2821. char* endp;
  2822. *value = strtoul(str, &endp, 10);
  2823. return (*endp == '\0') && (endp != str) && (errno == 0);
  2824. }
  2825. std::string cmSystemTools::EncodeURL(std::string const& in, bool escapeSlashes)
  2826. {
  2827. std::string out;
  2828. for (char c : in) {
  2829. char hexCh[4] = { 0, 0, 0, 0 };
  2830. hexCh[0] = c;
  2831. switch (c) {
  2832. case '+':
  2833. case '?':
  2834. case '\\':
  2835. case '&':
  2836. case ' ':
  2837. case '=':
  2838. case '%':
  2839. sprintf(hexCh, "%%%02X", static_cast<int>(c));
  2840. break;
  2841. case '/':
  2842. if (escapeSlashes) {
  2843. strcpy(hexCh, "%2F");
  2844. }
  2845. break;
  2846. default:
  2847. break;
  2848. }
  2849. out.append(hexCh);
  2850. }
  2851. return out;
  2852. }
  2853. bool cmSystemTools::CreateSymlink(const std::string& origName,
  2854. const std::string& newName,
  2855. std::string* errorMessage)
  2856. {
  2857. uv_fs_t req;
  2858. int flags = 0;
  2859. #if defined(_WIN32)
  2860. if (cmsys::SystemTools::FileIsDirectory(origName)) {
  2861. flags |= UV_FS_SYMLINK_DIR;
  2862. }
  2863. #endif
  2864. int err = uv_fs_symlink(nullptr, &req, origName.c_str(), newName.c_str(),
  2865. flags, nullptr);
  2866. if (err) {
  2867. std::string e =
  2868. "failed to create symbolic link '" + newName + "': " + uv_strerror(err);
  2869. if (errorMessage) {
  2870. *errorMessage = std::move(e);
  2871. } else {
  2872. cmSystemTools::Error(e.c_str());
  2873. }
  2874. return false;
  2875. }
  2876. return true;
  2877. }
  2878. bool cmSystemTools::CreateLink(const std::string& origName,
  2879. const std::string& newName,
  2880. std::string* errorMessage)
  2881. {
  2882. uv_fs_t req;
  2883. int err =
  2884. uv_fs_link(nullptr, &req, origName.c_str(), newName.c_str(), nullptr);
  2885. if (err) {
  2886. std::string e =
  2887. "failed to create link '" + newName + "': " + uv_strerror(err);
  2888. if (errorMessage) {
  2889. *errorMessage = std::move(e);
  2890. } else {
  2891. cmSystemTools::Error(e.c_str());
  2892. }
  2893. return false;
  2894. }
  2895. return true;
  2896. }