cmSystemTools.cxx 90 KB

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