cmSystemTools.cxx 52 KB

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