cmSystemTools.cxx 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835
  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 =
  1094. reinterpret_cast<unsigned char const*>(buffer);
  1095. // This copy loop is very sensitive on certain platforms with
  1096. // slightly broken stream libraries (like HPUX). Normally, it is
  1097. // incorrect to not check the error condition on the fin.read()
  1098. // before using the data, but the fin.gcount() will be zero if an
  1099. // error occurred. Therefore, the loop should be safe everywhere.
  1100. while(fin)
  1101. {
  1102. fin.read(buffer, bufferSize);
  1103. if(int gcount = static_cast<int>(fin.gcount()))
  1104. {
  1105. cmsysMD5_Append(md5, buffer_uc, gcount);
  1106. }
  1107. }
  1108. cmsysMD5_FinalizeHex(md5, md5out);
  1109. cmsysMD5_Delete(md5);
  1110. fin.close();
  1111. return true;
  1112. #else
  1113. (void)source;
  1114. (void)md5out;
  1115. cmSystemTools::Message("md5sum not supported in bootstrapping mode","Error");
  1116. return false;
  1117. #endif
  1118. }
  1119. std::string cmSystemTools::ComputeStringMD5(const char* input)
  1120. {
  1121. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1122. char md5out[32];
  1123. cmsysMD5* md5 = cmsysMD5_New();
  1124. cmsysMD5_Initialize(md5);
  1125. cmsysMD5_Append(md5, reinterpret_cast<unsigned char const*>(input), -1);
  1126. cmsysMD5_FinalizeHex(md5, md5out);
  1127. cmsysMD5_Delete(md5);
  1128. return std::string(md5out, 32);
  1129. #else
  1130. (void)input;
  1131. cmSystemTools::Message("md5sum not supported in bootstrapping mode","Error");
  1132. return "";
  1133. #endif
  1134. }
  1135. void cmSystemTools::Glob(const char *directory, const char *regexp,
  1136. std::vector<std::string>& files)
  1137. {
  1138. cmsys::Directory d;
  1139. cmsys::RegularExpression reg(regexp);
  1140. if (d.Load(directory))
  1141. {
  1142. size_t numf;
  1143. unsigned int i;
  1144. numf = d.GetNumberOfFiles();
  1145. for (i = 0; i < numf; i++)
  1146. {
  1147. std::string fname = d.GetFile(i);
  1148. if (reg.find(fname))
  1149. {
  1150. files.push_back(fname);
  1151. }
  1152. }
  1153. }
  1154. }
  1155. void cmSystemTools::GlobDirs(const char *fullPath,
  1156. std::vector<std::string>& files)
  1157. {
  1158. std::string path = fullPath;
  1159. std::string::size_type pos = path.find("/*");
  1160. if(pos == std::string::npos)
  1161. {
  1162. files.push_back(fullPath);
  1163. return;
  1164. }
  1165. std::string startPath = path.substr(0, pos);
  1166. std::string finishPath = path.substr(pos+2);
  1167. cmsys::Directory d;
  1168. if (d.Load(startPath.c_str()))
  1169. {
  1170. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)
  1171. {
  1172. if((std::string(d.GetFile(i)) != ".")
  1173. && (std::string(d.GetFile(i)) != ".."))
  1174. {
  1175. std::string fname = startPath;
  1176. fname +="/";
  1177. fname += d.GetFile(i);
  1178. if(cmSystemTools::FileIsDirectory(fname.c_str()))
  1179. {
  1180. fname += finishPath;
  1181. cmSystemTools::GlobDirs(fname.c_str(), files);
  1182. }
  1183. }
  1184. }
  1185. }
  1186. }
  1187. void cmSystemTools::ExpandList(std::vector<std::string> const& arguments,
  1188. std::vector<std::string>& newargs)
  1189. {
  1190. std::vector<std::string>::const_iterator i;
  1191. for(i = arguments.begin();i != arguments.end(); ++i)
  1192. {
  1193. cmSystemTools::ExpandListArgument(*i, newargs);
  1194. }
  1195. }
  1196. void cmSystemTools::ExpandListArgument(const std::string& arg,
  1197. std::vector<std::string>& newargs,
  1198. bool emptyArgs)
  1199. {
  1200. // If argument is empty, it is an empty list.
  1201. if(arg.length() == 0 && !emptyArgs)
  1202. {
  1203. return;
  1204. }
  1205. // if there are no ; in the name then just copy the current string
  1206. if(arg.find(';') == std::string::npos)
  1207. {
  1208. newargs.push_back(arg);
  1209. return;
  1210. }
  1211. std::vector<char> newArgVec;
  1212. // Break the string at non-escaped semicolons not nested in [].
  1213. int squareNesting = 0;
  1214. for(const char* c = arg.c_str(); *c; ++c)
  1215. {
  1216. switch(*c)
  1217. {
  1218. case '\\':
  1219. {
  1220. // We only want to allow escaping of semicolons. Other
  1221. // escapes should not be processed here.
  1222. ++c;
  1223. if(*c == ';')
  1224. {
  1225. newArgVec.push_back(*c);
  1226. }
  1227. else
  1228. {
  1229. newArgVec.push_back('\\');
  1230. if(*c)
  1231. {
  1232. newArgVec.push_back(*c);
  1233. }
  1234. else
  1235. {
  1236. // Terminate the loop properly.
  1237. --c;
  1238. }
  1239. }
  1240. } break;
  1241. case '[':
  1242. {
  1243. ++squareNesting;
  1244. newArgVec.push_back(*c);
  1245. } break;
  1246. case ']':
  1247. {
  1248. --squareNesting;
  1249. newArgVec.push_back(*c);
  1250. } break;
  1251. case ';':
  1252. {
  1253. // Break the string here if we are not nested inside square
  1254. // brackets.
  1255. if(squareNesting == 0)
  1256. {
  1257. if ( newArgVec.size() || emptyArgs )
  1258. {
  1259. // Add the last argument if the string is not empty.
  1260. newArgVec.push_back(0);
  1261. newargs.push_back(&*newArgVec.begin());
  1262. newArgVec.clear();
  1263. }
  1264. }
  1265. else
  1266. {
  1267. newArgVec.push_back(*c);
  1268. }
  1269. } break;
  1270. default:
  1271. {
  1272. // Just append this character.
  1273. newArgVec.push_back(*c);
  1274. } break;
  1275. }
  1276. }
  1277. if ( newArgVec.size() || emptyArgs )
  1278. {
  1279. // Add the last argument if the string is not empty.
  1280. newArgVec.push_back(0);
  1281. newargs.push_back(&*newArgVec.begin());
  1282. }
  1283. }
  1284. bool cmSystemTools::SimpleGlob(const cmStdString& glob,
  1285. std::vector<cmStdString>& files,
  1286. int type /* = 0 */)
  1287. {
  1288. files.clear();
  1289. if ( glob[glob.size()-1] != '*' )
  1290. {
  1291. return false;
  1292. }
  1293. std::string path = cmSystemTools::GetFilenamePath(glob);
  1294. std::string ppath = cmSystemTools::GetFilenameName(glob);
  1295. ppath = ppath.substr(0, ppath.size()-1);
  1296. if ( path.size() == 0 )
  1297. {
  1298. path = "/";
  1299. }
  1300. bool res = false;
  1301. cmsys::Directory d;
  1302. if (d.Load(path.c_str()))
  1303. {
  1304. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)
  1305. {
  1306. if((std::string(d.GetFile(i)) != ".")
  1307. && (std::string(d.GetFile(i)) != ".."))
  1308. {
  1309. std::string fname = path;
  1310. if ( path[path.size()-1] != '/' )
  1311. {
  1312. fname +="/";
  1313. }
  1314. fname += d.GetFile(i);
  1315. std::string sfname = d.GetFile(i);
  1316. if ( type > 0 && cmSystemTools::FileIsDirectory(fname.c_str()) )
  1317. {
  1318. continue;
  1319. }
  1320. if ( type < 0 && !cmSystemTools::FileIsDirectory(fname.c_str()) )
  1321. {
  1322. continue;
  1323. }
  1324. if ( sfname.size() >= ppath.size() &&
  1325. sfname.substr(0, ppath.size()) ==
  1326. ppath )
  1327. {
  1328. files.push_back(fname);
  1329. res = true;
  1330. }
  1331. }
  1332. }
  1333. }
  1334. return res;
  1335. }
  1336. cmSystemTools::FileFormat cmSystemTools::GetFileFormat(const char* cext)
  1337. {
  1338. if ( ! cext || *cext == 0 )
  1339. {
  1340. return cmSystemTools::NO_FILE_FORMAT;
  1341. }
  1342. //std::string ext = cmSystemTools::LowerCase(cext);
  1343. std::string ext = cext;
  1344. if ( ext == "c" || ext == ".c" ||
  1345. ext == "m" || ext == ".m"
  1346. ) { return cmSystemTools::C_FILE_FORMAT; }
  1347. if (
  1348. ext == "C" || ext == ".C" ||
  1349. ext == "M" || ext == ".M" ||
  1350. ext == "c++" || ext == ".c++" ||
  1351. ext == "cc" || ext == ".cc" ||
  1352. ext == "cpp" || ext == ".cpp" ||
  1353. ext == "cxx" || ext == ".cxx" ||
  1354. ext == "mm" || ext == ".mm"
  1355. ) { return cmSystemTools::CXX_FILE_FORMAT; }
  1356. if (
  1357. ext == "f" || ext == ".f" ||
  1358. ext == "F" || ext == ".F" ||
  1359. ext == "f77" || ext == ".f77" ||
  1360. ext == "f90" || ext == ".f90" ||
  1361. ext == "for" || ext == ".for" ||
  1362. ext == "f95" || ext == ".f95"
  1363. ) { return cmSystemTools::FORTRAN_FILE_FORMAT; }
  1364. if ( ext == "java" || ext == ".java" )
  1365. { return cmSystemTools::JAVA_FILE_FORMAT; }
  1366. if (
  1367. ext == "H" || ext == ".H" ||
  1368. ext == "h" || ext == ".h" ||
  1369. ext == "h++" || ext == ".h++" ||
  1370. ext == "hm" || ext == ".hm" ||
  1371. ext == "hpp" || ext == ".hpp" ||
  1372. ext == "hxx" || ext == ".hxx" ||
  1373. ext == "in" || ext == ".in" ||
  1374. ext == "txx" || ext == ".txx"
  1375. ) { return cmSystemTools::HEADER_FILE_FORMAT; }
  1376. if ( ext == "rc" || ext == ".rc" )
  1377. { return cmSystemTools::RESOURCE_FILE_FORMAT; }
  1378. if ( ext == "def" || ext == ".def" )
  1379. { return cmSystemTools::DEFINITION_FILE_FORMAT; }
  1380. if ( ext == "lib" || ext == ".lib" ||
  1381. ext == "a" || ext == ".a")
  1382. { return cmSystemTools::STATIC_LIBRARY_FILE_FORMAT; }
  1383. if ( ext == "o" || ext == ".o" ||
  1384. ext == "obj" || ext == ".obj")
  1385. { return cmSystemTools::OBJECT_FILE_FORMAT; }
  1386. #ifdef __APPLE__
  1387. if ( ext == "dylib" || ext == ".dylib" )
  1388. { return cmSystemTools::SHARED_LIBRARY_FILE_FORMAT; }
  1389. if ( ext == "so" || ext == ".so" ||
  1390. ext == "bundle" || ext == ".bundle" )
  1391. { return cmSystemTools::MODULE_FILE_FORMAT; }
  1392. #else // __APPLE__
  1393. if ( ext == "so" || ext == ".so" ||
  1394. ext == "sl" || ext == ".sl" ||
  1395. ext == "dll" || ext == ".dll" )
  1396. { return cmSystemTools::SHARED_LIBRARY_FILE_FORMAT; }
  1397. #endif // __APPLE__
  1398. return cmSystemTools::UNKNOWN_FILE_FORMAT;
  1399. }
  1400. bool cmSystemTools::Split(const char* s, std::vector<cmStdString>& l)
  1401. {
  1402. std::vector<std::string> temp;
  1403. bool res = Superclass::Split(s, temp);
  1404. for(std::vector<std::string>::const_iterator i = temp.begin();
  1405. i != temp.end(); ++i)
  1406. {
  1407. l.push_back(*i);
  1408. }
  1409. return res;
  1410. }
  1411. std::string cmSystemTools::ConvertToOutputPath(const char* path)
  1412. {
  1413. #if defined(_WIN32) && !defined(__CYGWIN__)
  1414. if(s_ForceUnixPaths)
  1415. {
  1416. return cmSystemTools::ConvertToUnixOutputPath(path);
  1417. }
  1418. return cmSystemTools::ConvertToWindowsOutputPath(path);
  1419. #else
  1420. return cmSystemTools::ConvertToUnixOutputPath(path);
  1421. #endif
  1422. }
  1423. void cmSystemTools::ConvertToOutputSlashes(std::string& path)
  1424. {
  1425. #if defined(_WIN32) && !defined(__CYGWIN__)
  1426. if(!s_ForceUnixPaths)
  1427. {
  1428. // Convert to windows slashes.
  1429. std::string::size_type pos = 0;
  1430. while((pos = path.find('/', pos)) != std::string::npos)
  1431. {
  1432. path[pos++] = '\\';
  1433. }
  1434. }
  1435. #else
  1436. static_cast<void>(path);
  1437. #endif
  1438. }
  1439. std::string cmSystemTools::ConvertToRunCommandPath(const char* path)
  1440. {
  1441. #if defined(_WIN32) && !defined(__CYGWIN__)
  1442. return cmSystemTools::ConvertToWindowsOutputPath(path);
  1443. #else
  1444. return cmSystemTools::ConvertToUnixOutputPath(path);
  1445. #endif
  1446. }
  1447. bool cmSystemTools::StringEndsWith(const char* str1, const char* str2)
  1448. {
  1449. if ( !str1 || !str2 || strlen(str1) < strlen(str2) )
  1450. {
  1451. return 0;
  1452. }
  1453. return !strncmp(str1 + (strlen(str1)-strlen(str2)), str2, strlen(str2));
  1454. }
  1455. // compute the relative path from here to there
  1456. std::string cmSystemTools::RelativePath(const char* local, const char* remote)
  1457. {
  1458. if(!cmSystemTools::FileIsFullPath(local))
  1459. {
  1460. cmSystemTools::Error("RelativePath must be passed a full path to local: ",
  1461. local);
  1462. }
  1463. if(!cmSystemTools::FileIsFullPath(remote))
  1464. {
  1465. cmSystemTools::Error
  1466. ("RelativePath must be passed a full path to remote: ", remote);
  1467. }
  1468. return cmsys::SystemTools::RelativePath(local, remote);
  1469. }
  1470. #ifdef CMAKE_BUILD_WITH_CMAKE
  1471. //----------------------------------------------------------------------
  1472. bool cmSystemTools::UnsetEnv(const char* value)
  1473. {
  1474. #if !defined(HAVE_UNSETENV)
  1475. std::string var = value;
  1476. var += "=";
  1477. return cmSystemTools::PutEnv(var.c_str());
  1478. #else
  1479. unsetenv(value);
  1480. return true;
  1481. #endif
  1482. }
  1483. //----------------------------------------------------------------------
  1484. std::vector<std::string> cmSystemTools::GetEnvironmentVariables()
  1485. {
  1486. std::vector<std::string> env;
  1487. int cc;
  1488. for ( cc = 0; environ[cc]; ++ cc )
  1489. {
  1490. env.push_back(environ[cc]);
  1491. }
  1492. return env;
  1493. }
  1494. //----------------------------------------------------------------------
  1495. std::vector<std::string> cmSystemTools::AppendEnv(
  1496. std::vector<std::string>* env)
  1497. {
  1498. std::vector<std::string> origEnv = GetEnvironmentVariables();
  1499. if (env && env->size()>0)
  1500. {
  1501. std::vector<std::string>::const_iterator eit;
  1502. for (eit = env->begin(); eit!= env->end(); ++eit)
  1503. {
  1504. PutEnv(eit->c_str());
  1505. }
  1506. }
  1507. return origEnv;
  1508. }
  1509. //----------------------------------------------------------------------
  1510. void cmSystemTools::RestoreEnv(const std::vector<std::string>& env)
  1511. {
  1512. std::vector<std::string>::const_iterator eit;
  1513. // First clear everything in the current environment:
  1514. //
  1515. std::vector<std::string> currentEnv = GetEnvironmentVariables();
  1516. for (eit = currentEnv.begin(); eit!= currentEnv.end(); ++eit)
  1517. {
  1518. std::string var(*eit);
  1519. std::string::size_type pos = var.find("=");
  1520. if (pos != std::string::npos)
  1521. {
  1522. var = var.substr(0, pos);
  1523. }
  1524. UnsetEnv(var.c_str());
  1525. }
  1526. // Then put back each entry from the original environment:
  1527. //
  1528. for (eit = env.begin(); eit!= env.end(); ++eit)
  1529. {
  1530. PutEnv(eit->c_str());
  1531. }
  1532. }
  1533. //----------------------------------------------------------------------
  1534. cmSystemTools::SaveRestoreEnvironment::SaveRestoreEnvironment()
  1535. {
  1536. this->Env = cmSystemTools::GetEnvironmentVariables();
  1537. }
  1538. //----------------------------------------------------------------------
  1539. cmSystemTools::SaveRestoreEnvironment::~SaveRestoreEnvironment()
  1540. {
  1541. cmSystemTools::RestoreEnv(this->Env);
  1542. }
  1543. #endif
  1544. void cmSystemTools::EnableVSConsoleOutput()
  1545. {
  1546. // Visual Studio 8 2005 (devenv.exe or VCExpress.exe) will not
  1547. // display output to the console unless this environment variable is
  1548. // set. We need it to capture the output of these build tools.
  1549. // Note for future work that one could pass "/out \\.\pipe\NAME" to
  1550. // either of these executables where NAME is created with
  1551. // CreateNamedPipe. This would bypass the internal buffering of the
  1552. // output and allow it to be captured on the fly.
  1553. #ifdef _WIN32
  1554. cmSystemTools::PutEnv("vsconsoleoutput=1");
  1555. #endif
  1556. }
  1557. bool cmSystemTools::IsPathToFramework(const char* path)
  1558. {
  1559. if(cmSystemTools::FileIsFullPath(path))
  1560. {
  1561. std::string libname = path;
  1562. if(libname.find(".framework") == libname.size()+1-sizeof(".framework"))
  1563. {
  1564. return true;
  1565. }
  1566. }
  1567. return false;
  1568. }
  1569. bool cmSystemTools::CreateTar(const char* outFileName,
  1570. const std::vector<cmStdString>& files,
  1571. bool gzip, bool bzip2, bool verbose)
  1572. {
  1573. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1574. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1575. std::ofstream fout(outFileName, std::ios::out | cmsys_ios_binary);
  1576. if(!fout)
  1577. {
  1578. std::string e = "Cannot open output file \"";
  1579. e += outFileName;
  1580. e += "\": ";
  1581. e += cmSystemTools::GetLastSystemError();
  1582. cmSystemTools::Error(e.c_str());
  1583. return false;
  1584. }
  1585. cmArchiveWrite a(fout, (gzip? cmArchiveWrite::CompressGZip :
  1586. (bzip2? cmArchiveWrite::CompressBZip2 :
  1587. cmArchiveWrite::CompressNone)),
  1588. cmArchiveWrite::TypeTAR);
  1589. a.SetVerbose(verbose);
  1590. for(std::vector<cmStdString>::const_iterator i = files.begin();
  1591. i != files.end(); ++i)
  1592. {
  1593. std::string path = *i;
  1594. if(cmSystemTools::FileIsFullPath(path.c_str()))
  1595. {
  1596. // Get the relative path to the file.
  1597. path = cmSystemTools::RelativePath(cwd.c_str(), path.c_str());
  1598. }
  1599. if(!a.Add(path))
  1600. {
  1601. break;
  1602. }
  1603. }
  1604. if(!a)
  1605. {
  1606. cmSystemTools::Error(a.GetError().c_str());
  1607. return false;
  1608. }
  1609. return true;
  1610. #else
  1611. (void)outFileName;
  1612. (void)files;
  1613. (void)gzip;
  1614. (void)verbose;
  1615. return false;
  1616. #endif
  1617. }
  1618. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1619. namespace{
  1620. #define BSDTAR_FILESIZE_PRINTF "%lu"
  1621. #define BSDTAR_FILESIZE_TYPE unsigned long
  1622. void
  1623. list_item_verbose(FILE *out, struct archive_entry *entry)
  1624. {
  1625. char tmp[100];
  1626. size_t w;
  1627. const char *p;
  1628. const char *fmt;
  1629. time_t tim;
  1630. static time_t now;
  1631. size_t u_width = 6;
  1632. size_t gs_width = 13;
  1633. /*
  1634. * We avoid collecting the entire list in memory at once by
  1635. * listing things as we see them. However, that also means we can't
  1636. * just pre-compute the field widths. Instead, we start with guesses
  1637. * and just widen them as necessary. These numbers are completely
  1638. * arbitrary.
  1639. */
  1640. if (!now)
  1641. {
  1642. time(&now);
  1643. }
  1644. fprintf(out, "%s %d ",
  1645. archive_entry_strmode(entry),
  1646. archive_entry_nlink(entry));
  1647. /* Use uname if it's present, else uid. */
  1648. p = archive_entry_uname(entry);
  1649. if ((p == NULL) || (*p == '\0'))
  1650. {
  1651. sprintf(tmp, "%lu ",
  1652. (unsigned long)archive_entry_uid(entry));
  1653. p = tmp;
  1654. }
  1655. w = strlen(p);
  1656. if (w > u_width)
  1657. {
  1658. u_width = w;
  1659. }
  1660. fprintf(out, "%-*s ", (int)u_width, p);
  1661. /* Use gname if it's present, else gid. */
  1662. p = archive_entry_gname(entry);
  1663. if (p != NULL && p[0] != '\0')
  1664. {
  1665. fprintf(out, "%s", p);
  1666. w = strlen(p);
  1667. }
  1668. else
  1669. {
  1670. sprintf(tmp, "%lu",
  1671. (unsigned long)archive_entry_gid(entry));
  1672. w = strlen(tmp);
  1673. fprintf(out, "%s", tmp);
  1674. }
  1675. /*
  1676. * Print device number or file size, right-aligned so as to make
  1677. * total width of group and devnum/filesize fields be gs_width.
  1678. * If gs_width is too small, grow it.
  1679. */
  1680. if (archive_entry_filetype(entry) == AE_IFCHR
  1681. || archive_entry_filetype(entry) == AE_IFBLK)
  1682. {
  1683. sprintf(tmp, "%lu,%lu",
  1684. (unsigned long)archive_entry_rdevmajor(entry),
  1685. (unsigned long)archive_entry_rdevminor(entry));
  1686. }
  1687. else
  1688. {
  1689. /*
  1690. * Note the use of platform-dependent macros to format
  1691. * the filesize here. We need the format string and the
  1692. * corresponding type for the cast.
  1693. */
  1694. sprintf(tmp, BSDTAR_FILESIZE_PRINTF,
  1695. (BSDTAR_FILESIZE_TYPE)archive_entry_size(entry));
  1696. }
  1697. if (w + strlen(tmp) >= gs_width)
  1698. {
  1699. gs_width = w+strlen(tmp)+1;
  1700. }
  1701. fprintf(out, "%*s", (int)(gs_width - w), tmp);
  1702. /* Format the time using 'ls -l' conventions. */
  1703. tim = archive_entry_mtime(entry);
  1704. #define HALF_YEAR (time_t)365 * 86400 / 2
  1705. #if defined(_WIN32) && !defined(__CYGWIN__)
  1706. /* Windows' strftime function does not support %e format. */
  1707. #define DAY_FMT "%d"
  1708. #else
  1709. #define DAY_FMT "%e" /* Day number without leading zeros */
  1710. #endif
  1711. if (tim < now - HALF_YEAR || tim > now + HALF_YEAR)
  1712. {
  1713. fmt = DAY_FMT " %b %Y";
  1714. }
  1715. else
  1716. {
  1717. fmt = DAY_FMT " %b %H:%M";
  1718. }
  1719. strftime(tmp, sizeof(tmp), fmt, localtime(&tim));
  1720. fprintf(out, " %s ", tmp);
  1721. fprintf(out, "%s", archive_entry_pathname(entry));
  1722. /* Extra information for links. */
  1723. if (archive_entry_hardlink(entry)) /* Hard link */
  1724. {
  1725. fprintf(out, " link to %s",
  1726. archive_entry_hardlink(entry));
  1727. }
  1728. else if (archive_entry_symlink(entry)) /* Symbolic link */
  1729. {
  1730. fprintf(out, " -> %s", archive_entry_symlink(entry));
  1731. }
  1732. }
  1733. #ifdef __BORLANDC__
  1734. # pragma warn -8066 /* unreachable code */
  1735. #endif
  1736. long copy_data(struct archive *ar, struct archive *aw)
  1737. {
  1738. long r;
  1739. const void *buff;
  1740. size_t size;
  1741. off_t offset;
  1742. for (;;)
  1743. {
  1744. r = archive_read_data_block(ar, &buff, &size, &offset);
  1745. if (r == ARCHIVE_EOF)
  1746. {
  1747. return (ARCHIVE_OK);
  1748. }
  1749. if (r != ARCHIVE_OK)
  1750. {
  1751. return (r);
  1752. }
  1753. r = archive_write_data_block(aw, buff, size, offset);
  1754. if (r != ARCHIVE_OK)
  1755. {
  1756. cmSystemTools::Message("archive_write_data_block()",
  1757. archive_error_string(aw));
  1758. return (r);
  1759. }
  1760. }
  1761. return r;
  1762. }
  1763. bool extract_tar(const char* outFileName, bool verbose,
  1764. bool extract)
  1765. {
  1766. struct archive* a = archive_read_new();
  1767. struct archive *ext = archive_write_disk_new();
  1768. archive_read_support_compression_all(a);
  1769. archive_read_support_format_all(a);
  1770. struct archive_entry *entry;
  1771. int r = archive_read_open_file(a, outFileName, 10240);
  1772. if(r)
  1773. {
  1774. cmSystemTools::Error("Problem with archive_read_open_file(): ",
  1775. archive_error_string(a));
  1776. return false;
  1777. }
  1778. for (;;)
  1779. {
  1780. r = archive_read_next_header(a, &entry);
  1781. if (r == ARCHIVE_EOF)
  1782. {
  1783. break;
  1784. }
  1785. if (r != ARCHIVE_OK)
  1786. {
  1787. cmSystemTools::Error("Problem with archive_read_next_header(): ",
  1788. archive_error_string(a));
  1789. }
  1790. if (verbose && extract)
  1791. {
  1792. cmSystemTools::Stdout("x ");
  1793. cmSystemTools::Stdout(archive_entry_pathname(entry));
  1794. }
  1795. if(verbose && !extract)
  1796. {
  1797. list_item_verbose(stdout, entry);
  1798. }
  1799. else if(!extract)
  1800. {
  1801. cmSystemTools::Stdout(archive_entry_pathname(entry));
  1802. }
  1803. if(extract)
  1804. {
  1805. r = archive_write_disk_set_options(ext, ARCHIVE_EXTRACT_TIME);
  1806. if (r != ARCHIVE_OK)
  1807. {
  1808. cmSystemTools::Error(
  1809. "Problem with archive_write_disk_set_options(): ",
  1810. archive_error_string(ext));
  1811. }
  1812. r = archive_write_header(ext, entry);
  1813. if (r != ARCHIVE_OK)
  1814. {
  1815. cmSystemTools::Error("Problem with archive_write_header(): ",
  1816. archive_error_string(ext));
  1817. cmSystemTools::Error("Current file:",
  1818. archive_entry_pathname(entry));
  1819. }
  1820. else
  1821. {
  1822. copy_data(a, ext);
  1823. r = archive_write_finish_entry(ext);
  1824. if (r != ARCHIVE_OK)
  1825. {
  1826. cmSystemTools::Error("Problem with archive_write_finish_entry(): ",
  1827. archive_error_string(ext));
  1828. }
  1829. }
  1830. }
  1831. if (verbose || !extract)
  1832. {
  1833. cmSystemTools::Stdout("\n");
  1834. }
  1835. }
  1836. archive_read_close(a);
  1837. archive_read_finish(a);
  1838. return true;
  1839. }
  1840. }
  1841. #endif
  1842. bool cmSystemTools::ExtractTar(const char* outFileName,
  1843. bool , bool verbose)
  1844. {
  1845. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1846. return extract_tar(outFileName, verbose, true);
  1847. #else
  1848. (void)outFileName;
  1849. (void)verbose;
  1850. return false;
  1851. #endif
  1852. }
  1853. bool cmSystemTools::ListTar(const char* outFileName,
  1854. bool ,
  1855. bool verbose)
  1856. {
  1857. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1858. return extract_tar(outFileName, verbose, false);
  1859. #else
  1860. (void)outFileName;
  1861. (void)verbose;
  1862. return false;
  1863. #endif
  1864. }
  1865. int cmSystemTools::WaitForLine(cmsysProcess* process, std::string& line,
  1866. double timeout,
  1867. std::vector<char>& out,
  1868. std::vector<char>& err)
  1869. {
  1870. line = "";
  1871. std::vector<char>::iterator outiter = out.begin();
  1872. std::vector<char>::iterator erriter = err.begin();
  1873. while(1)
  1874. {
  1875. // Check for a newline in stdout.
  1876. for(;outiter != out.end(); ++outiter)
  1877. {
  1878. if((*outiter == '\r') && ((outiter+1) == out.end()))
  1879. {
  1880. break;
  1881. }
  1882. else if(*outiter == '\n' || *outiter == '\0')
  1883. {
  1884. std::vector<char>::size_type length = outiter-out.begin();
  1885. if(length > 1 && *(outiter-1) == '\r')
  1886. {
  1887. --length;
  1888. }
  1889. if(length > 0)
  1890. {
  1891. line.append(&out[0], length);
  1892. }
  1893. out.erase(out.begin(), outiter+1);
  1894. return cmsysProcess_Pipe_STDOUT;
  1895. }
  1896. }
  1897. // Check for a newline in stderr.
  1898. for(;erriter != err.end(); ++erriter)
  1899. {
  1900. if((*erriter == '\r') && ((erriter+1) == err.end()))
  1901. {
  1902. break;
  1903. }
  1904. else if(*erriter == '\n' || *erriter == '\0')
  1905. {
  1906. std::vector<char>::size_type length = erriter-err.begin();
  1907. if(length > 1 && *(erriter-1) == '\r')
  1908. {
  1909. --length;
  1910. }
  1911. if(length > 0)
  1912. {
  1913. line.append(&err[0], length);
  1914. }
  1915. err.erase(err.begin(), erriter+1);
  1916. return cmsysProcess_Pipe_STDERR;
  1917. }
  1918. }
  1919. // No newlines found. Wait for more data from the process.
  1920. int length;
  1921. char* data;
  1922. int pipe = cmsysProcess_WaitForData(process, &data, &length, &timeout);
  1923. if(pipe == cmsysProcess_Pipe_Timeout)
  1924. {
  1925. // Timeout has been exceeded.
  1926. return pipe;
  1927. }
  1928. else if(pipe == cmsysProcess_Pipe_STDOUT)
  1929. {
  1930. // Append to the stdout buffer.
  1931. std::vector<char>::size_type size = out.size();
  1932. out.insert(out.end(), data, data+length);
  1933. outiter = out.begin()+size;
  1934. }
  1935. else if(pipe == cmsysProcess_Pipe_STDERR)
  1936. {
  1937. // Append to the stderr buffer.
  1938. std::vector<char>::size_type size = err.size();
  1939. err.insert(err.end(), data, data+length);
  1940. erriter = err.begin()+size;
  1941. }
  1942. else if(pipe == cmsysProcess_Pipe_None)
  1943. {
  1944. // Both stdout and stderr pipes have broken. Return leftover data.
  1945. if(!out.empty())
  1946. {
  1947. line.append(&out[0], outiter-out.begin());
  1948. out.erase(out.begin(), out.end());
  1949. return cmsysProcess_Pipe_STDOUT;
  1950. }
  1951. else if(!err.empty())
  1952. {
  1953. line.append(&err[0], erriter-err.begin());
  1954. err.erase(err.begin(), err.end());
  1955. return cmsysProcess_Pipe_STDERR;
  1956. }
  1957. else
  1958. {
  1959. return cmsysProcess_Pipe_None;
  1960. }
  1961. }
  1962. }
  1963. }
  1964. void cmSystemTools::DoNotInheritStdPipes()
  1965. {
  1966. #ifdef _WIN32
  1967. // Check to see if we are attached to a console
  1968. // if so, then do not stop the inherited pipes
  1969. // or stdout and stderr will not show up in dos
  1970. // shell windows
  1971. CONSOLE_SCREEN_BUFFER_INFO hOutInfo;
  1972. HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
  1973. if(GetConsoleScreenBufferInfo(hOut, &hOutInfo))
  1974. {
  1975. return;
  1976. }
  1977. {
  1978. HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
  1979. DuplicateHandle(GetCurrentProcess(), out,
  1980. GetCurrentProcess(), &out, 0, FALSE,
  1981. DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
  1982. SetStdHandle(STD_OUTPUT_HANDLE, out);
  1983. }
  1984. {
  1985. HANDLE out = GetStdHandle(STD_ERROR_HANDLE);
  1986. DuplicateHandle(GetCurrentProcess(), out,
  1987. GetCurrentProcess(), &out, 0, FALSE,
  1988. DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
  1989. SetStdHandle(STD_ERROR_HANDLE, out);
  1990. }
  1991. #endif
  1992. }
  1993. //----------------------------------------------------------------------------
  1994. bool cmSystemTools::CopyFileTime(const char* fromFile, const char* toFile)
  1995. {
  1996. #if defined(_WIN32) && !defined(__CYGWIN__)
  1997. cmSystemToolsWindowsHandle hFrom =
  1998. CreateFile(fromFile, GENERIC_READ, FILE_SHARE_READ, 0,
  1999. OPEN_EXISTING, 0, 0);
  2000. cmSystemToolsWindowsHandle hTo =
  2001. CreateFile(toFile, GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
  2002. if(!hFrom || !hTo)
  2003. {
  2004. return false;
  2005. }
  2006. FILETIME timeCreation;
  2007. FILETIME timeLastAccess;
  2008. FILETIME timeLastWrite;
  2009. if(!GetFileTime(hFrom, &timeCreation, &timeLastAccess, &timeLastWrite))
  2010. {
  2011. return false;
  2012. }
  2013. if(!SetFileTime(hTo, &timeCreation, &timeLastAccess, &timeLastWrite))
  2014. {
  2015. return false;
  2016. }
  2017. #else
  2018. struct stat fromStat;
  2019. if(stat(fromFile, &fromStat) < 0)
  2020. {
  2021. return false;
  2022. }
  2023. struct utimbuf buf;
  2024. buf.actime = fromStat.st_atime;
  2025. buf.modtime = fromStat.st_mtime;
  2026. if(utime(toFile, &buf) < 0)
  2027. {
  2028. return false;
  2029. }
  2030. #endif
  2031. return true;
  2032. }
  2033. //----------------------------------------------------------------------------
  2034. cmSystemToolsFileTime* cmSystemTools::FileTimeNew()
  2035. {
  2036. return new cmSystemToolsFileTime;
  2037. }
  2038. //----------------------------------------------------------------------------
  2039. void cmSystemTools::FileTimeDelete(cmSystemToolsFileTime* t)
  2040. {
  2041. delete t;
  2042. }
  2043. //----------------------------------------------------------------------------
  2044. bool cmSystemTools::FileTimeGet(const char* fname, cmSystemToolsFileTime* t)
  2045. {
  2046. #if defined(_WIN32) && !defined(__CYGWIN__)
  2047. cmSystemToolsWindowsHandle h =
  2048. CreateFile(fname, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
  2049. if(!h)
  2050. {
  2051. return false;
  2052. }
  2053. if(!GetFileTime(h, &t->timeCreation, &t->timeLastAccess, &t->timeLastWrite))
  2054. {
  2055. return false;
  2056. }
  2057. #else
  2058. struct stat st;
  2059. if(stat(fname, &st) < 0)
  2060. {
  2061. return false;
  2062. }
  2063. t->timeBuf.actime = st.st_atime;
  2064. t->timeBuf.modtime = st.st_mtime;
  2065. #endif
  2066. return true;
  2067. }
  2068. //----------------------------------------------------------------------------
  2069. bool cmSystemTools::FileTimeSet(const char* fname, cmSystemToolsFileTime* t)
  2070. {
  2071. #if defined(_WIN32) && !defined(__CYGWIN__)
  2072. cmSystemToolsWindowsHandle h =
  2073. CreateFile(fname, GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
  2074. if(!h)
  2075. {
  2076. return false;
  2077. }
  2078. if(!SetFileTime(h, &t->timeCreation, &t->timeLastAccess, &t->timeLastWrite))
  2079. {
  2080. return false;
  2081. }
  2082. #else
  2083. if(utime(fname, &t->timeBuf) < 0)
  2084. {
  2085. return false;
  2086. }
  2087. #endif
  2088. return true;
  2089. }
  2090. //----------------------------------------------------------------------------
  2091. static std::string cmSystemToolsExecutableDirectory;
  2092. void cmSystemTools::FindExecutableDirectory(const char* argv0)
  2093. {
  2094. #if defined(_WIN32) && !defined(__CYGWIN__)
  2095. (void)argv0; // ignore this on windows
  2096. char modulepath[_MAX_PATH];
  2097. ::GetModuleFileName(NULL, modulepath, sizeof(modulepath));
  2098. cmSystemToolsExecutableDirectory =
  2099. cmSystemTools::GetFilenamePath(modulepath);
  2100. return;
  2101. #else
  2102. std::string errorMsg;
  2103. std::string exe;
  2104. if(cmSystemTools::FindProgramPath(argv0, exe, errorMsg))
  2105. {
  2106. // remove symlinks
  2107. exe = cmSystemTools::GetRealPath(exe.c_str());
  2108. cmSystemToolsExecutableDirectory =
  2109. cmSystemTools::GetFilenamePath(exe.c_str());
  2110. }
  2111. else
  2112. {
  2113. // ???
  2114. }
  2115. #endif
  2116. }
  2117. //----------------------------------------------------------------------------
  2118. const char* cmSystemTools::GetExecutableDirectory()
  2119. {
  2120. return cmSystemToolsExecutableDirectory.c_str();
  2121. }
  2122. //----------------------------------------------------------------------------
  2123. #if defined(CMAKE_BUILD_WITH_CMAKE)
  2124. void cmSystemTools::MakefileColorEcho(int color, const char* message,
  2125. bool newline, bool enabled)
  2126. {
  2127. // On some platforms (an MSYS prompt) cmsysTerminal may not be able
  2128. // to determine whether the stream is displayed on a tty. In this
  2129. // case it assumes no unless we tell it otherwise. Since we want
  2130. // color messages to be displayed for users we will assume yes.
  2131. // However, we can test for some situations when the answer is most
  2132. // likely no.
  2133. int assumeTTY = cmsysTerminal_Color_AssumeTTY;
  2134. if(cmSystemTools::GetEnv("DART_TEST_FROM_DART") ||
  2135. cmSystemTools::GetEnv("DASHBOARD_TEST_FROM_CTEST") ||
  2136. cmSystemTools::GetEnv("CTEST_INTERACTIVE_DEBUG_MODE"))
  2137. {
  2138. // Avoid printing color escapes during dashboard builds.
  2139. assumeTTY = 0;
  2140. }
  2141. if(enabled)
  2142. {
  2143. cmsysTerminal_cfprintf(color | assumeTTY, stdout, "%s%s",
  2144. message, newline? "\n" : "");
  2145. }
  2146. else
  2147. {
  2148. // Color is disabled. Print without color.
  2149. fprintf(stdout, "%s%s", message, newline? "\n" : "");
  2150. }
  2151. }
  2152. #endif
  2153. //----------------------------------------------------------------------------
  2154. bool cmSystemTools::GuessLibrarySOName(std::string const& fullPath,
  2155. std::string& soname)
  2156. {
  2157. // For ELF shared libraries use a real parser to get the correct
  2158. // soname.
  2159. #if defined(CMAKE_USE_ELF_PARSER)
  2160. cmELF elf(fullPath.c_str());
  2161. if(elf)
  2162. {
  2163. return elf.GetSOName(soname);
  2164. }
  2165. #endif
  2166. // If the file is not a symlink we have no guess for its soname.
  2167. if(!cmSystemTools::FileIsSymlink(fullPath.c_str()))
  2168. {
  2169. return false;
  2170. }
  2171. if(!cmSystemTools::ReadSymlink(fullPath.c_str(), soname))
  2172. {
  2173. return false;
  2174. }
  2175. // If the symlink has a path component we have no guess for the soname.
  2176. if(!cmSystemTools::GetFilenamePath(soname).empty())
  2177. {
  2178. return false;
  2179. }
  2180. // If the symlink points at an extended version of the same name
  2181. // assume it is the soname.
  2182. std::string name = cmSystemTools::GetFilenameName(fullPath);
  2183. if(soname.length() > name.length() &&
  2184. soname.substr(0, name.length()) == name)
  2185. {
  2186. return true;
  2187. }
  2188. return false;
  2189. }
  2190. //----------------------------------------------------------------------------
  2191. #if defined(CMAKE_USE_ELF_PARSER)
  2192. std::string::size_type cmSystemToolsFindRPath(std::string const& have,
  2193. std::string const& want)
  2194. {
  2195. // Search for the desired rpath.
  2196. std::string::size_type pos = have.find(want);
  2197. // If the path is not present we are done.
  2198. if(pos == std::string::npos)
  2199. {
  2200. return pos;
  2201. }
  2202. // Build a regex to match a properly separated path instance.
  2203. std::string regex_str = "(^|:)(";
  2204. for(std::string::const_iterator i = want.begin(); i != want.end(); ++i)
  2205. {
  2206. int ch = *i;
  2207. if(!(('a' <= ch && ch <= 'z') ||
  2208. ('A' <= ch && ch <= 'Z') ||
  2209. ('0' <= ch && ch <= '9')))
  2210. {
  2211. // Escape the non-alphanumeric character.
  2212. regex_str += "\\";
  2213. }
  2214. // Store the character.
  2215. regex_str.append(1, static_cast<char>(ch));
  2216. }
  2217. regex_str += ")(:|$)";
  2218. // Look for the separated path.
  2219. cmsys::RegularExpression regex(regex_str.c_str());
  2220. if(regex.find(have))
  2221. {
  2222. // Return the position of the path portion.
  2223. return regex.start(2);
  2224. }
  2225. else
  2226. {
  2227. // The desired rpath was not found.
  2228. return std::string::npos;
  2229. }
  2230. }
  2231. #endif
  2232. #if defined(CMAKE_USE_ELF_PARSER)
  2233. struct cmSystemToolsRPathInfo
  2234. {
  2235. unsigned long Position;
  2236. unsigned long Size;
  2237. std::string Name;
  2238. std::string Value;
  2239. };
  2240. #endif
  2241. //----------------------------------------------------------------------------
  2242. bool cmSystemTools::ChangeRPath(std::string const& file,
  2243. std::string const& oldRPath,
  2244. std::string const& newRPath,
  2245. std::string* emsg,
  2246. bool* changed)
  2247. {
  2248. #if defined(CMAKE_USE_ELF_PARSER)
  2249. if(changed)
  2250. {
  2251. *changed = false;
  2252. }
  2253. int rp_count = 0;
  2254. cmSystemToolsRPathInfo rp[2];
  2255. {
  2256. // Parse the ELF binary.
  2257. cmELF elf(file.c_str());
  2258. // Get the RPATH and RUNPATH entries from it.
  2259. int se_count = 0;
  2260. cmELF::StringEntry const* se[2] = {0, 0};
  2261. const char* se_name[2] = {0, 0};
  2262. if(cmELF::StringEntry const* se_rpath = elf.GetRPath())
  2263. {
  2264. se[se_count] = se_rpath;
  2265. se_name[se_count] = "RPATH";
  2266. ++se_count;
  2267. }
  2268. if(cmELF::StringEntry const* se_runpath = elf.GetRunPath())
  2269. {
  2270. se[se_count] = se_runpath;
  2271. se_name[se_count] = "RUNPATH";
  2272. ++se_count;
  2273. }
  2274. if(se_count == 0)
  2275. {
  2276. if(newRPath.empty())
  2277. {
  2278. // The new rpath is empty and there is no rpath anyway so it is
  2279. // okay.
  2280. return true;
  2281. }
  2282. else
  2283. {
  2284. if(emsg)
  2285. {
  2286. *emsg = "No valid ELF RPATH or RUNPATH entry exists in the file; ";
  2287. *emsg += elf.GetErrorMessage();
  2288. }
  2289. return false;
  2290. }
  2291. }
  2292. for(int i=0; i < se_count; ++i)
  2293. {
  2294. // If both RPATH and RUNPATH refer to the same string literal it
  2295. // needs to be changed only once.
  2296. if(rp_count && rp[0].Position == se[i]->Position)
  2297. {
  2298. continue;
  2299. }
  2300. // Make sure the current rpath contains the old rpath.
  2301. std::string::size_type pos =
  2302. cmSystemToolsFindRPath(se[i]->Value, oldRPath);
  2303. if(pos == std::string::npos)
  2304. {
  2305. // If it contains the new rpath instead then it is okay.
  2306. if(cmSystemToolsFindRPath(se[i]->Value, newRPath) != std::string::npos)
  2307. {
  2308. continue;
  2309. }
  2310. if(emsg)
  2311. {
  2312. cmOStringStream e;
  2313. e << "The current " << se_name[i] << " is:\n"
  2314. << " " << se[i]->Value << "\n"
  2315. << "which does not contain:\n"
  2316. << " " << oldRPath << "\n"
  2317. << "as was expected.";
  2318. *emsg = e.str();
  2319. }
  2320. return false;
  2321. }
  2322. // Store information about the entry in the file.
  2323. rp[rp_count].Position = se[i]->Position;
  2324. rp[rp_count].Size = se[i]->Size;
  2325. rp[rp_count].Name = se_name[i];
  2326. // Construct the new value which preserves the part of the path
  2327. // not being changed.
  2328. rp[rp_count].Value = se[i]->Value.substr(0, pos);
  2329. rp[rp_count].Value += newRPath;
  2330. rp[rp_count].Value += se[i]->Value.substr(pos+oldRPath.length(),
  2331. oldRPath.npos);
  2332. // Make sure there is enough room to store the new rpath and at
  2333. // least one null terminator.
  2334. if(rp[rp_count].Size < rp[rp_count].Value.length()+1)
  2335. {
  2336. if(emsg)
  2337. {
  2338. *emsg = "The replacement path is too long for the ";
  2339. *emsg += se_name[i];
  2340. *emsg += " entry.";
  2341. }
  2342. return false;
  2343. }
  2344. // This entry is ready for update.
  2345. ++rp_count;
  2346. }
  2347. }
  2348. // If no runtime path needs to be changed, we are done.
  2349. if(rp_count == 0)
  2350. {
  2351. return true;
  2352. }
  2353. {
  2354. // Open the file for update.
  2355. std::ofstream f(file.c_str(),
  2356. std::ios::in | std::ios::out | std::ios::binary);
  2357. if(!f)
  2358. {
  2359. if(emsg)
  2360. {
  2361. *emsg = "Error opening file for update.";
  2362. }
  2363. return false;
  2364. }
  2365. // Store the new RPATH and RUNPATH strings.
  2366. for(int i=0; i < rp_count; ++i)
  2367. {
  2368. // Seek to the RPATH position.
  2369. if(!f.seekp(rp[i].Position))
  2370. {
  2371. if(emsg)
  2372. {
  2373. *emsg = "Error seeking to ";
  2374. *emsg += rp[i].Name;
  2375. *emsg += " position.";
  2376. }
  2377. return false;
  2378. }
  2379. // Write the new rpath. Follow it with enough null terminators to
  2380. // fill the string table entry.
  2381. f << rp[i].Value;
  2382. for(unsigned long j=rp[i].Value.length(); j < rp[i].Size; ++j)
  2383. {
  2384. f << '\0';
  2385. }
  2386. // Make sure it wrote correctly.
  2387. if(!f)
  2388. {
  2389. if(emsg)
  2390. {
  2391. *emsg = "Error writing the new ";
  2392. *emsg += rp[i].Name;
  2393. *emsg += " string to the file.";
  2394. }
  2395. return false;
  2396. }
  2397. }
  2398. }
  2399. // Everything was updated successfully.
  2400. if(changed)
  2401. {
  2402. *changed = true;
  2403. }
  2404. return true;
  2405. #else
  2406. (void)file;
  2407. (void)oldRPath;
  2408. (void)newRPath;
  2409. (void)emsg;
  2410. (void)changed;
  2411. return false;
  2412. #endif
  2413. }
  2414. //----------------------------------------------------------------------------
  2415. bool cmSystemTools::VersionCompare(cmSystemTools::CompareOp op,
  2416. const char* lhss, const char* rhss)
  2417. {
  2418. unsigned int lhs[4] = {0,0,0,0};
  2419. unsigned int rhs[4] = {0,0,0,0};
  2420. sscanf(lhss, "%u.%u.%u.%u", &lhs[0], &lhs[1], &lhs[2], &lhs[3]);
  2421. sscanf(rhss, "%u.%u.%u.%u", &rhs[0], &rhs[1], &rhs[2], &rhs[3]);
  2422. // Do component-wise comparison.
  2423. for(unsigned int i=0; i < 4; ++i)
  2424. {
  2425. if(lhs[i] < rhs[i])
  2426. {
  2427. // lhs < rhs, so true if operation is LESS
  2428. return op == cmSystemTools::OP_LESS;
  2429. }
  2430. else if(lhs[i] > rhs[i])
  2431. {
  2432. // lhs > rhs, so true if operation is GREATER
  2433. return op == cmSystemTools::OP_GREATER;
  2434. }
  2435. }
  2436. // lhs == rhs, so true if operation is EQUAL
  2437. return op == cmSystemTools::OP_EQUAL;
  2438. }
  2439. //----------------------------------------------------------------------------
  2440. bool cmSystemTools::RemoveRPath(std::string const& file, std::string* emsg,
  2441. bool* removed)
  2442. {
  2443. #if defined(CMAKE_USE_ELF_PARSER)
  2444. if(removed)
  2445. {
  2446. *removed = false;
  2447. }
  2448. int zeroCount = 0;
  2449. unsigned long zeroPosition[2] = {0,0};
  2450. unsigned long zeroSize[2] = {0,0};
  2451. unsigned long bytesBegin = 0;
  2452. std::vector<char> bytes;
  2453. {
  2454. // Parse the ELF binary.
  2455. cmELF elf(file.c_str());
  2456. // Get the RPATH and RUNPATH entries from it and sort them by index
  2457. // in the dynamic section header.
  2458. int se_count = 0;
  2459. cmELF::StringEntry const* se[2] = {0, 0};
  2460. if(cmELF::StringEntry const* se_rpath = elf.GetRPath())
  2461. {
  2462. se[se_count++] = se_rpath;
  2463. }
  2464. if(cmELF::StringEntry const* se_runpath = elf.GetRunPath())
  2465. {
  2466. se[se_count++] = se_runpath;
  2467. }
  2468. if(se_count == 0)
  2469. {
  2470. // There is no RPATH or RUNPATH anyway.
  2471. return true;
  2472. }
  2473. if(se_count == 2 && se[1]->IndexInSection < se[0]->IndexInSection)
  2474. {
  2475. cmsys_stl::swap(se[0], se[1]);
  2476. }
  2477. // Get the size of the dynamic section header.
  2478. unsigned int count = elf.GetDynamicEntryCount();
  2479. if(count == 0)
  2480. {
  2481. // This should happen only for invalid ELF files where a DT_NULL
  2482. // appears before the end of the table.
  2483. if(emsg)
  2484. {
  2485. *emsg = "DYNAMIC section contains a DT_NULL before the end.";
  2486. }
  2487. return false;
  2488. }
  2489. // Save information about the string entries to be zeroed.
  2490. zeroCount = se_count;
  2491. for(int i=0; i < se_count; ++i)
  2492. {
  2493. zeroPosition[i] = se[i]->Position;
  2494. zeroSize[i] = se[i]->Size;
  2495. }
  2496. // Get the range of file positions corresponding to each entry and
  2497. // the rest of the table after them.
  2498. unsigned long entryBegin[3] = {0,0,0};
  2499. unsigned long entryEnd[2] = {0,0};
  2500. for(int i=0; i < se_count; ++i)
  2501. {
  2502. entryBegin[i] = elf.GetDynamicEntryPosition(se[i]->IndexInSection);
  2503. entryEnd[i] = elf.GetDynamicEntryPosition(se[i]->IndexInSection+1);
  2504. }
  2505. entryBegin[se_count] = elf.GetDynamicEntryPosition(count);
  2506. // The data are to be written over the old table entries starting at
  2507. // the first one being removed.
  2508. bytesBegin = entryBegin[0];
  2509. unsigned long bytesEnd = entryBegin[se_count];
  2510. // Allocate a buffer to hold the part of the file to be written.
  2511. // Initialize it with zeros.
  2512. bytes.resize(bytesEnd - bytesBegin, 0);
  2513. // Read the part of the DYNAMIC section header that will move.
  2514. // The remainder of the buffer will be left with zeros which
  2515. // represent a DT_NULL entry.
  2516. char* data = &bytes[0];
  2517. for(int i=0; i < se_count; ++i)
  2518. {
  2519. // Read data between the entries being removed.
  2520. unsigned long sz = entryBegin[i+1] - entryEnd[i];
  2521. if(sz > 0 && !elf.ReadBytes(entryEnd[i], sz, data))
  2522. {
  2523. if(emsg)
  2524. {
  2525. *emsg = "Failed to read DYNAMIC section header.";
  2526. }
  2527. return false;
  2528. }
  2529. data += sz;
  2530. }
  2531. }
  2532. // Open the file for update.
  2533. std::ofstream f(file.c_str(),
  2534. std::ios::in | std::ios::out | std::ios::binary);
  2535. if(!f)
  2536. {
  2537. if(emsg)
  2538. {
  2539. *emsg = "Error opening file for update.";
  2540. }
  2541. return false;
  2542. }
  2543. // Write the new DYNAMIC table header.
  2544. if(!f.seekp(bytesBegin))
  2545. {
  2546. if(emsg)
  2547. {
  2548. *emsg = "Error seeking to DYNAMIC table header for RPATH.";
  2549. }
  2550. return false;
  2551. }
  2552. if(!f.write(&bytes[0], bytes.size()))
  2553. {
  2554. if(emsg)
  2555. {
  2556. *emsg = "Error replacing DYNAMIC table header.";
  2557. }
  2558. return false;
  2559. }
  2560. // Fill the RPATH and RUNPATH strings with zero bytes.
  2561. for(int i=0; i < zeroCount; ++i)
  2562. {
  2563. if(!f.seekp(zeroPosition[i]))
  2564. {
  2565. if(emsg)
  2566. {
  2567. *emsg = "Error seeking to RPATH position.";
  2568. }
  2569. return false;
  2570. }
  2571. for(unsigned long j=0; j < zeroSize[i]; ++j)
  2572. {
  2573. f << '\0';
  2574. }
  2575. if(!f)
  2576. {
  2577. if(emsg)
  2578. {
  2579. *emsg = "Error writing the empty rpath string to the file.";
  2580. }
  2581. return false;
  2582. }
  2583. }
  2584. // Everything was updated successfully.
  2585. if(removed)
  2586. {
  2587. *removed = true;
  2588. }
  2589. return true;
  2590. #else
  2591. (void)file;
  2592. (void)emsg;
  2593. (void)removed;
  2594. return false;
  2595. #endif
  2596. }
  2597. //----------------------------------------------------------------------------
  2598. bool cmSystemTools::CheckRPath(std::string const& file,
  2599. std::string const& newRPath)
  2600. {
  2601. #if defined(CMAKE_USE_ELF_PARSER)
  2602. // Parse the ELF binary.
  2603. cmELF elf(file.c_str());
  2604. // Get the RPATH or RUNPATH entry from it.
  2605. cmELF::StringEntry const* se = elf.GetRPath();
  2606. if(!se)
  2607. {
  2608. se = elf.GetRunPath();
  2609. }
  2610. // Make sure the current rpath contains the new rpath.
  2611. if(newRPath.empty())
  2612. {
  2613. if(!se)
  2614. {
  2615. return true;
  2616. }
  2617. }
  2618. else
  2619. {
  2620. if(se &&
  2621. cmSystemToolsFindRPath(se->Value, newRPath) != std::string::npos)
  2622. {
  2623. return true;
  2624. }
  2625. }
  2626. return false;
  2627. #else
  2628. (void)file;
  2629. (void)newRPath;
  2630. return false;
  2631. #endif
  2632. }
  2633. //----------------------------------------------------------------------------
  2634. bool cmSystemTools::RepeatedRemoveDirectory(const char* dir)
  2635. {
  2636. // Windows sometimes locks files temporarily so try a few times.
  2637. for(int i = 0; i < 10; ++i)
  2638. {
  2639. if(cmSystemTools::RemoveADirectory(dir))
  2640. {
  2641. return true;
  2642. }
  2643. cmSystemTools::Delay(100);
  2644. }
  2645. return false;
  2646. }