cmSystemTools.cxx 79 KB

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