cmSystemTools.cxx 72 KB

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