cmSystemTools.cxx 91 KB

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