cmSystemTools.cxx 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142
  1. /*=========================================================================
  2. Program: Insight Segmentation & Registration Toolkit
  3. Module: $RCSfile$
  4. Language: C++
  5. Date: $Date$
  6. Version: $Revision$
  7. Copyright (c) 2002 Insight Consortium. All rights reserved.
  8. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
  9. This software is distributed WITHOUT ANY WARRANTY; without even
  10. the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  11. PURPOSE. See the above copyright notices for more information.
  12. =========================================================================*/
  13. #include "cmSystemTools.h"
  14. #include "errno.h"
  15. #include "stdio.h"
  16. #include <sys/stat.h>
  17. #include "cmRegularExpression.h"
  18. #include <ctype.h>
  19. #include "cmDirectory.h"
  20. #include "cmMakefile.h"
  21. // support for realpath call
  22. #ifndef _WIN32
  23. #include <limits.h>
  24. #include <stdlib.h>
  25. #include <sys/param.h>
  26. #include <sys/wait.h>
  27. #endif
  28. #if defined(_WIN32) && (defined(_MSC_VER) || defined(__BORLANDC__))
  29. #include <string.h>
  30. #include <windows.h>
  31. #include <direct.h>
  32. #define _unlink unlink
  33. inline int Mkdir(const char* dir)
  34. {
  35. return _mkdir(dir);
  36. }
  37. inline const char* Getcwd(char* buf, unsigned int len)
  38. {
  39. return _getcwd(buf, len);
  40. }
  41. inline int Chdir(const char* dir)
  42. {
  43. #if defined(__BORLANDC__)
  44. return chdir(dir);
  45. #else
  46. return _chdir(dir);
  47. #endif
  48. }
  49. #else
  50. #include <sys/types.h>
  51. #include <fcntl.h>
  52. #include <unistd.h>
  53. inline int Mkdir(const char* dir)
  54. {
  55. return mkdir(dir, 00777);
  56. }
  57. inline const char* Getcwd(char* buf, unsigned int len)
  58. {
  59. return getcwd(buf, len);
  60. }
  61. inline int Chdir(const char* dir)
  62. {
  63. return chdir(dir);
  64. }
  65. #endif
  66. bool cmSystemTools::s_DisableRunCommandOutput = false;
  67. bool cmSystemTools::s_ErrorOccured = false;
  68. bool cmSystemTools::s_DisableMessages = false;
  69. void (*cmSystemTools::s_ErrorCallback)(const char*, const char*, bool&, void*);
  70. void* cmSystemTools::s_ErrorCallbackClientData = 0;
  71. // adds the elements of the env variable path to the arg passed in
  72. void cmSystemTools::GetPath(std::vector<std::string>& path)
  73. {
  74. #if defined(_WIN32) && !defined(__CYGWIN__)
  75. const char* pathSep = ";";
  76. #else
  77. const char* pathSep = ":";
  78. #endif
  79. std::string pathEnv = getenv("PATH");
  80. // A hack to make the below algorithm work.
  81. if(pathEnv[pathEnv.length()-1] != ':')
  82. {
  83. pathEnv += pathSep;
  84. }
  85. std::string::size_type start =0;
  86. bool done = false;
  87. while(!done)
  88. {
  89. std::string::size_type endpos = pathEnv.find(pathSep, start);
  90. if(endpos != std::string::npos)
  91. {
  92. path.push_back(pathEnv.substr(start, endpos-start));
  93. start = endpos+1;
  94. }
  95. else
  96. {
  97. done = true;
  98. }
  99. }
  100. for(std::vector<std::string>::iterator i = path.begin();
  101. i != path.end(); ++i)
  102. {
  103. cmSystemTools::ConvertToUnixSlashes(*i);
  104. }
  105. }
  106. const char* cmSystemTools::GetExecutableExtension()
  107. {
  108. #if defined(_WIN32) || defined(__CYGWIN__)
  109. return ".exe";
  110. #else
  111. return "";
  112. #endif
  113. }
  114. bool cmSystemTools::MakeDirectory(const char* path)
  115. {
  116. if(cmSystemTools::FileExists(path))
  117. {
  118. return true;
  119. }
  120. std::string dir = path;
  121. if(dir.size() == 0)
  122. {
  123. return false;
  124. }
  125. cmSystemTools::ConvertToUnixSlashes(dir);
  126. std::string::size_type pos = dir.find(':');
  127. if(pos == std::string::npos)
  128. {
  129. pos = 0;
  130. }
  131. std::string topdir;
  132. while((pos = dir.find('/', pos)) != std::string::npos)
  133. {
  134. topdir = dir.substr(0, pos);
  135. Mkdir(topdir.c_str());
  136. pos++;
  137. }
  138. if(dir[dir.size()-1] == '/')
  139. {
  140. topdir = dir.substr(0, dir.size());
  141. }
  142. else
  143. {
  144. topdir = dir;
  145. }
  146. if(Mkdir(topdir.c_str()) != 0)
  147. {
  148. // There is a bug in the Borland Run time library which makes MKDIR
  149. // return EACCES when it should return EEXISTS
  150. // if it is some other error besides directory exists
  151. // then return false
  152. if( (errno != EEXIST)
  153. #ifdef __BORLANDC__
  154. && (errno != EACCES)
  155. #endif
  156. )
  157. {
  158. cmSystemTools::Error("Faild to create directory:", path);
  159. return false;
  160. }
  161. }
  162. return true;
  163. }
  164. // replace replace with with as many times as it shows up in source.
  165. // write the result into source.
  166. void cmSystemTools::ReplaceString(std::string& source,
  167. const char* replace,
  168. const char* with)
  169. {
  170. std::string::size_type lengthReplace = strlen(replace);
  171. std::string::size_type lengthWith = strlen(with);
  172. std::string rest;
  173. std::string::size_type start = source.find(replace);
  174. while(start != std::string::npos)
  175. {
  176. rest = source.substr(start+lengthReplace);
  177. source = source.substr(0, start);
  178. source += with;
  179. source += rest;
  180. start = source.find(replace, start + lengthWith );
  181. }
  182. }
  183. // Read a registry value.
  184. // Example :
  185. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  186. // => will return the data of the "default" value of the key
  187. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  188. // => will return the data of the "Root" value of the key
  189. #if defined(_WIN32) && !defined(__CYGWIN__)
  190. bool cmSystemTools::ReadRegistryValue(const char *key, std::string &value)
  191. {
  192. std::string primary = key;
  193. std::string second;
  194. std::string valuename;
  195. size_t start = primary.find("\\");
  196. if (start == std::string::npos)
  197. {
  198. return false;
  199. }
  200. size_t valuenamepos = primary.find(";");
  201. if (valuenamepos != std::string::npos)
  202. {
  203. valuename = primary.substr(valuenamepos+1);
  204. }
  205. second = primary.substr(start+1, valuenamepos-start-1);
  206. primary = primary.substr(0, start);
  207. HKEY primaryKey;
  208. if (primary == "HKEY_CURRENT_USER")
  209. {
  210. primaryKey = HKEY_CURRENT_USER;
  211. }
  212. if (primary == "HKEY_CURRENT_CONFIG")
  213. {
  214. primaryKey = HKEY_CURRENT_CONFIG;
  215. }
  216. if (primary == "HKEY_CLASSES_ROOT")
  217. {
  218. primaryKey = HKEY_CLASSES_ROOT;
  219. }
  220. if (primary == "HKEY_LOCAL_MACHINE")
  221. {
  222. primaryKey = HKEY_LOCAL_MACHINE;
  223. }
  224. if (primary == "HKEY_USERS")
  225. {
  226. primaryKey = HKEY_USERS;
  227. }
  228. HKEY hKey;
  229. if(RegOpenKeyEx(primaryKey,
  230. second.c_str(),
  231. 0,
  232. KEY_READ,
  233. &hKey) != ERROR_SUCCESS)
  234. {
  235. return false;
  236. }
  237. else
  238. {
  239. DWORD dwType, dwSize;
  240. dwSize = 1023;
  241. char data[1024];
  242. if(RegQueryValueEx(hKey,
  243. (LPTSTR)valuename.c_str(),
  244. NULL,
  245. &dwType,
  246. (BYTE *)data,
  247. &dwSize) == ERROR_SUCCESS)
  248. {
  249. if (dwType == REG_SZ)
  250. {
  251. value = data;
  252. return true;
  253. }
  254. }
  255. }
  256. return false;
  257. }
  258. #else
  259. bool cmSystemTools::ReadRegistryValue(const char *, std::string &)
  260. {
  261. return false;
  262. }
  263. #endif
  264. // Write a registry value.
  265. // Example :
  266. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  267. // => will set the data of the "default" value of the key
  268. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  269. // => will set the data of the "Root" value of the key
  270. #if defined(_WIN32) && !defined(__CYGWIN__)
  271. bool cmSystemTools::WriteRegistryValue(const char *key, const char *value)
  272. {
  273. std::string primary = key;
  274. std::string second;
  275. std::string valuename;
  276. size_t start = primary.find("\\");
  277. if (start == std::string::npos)
  278. {
  279. return false;
  280. }
  281. size_t valuenamepos = primary.find(";");
  282. if (valuenamepos != std::string::npos)
  283. {
  284. valuename = primary.substr(valuenamepos+1);
  285. }
  286. second = primary.substr(start+1, valuenamepos-start-1);
  287. primary = primary.substr(0, start);
  288. HKEY primaryKey;
  289. if (primary == "HKEY_CURRENT_USER")
  290. {
  291. primaryKey = HKEY_CURRENT_USER;
  292. }
  293. if (primary == "HKEY_CURRENT_CONFIG")
  294. {
  295. primaryKey = HKEY_CURRENT_CONFIG;
  296. }
  297. if (primary == "HKEY_CLASSES_ROOT")
  298. {
  299. primaryKey = HKEY_CLASSES_ROOT;
  300. }
  301. if (primary == "HKEY_LOCAL_MACHINE")
  302. {
  303. primaryKey = HKEY_LOCAL_MACHINE;
  304. }
  305. if (primary == "HKEY_USERS")
  306. {
  307. primaryKey = HKEY_USERS;
  308. }
  309. HKEY hKey;
  310. DWORD dwDummy;
  311. if(RegCreateKeyEx(primaryKey,
  312. second.c_str(),
  313. 0,
  314. "",
  315. REG_OPTION_NON_VOLATILE,
  316. KEY_WRITE,
  317. NULL,
  318. &hKey,
  319. &dwDummy) != ERROR_SUCCESS)
  320. {
  321. return false;
  322. }
  323. if(RegSetValueEx(hKey,
  324. (LPTSTR)valuename.c_str(),
  325. 0,
  326. REG_SZ,
  327. (CONST BYTE *)value,
  328. (DWORD)(strlen(value) + 1)) == ERROR_SUCCESS)
  329. {
  330. return true;
  331. }
  332. return false;
  333. }
  334. #else
  335. bool cmSystemTools::WriteRegistryValue(const char *, const char *)
  336. {
  337. return false;
  338. }
  339. #endif
  340. // Delete a registry value.
  341. // Example :
  342. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  343. // => will delete the data of the "default" value of the key
  344. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  345. // => will delete the data of the "Root" value of the key
  346. #if defined(_WIN32) && !defined(__CYGWIN__)
  347. bool cmSystemTools::DeleteRegistryValue(const char *key)
  348. {
  349. std::string primary = key;
  350. std::string second;
  351. std::string valuename;
  352. size_t start = primary.find("\\");
  353. if (start == std::string::npos)
  354. {
  355. return false;
  356. }
  357. size_t valuenamepos = primary.find(";");
  358. if (valuenamepos != std::string::npos)
  359. {
  360. valuename = primary.substr(valuenamepos+1);
  361. }
  362. second = primary.substr(start+1, valuenamepos-start-1);
  363. primary = primary.substr(0, start);
  364. HKEY primaryKey;
  365. if (primary == "HKEY_CURRENT_USER")
  366. {
  367. primaryKey = HKEY_CURRENT_USER;
  368. }
  369. if (primary == "HKEY_CURRENT_CONFIG")
  370. {
  371. primaryKey = HKEY_CURRENT_CONFIG;
  372. }
  373. if (primary == "HKEY_CLASSES_ROOT")
  374. {
  375. primaryKey = HKEY_CLASSES_ROOT;
  376. }
  377. if (primary == "HKEY_LOCAL_MACHINE")
  378. {
  379. primaryKey = HKEY_LOCAL_MACHINE;
  380. }
  381. if (primary == "HKEY_USERS")
  382. {
  383. primaryKey = HKEY_USERS;
  384. }
  385. HKEY hKey;
  386. if(RegOpenKeyEx(primaryKey,
  387. second.c_str(),
  388. 0,
  389. KEY_WRITE,
  390. &hKey) != ERROR_SUCCESS)
  391. {
  392. return false;
  393. }
  394. else
  395. {
  396. if(RegDeleteValue(hKey,
  397. (LPTSTR)valuename.c_str()) == ERROR_SUCCESS)
  398. {
  399. return true;
  400. }
  401. }
  402. return false;
  403. }
  404. #else
  405. bool cmSystemTools::DeleteRegistryValue(const char *)
  406. {
  407. return false;
  408. }
  409. #endif
  410. // replace replace with with as many times as it shows up in source.
  411. // write the result into source.
  412. #if defined(_WIN32) && !defined(__CYGWIN__)
  413. void cmSystemTools::ExpandRegistryValues(std::string& source)
  414. {
  415. // Regular expression to match anything inside [...] that begins in HKEY.
  416. // Note that there is a special rule for regular expressions to match a
  417. // close square-bracket inside a list delimited by square brackets.
  418. // The "[^]]" part of this expression will match any character except
  419. // a close square-bracket. The ']' character must be the first in the
  420. // list of characters inside the [^...] block of the expression.
  421. cmRegularExpression regEntry("\\[(HKEY[^]]*)\\]");
  422. // check for black line or comment
  423. while (regEntry.find(source))
  424. {
  425. // the arguments are the second match
  426. std::string key = regEntry.match(1);
  427. std::string val;
  428. if (ReadRegistryValue(key.c_str(), val))
  429. {
  430. std::string reg = "[";
  431. reg += key + "]";
  432. cmSystemTools::ReplaceString(source, reg.c_str(), val.c_str());
  433. }
  434. else
  435. {
  436. std::string reg = "[";
  437. reg += key + "]";
  438. cmSystemTools::ReplaceString(source, reg.c_str(), "/registry");
  439. }
  440. }
  441. }
  442. #else
  443. void cmSystemTools::ExpandRegistryValues(std::string&)
  444. {
  445. }
  446. #endif
  447. std::string cmSystemTools::EscapeQuotes(const char* str)
  448. {
  449. std::string result = "";
  450. for(const char* ch = str; *ch != '\0'; ++ch)
  451. {
  452. if(*ch == '"')
  453. {
  454. result += '\\';
  455. }
  456. result += *ch;
  457. }
  458. return result;
  459. }
  460. bool cmSystemTools::SameFile(const char* file1, const char* file2)
  461. {
  462. #ifdef _WIN32
  463. HANDLE hFile1, hFile2;
  464. hFile1 = CreateFile( file1,
  465. GENERIC_READ,
  466. FILE_SHARE_READ ,
  467. NULL,
  468. OPEN_EXISTING,
  469. FILE_FLAG_BACKUP_SEMANTICS,
  470. NULL
  471. );
  472. hFile2 = CreateFile( file2,
  473. GENERIC_READ,
  474. FILE_SHARE_READ,
  475. NULL,
  476. OPEN_EXISTING,
  477. FILE_FLAG_BACKUP_SEMANTICS,
  478. NULL
  479. );
  480. if( hFile1 == INVALID_HANDLE_VALUE || hFile2 == INVALID_HANDLE_VALUE)
  481. {
  482. if(hFile1 != INVALID_HANDLE_VALUE)
  483. {
  484. CloseHandle(hFile1);
  485. }
  486. if(hFile2 != INVALID_HANDLE_VALUE)
  487. {
  488. CloseHandle(hFile2);
  489. }
  490. return false;
  491. }
  492. BY_HANDLE_FILE_INFORMATION fiBuf1;
  493. BY_HANDLE_FILE_INFORMATION fiBuf2;
  494. GetFileInformationByHandle( hFile1, &fiBuf1 );
  495. GetFileInformationByHandle( hFile2, &fiBuf2 );
  496. CloseHandle(hFile1);
  497. CloseHandle(hFile2);
  498. return (fiBuf1.nFileIndexHigh == fiBuf2.nFileIndexHigh &&
  499. fiBuf1.nFileIndexLow == fiBuf2.nFileIndexLow);
  500. #else
  501. struct stat fileStat1, fileStat2;
  502. if (stat(file1, &fileStat1) == 0 && stat(file2, &fileStat2) == 0)
  503. {
  504. // see if the files are the same file
  505. // check the device inode and size
  506. if(memcmp(&fileStat2.st_dev, &fileStat1.st_dev, sizeof(fileStat1.st_dev)) == 0 &&
  507. memcmp(&fileStat2.st_ino, &fileStat1.st_ino, sizeof(fileStat1.st_ino)) == 0 &&
  508. fileStat2.st_size == fileStat1.st_size
  509. )
  510. {
  511. return true;
  512. }
  513. }
  514. return false;
  515. #endif
  516. }
  517. // return true if the file exists
  518. bool cmSystemTools::FileExists(const char* filename)
  519. {
  520. struct stat fs;
  521. if (stat(filename, &fs) != 0)
  522. {
  523. return false;
  524. }
  525. else
  526. {
  527. return true;
  528. }
  529. }
  530. // Return a capitalized string (i.e the first letter is uppercased, all other
  531. // are lowercased)
  532. std::string cmSystemTools::Capitalized(const std::string& s)
  533. {
  534. std::string n;
  535. n.resize(s.size());
  536. n[0] = toupper(s[0]);
  537. for (size_t i = 1; i < s.size(); i++)
  538. {
  539. n[i] = tolower(s[i]);
  540. }
  541. return n;
  542. }
  543. // Return a lower case string
  544. std::string cmSystemTools::LowerCase(const std::string& s)
  545. {
  546. std::string n;
  547. n.resize(s.size());
  548. for (size_t i = 0; i < s.size(); i++)
  549. {
  550. n[i] = tolower(s[i]);
  551. }
  552. return n;
  553. }
  554. // Return a lower case string
  555. std::string cmSystemTools::UpperCase(const std::string& s)
  556. {
  557. std::string n;
  558. n.resize(s.size());
  559. for (size_t i = 0; i < s.size(); i++)
  560. {
  561. n[i] = toupper(s[i]);
  562. }
  563. return n;
  564. }
  565. // convert windows slashes to unix slashes
  566. void cmSystemTools::ConvertToUnixSlashes(std::string& path)
  567. {
  568. std::string::size_type pos = 0;
  569. while((pos = path.find('\\', pos)) != std::string::npos)
  570. {
  571. path[pos] = '/';
  572. pos++;
  573. }
  574. // remove any trailing slash
  575. if(path.size() && path[path.size()-1] == '/')
  576. {
  577. path = path.substr(0, path.size()-1);
  578. }
  579. // if there is a tilda ~ then replace it with HOME
  580. if(path.find("~") == 0)
  581. {
  582. if (getenv("HOME"))
  583. {
  584. path = std::string(getenv("HOME")) + path.substr(1);
  585. }
  586. }
  587. // if there is a /tmp_mnt in a path get rid of it!
  588. // stupid sgi's
  589. if(path.find("/tmp_mnt") == 0)
  590. {
  591. path = path.substr(8);
  592. }
  593. }
  594. // change // to /, and escape any spaces in the path
  595. std::string cmSystemTools::ConvertToUnixOutputPath(const char* path)
  596. {
  597. std::string ret = path;
  598. // remove // except at the beginning might be a cygwin drive
  599. std::string::size_type pos = 1;
  600. while((pos = ret.find("//", pos)) != std::string::npos)
  601. {
  602. ret.erase(pos, 1);
  603. }
  604. // now escape spaces if there is a space in the path
  605. if(ret.find(" ") != std::string::npos)
  606. {
  607. std::string result = "";
  608. char lastch = 1;
  609. for(const char* ch = ret.c_str(); *ch != '\0'; ++ch)
  610. {
  611. // if it is already escaped then don't try to escape it again
  612. if(*ch == ' ' && lastch != '\\')
  613. {
  614. result += '\\';
  615. }
  616. result += *ch;
  617. lastch = *ch;
  618. }
  619. ret = result;
  620. }
  621. return ret;
  622. }
  623. std::string cmSystemTools::EscapeSpaces(const char* str)
  624. {
  625. #if defined(_WIN32) && !defined(__CYGWIN__)
  626. std::string result;
  627. // if there are spaces
  628. std::string temp = str;
  629. if (temp.find(" ") != std::string::npos &&
  630. temp.find("\"")==std::string::npos)
  631. {
  632. result = "\"";
  633. result += str;
  634. result += "\"";
  635. return result;
  636. }
  637. return str;
  638. #else
  639. std::string result = "";
  640. for(const char* ch = str; *ch != '\0'; ++ch)
  641. {
  642. if(*ch == ' ')
  643. {
  644. result += '\\';
  645. }
  646. result += *ch;
  647. }
  648. return result;
  649. #endif
  650. }
  651. std::string cmSystemTools::ConvertToOutputPath(const char* path)
  652. {
  653. #if defined(_WIN32) && !defined(__CYGWIN__)
  654. return cmSystemTools::ConvertToWindowsOutputPath(path);
  655. #else
  656. return cmSystemTools::ConvertToUnixOutputPath(path);
  657. #endif
  658. }
  659. // remove double slashes not at the start
  660. std::string cmSystemTools::ConvertToWindowsOutputPath(const char* path)
  661. {
  662. std::string ret = path;
  663. std::string::size_type pos = 0;
  664. // first convert all of the slashes
  665. while((pos = ret.find('/', pos)) != std::string::npos)
  666. {
  667. ret[pos] = '\\';
  668. pos++;
  669. }
  670. // check for really small paths
  671. if(ret.size() < 2)
  672. {
  673. return ret;
  674. }
  675. // now clean up a bit and remove double slashes
  676. // Only if it is not the first position in the path which is a network
  677. // path on windows
  678. pos = 1; // start at position 1
  679. while((pos = ret.find("\\\\", pos)) != std::string::npos)
  680. {
  681. ret.erase(pos, 1);
  682. }
  683. // now double quote the path if it has spaces in it
  684. // and is not already double quoted
  685. if(ret.find(" ") != std::string::npos
  686. && ret[0] != '\"')
  687. {
  688. std::string result;
  689. result = "\"" + ret + "\"";
  690. ret = result;
  691. }
  692. return ret;
  693. }
  694. inline void RemoveComments(char* ptr)
  695. {
  696. while(*ptr)
  697. {
  698. if(*ptr == '#')
  699. {
  700. *ptr = 0;
  701. break;
  702. }
  703. ++ptr;
  704. }
  705. }
  706. bool cmSystemTools::ParseFunction(std::ifstream& fin,
  707. std::string& name,
  708. std::vector<std::string>& arguments,
  709. const char* filename,
  710. bool& parseError)
  711. {
  712. parseError = false;
  713. name = "";
  714. arguments = std::vector<std::string>();
  715. const int BUFFER_SIZE = 4096;
  716. char inbuffer[BUFFER_SIZE];
  717. if(!fin)
  718. {
  719. return false;
  720. }
  721. if(fin.getline(inbuffer, BUFFER_SIZE ) )
  722. {
  723. RemoveComments(inbuffer);
  724. cmRegularExpression blankLine("^[ \t\r]*$");
  725. // cmRegularExpression comment("^[ \t]*#.*$");
  726. cmRegularExpression oneLiner("^[ \t]*([A-Za-z_0-9]*)[ \t]*\\((.*)\\)[ \t\r]*$");
  727. cmRegularExpression multiLine("^[ \t]*([A-Za-z_0-9]*)[ \t]*\\((.*)$");
  728. cmRegularExpression lastLine("^(.*)\\)[ \t\r]*$");
  729. // check for blank line or comment
  730. if(blankLine.find(inbuffer) )
  731. {
  732. return false;
  733. }
  734. // look for a oneline fun(arg arg2)
  735. else if(oneLiner.find(inbuffer))
  736. {
  737. // the arguments are the second match
  738. std::string args = oneLiner.match(2);
  739. name = oneLiner.match(1);
  740. // break up the arguments
  741. cmSystemTools::GetArguments(args, arguments);
  742. return true;
  743. }
  744. // look for a start of a multiline with no trailing ")" fun(arg arg2
  745. else if(multiLine.find(inbuffer))
  746. {
  747. name = multiLine.match(1);
  748. std::string args = multiLine.match(2);
  749. cmSystemTools::GetArguments(args, arguments);
  750. // Read lines until the closing paren is hit
  751. bool done = false;
  752. while(!done)
  753. {
  754. // read lines until the end paren is found
  755. if(fin.getline(inbuffer, BUFFER_SIZE ) )
  756. {
  757. RemoveComments(inbuffer);
  758. // Check for comment lines and ignore them.
  759. if(blankLine.find(inbuffer))
  760. { continue; }
  761. // Is this the last line?
  762. if(lastLine.find(inbuffer))
  763. {
  764. done = true;
  765. std::string args = lastLine.match(1);
  766. cmSystemTools::GetArguments(args, arguments);
  767. }
  768. else
  769. {
  770. std::string line = inbuffer;
  771. cmSystemTools::GetArguments(line, arguments);
  772. }
  773. }
  774. else
  775. {
  776. parseError = true;
  777. cmSystemTools::Error("Parse error in read function missing end )\nIn File: ",
  778. filename, "\nCurrent line:", inbuffer);
  779. return false;
  780. }
  781. }
  782. return true;
  783. }
  784. else
  785. {
  786. parseError = true;
  787. cmSystemTools::Error("Parse error in read function\nIn file:",
  788. filename, "\nCurrent line:", inbuffer);
  789. return false;
  790. }
  791. }
  792. return false;
  793. }
  794. void cmSystemTools::GetArguments(std::string& line,
  795. std::vector<std::string>& arguments)
  796. {
  797. // Match a normal argument (not quoted, no spaces).
  798. cmRegularExpression normalArgument("[ \t]*(([^ \t\r\\]|[\\].)+)[ \t\r]*");
  799. // Match a quoted argument (surrounded by double quotes, spaces allowed).
  800. cmRegularExpression quotedArgument("[ \t]*(\"([^\"\\]|[\\].)*\")[ \t\r]*");
  801. bool done = false;
  802. while(!done)
  803. {
  804. std::string arg;
  805. std::string::size_type endpos=0;
  806. bool foundQuoted = quotedArgument.find(line.c_str());
  807. bool foundNormal = normalArgument.find(line.c_str());
  808. if(foundQuoted && foundNormal)
  809. {
  810. // Both matches were found. Take the earlier one.
  811. // Favor double-quoted version if there is a tie.
  812. if(normalArgument.start(1) < quotedArgument.start(1))
  813. {
  814. arg = normalArgument.match(1);
  815. endpos = normalArgument.end(1);
  816. }
  817. else
  818. {
  819. arg = quotedArgument.match(1);
  820. endpos = quotedArgument.end(1);
  821. // Strip off the double quotes on the ends.
  822. arg = arg.substr(1, arg.length()-2);
  823. }
  824. }
  825. else if (foundQuoted)
  826. {
  827. arg = quotedArgument.match(1);
  828. endpos = quotedArgument.end(1);
  829. // Strip off the double quotes on the ends.
  830. arg = arg.substr(1, arg.length()-2);
  831. }
  832. else if(foundNormal)
  833. {
  834. arg = normalArgument.match(1);
  835. endpos = normalArgument.end(1);
  836. }
  837. else
  838. {
  839. done = true;
  840. }
  841. if(!done)
  842. {
  843. arguments.push_back(cmSystemTools::RemoveEscapes(arg.c_str()));
  844. line = line.substr(endpos, line.length() - endpos);
  845. }
  846. }
  847. }
  848. std::string cmSystemTools::RemoveEscapes(const char* s)
  849. {
  850. std::string result = "";
  851. for(const char* ch = s; *ch; ++ch)
  852. {
  853. if(*ch == '\\' && *(ch+1) != ';')
  854. {
  855. ++ch;
  856. switch (*ch)
  857. {
  858. case '\\': result.insert(result.end(), '\\'); break;
  859. case '"': result.insert(result.end(), '"'); break;
  860. case ' ': result.insert(result.end(), ' '); break;
  861. case 't': result.insert(result.end(), '\t'); break;
  862. case 'n': result.insert(result.end(), '\n'); break;
  863. case 'r': result.insert(result.end(), '\r'); break;
  864. case '0': result.insert(result.end(), '\0'); break;
  865. case '\0':
  866. {
  867. cmSystemTools::Error("Trailing backslash in argument:\n", s);
  868. return result;
  869. }
  870. default:
  871. {
  872. std::string chStr(1, *ch);
  873. cmSystemTools::Error("Invalid escape sequence \\", chStr.c_str(),
  874. "\nin argument ", s);
  875. }
  876. }
  877. }
  878. else
  879. {
  880. result.insert(result.end(), *ch);
  881. }
  882. }
  883. return result;
  884. }
  885. void cmSystemTools::Error(const char* m1, const char* m2,
  886. const char* m3, const char* m4)
  887. {
  888. std::string message = "CMake Error: ";
  889. if(m1)
  890. {
  891. message += m1;
  892. }
  893. if(m2)
  894. {
  895. message += m2;
  896. }
  897. if(m3)
  898. {
  899. message += m3;
  900. }
  901. if(m4)
  902. {
  903. message += m4;
  904. }
  905. cmSystemTools::s_ErrorOccured = true;
  906. cmSystemTools::Message(message.c_str(),"Error");
  907. }
  908. void cmSystemTools::SetErrorCallback(ErrorCallback f, void* clientData)
  909. {
  910. s_ErrorCallback = f;
  911. s_ErrorCallbackClientData = clientData;
  912. }
  913. void cmSystemTools::Message(const char* m1, const char *title)
  914. {
  915. if(s_DisableMessages)
  916. {
  917. return;
  918. }
  919. if(s_ErrorCallback)
  920. {
  921. (*s_ErrorCallback)(m1, title, s_DisableMessages, s_ErrorCallbackClientData);
  922. return;
  923. }
  924. else
  925. {
  926. std::cerr << m1 << std::endl;
  927. }
  928. }
  929. bool cmSystemTools::CopyFileIfDifferent(const char* source,
  930. const char* destination)
  931. {
  932. if(cmSystemTools::FilesDiffer(source, destination))
  933. {
  934. cmSystemTools::cmCopyFile(source, destination);
  935. return true;
  936. }
  937. return false;
  938. }
  939. bool cmSystemTools::FilesDiffer(const char* source,
  940. const char* destination)
  941. {
  942. struct stat statSource;
  943. if (stat(source, &statSource) != 0)
  944. {
  945. return true;
  946. }
  947. struct stat statDestination;
  948. if (stat(destination, &statDestination) != 0)
  949. {
  950. return true;
  951. }
  952. if(statSource.st_size != statDestination.st_size)
  953. {
  954. return true;
  955. }
  956. if(statSource.st_size == 0)
  957. {
  958. return false;
  959. }
  960. #if defined(_WIN32) || defined(__CYGWIN__)
  961. std::ifstream finSource(source,
  962. std::ios::binary | std::ios::in);
  963. std::ifstream finDestination(destination,
  964. std::ios::binary | std::ios::in);
  965. #else
  966. std::ifstream finSource(source);
  967. std::ifstream finDestination(destination);
  968. #endif
  969. if(!finSource || !finDestination)
  970. {
  971. return true;
  972. }
  973. char* source_buf = new char[statSource.st_size];
  974. char* dest_buf = new char[statSource.st_size];
  975. finSource.read(source_buf, statSource.st_size);
  976. finDestination.read(dest_buf, statSource.st_size);
  977. if(statSource.st_size != static_cast<long>(finSource.gcount()) ||
  978. statSource.st_size != static_cast<long>(finDestination.gcount()))
  979. {
  980. cmStringStream msg;
  981. msg << "FilesDiffer failed to read files (allocated: "
  982. << statSource.st_size << ", read source: " << finSource.gcount()
  983. << ", read dest: " << finDestination.gcount();
  984. cmSystemTools::Error(msg.str().c_str());
  985. delete [] source_buf;
  986. delete [] dest_buf;
  987. return false;
  988. }
  989. int ret = memcmp((const void*)source_buf,
  990. (const void*)dest_buf,
  991. statSource.st_size);
  992. delete [] dest_buf;
  993. delete [] source_buf;
  994. return ret != 0;
  995. }
  996. /**
  997. * Copy a file named by "source" to the file named by "destination".
  998. */
  999. void cmSystemTools::cmCopyFile(const char* source,
  1000. const char* destination)
  1001. {
  1002. const int bufferSize = 4096;
  1003. char buffer[bufferSize];
  1004. // If destination is a directory, try to create a file with the same
  1005. // name as the source in that directory.
  1006. std::string new_destination;
  1007. if(cmSystemTools::FileExists(destination) &&
  1008. cmSystemTools::FileIsDirectory(destination))
  1009. {
  1010. new_destination = destination;
  1011. cmSystemTools::ConvertToUnixSlashes(new_destination);
  1012. new_destination += '/';
  1013. std::string source_name = source;
  1014. new_destination += cmSystemTools::GetFilenameName(source_name);
  1015. destination = new_destination.c_str();
  1016. }
  1017. // Create destination directory
  1018. std::string destination_dir = destination;
  1019. destination_dir = cmSystemTools::GetFilenamePath(destination_dir);
  1020. cmSystemTools::MakeDirectory(destination_dir.c_str());
  1021. // Open files
  1022. #if defined(_WIN32) || defined(__CYGWIN__)
  1023. std::ifstream fin(source,
  1024. std::ios::binary | std::ios::in);
  1025. #else
  1026. std::ifstream fin(source);
  1027. #endif
  1028. if(!fin)
  1029. {
  1030. cmSystemTools::Error("CopyFile failed to open input file \"",
  1031. source, "\"");
  1032. return;
  1033. }
  1034. #if defined(_WIN32) || defined(__CYGWIN__)
  1035. std::ofstream fout(destination,
  1036. std::ios::binary | std::ios::out | std::ios::trunc);
  1037. #else
  1038. std::ofstream fout(destination,
  1039. std::ios::out | std::ios::trunc);
  1040. #endif
  1041. if(!fout)
  1042. {
  1043. cmSystemTools::Error("CopyFile failed to open output file \"",
  1044. destination, "\"");
  1045. return;
  1046. }
  1047. // This copy loop is very sensitive on certain platforms with
  1048. // slightly broken stream libraries (like HPUX). Normally, it is
  1049. // incorrect to not check the error condition on the fin.read()
  1050. // before using the data, but the fin.gcount() will be zero if an
  1051. // error occurred. Therefore, the loop should be safe everywhere.
  1052. while(fin)
  1053. {
  1054. fin.read(buffer, bufferSize);
  1055. if(fin.gcount())
  1056. {
  1057. fout.write(buffer, fin.gcount());
  1058. }
  1059. }
  1060. fin.close();
  1061. fout.close();
  1062. // More checks
  1063. struct stat statSource, statDestination;
  1064. if (stat(source, &statSource) != 0 ||
  1065. stat(destination, &statDestination) != 0)
  1066. {
  1067. cmSystemTools::Error("CopyFile failed to copy files!");
  1068. }
  1069. if (statSource.st_size != statDestination.st_size)
  1070. {
  1071. cmStringStream msg;
  1072. msg << "CopyFile failed to copy files (sizes differ, source: "
  1073. << statSource.st_size << " , dest: " << statDestination.st_size;
  1074. cmSystemTools::Error(msg.str().c_str());
  1075. }
  1076. }
  1077. // return true if the file exists
  1078. long int cmSystemTools::ModifiedTime(const char* filename)
  1079. {
  1080. struct stat fs;
  1081. if (stat(filename, &fs) != 0)
  1082. {
  1083. return 0;
  1084. }
  1085. else
  1086. {
  1087. return (long int)fs.st_mtime;
  1088. }
  1089. }
  1090. bool cmSystemTools::RemoveFile(const char* source)
  1091. {
  1092. return unlink(source) != 0 ? false : true;
  1093. }
  1094. bool cmSystemTools::IsOn(const char* val)
  1095. {
  1096. if (!val)
  1097. {
  1098. return false;
  1099. }
  1100. std::basic_string<char> v = val;
  1101. for(std::basic_string<char>::iterator c = v.begin();
  1102. c != v.end(); c++)
  1103. {
  1104. *c = toupper(*c);
  1105. }
  1106. return (v == "ON" || v == "1" || v == "YES" || v == "TRUE" || v == "Y");
  1107. }
  1108. bool cmSystemTools::IsOff(const char* val)
  1109. {
  1110. if (!val || strlen(val) == 0)
  1111. {
  1112. return true;
  1113. }
  1114. std::basic_string<char> v = val;
  1115. for(std::basic_string<char>::iterator c = v.begin();
  1116. c != v.end(); c++)
  1117. {
  1118. *c = toupper(*c);
  1119. }
  1120. return (v == "OFF" || v == "0" || v == "NO" || v == "FALSE" ||
  1121. v == "N" || v == "NOTFOUND" || v == "IGNORE");
  1122. }
  1123. bool cmSystemTools::RunCommand(const char* command,
  1124. std::string& output,
  1125. const char* dir,
  1126. bool verbose)
  1127. {
  1128. int foo;
  1129. return cmSystemTools::RunCommand(command, output, foo, dir, verbose);
  1130. }
  1131. #if defined(WIN32) && !defined(__CYGWIN__)
  1132. // use this for shell commands like echo and dir
  1133. bool RunCommandViaSystem(const char* command,
  1134. const char* dir,
  1135. std::string& output,
  1136. int& retVal,
  1137. bool verbose)
  1138. {
  1139. const int BUFFER_SIZE = 4096;
  1140. char buffer[BUFFER_SIZE];
  1141. std::string commandInDir;
  1142. if(dir)
  1143. {
  1144. commandInDir = "cd ";
  1145. commandInDir += cmSystemTools::ConvertToOutputPath(dir);
  1146. commandInDir += " && ";
  1147. commandInDir += command;
  1148. }
  1149. else
  1150. {
  1151. commandInDir = command;
  1152. }
  1153. command = commandInDir.c_str();
  1154. std::string commandToFile = command;
  1155. commandToFile += " > ";
  1156. std::string tempFile;
  1157. tempFile += _tempnam(0, "cmake");
  1158. commandToFile += tempFile;
  1159. retVal = system(commandToFile.c_str());
  1160. std::ifstream fin(tempFile.c_str());
  1161. if(!fin)
  1162. {
  1163. if(verbose)
  1164. {
  1165. std::string errormsg = "RunCommand produced no output: command: \"";
  1166. errormsg += command;
  1167. errormsg += "\"";
  1168. errormsg += "\nOutput file: ";
  1169. errormsg += tempFile;
  1170. cmSystemTools::Error(errormsg.c_str());
  1171. }
  1172. fin.close();
  1173. cmSystemTools::RemoveFile(tempFile.c_str());
  1174. return false;
  1175. }
  1176. bool multiLine = false;
  1177. while(fin)
  1178. {
  1179. fin.getline(buffer, BUFFER_SIZE);
  1180. output += buffer;
  1181. if(multiLine)
  1182. {
  1183. output += "\n";
  1184. }
  1185. multiLine = true;
  1186. }
  1187. fin.close();
  1188. cmSystemTools::RemoveFile(tempFile.c_str());
  1189. return true;
  1190. }
  1191. #endif // endif WIN32 not CYGWIN
  1192. // run a command unix uses popen (easy)
  1193. // windows uses system and ShortPath
  1194. bool cmSystemTools::RunCommand(const char* command,
  1195. std::string& output,
  1196. int &retVal,
  1197. const char* dir,
  1198. bool verbose)
  1199. {
  1200. if(s_DisableRunCommandOutput)
  1201. {
  1202. verbose = false;
  1203. }
  1204. #if defined(WIN32) && !defined(__CYGWIN__)
  1205. // if the command does not start with a quote, then
  1206. // try to find the program, and if the program can not be
  1207. // found use system to run the command as it must be a built in
  1208. // shell command like echo or dir
  1209. int count = 0;
  1210. if(command[0] == '\"')
  1211. {
  1212. // count the number of quotes
  1213. for(const char* s = command; *s != 0; ++s)
  1214. {
  1215. if(*s == '\"')
  1216. {
  1217. count++;
  1218. if(count > 2)
  1219. {
  1220. break;
  1221. }
  1222. }
  1223. }
  1224. // if there are more than two double quotes use
  1225. // GetShortPathName, the cmd.exe program in windows which
  1226. // is used by system fails to execute if there are more than
  1227. // one set of quotes in the arguments
  1228. if(count > 2)
  1229. {
  1230. cmRegularExpression quoted("^\"([^\"]*)\"[ \t](.*)");
  1231. if(quoted.find(command))
  1232. {
  1233. std::string shortCmd;
  1234. std::string cmd = quoted.match(1);
  1235. std::string args = quoted.match(2);
  1236. if(!cmSystemTools::GetShortPath(cmd.c_str(), shortCmd))
  1237. {
  1238. cmSystemTools::Error("GetShortPath failed for " , cmd.c_str());
  1239. return false;
  1240. }
  1241. shortCmd += " ";
  1242. shortCmd += args;
  1243. return RunCommandViaSystem(shortCmd.c_str(), dir,
  1244. output, retVal, verbose);
  1245. }
  1246. else
  1247. {
  1248. cmSystemTools::Error("Could not parse command line with quotes ",
  1249. command);
  1250. }
  1251. }
  1252. }
  1253. // if there is only one set of quotes or no quotes then just run the command
  1254. return RunCommandViaSystem(command, dir, output, retVal, verbose);
  1255. #else
  1256. // if only popen worked on windows.....
  1257. std::string commandInDir;
  1258. if(dir)
  1259. {
  1260. commandInDir = "cd ";
  1261. commandInDir += dir;
  1262. commandInDir += " && ";
  1263. commandInDir += command;
  1264. }
  1265. else
  1266. {
  1267. commandInDir = command;
  1268. }
  1269. commandInDir += " 2>&1";
  1270. command = commandInDir.c_str();
  1271. const int BUFFER_SIZE = 4096;
  1272. char buffer[BUFFER_SIZE];
  1273. if(verbose)
  1274. {
  1275. std::cout << "running " << command << std::endl;
  1276. }
  1277. fflush(stdout);
  1278. fflush(stderr);
  1279. FILE* cpipe = popen(command, "r");
  1280. if(!cpipe)
  1281. {
  1282. return false;
  1283. }
  1284. fgets(buffer, BUFFER_SIZE, cpipe);
  1285. while(!feof(cpipe))
  1286. {
  1287. if(verbose)
  1288. {
  1289. std::cout << buffer << std::flush;
  1290. }
  1291. output += buffer;
  1292. fgets(buffer, BUFFER_SIZE, cpipe);
  1293. }
  1294. retVal = pclose(cpipe);
  1295. if (WIFEXITED(retVal))
  1296. {
  1297. retVal = WEXITSTATUS(retVal);
  1298. return true;
  1299. }
  1300. if (WIFSIGNALED(retVal))
  1301. {
  1302. retVal = WTERMSIG(retVal);
  1303. cmStringStream error;
  1304. error << "\nProcess terminated due to ";
  1305. switch (retVal)
  1306. {
  1307. #ifdef SIGKILL
  1308. case SIGKILL:
  1309. error << "SIGKILL";
  1310. break;
  1311. #endif
  1312. #ifdef SIGFPE
  1313. case SIGFPE:
  1314. error << "SIGFPE";
  1315. break;
  1316. #endif
  1317. #ifdef SIGBUS
  1318. case SIGBUS:
  1319. error << "SIGBUS";
  1320. break;
  1321. #endif
  1322. #ifdef SIGSEGV
  1323. case SIGSEGV:
  1324. error << "SIGSEGV";
  1325. break;
  1326. #endif
  1327. default:
  1328. error << "signal " << retVal;
  1329. break;
  1330. }
  1331. output += error.str();
  1332. }
  1333. return false;
  1334. #endif
  1335. }
  1336. /**
  1337. * Find the file the given name. Searches the given path and then
  1338. * the system search path. Returns the full path to the file if it is
  1339. * found. Otherwise, the empty string is returned.
  1340. */
  1341. std::string cmSystemTools::FindFile(const char* name,
  1342. const std::vector<std::string>& userPaths)
  1343. {
  1344. // Add the system search path to our path.
  1345. std::vector<std::string> path = userPaths;
  1346. cmSystemTools::GetPath(path);
  1347. std::string tryPath;
  1348. for(std::vector<std::string>::const_iterator p = path.begin();
  1349. p != path.end(); ++p)
  1350. {
  1351. tryPath = *p;
  1352. tryPath += "/";
  1353. tryPath += name;
  1354. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1355. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1356. {
  1357. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1358. }
  1359. }
  1360. // Couldn't find the file.
  1361. return "";
  1362. }
  1363. /**
  1364. * Find the executable with the given name. Searches the given path and then
  1365. * the system search path. Returns the full path to the executable if it is
  1366. * found. Otherwise, the empty string is returned.
  1367. */
  1368. std::string cmSystemTools::FindProgram(const char* name,
  1369. const std::vector<std::string>& userPaths,
  1370. bool no_system_path)
  1371. {
  1372. // See if the executable exists as written.
  1373. if(cmSystemTools::FileExists(name) &&
  1374. !cmSystemTools::FileIsDirectory(name))
  1375. {
  1376. return cmSystemTools::CollapseFullPath(name);
  1377. }
  1378. std::string tryPath = name;
  1379. tryPath += cmSystemTools::GetExecutableExtension();
  1380. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1381. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1382. {
  1383. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1384. }
  1385. // Add the system search path to our path.
  1386. std::vector<std::string> path = userPaths;
  1387. if (!no_system_path)
  1388. {
  1389. cmSystemTools::GetPath(path);
  1390. }
  1391. for(std::vector<std::string>::const_iterator p = path.begin();
  1392. p != path.end(); ++p)
  1393. {
  1394. tryPath = *p;
  1395. tryPath += "/";
  1396. tryPath += name;
  1397. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1398. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1399. {
  1400. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1401. }
  1402. #ifdef _WIN32
  1403. tryPath += ".com";
  1404. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1405. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1406. {
  1407. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1408. }
  1409. tryPath = *p;
  1410. tryPath += "/";
  1411. tryPath += name;
  1412. #endif
  1413. tryPath += cmSystemTools::GetExecutableExtension();
  1414. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1415. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1416. {
  1417. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1418. }
  1419. }
  1420. // Couldn't find the program.
  1421. return "";
  1422. }
  1423. /**
  1424. * Find the library with the given name. Searches the given path and then
  1425. * the system search path. Returns the full path to the library if it is
  1426. * found. Otherwise, the empty string is returned.
  1427. */
  1428. std::string cmSystemTools::FindLibrary(const char* name,
  1429. const std::vector<std::string>& userPaths,
  1430. const cmMakefile *makefile)
  1431. {
  1432. // See if the executable exists as written.
  1433. if(cmSystemTools::FileExists(name))
  1434. {
  1435. return cmSystemTools::CollapseFullPath(name);
  1436. }
  1437. // Add the system search path to our path.
  1438. std::vector<std::string> path = userPaths;
  1439. cmSystemTools::GetPath(path);
  1440. // Add some lib directories specific to compilers, depending on the
  1441. // current generator, so that library that might have been stored here
  1442. // can be found too.
  1443. // i.e. Microsoft Visual Studio or .Net: path to compiler/../Lib
  1444. // Borland: path to compiler/../Lib
  1445. if (makefile)
  1446. {
  1447. const char* genName = makefile->GetDefinition("CMAKE_GENERATOR");
  1448. if (genName)
  1449. {
  1450. if (!strcmp(genName, "NMake Makefiles") ||
  1451. !strcmp(genName, "Visual Studio 6"))
  1452. {
  1453. const char* compiler = makefile->GetDefinition("CMAKE_CXX_COMPILER");
  1454. if (compiler)
  1455. {
  1456. std::string compiler_path = cmSystemTools::FindProgram(compiler);
  1457. if (compiler_path.size())
  1458. {
  1459. std::string lib_path =
  1460. cmSystemTools::GetFilenamePath(
  1461. cmSystemTools::GetFilenamePath(compiler_path)) + "/Lib";
  1462. path.push_back(lib_path);
  1463. }
  1464. }
  1465. }
  1466. else if (!strcmp(genName, "Visual Studio 7"))
  1467. {
  1468. // It is likely that the compiler won't be in the path for .Net, but
  1469. // we know where devenv is.
  1470. const char* devenv = makefile->GetDefinition("MICROSOFT_DEVENV");
  1471. if (devenv)
  1472. {
  1473. std::string devenv_path = cmSystemTools::FindProgram(devenv);
  1474. if (devenv_path.size())
  1475. {
  1476. std::string vc7_path =
  1477. cmSystemTools::GetFilenamePath(
  1478. cmSystemTools::GetFilenamePath(
  1479. cmSystemTools::GetFilenamePath(devenv_path))) + "/Vc7";
  1480. path.push_back(vc7_path + "/lib");
  1481. path.push_back(vc7_path + "/PlatformSDK/lib");
  1482. }
  1483. }
  1484. }
  1485. else if (!strcmp(genName, "Borland Makefiles"))
  1486. {
  1487. const char* bcb_bin_path = makefile->GetDefinition("BCB_BIN_PATH");
  1488. if (bcb_bin_path)
  1489. {
  1490. std::string lib_path =
  1491. cmSystemTools::GetFilenamePath(bcb_bin_path) + "/Lib";
  1492. path.push_back(lib_path);
  1493. }
  1494. }
  1495. }
  1496. }
  1497. std::string tryPath;
  1498. for(std::vector<std::string>::const_iterator p = path.begin();
  1499. p != path.end(); ++p)
  1500. {
  1501. #if defined(_WIN32) && !defined(__CYGWIN__)
  1502. tryPath = *p;
  1503. tryPath += "/";
  1504. tryPath += name;
  1505. tryPath += ".lib";
  1506. if(cmSystemTools::FileExists(tryPath.c_str()))
  1507. {
  1508. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1509. }
  1510. #else
  1511. tryPath = *p;
  1512. tryPath += "/lib";
  1513. tryPath += name;
  1514. tryPath += ".so";
  1515. if(cmSystemTools::FileExists(tryPath.c_str()))
  1516. {
  1517. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1518. }
  1519. tryPath = *p;
  1520. tryPath += "/lib";
  1521. tryPath += name;
  1522. tryPath += ".a";
  1523. if(cmSystemTools::FileExists(tryPath.c_str()))
  1524. {
  1525. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1526. }
  1527. tryPath = *p;
  1528. tryPath += "/lib";
  1529. tryPath += name;
  1530. tryPath += ".sl";
  1531. if(cmSystemTools::FileExists(tryPath.c_str()))
  1532. {
  1533. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1534. }
  1535. #endif
  1536. }
  1537. // Couldn't find the library.
  1538. return "";
  1539. }
  1540. bool cmSystemTools::FileIsDirectory(const char* name)
  1541. {
  1542. struct stat fs;
  1543. if(stat(name, &fs) == 0)
  1544. {
  1545. #if _WIN32
  1546. return ((fs.st_mode & _S_IFDIR) != 0);
  1547. #else
  1548. return S_ISDIR(fs.st_mode);
  1549. #endif
  1550. }
  1551. else
  1552. {
  1553. return false;
  1554. }
  1555. }
  1556. int cmSystemTools::ChangeDirectory(const char *dir)
  1557. {
  1558. return Chdir(dir);
  1559. }
  1560. std::string cmSystemTools::GetCurrentWorkingDirectory()
  1561. {
  1562. char buf[2048];
  1563. std::string path = Getcwd(buf, 2048);
  1564. return path;
  1565. }
  1566. /**
  1567. * Given the path to a program executable, get the directory part of the path with the
  1568. * file stripped off. If there is no directory part, the empty string is returned.
  1569. */
  1570. std::string cmSystemTools::GetProgramPath(const char* in_name)
  1571. {
  1572. std::string dir, file;
  1573. cmSystemTools::SplitProgramPath(in_name, dir, file);
  1574. return dir;
  1575. }
  1576. /**
  1577. * Given the path to a program executable, get the directory part of the path
  1578. * with the file stripped off. If there is no directory part, the empty
  1579. * string is returned.
  1580. */
  1581. void cmSystemTools::SplitProgramPath(const char* in_name,
  1582. std::string& dir,
  1583. std::string& file)
  1584. {
  1585. dir = in_name;
  1586. file = "";
  1587. cmSystemTools::ConvertToUnixSlashes(dir);
  1588. if(!cmSystemTools::FileIsDirectory(dir.c_str()))
  1589. {
  1590. std::string::size_type slashPos = dir.rfind("/");
  1591. if(slashPos != std::string::npos)
  1592. {
  1593. file = dir.substr(slashPos+1);
  1594. dir = dir.substr(0, slashPos);
  1595. }
  1596. else
  1597. {
  1598. file = dir;
  1599. dir = "";
  1600. }
  1601. }
  1602. if((dir != "") && !cmSystemTools::FileIsDirectory(dir.c_str()))
  1603. {
  1604. std::string oldDir = in_name;
  1605. cmSystemTools::ConvertToUnixSlashes(oldDir);
  1606. cmSystemTools::Error("Error splitting file name off end of path:\n",
  1607. oldDir.c_str(), "\nDirectory not found: ",
  1608. dir.c_str());
  1609. dir = in_name;
  1610. return;
  1611. }
  1612. }
  1613. /**
  1614. * Given a path to a file or directory, convert it to a full path.
  1615. * This collapses away relative paths. The full path is returned.
  1616. */
  1617. std::string cmSystemTools::CollapseFullPath(const char* in_name)
  1618. {
  1619. std::string dir, file;
  1620. cmSystemTools::SplitProgramPath(in_name, dir, file);
  1621. #ifdef _WIN32
  1622. // Ultra-hack warning:
  1623. // This changes to the target directory, saves the working directory,
  1624. // and then changes back to the original working directory.
  1625. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1626. if(dir != "") { Chdir(dir.c_str()); }
  1627. std::string newDir = cmSystemTools::GetCurrentWorkingDirectory();
  1628. Chdir(cwd.c_str());
  1629. cmSystemTools::ConvertToUnixSlashes(newDir);
  1630. std::string newPath = newDir+"/"+file;
  1631. return newPath;
  1632. #else
  1633. # ifdef MAXPATHLEN
  1634. char resolved_name[MAXPATHLEN];
  1635. # else
  1636. # ifdef PATH_MAX
  1637. char resolved_name[PATH_MAX];
  1638. # else
  1639. char resolved_name[5024];
  1640. # endif
  1641. # endif
  1642. if(dir != "")
  1643. {
  1644. realpath(dir.c_str(), resolved_name);
  1645. dir = resolved_name;
  1646. }
  1647. else
  1648. {
  1649. dir = cmSystemTools::GetCurrentWorkingDirectory();
  1650. }
  1651. if(file == "")
  1652. {
  1653. return dir;
  1654. }
  1655. return dir + "/" + file;
  1656. #endif
  1657. }
  1658. /**
  1659. * Return path of a full filename (no trailing slashes).
  1660. * Warning: returned path is converted to Unix slashes format.
  1661. */
  1662. std::string cmSystemTools::GetFilenamePath(const std::string& filename)
  1663. {
  1664. std::string fn = filename;
  1665. cmSystemTools::ConvertToUnixSlashes(fn);
  1666. std::string::size_type slash_pos = fn.rfind("/");
  1667. if(slash_pos != std::string::npos)
  1668. {
  1669. return fn.substr(0, slash_pos);
  1670. }
  1671. else
  1672. {
  1673. return "";
  1674. }
  1675. }
  1676. /**
  1677. * Return file name of a full filename (i.e. file name without path).
  1678. */
  1679. std::string cmSystemTools::GetFilenameName(const std::string& filename)
  1680. {
  1681. std::string fn = filename;
  1682. cmSystemTools::ConvertToUnixSlashes(fn);
  1683. std::string::size_type slash_pos = fn.rfind("/");
  1684. if(slash_pos != std::string::npos)
  1685. {
  1686. return fn.substr(slash_pos + 1);
  1687. }
  1688. else
  1689. {
  1690. return filename;
  1691. }
  1692. }
  1693. /**
  1694. * Return file extension of a full filename (dot included).
  1695. * Warning: this is the longest extension (for example: .tar.gz)
  1696. */
  1697. std::string cmSystemTools::GetFilenameExtension(const std::string& filename)
  1698. {
  1699. std::string name = cmSystemTools::GetFilenameName(filename);
  1700. std::string::size_type dot_pos = name.find(".");
  1701. if(dot_pos != std::string::npos)
  1702. {
  1703. return name.substr(dot_pos);
  1704. }
  1705. else
  1706. {
  1707. return "";
  1708. }
  1709. }
  1710. /**
  1711. * Return file name without extension of a full filename (i.e. without path).
  1712. * Warning: it considers the longest extension (for example: .tar.gz)
  1713. */
  1714. std::string cmSystemTools::GetFilenameWithoutExtension(const std::string& filename)
  1715. {
  1716. std::string name = cmSystemTools::GetFilenameName(filename);
  1717. std::string::size_type dot_pos = name.find(".");
  1718. if(dot_pos != std::string::npos)
  1719. {
  1720. return name.substr(0, dot_pos);
  1721. }
  1722. else
  1723. {
  1724. return name;
  1725. }
  1726. }
  1727. /**
  1728. * Return file name without extension of a full filename (i.e. without path).
  1729. * Warning: it considers the last extension (for example: removes .gz
  1730. * from .tar.gz)
  1731. */
  1732. std::string
  1733. cmSystemTools::GetFilenameWithoutLastExtension(const std::string& filename)
  1734. {
  1735. std::string name = cmSystemTools::GetFilenameName(filename);
  1736. std::string::size_type dot_pos = name.rfind(".");
  1737. if(dot_pos != std::string::npos)
  1738. {
  1739. return name.substr(0, dot_pos);
  1740. }
  1741. else
  1742. {
  1743. return name;
  1744. }
  1745. }
  1746. bool cmSystemTools::FileIsFullPath(const char* in_name)
  1747. {
  1748. std::string name = in_name;
  1749. #if defined(_WIN32)
  1750. // On Windows, the name must be at least two characters long.
  1751. if(name.length() < 2)
  1752. {
  1753. return false;
  1754. }
  1755. if(name[1] == ':')
  1756. {
  1757. return true;
  1758. }
  1759. if(name[0] == '\\')
  1760. {
  1761. return true;
  1762. }
  1763. #else
  1764. // On UNIX, the name must be at least one character long.
  1765. if(name.length() < 1)
  1766. {
  1767. return false;
  1768. }
  1769. #endif
  1770. // On UNIX, the name must begin in a '/'.
  1771. // On Windows, if the name begins in a '/', then it is a full
  1772. // network path.
  1773. if(name[0] == '/')
  1774. {
  1775. return true;
  1776. }
  1777. return false;
  1778. }
  1779. void cmSystemTools::Glob(const char *directory, const char *regexp,
  1780. std::vector<std::string>& files)
  1781. {
  1782. cmDirectory d;
  1783. cmRegularExpression reg(regexp);
  1784. if (d.Load(directory))
  1785. {
  1786. size_t numf;
  1787. unsigned int i;
  1788. numf = d.GetNumberOfFiles();
  1789. for (i = 0; i < numf; i++)
  1790. {
  1791. std::string fname = d.GetFile(i);
  1792. if (reg.find(fname))
  1793. {
  1794. files.push_back(fname);
  1795. }
  1796. }
  1797. }
  1798. }
  1799. void cmSystemTools::GlobDirs(const char *fullPath,
  1800. std::vector<std::string>& files)
  1801. {
  1802. std::string path = fullPath;
  1803. std::string::size_type pos = path.find("/*");
  1804. if(pos == std::string::npos)
  1805. {
  1806. files.push_back(fullPath);
  1807. return;
  1808. }
  1809. std::string startPath = path.substr(0, pos);
  1810. std::string finishPath = path.substr(pos+2);
  1811. cmDirectory d;
  1812. if (d.Load(startPath.c_str()))
  1813. {
  1814. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)
  1815. {
  1816. if((std::string(d.GetFile(i)) != ".")
  1817. && (std::string(d.GetFile(i)) != ".."))
  1818. {
  1819. std::string fname = startPath;
  1820. fname +="/";
  1821. fname += d.GetFile(i);
  1822. if(cmSystemTools::FileIsDirectory(fname.c_str()))
  1823. {
  1824. fname += finishPath;
  1825. cmSystemTools::GlobDirs(fname.c_str(), files);
  1826. }
  1827. }
  1828. }
  1829. }
  1830. }
  1831. void cmSystemTools::ExpandListArguments(std::vector<std::string> const& arguments,
  1832. std::vector<std::string>& newargs)
  1833. {
  1834. std::vector<std::string>::const_iterator i;
  1835. std::string newarg;
  1836. for(i = arguments.begin();i != arguments.end(); ++i)
  1837. {
  1838. // if there are no ; in the name then just copy the current string
  1839. if(i->find(';') == std::string::npos)
  1840. {
  1841. newargs.push_back(*i);
  1842. }
  1843. else
  1844. {
  1845. std::string::size_type start = 0;
  1846. std::string::size_type endpos = 0;
  1847. const std::string::size_type size = i->size();
  1848. // break up ; separated sections of the string into separate strings
  1849. while(endpos != size)
  1850. {
  1851. endpos = i->find(';', start);
  1852. if(endpos == std::string::npos)
  1853. {
  1854. endpos = i->size();
  1855. }
  1856. else
  1857. {
  1858. // skip right over escaped ; ( \; )
  1859. while((endpos != std::string::npos)
  1860. && (endpos > 0)
  1861. && ((*i)[endpos-1] == '\\') )
  1862. {
  1863. endpos = i->find(';', endpos+1);
  1864. }
  1865. if(endpos == std::string::npos)
  1866. {
  1867. endpos = i->size();
  1868. }
  1869. }
  1870. std::string::size_type len = endpos - start;
  1871. if (len > 0)
  1872. {
  1873. // check for a closing ] after the start position
  1874. if(i->find('[', start) == std::string::npos)
  1875. {
  1876. // if there is no [ in the string then keep it
  1877. newarg = i->substr(start, len);
  1878. }
  1879. else
  1880. {
  1881. int opencount = 0;
  1882. int closecount = 0;
  1883. for(std::string::size_type j = start; j < endpos; ++j)
  1884. {
  1885. if(i->at(j) == '[')
  1886. {
  1887. ++opencount;
  1888. }
  1889. else if (i->at(j) == ']')
  1890. {
  1891. ++closecount;
  1892. }
  1893. }
  1894. if(opencount != closecount)
  1895. {
  1896. // skip this one
  1897. endpos = i->find(';', endpos+1);
  1898. if(endpos == std::string::npos)
  1899. {
  1900. endpos = i->size();
  1901. }
  1902. len = endpos - start;
  1903. }
  1904. newarg = i->substr(start, len);
  1905. }
  1906. std::string::size_type pos = newarg.find("\\;");
  1907. if(pos != std::string::npos)
  1908. {
  1909. newarg.erase(pos, 1);
  1910. }
  1911. newargs.push_back(newarg);
  1912. }
  1913. start = endpos+1;
  1914. }
  1915. }
  1916. }
  1917. }
  1918. bool cmSystemTools::GetShortPath(const char* path, std::string& shortPath)
  1919. {
  1920. #if defined(WIN32) && !defined(__CYGWIN__)
  1921. const int size = int(strlen(path)) +1; // size of return
  1922. char *buffer = new char[size]; // create a buffer
  1923. char *tempPath = new char[size]; // create a buffer
  1924. int ret;
  1925. // if the path passed in has quotes around it, first remove the quotes
  1926. if (path[0] == '"' && path[strlen(path)-1] == '"')
  1927. {
  1928. strcpy(tempPath,path+1);
  1929. tempPath[strlen(tempPath)-1] = '\0';
  1930. }
  1931. else
  1932. {
  1933. strcpy(tempPath,path);
  1934. }
  1935. buffer[0] = 0;
  1936. ret = GetShortPathName(tempPath, buffer, size);
  1937. if(buffer[0] == 0 || ret > size)
  1938. {
  1939. if(ret < size)
  1940. {
  1941. LPVOID lpMsgBuf;
  1942. FormatMessage(
  1943. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  1944. FORMAT_MESSAGE_FROM_SYSTEM |
  1945. FORMAT_MESSAGE_IGNORE_INSERTS,
  1946. NULL,
  1947. GetLastError(),
  1948. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
  1949. (LPTSTR) &lpMsgBuf,
  1950. 0,
  1951. NULL
  1952. );
  1953. cmSystemTools::Error((LPCTSTR)lpMsgBuf);
  1954. LocalFree( lpMsgBuf );
  1955. }
  1956. cmSystemTools::Error("Unable to get a short path: ", path);
  1957. delete [] tempPath;
  1958. return false;
  1959. }
  1960. else
  1961. {
  1962. shortPath = buffer;
  1963. delete [] buffer;
  1964. delete [] tempPath;
  1965. return true;
  1966. }
  1967. #else
  1968. shortPath = path;
  1969. return true;
  1970. #endif
  1971. }