cmSystemTools.cxx 68 KB

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