cmSystemTools.cxx 70 KB

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