cmSystemTools.cxx 82 KB

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