cmSystemTools.cxx 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071
  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. std::strstream msg;
  979. msg << "FilesDiffer failed to read files (allocated: "
  980. << statSource.st_size << ", read source: " << finSource.gcount()
  981. << ", read dest: " << finDestination.gcount() << std::ends;
  982. cmSystemTools::Error(msg.str());
  983. delete [] msg.str();
  984. delete [] source_buf;
  985. delete [] dest_buf;
  986. return false;
  987. }
  988. int ret = memcmp((const void*)source_buf,
  989. (const void*)dest_buf,
  990. statSource.st_size);
  991. delete [] dest_buf;
  992. delete [] source_buf;
  993. return ret != 0;
  994. }
  995. /**
  996. * Copy a file named by "source" to the file named by "destination".
  997. */
  998. void cmSystemTools::cmCopyFile(const char* source,
  999. const char* destination)
  1000. {
  1001. const int bufferSize = 4096;
  1002. char buffer[bufferSize];
  1003. // If destination is a directory, try to create a file with the same
  1004. // name as the source in that directory.
  1005. std::string new_destination;
  1006. if(cmSystemTools::FileExists(destination) &&
  1007. cmSystemTools::FileIsDirectory(destination))
  1008. {
  1009. new_destination = destination;
  1010. cmSystemTools::ConvertToUnixSlashes(new_destination);
  1011. new_destination += '/';
  1012. std::string source_name = source;
  1013. new_destination += cmSystemTools::GetFilenameName(source_name);
  1014. destination = new_destination.c_str();
  1015. }
  1016. // Create destination directory
  1017. std::string destination_dir = destination;
  1018. destination_dir = cmSystemTools::GetFilenamePath(destination_dir);
  1019. cmSystemTools::MakeDirectory(destination_dir.c_str());
  1020. // Open files
  1021. #if defined(_WIN32) || defined(__CYGWIN__)
  1022. std::ifstream fin(source,
  1023. std::ios::binary | std::ios::in);
  1024. #else
  1025. std::ifstream fin(source);
  1026. #endif
  1027. if(!fin)
  1028. {
  1029. cmSystemTools::Error("CopyFile failed to open input file \"",
  1030. source, "\"");
  1031. return;
  1032. }
  1033. #if defined(_WIN32) || defined(__CYGWIN__)
  1034. std::ofstream fout(destination,
  1035. std::ios::binary | std::ios::out | std::ios::trunc);
  1036. #else
  1037. std::ofstream fout(destination,
  1038. std::ios::out | std::ios::trunc);
  1039. #endif
  1040. if(!fout)
  1041. {
  1042. cmSystemTools::Error("CopyFile failed to open output file \"",
  1043. destination, "\"");
  1044. return;
  1045. }
  1046. // This copy loop is very sensitive on certain platforms with
  1047. // slightly broken stream libraries (like HPUX). Normally, it is
  1048. // incorrect to not check the error condition on the fin.read()
  1049. // before using the data, but the fin.gcount() will be zero if an
  1050. // error occurred. Therefore, the loop should be safe everywhere.
  1051. while(fin)
  1052. {
  1053. fin.read(buffer, bufferSize);
  1054. if(fin.gcount())
  1055. {
  1056. fout.write(buffer, fin.gcount());
  1057. }
  1058. }
  1059. fin.close();
  1060. fout.close();
  1061. // More checks
  1062. struct stat statSource, statDestination;
  1063. if (stat(source, &statSource) != 0 ||
  1064. stat(destination, &statDestination) != 0)
  1065. {
  1066. cmSystemTools::Error("CopyFile failed to copy files!");
  1067. }
  1068. if (statSource.st_size != statDestination.st_size)
  1069. {
  1070. std::strstream msg;
  1071. msg << "CopyFile failed to copy files (sizes differ, source: "
  1072. << statSource.st_size << " , dest: " << statDestination.st_size
  1073. << std::ends;
  1074. cmSystemTools::Error(msg.str());
  1075. delete [] msg.str();
  1076. }
  1077. }
  1078. // return true if the file exists
  1079. long int cmSystemTools::ModifiedTime(const char* filename)
  1080. {
  1081. struct stat fs;
  1082. if (stat(filename, &fs) != 0)
  1083. {
  1084. return 0;
  1085. }
  1086. else
  1087. {
  1088. return (long int)fs.st_mtime;
  1089. }
  1090. }
  1091. bool cmSystemTools::RemoveFile(const char* source)
  1092. {
  1093. return unlink(source) != 0 ? false : true;
  1094. }
  1095. bool cmSystemTools::IsOn(const char* val)
  1096. {
  1097. if (!val)
  1098. {
  1099. return false;
  1100. }
  1101. std::basic_string<char> v = val;
  1102. for(std::basic_string<char>::iterator c = v.begin();
  1103. c != v.end(); c++)
  1104. {
  1105. *c = toupper(*c);
  1106. }
  1107. return (v == "ON" || v == "1" || v == "YES" || v == "TRUE" || v == "Y");
  1108. }
  1109. bool cmSystemTools::IsOff(const char* val)
  1110. {
  1111. if (!val || strlen(val) == 0)
  1112. {
  1113. return true;
  1114. }
  1115. std::basic_string<char> v = val;
  1116. for(std::basic_string<char>::iterator c = v.begin();
  1117. c != v.end(); c++)
  1118. {
  1119. *c = toupper(*c);
  1120. }
  1121. return (v == "OFF" || v == "0" || v == "NO" || v == "FALSE" ||
  1122. v == "N" || v == "NOTFOUND" || v == "IGNORE");
  1123. }
  1124. bool cmSystemTools::RunCommand(const char* command,
  1125. std::string& output,
  1126. const char* dir,
  1127. bool verbose)
  1128. {
  1129. int foo;
  1130. return cmSystemTools::RunCommand(command, output, foo, dir, verbose);
  1131. }
  1132. #if defined(WIN32) && !defined(__CYGWIN__)
  1133. // use this for shell commands like echo and dir
  1134. bool RunCommandViaSystem(const char* command,
  1135. const char* dir,
  1136. std::string& output,
  1137. int& retVal,
  1138. bool verbose)
  1139. {
  1140. const int BUFFER_SIZE = 4096;
  1141. char buffer[BUFFER_SIZE];
  1142. std::string commandInDir;
  1143. if(dir)
  1144. {
  1145. commandInDir = "cd ";
  1146. commandInDir += dir;
  1147. commandInDir += " && ";
  1148. commandInDir += command;
  1149. }
  1150. else
  1151. {
  1152. commandInDir = command;
  1153. }
  1154. command = commandInDir.c_str();
  1155. std::string commandToFile = command;
  1156. commandToFile += " > ";
  1157. std::string tempFile;
  1158. tempFile += _tempnam(0, "cmake");
  1159. commandToFile += tempFile;
  1160. retVal = system(commandToFile.c_str());
  1161. std::ifstream fin(tempFile.c_str());
  1162. if(!fin)
  1163. {
  1164. if(verbose)
  1165. {
  1166. std::string errormsg = "RunCommand produced no output: command: \"";
  1167. errormsg += command;
  1168. errormsg += "\"";
  1169. errormsg += "\nOutput file: ";
  1170. errormsg += tempFile;
  1171. cmSystemTools::Error(errormsg.c_str());
  1172. }
  1173. fin.close();
  1174. cmSystemTools::RemoveFile(tempFile.c_str());
  1175. return false;
  1176. }
  1177. bool multiLine = false;
  1178. while(fin)
  1179. {
  1180. fin.getline(buffer, BUFFER_SIZE);
  1181. output += buffer;
  1182. if(multiLine)
  1183. {
  1184. output += "\n";
  1185. }
  1186. multiLine = true;
  1187. }
  1188. fin.close();
  1189. cmSystemTools::RemoveFile(tempFile.c_str());
  1190. return true;
  1191. }
  1192. #endif // endif WIN32 not CYGWIN
  1193. // run a command unix uses popen (easy)
  1194. // windows uses system and ShortPath
  1195. bool cmSystemTools::RunCommand(const char* command,
  1196. std::string& output,
  1197. int &retVal,
  1198. const char* dir,
  1199. bool verbose)
  1200. {
  1201. if(s_DisableRunCommandOutput)
  1202. {
  1203. verbose = false;
  1204. }
  1205. #if defined(WIN32) && !defined(__CYGWIN__)
  1206. // if the command does not start with a quote, then
  1207. // try to find the program, and if the program can not be
  1208. // found use system to run the command as it must be a built in
  1209. // shell command like echo or dir
  1210. int count = 0;
  1211. if(command[0] == '\"')
  1212. {
  1213. // count the number of quotes
  1214. for(const char* s = command; *s != 0; ++s)
  1215. {
  1216. if(*s == '\"')
  1217. {
  1218. count++;
  1219. if(count > 2)
  1220. {
  1221. break;
  1222. }
  1223. }
  1224. }
  1225. // if there are more than two double quotes use
  1226. // GetShortPathName, the cmd.exe program in windows which
  1227. // is used by system fails to execute if there are more than
  1228. // one set of quotes in the arguments
  1229. if(count > 2)
  1230. {
  1231. cmRegularExpression quoted("^\"([^\"]*)\"[ \t](.*)");
  1232. if(quoted.find(command))
  1233. {
  1234. std::string shortCmd;
  1235. std::string cmd = quoted.match(1);
  1236. std::string args = quoted.match(2);
  1237. if(!cmSystemTools::GetShortPath(cmd.c_str(), shortCmd))
  1238. {
  1239. cmSystemTools::Error("GetShortPath failed for " , cmd.c_str());
  1240. return false;
  1241. }
  1242. shortCmd += " ";
  1243. shortCmd += args;
  1244. return RunCommandViaSystem(shortCmd.c_str(), dir,
  1245. output, retVal, verbose);
  1246. }
  1247. else
  1248. {
  1249. cmSystemTools::Error("Could not parse command line with quotes ",
  1250. command);
  1251. }
  1252. }
  1253. }
  1254. // if there is only one set of quotes or no quotes then just run the command
  1255. return RunCommandViaSystem(command, dir, output, retVal, verbose);
  1256. #else
  1257. // if only popen worked on windows.....
  1258. std::string commandInDir;
  1259. if(dir)
  1260. {
  1261. commandInDir = "cd ";
  1262. commandInDir += dir;
  1263. commandInDir += " && ";
  1264. commandInDir += command;
  1265. }
  1266. else
  1267. {
  1268. commandInDir = command;
  1269. }
  1270. command = commandInDir.c_str();
  1271. const int BUFFER_SIZE = 4096;
  1272. char buffer[BUFFER_SIZE];
  1273. if(verbose)
  1274. {
  1275. std::cout << "running " << command << std::endl;
  1276. }
  1277. fflush(stdout);
  1278. fflush(stderr);
  1279. FILE* cpipe = popen(command, "r");
  1280. if(!cpipe)
  1281. {
  1282. return false;
  1283. }
  1284. fgets(buffer, BUFFER_SIZE, cpipe);
  1285. while(!feof(cpipe))
  1286. {
  1287. if(verbose)
  1288. {
  1289. std::cout << buffer << std::flush;
  1290. }
  1291. output += buffer;
  1292. fgets(buffer, BUFFER_SIZE, cpipe);
  1293. }
  1294. retVal = pclose(cpipe);
  1295. if (WIFEXITED(retVal))
  1296. {
  1297. retVal = WEXITSTATUS(retVal);
  1298. return true;
  1299. }
  1300. if (WIFSIGNALED(retVal))
  1301. {
  1302. retVal = WTERMSIG(retVal);
  1303. std::strstream error;
  1304. error << "\nProcess terminated due to ";
  1305. switch (retVal)
  1306. {
  1307. #ifdef SIGKILL
  1308. case SIGKILL:
  1309. error << "SIGKILL";
  1310. break;
  1311. #endif
  1312. #ifdef SIGFPE
  1313. case SIGFPE:
  1314. error << "SIGFPE";
  1315. break;
  1316. #endif
  1317. #ifdef SIGBUS
  1318. case SIGBUS:
  1319. error << "SIGBUS";
  1320. break;
  1321. #endif
  1322. #ifdef SIGSEGV
  1323. case SIGSEGV:
  1324. error << "SIGSEGV";
  1325. break;
  1326. #endif
  1327. default:
  1328. error << "signal " << retVal;
  1329. break;
  1330. }
  1331. error << std::ends;
  1332. output += error.str();
  1333. error.rdbuf()->freeze(0);
  1334. }
  1335. return false;
  1336. #endif
  1337. }
  1338. /**
  1339. * Find the file the given name. Searches the given path and then
  1340. * the system search path. Returns the full path to the file if it is
  1341. * found. Otherwise, the empty string is returned.
  1342. */
  1343. std::string cmSystemTools::FindFile(const char* name,
  1344. const std::vector<std::string>& userPaths)
  1345. {
  1346. // Add the system search path to our path.
  1347. std::vector<std::string> path = userPaths;
  1348. cmSystemTools::GetPath(path);
  1349. std::string tryPath;
  1350. for(std::vector<std::string>::const_iterator p = path.begin();
  1351. p != path.end(); ++p)
  1352. {
  1353. tryPath = *p;
  1354. tryPath += "/";
  1355. tryPath += name;
  1356. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1357. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1358. {
  1359. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1360. }
  1361. }
  1362. // Couldn't find the file.
  1363. return "";
  1364. }
  1365. /**
  1366. * Find the executable with the given name. Searches the given path and then
  1367. * the system search path. Returns the full path to the executable if it is
  1368. * found. Otherwise, the empty string is returned.
  1369. */
  1370. std::string cmSystemTools::FindProgram(const char* name,
  1371. const std::vector<std::string>& userPaths,
  1372. bool no_system_path)
  1373. {
  1374. // See if the executable exists as written.
  1375. if(cmSystemTools::FileExists(name) &&
  1376. !cmSystemTools::FileIsDirectory(name))
  1377. {
  1378. return cmSystemTools::CollapseFullPath(name);
  1379. }
  1380. std::string tryPath = name;
  1381. tryPath += cmSystemTools::GetExecutableExtension();
  1382. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1383. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1384. {
  1385. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1386. }
  1387. // Add the system search path to our path.
  1388. std::vector<std::string> path = userPaths;
  1389. if (!no_system_path)
  1390. {
  1391. cmSystemTools::GetPath(path);
  1392. }
  1393. for(std::vector<std::string>::const_iterator p = path.begin();
  1394. p != path.end(); ++p)
  1395. {
  1396. tryPath = *p;
  1397. tryPath += "/";
  1398. tryPath += name;
  1399. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1400. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1401. {
  1402. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1403. }
  1404. #ifdef _WIN32
  1405. tryPath += ".com";
  1406. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1407. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1408. {
  1409. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1410. }
  1411. tryPath = *p;
  1412. tryPath += "/";
  1413. tryPath += name;
  1414. #endif
  1415. tryPath += cmSystemTools::GetExecutableExtension();
  1416. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1417. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1418. {
  1419. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1420. }
  1421. }
  1422. // Couldn't find the program.
  1423. return "";
  1424. }
  1425. /**
  1426. * Find the library with the given name. Searches the given path and then
  1427. * the system search path. Returns the full path to the library if it is
  1428. * found. Otherwise, the empty string is returned.
  1429. */
  1430. std::string cmSystemTools::FindLibrary(const char* name,
  1431. const std::vector<std::string>& userPaths,
  1432. const cmMakefile *makefile)
  1433. {
  1434. // See if the executable exists as written.
  1435. if(cmSystemTools::FileExists(name))
  1436. {
  1437. return cmSystemTools::CollapseFullPath(name);
  1438. }
  1439. // Add the system search path to our path.
  1440. std::vector<std::string> path = userPaths;
  1441. cmSystemTools::GetPath(path);
  1442. // Add some lib directories specific to compilers, depending on the
  1443. // current generator, so that library that might have been stored here
  1444. // can be found too.
  1445. // i.e. Microsoft Visual Studio or .Net: path to compiler/../Lib
  1446. // Borland: path to compiler/../Lib
  1447. if (makefile)
  1448. {
  1449. const char* genName = makefile->GetDefinition("CMAKE_GENERATOR");
  1450. if (genName)
  1451. {
  1452. if (!strcmp(genName, "NMake Makefiles") ||
  1453. !strncmp(genName, "Visual Studio ", 14))
  1454. {
  1455. const char* compiler = makefile->GetDefinition("CMAKE_CXX_COMPILER");
  1456. if (compiler)
  1457. {
  1458. std::string compiler_path = cmSystemTools::FindProgram(compiler);
  1459. if (compiler_path.size())
  1460. {
  1461. std::string lib_path =
  1462. cmSystemTools::GetFilenamePath(
  1463. cmSystemTools::GetFilenamePath(compiler_path)) + "/Lib";
  1464. path.push_back(lib_path);
  1465. }
  1466. }
  1467. }
  1468. else if (!strcmp(genName, "Borland Makefiles"))
  1469. {
  1470. const char* bcb_bin_path = makefile->GetDefinition("BCB_BIN_PATH");
  1471. if (bcb_bin_path)
  1472. {
  1473. std::string lib_path =
  1474. cmSystemTools::GetFilenamePath(bcb_bin_path) + "/Lib";
  1475. path.push_back(lib_path);
  1476. }
  1477. }
  1478. }
  1479. }
  1480. std::string tryPath;
  1481. for(std::vector<std::string>::const_iterator p = path.begin();
  1482. p != path.end(); ++p)
  1483. {
  1484. #if defined(_WIN32) && !defined(__CYGWIN__)
  1485. tryPath = *p;
  1486. tryPath += "/";
  1487. tryPath += name;
  1488. tryPath += ".lib";
  1489. if(cmSystemTools::FileExists(tryPath.c_str()))
  1490. {
  1491. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1492. }
  1493. #else
  1494. tryPath = *p;
  1495. tryPath += "/lib";
  1496. tryPath += name;
  1497. tryPath += ".so";
  1498. if(cmSystemTools::FileExists(tryPath.c_str()))
  1499. {
  1500. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1501. }
  1502. tryPath = *p;
  1503. tryPath += "/lib";
  1504. tryPath += name;
  1505. tryPath += ".a";
  1506. if(cmSystemTools::FileExists(tryPath.c_str()))
  1507. {
  1508. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1509. }
  1510. tryPath = *p;
  1511. tryPath += "/lib";
  1512. tryPath += name;
  1513. tryPath += ".sl";
  1514. if(cmSystemTools::FileExists(tryPath.c_str()))
  1515. {
  1516. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1517. }
  1518. #endif
  1519. }
  1520. // Couldn't find the library.
  1521. return "";
  1522. }
  1523. bool cmSystemTools::FileIsDirectory(const char* name)
  1524. {
  1525. struct stat fs;
  1526. if(stat(name, &fs) == 0)
  1527. {
  1528. #if _WIN32
  1529. return ((fs.st_mode & _S_IFDIR) != 0);
  1530. #else
  1531. return S_ISDIR(fs.st_mode);
  1532. #endif
  1533. }
  1534. else
  1535. {
  1536. return false;
  1537. }
  1538. }
  1539. int cmSystemTools::ChangeDirectory(const char *dir)
  1540. {
  1541. return Chdir(dir);
  1542. }
  1543. std::string cmSystemTools::GetCurrentWorkingDirectory()
  1544. {
  1545. char buf[2048];
  1546. std::string path = Getcwd(buf, 2048);
  1547. return path;
  1548. }
  1549. /**
  1550. * Given the path to a program executable, get the directory part of the path with the
  1551. * file stripped off. If there is no directory part, the empty string is returned.
  1552. */
  1553. std::string cmSystemTools::GetProgramPath(const char* in_name)
  1554. {
  1555. std::string dir, file;
  1556. cmSystemTools::SplitProgramPath(in_name, dir, file);
  1557. return dir;
  1558. }
  1559. /**
  1560. * Given the path to a program executable, get the directory part of the path
  1561. * with the file stripped off. If there is no directory part, the empty
  1562. * string is returned.
  1563. */
  1564. void cmSystemTools::SplitProgramPath(const char* in_name,
  1565. std::string& dir,
  1566. std::string& file)
  1567. {
  1568. dir = in_name;
  1569. file = "";
  1570. cmSystemTools::ConvertToUnixSlashes(dir);
  1571. if(!cmSystemTools::FileIsDirectory(dir.c_str()))
  1572. {
  1573. std::string::size_type slashPos = dir.rfind("/");
  1574. if(slashPos != std::string::npos)
  1575. {
  1576. file = dir.substr(slashPos+1);
  1577. dir = dir.substr(0, slashPos);
  1578. }
  1579. else
  1580. {
  1581. file = dir;
  1582. dir = "";
  1583. }
  1584. }
  1585. if((dir != "") && !cmSystemTools::FileIsDirectory(dir.c_str()))
  1586. {
  1587. std::string oldDir = in_name;
  1588. cmSystemTools::ConvertToUnixSlashes(oldDir);
  1589. cmSystemTools::Error("Error splitting file name off end of path:\n",
  1590. oldDir.c_str(), "\nDirectory not found: ",
  1591. dir.c_str());
  1592. dir = in_name;
  1593. return;
  1594. }
  1595. }
  1596. /**
  1597. * Given a path to a file or directory, convert it to a full path.
  1598. * This collapses away relative paths. The full path is returned.
  1599. */
  1600. std::string cmSystemTools::CollapseFullPath(const char* in_name)
  1601. {
  1602. std::string dir, file;
  1603. cmSystemTools::SplitProgramPath(in_name, dir, file);
  1604. #ifdef _WIN32
  1605. // Ultra-hack warning:
  1606. // This changes to the target directory, saves the working directory,
  1607. // and then changes back to the original working directory.
  1608. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1609. if(dir != "") { Chdir(dir.c_str()); }
  1610. std::string newDir = cmSystemTools::GetCurrentWorkingDirectory();
  1611. Chdir(cwd.c_str());
  1612. cmSystemTools::ConvertToUnixSlashes(newDir);
  1613. std::string newPath = newDir+"/"+file;
  1614. return newPath;
  1615. #else
  1616. # ifdef MAXPATHLEN
  1617. char resolved_name[MAXPATHLEN];
  1618. # else
  1619. # ifdef PATH_MAX
  1620. char resolved_name[PATH_MAX];
  1621. # else
  1622. char resolved_name[5024];
  1623. # endif
  1624. # endif
  1625. if(dir != "")
  1626. {
  1627. realpath(dir.c_str(), resolved_name);
  1628. dir = resolved_name;
  1629. }
  1630. else
  1631. {
  1632. dir = cmSystemTools::GetCurrentWorkingDirectory();
  1633. }
  1634. if(file == "")
  1635. {
  1636. return dir;
  1637. }
  1638. return dir + "/" + file;
  1639. #endif
  1640. }
  1641. /**
  1642. * Return path of a full filename (no trailing slashes).
  1643. * Warning: returned path is converted to Unix slashes format.
  1644. */
  1645. std::string cmSystemTools::GetFilenamePath(const std::string& filename)
  1646. {
  1647. std::string fn = filename;
  1648. cmSystemTools::ConvertToUnixSlashes(fn);
  1649. std::string::size_type slash_pos = fn.rfind("/");
  1650. if(slash_pos != std::string::npos)
  1651. {
  1652. return fn.substr(0, slash_pos);
  1653. }
  1654. else
  1655. {
  1656. return "";
  1657. }
  1658. }
  1659. /**
  1660. * Return file name of a full filename (i.e. file name without path).
  1661. */
  1662. std::string cmSystemTools::GetFilenameName(const std::string& filename)
  1663. {
  1664. std::string fn = filename;
  1665. cmSystemTools::ConvertToUnixSlashes(fn);
  1666. std::string::size_type slash_pos = fn.rfind("/");
  1667. if(slash_pos != std::string::npos)
  1668. {
  1669. return fn.substr(slash_pos + 1);
  1670. }
  1671. else
  1672. {
  1673. return filename;
  1674. }
  1675. }
  1676. /**
  1677. * Return file extension of a full filename (dot included).
  1678. * Warning: this is the longest extension (for example: .tar.gz)
  1679. */
  1680. std::string cmSystemTools::GetFilenameExtension(const std::string& filename)
  1681. {
  1682. std::string name = cmSystemTools::GetFilenameName(filename);
  1683. std::string::size_type dot_pos = name.find(".");
  1684. if(dot_pos != std::string::npos)
  1685. {
  1686. return name.substr(dot_pos);
  1687. }
  1688. else
  1689. {
  1690. return "";
  1691. }
  1692. }
  1693. /**
  1694. * Return file name without extension of a full filename (i.e. without path).
  1695. * Warning: it considers the longest extension (for example: .tar.gz)
  1696. */
  1697. std::string cmSystemTools::GetFilenameNameWithoutExtension(const std::string& filename)
  1698. {
  1699. std::string name = cmSystemTools::GetFilenameName(filename);
  1700. std::string::size_type dot_pos = name.find(".");
  1701. if(dot_pos != std::string::npos)
  1702. {
  1703. return name.substr(0, dot_pos);
  1704. }
  1705. else
  1706. {
  1707. return name;
  1708. }
  1709. }
  1710. void cmSystemTools::Glob(const char *directory, const char *regexp,
  1711. std::vector<std::string>& files)
  1712. {
  1713. cmDirectory d;
  1714. cmRegularExpression reg(regexp);
  1715. if (d.Load(directory))
  1716. {
  1717. size_t numf;
  1718. unsigned int i;
  1719. numf = d.GetNumberOfFiles();
  1720. for (i = 0; i < numf; i++)
  1721. {
  1722. std::string fname = d.GetFile(i);
  1723. if (reg.find(fname))
  1724. {
  1725. files.push_back(fname);
  1726. }
  1727. }
  1728. }
  1729. }
  1730. void cmSystemTools::GlobDirs(const char *fullPath,
  1731. std::vector<std::string>& files)
  1732. {
  1733. std::string path = fullPath;
  1734. std::string::size_type pos = path.find("/*");
  1735. if(pos == std::string::npos)
  1736. {
  1737. files.push_back(fullPath);
  1738. return;
  1739. }
  1740. std::string startPath = path.substr(0, pos);
  1741. std::string finishPath = path.substr(pos+2);
  1742. cmDirectory d;
  1743. if (d.Load(startPath.c_str()))
  1744. {
  1745. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)
  1746. {
  1747. if((std::string(d.GetFile(i)) != ".")
  1748. && (std::string(d.GetFile(i)) != ".."))
  1749. {
  1750. std::string fname = startPath;
  1751. fname +="/";
  1752. fname += d.GetFile(i);
  1753. if(cmSystemTools::FileIsDirectory(fname.c_str()))
  1754. {
  1755. fname += finishPath;
  1756. cmSystemTools::GlobDirs(fname.c_str(), files);
  1757. }
  1758. }
  1759. }
  1760. }
  1761. }
  1762. void cmSystemTools::ExpandListArguments(std::vector<std::string> const& arguments,
  1763. std::vector<std::string>& newargs)
  1764. {
  1765. std::vector<std::string>::const_iterator i;
  1766. std::string newarg;
  1767. for(i = arguments.begin();i != arguments.end(); ++i)
  1768. {
  1769. // if there are no ; in the name then just copy the current string
  1770. if(i->find(';') == std::string::npos)
  1771. {
  1772. newargs.push_back(*i);
  1773. }
  1774. else
  1775. {
  1776. std::string::size_type start = 0;
  1777. std::string::size_type endpos = 0;
  1778. const std::string::size_type size = i->size();
  1779. // break up ; separated sections of the string into separate strings
  1780. while(endpos != size)
  1781. {
  1782. endpos = i->find(';', start);
  1783. if(endpos == std::string::npos)
  1784. {
  1785. endpos = i->size();
  1786. }
  1787. else
  1788. {
  1789. // skip right over escaped ; ( \; )
  1790. while((endpos != std::string::npos)
  1791. && (endpos > 0)
  1792. && ((*i)[endpos-1] == '\\') )
  1793. {
  1794. endpos = i->find(';', endpos+1);
  1795. }
  1796. if(endpos == std::string::npos)
  1797. {
  1798. endpos = i->size();
  1799. }
  1800. }
  1801. std::string::size_type len = endpos - start;
  1802. if (len > 0)
  1803. {
  1804. // check for a closing ] after the start position
  1805. if(i->find('[', start) == std::string::npos)
  1806. {
  1807. // if there is no [ in the string then keep it
  1808. newarg = i->substr(start, len);
  1809. }
  1810. else
  1811. {
  1812. int opencount = 0;
  1813. int closecount = 0;
  1814. for(std::string::size_type j = start; j < endpos; ++j)
  1815. {
  1816. if(i->at(j) == '[')
  1817. {
  1818. ++opencount;
  1819. }
  1820. else if (i->at(j) == ']')
  1821. {
  1822. ++closecount;
  1823. }
  1824. }
  1825. if(opencount != closecount)
  1826. {
  1827. // skip this one
  1828. endpos = i->find(';', endpos+1);
  1829. if(endpos == std::string::npos)
  1830. {
  1831. endpos = i->size();
  1832. }
  1833. len = endpos - start;
  1834. }
  1835. newarg = i->substr(start, len);
  1836. }
  1837. std::string::size_type pos = newarg.find("\\;");
  1838. if(pos != std::string::npos)
  1839. {
  1840. newarg.erase(pos, 1);
  1841. }
  1842. newargs.push_back(newarg);
  1843. }
  1844. start = endpos+1;
  1845. }
  1846. }
  1847. }
  1848. }
  1849. bool cmSystemTools::GetShortPath(const char* path, std::string& shortPath)
  1850. {
  1851. #if defined(WIN32) && !defined(__CYGWIN__)
  1852. const int size = int(strlen(path)) +1; // size of return
  1853. char *buffer = new char[size]; // create a buffer
  1854. char *tempPath = new char[size]; // create a buffer
  1855. int ret;
  1856. // if the path passed in has quotes around it, first remove the quotes
  1857. if (path[0] == '"' && path[strlen(path)-1] == '"')
  1858. {
  1859. strcpy(tempPath,path+1);
  1860. tempPath[strlen(tempPath)-1] = '\0';
  1861. }
  1862. else
  1863. {
  1864. strcpy(tempPath,path);
  1865. }
  1866. buffer[0] = 0;
  1867. ret = GetShortPathName(tempPath, buffer, size);
  1868. if(buffer[0] == 0 || ret > size)
  1869. {
  1870. if(ret < size)
  1871. {
  1872. LPVOID lpMsgBuf;
  1873. FormatMessage(
  1874. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  1875. FORMAT_MESSAGE_FROM_SYSTEM |
  1876. FORMAT_MESSAGE_IGNORE_INSERTS,
  1877. NULL,
  1878. GetLastError(),
  1879. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
  1880. (LPTSTR) &lpMsgBuf,
  1881. 0,
  1882. NULL
  1883. );
  1884. cmSystemTools::Error((LPCTSTR)lpMsgBuf);
  1885. LocalFree( lpMsgBuf );
  1886. }
  1887. cmSystemTools::Error("Unable to get a short path: ", path);
  1888. delete [] tempPath;
  1889. return false;
  1890. }
  1891. else
  1892. {
  1893. shortPath = buffer;
  1894. delete [] buffer;
  1895. delete [] tempPath;
  1896. return true;
  1897. }
  1898. #else
  1899. shortPath = path;
  1900. return true;
  1901. #endif
  1902. }