cmSystemTools.cxx 50 KB

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