cmSystemTools.cxx 75 KB

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