cmSystemTools.cxx 71 KB

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