cmSystemTools.cxx 91 KB

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