cmSystemTools.cxx 51 KB

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