cmSystemTools.cxx 91 KB

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