cmSystemTools.cxx 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459
  1. /*=========================================================================
  2. Program: CMake - Cross-Platform Makefile Generator
  3. Module: $RCSfile$
  4. Language: C++
  5. Date: $Date$
  6. Version: $Revision$
  7. Copyright (c) 2002 Kitware, Inc., Insight Consortium. All rights reserved.
  8. See Copyright.txt or http://www.cmake.org/HTML/Copyright.html 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 <stdio.h>
  15. #include <sys/stat.h>
  16. #include "cmRegularExpression.h"
  17. #include <ctype.h>
  18. #include "cmDirectory.h"
  19. #include <errno.h>
  20. #include <time.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. /* Implement floattime() for various platforms */
  67. // Taken from Python 2.1.3
  68. #if defined( _WIN32 ) && !defined( __CYGWIN__ )
  69. # include <sys/timeb.h>
  70. # define HAVE_FTIME
  71. # if defined( __BORLANDC__)
  72. # define FTIME ftime
  73. # define TIMEB timeb
  74. # else // Visual studio?
  75. # define FTIME _ftime
  76. # define TIMEB _timeb
  77. # endif
  78. #elif defined( __CYGWIN__ ) || defined( __linux__ )
  79. # include <sys/time.h>
  80. # include <time.h>
  81. # define HAVE_GETTIMEOFDAY
  82. #endif
  83. double
  84. cmSystemTools::GetTime(void)
  85. {
  86. /* There are three ways to get the time:
  87. (1) gettimeofday() -- resolution in microseconds
  88. (2) ftime() -- resolution in milliseconds
  89. (3) time() -- resolution in seconds
  90. In all cases the return value is a float in seconds.
  91. Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
  92. fail, so we fall back on ftime() or time().
  93. Note: clock resolution does not imply clock accuracy! */
  94. #ifdef HAVE_GETTIMEOFDAY
  95. {
  96. struct timeval t;
  97. #ifdef GETTIMEOFDAY_NO_TZ
  98. if (gettimeofday(&t) == 0)
  99. return (double)t.tv_sec + t.tv_usec*0.000001;
  100. #else /* !GETTIMEOFDAY_NO_TZ */
  101. if (gettimeofday(&t, (struct timezone *)NULL) == 0)
  102. return (double)t.tv_sec + t.tv_usec*0.000001;
  103. #endif /* !GETTIMEOFDAY_NO_TZ */
  104. }
  105. #endif /* !HAVE_GETTIMEOFDAY */
  106. {
  107. #if defined(HAVE_FTIME)
  108. struct TIMEB t;
  109. FTIME(&t);
  110. return (double)t.time + (double)t.millitm * (double)0.001;
  111. #else /* !HAVE_FTIME */
  112. time_t secs;
  113. time(&secs);
  114. return (double)secs;
  115. #endif /* !HAVE_FTIME */
  116. }
  117. }
  118. bool cmSystemTools::s_RunCommandHideConsole = false;
  119. bool cmSystemTools::s_DisableRunCommandOutput = false;
  120. bool cmSystemTools::s_ErrorOccured = false;
  121. bool cmSystemTools::s_FatalErrorOccured = false;
  122. bool cmSystemTools::s_DisableMessages = false;
  123. std::string cmSystemTools::s_Windows9xComspecSubstitute = "command.com";
  124. void cmSystemTools::SetWindows9xComspecSubstitute(const char* str)
  125. {
  126. if ( str )
  127. {
  128. cmSystemTools::s_Windows9xComspecSubstitute = str;
  129. }
  130. }
  131. const char* cmSystemTools::GetWindows9xComspecSubstitute()
  132. {
  133. return cmSystemTools::s_Windows9xComspecSubstitute.c_str();
  134. }
  135. void (*cmSystemTools::s_ErrorCallback)(const char*, const char*, bool&, void*);
  136. void* cmSystemTools::s_ErrorCallbackClientData = 0;
  137. // adds the elements of the env variable path to the arg passed in
  138. void cmSystemTools::GetPath(std::vector<std::string>& path)
  139. {
  140. #if defined(_WIN32) && !defined(__CYGWIN__)
  141. const char* pathSep = ";";
  142. #else
  143. const char* pathSep = ":";
  144. #endif
  145. std::string pathEnv = getenv("PATH");
  146. // A hack to make the below algorithm work.
  147. if(pathEnv[pathEnv.length()-1] != ':')
  148. {
  149. pathEnv += pathSep;
  150. }
  151. std::string::size_type start =0;
  152. bool done = false;
  153. while(!done)
  154. {
  155. std::string::size_type endpos = pathEnv.find(pathSep, start);
  156. if(endpos != std::string::npos)
  157. {
  158. path.push_back(pathEnv.substr(start, endpos-start));
  159. start = endpos+1;
  160. }
  161. else
  162. {
  163. done = true;
  164. }
  165. }
  166. for(std::vector<std::string>::iterator i = path.begin();
  167. i != path.end(); ++i)
  168. {
  169. cmSystemTools::ConvertToUnixSlashes(*i);
  170. }
  171. }
  172. const char* cmSystemTools::GetExecutableExtension()
  173. {
  174. #if defined(_WIN32) || defined(__CYGWIN__)
  175. return ".exe";
  176. #else
  177. return "";
  178. #endif
  179. }
  180. bool cmSystemTools::MakeDirectory(const char* path)
  181. {
  182. if(cmSystemTools::FileExists(path))
  183. {
  184. return true;
  185. }
  186. std::string dir = path;
  187. if(dir.size() == 0)
  188. {
  189. return false;
  190. }
  191. cmSystemTools::ConvertToUnixSlashes(dir);
  192. std::string::size_type pos = dir.find(':');
  193. if(pos == std::string::npos)
  194. {
  195. pos = 0;
  196. }
  197. std::string topdir;
  198. while((pos = dir.find('/', pos)) != std::string::npos)
  199. {
  200. topdir = dir.substr(0, pos);
  201. Mkdir(topdir.c_str());
  202. pos++;
  203. }
  204. if(dir[dir.size()-1] == '/')
  205. {
  206. topdir = dir.substr(0, dir.size());
  207. }
  208. else
  209. {
  210. topdir = dir;
  211. }
  212. if(Mkdir(topdir.c_str()) != 0)
  213. {
  214. // There is a bug in the Borland Run time library which makes MKDIR
  215. // return EACCES when it should return EEXISTS
  216. // if it is some other error besides directory exists
  217. // then return false
  218. if( (errno != EEXIST)
  219. #ifdef __BORLANDC__
  220. && (errno != EACCES)
  221. #endif
  222. )
  223. {
  224. cmSystemTools::Error("Failed to create directory:", path);
  225. return false;
  226. }
  227. }
  228. return true;
  229. }
  230. // replace replace with with as many times as it shows up in source.
  231. // write the result into source.
  232. void cmSystemTools::ReplaceString(std::string& source,
  233. const char* replace,
  234. const char* with)
  235. {
  236. // get out quick if string is not found
  237. std::string::size_type start = source.find(replace);
  238. if(start == std::string::npos)
  239. {
  240. return;
  241. }
  242. std::string rest;
  243. std::string::size_type lengthReplace = strlen(replace);
  244. std::string::size_type lengthWith = strlen(with);
  245. while(start != std::string::npos)
  246. {
  247. rest = source.substr(start+lengthReplace);
  248. source = source.substr(0, start);
  249. source += with;
  250. source += rest;
  251. start = source.find(replace, start + lengthWith );
  252. }
  253. }
  254. // Read a registry value.
  255. // Example :
  256. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  257. // => will return the data of the "default" value of the key
  258. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  259. // => will return the data of the "Root" value of the key
  260. #if defined(_WIN32) && !defined(__CYGWIN__)
  261. bool cmSystemTools::ReadRegistryValue(const char *key, std::string &value)
  262. {
  263. std::string primary = key;
  264. std::string second;
  265. std::string valuename;
  266. size_t start = primary.find("\\");
  267. if (start == std::string::npos)
  268. {
  269. return false;
  270. }
  271. size_t valuenamepos = primary.find(";");
  272. if (valuenamepos != std::string::npos)
  273. {
  274. valuename = primary.substr(valuenamepos+1);
  275. }
  276. second = primary.substr(start+1, valuenamepos-start-1);
  277. primary = primary.substr(0, start);
  278. HKEY primaryKey;
  279. if (primary == "HKEY_CURRENT_USER")
  280. {
  281. primaryKey = HKEY_CURRENT_USER;
  282. }
  283. if (primary == "HKEY_CURRENT_CONFIG")
  284. {
  285. primaryKey = HKEY_CURRENT_CONFIG;
  286. }
  287. if (primary == "HKEY_CLASSES_ROOT")
  288. {
  289. primaryKey = HKEY_CLASSES_ROOT;
  290. }
  291. if (primary == "HKEY_LOCAL_MACHINE")
  292. {
  293. primaryKey = HKEY_LOCAL_MACHINE;
  294. }
  295. if (primary == "HKEY_USERS")
  296. {
  297. primaryKey = HKEY_USERS;
  298. }
  299. HKEY hKey;
  300. if(RegOpenKeyEx(primaryKey,
  301. second.c_str(),
  302. 0,
  303. KEY_READ,
  304. &hKey) != ERROR_SUCCESS)
  305. {
  306. return false;
  307. }
  308. else
  309. {
  310. DWORD dwType, dwSize;
  311. dwSize = 1023;
  312. char data[1024];
  313. if(RegQueryValueEx(hKey,
  314. (LPTSTR)valuename.c_str(),
  315. NULL,
  316. &dwType,
  317. (BYTE *)data,
  318. &dwSize) == ERROR_SUCCESS)
  319. {
  320. if (dwType == REG_SZ)
  321. {
  322. value = data;
  323. return true;
  324. }
  325. }
  326. }
  327. return false;
  328. }
  329. #else
  330. bool cmSystemTools::ReadRegistryValue(const char *, std::string &)
  331. {
  332. return false;
  333. }
  334. #endif
  335. // Write a registry value.
  336. // Example :
  337. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  338. // => will set the data of the "default" value of the key
  339. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  340. // => will set the data of the "Root" value of the key
  341. #if defined(_WIN32) && !defined(__CYGWIN__)
  342. bool cmSystemTools::WriteRegistryValue(const char *key, const char *value)
  343. {
  344. std::string primary = key;
  345. std::string second;
  346. std::string valuename;
  347. size_t start = primary.find("\\");
  348. if (start == std::string::npos)
  349. {
  350. return false;
  351. }
  352. size_t valuenamepos = primary.find(";");
  353. if (valuenamepos != std::string::npos)
  354. {
  355. valuename = primary.substr(valuenamepos+1);
  356. }
  357. second = primary.substr(start+1, valuenamepos-start-1);
  358. primary = primary.substr(0, start);
  359. HKEY primaryKey;
  360. if (primary == "HKEY_CURRENT_USER")
  361. {
  362. primaryKey = HKEY_CURRENT_USER;
  363. }
  364. if (primary == "HKEY_CURRENT_CONFIG")
  365. {
  366. primaryKey = HKEY_CURRENT_CONFIG;
  367. }
  368. if (primary == "HKEY_CLASSES_ROOT")
  369. {
  370. primaryKey = HKEY_CLASSES_ROOT;
  371. }
  372. if (primary == "HKEY_LOCAL_MACHINE")
  373. {
  374. primaryKey = HKEY_LOCAL_MACHINE;
  375. }
  376. if (primary == "HKEY_USERS")
  377. {
  378. primaryKey = HKEY_USERS;
  379. }
  380. HKEY hKey;
  381. DWORD dwDummy;
  382. if(RegCreateKeyEx(primaryKey,
  383. second.c_str(),
  384. 0,
  385. "",
  386. REG_OPTION_NON_VOLATILE,
  387. KEY_WRITE,
  388. NULL,
  389. &hKey,
  390. &dwDummy) != ERROR_SUCCESS)
  391. {
  392. return false;
  393. }
  394. if(RegSetValueEx(hKey,
  395. (LPTSTR)valuename.c_str(),
  396. 0,
  397. REG_SZ,
  398. (CONST BYTE *)value,
  399. (DWORD)(strlen(value) + 1)) == ERROR_SUCCESS)
  400. {
  401. return true;
  402. }
  403. return false;
  404. }
  405. #else
  406. bool cmSystemTools::WriteRegistryValue(const char *, const char *)
  407. {
  408. return false;
  409. }
  410. #endif
  411. // Delete a registry value.
  412. // Example :
  413. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  414. // => will delete the data of the "default" value of the key
  415. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  416. // => will delete the data of the "Root" value of the key
  417. #if defined(_WIN32) && !defined(__CYGWIN__)
  418. bool cmSystemTools::DeleteRegistryValue(const char *key)
  419. {
  420. std::string primary = key;
  421. std::string second;
  422. std::string valuename;
  423. size_t start = primary.find("\\");
  424. if (start == std::string::npos)
  425. {
  426. return false;
  427. }
  428. size_t valuenamepos = primary.find(";");
  429. if (valuenamepos != std::string::npos)
  430. {
  431. valuename = primary.substr(valuenamepos+1);
  432. }
  433. second = primary.substr(start+1, valuenamepos-start-1);
  434. primary = primary.substr(0, start);
  435. HKEY primaryKey;
  436. if (primary == "HKEY_CURRENT_USER")
  437. {
  438. primaryKey = HKEY_CURRENT_USER;
  439. }
  440. if (primary == "HKEY_CURRENT_CONFIG")
  441. {
  442. primaryKey = HKEY_CURRENT_CONFIG;
  443. }
  444. if (primary == "HKEY_CLASSES_ROOT")
  445. {
  446. primaryKey = HKEY_CLASSES_ROOT;
  447. }
  448. if (primary == "HKEY_LOCAL_MACHINE")
  449. {
  450. primaryKey = HKEY_LOCAL_MACHINE;
  451. }
  452. if (primary == "HKEY_USERS")
  453. {
  454. primaryKey = HKEY_USERS;
  455. }
  456. HKEY hKey;
  457. if(RegOpenKeyEx(primaryKey,
  458. second.c_str(),
  459. 0,
  460. KEY_WRITE,
  461. &hKey) != ERROR_SUCCESS)
  462. {
  463. return false;
  464. }
  465. else
  466. {
  467. if(RegDeleteValue(hKey,
  468. (LPTSTR)valuename.c_str()) == ERROR_SUCCESS)
  469. {
  470. return true;
  471. }
  472. }
  473. return false;
  474. }
  475. #else
  476. bool cmSystemTools::DeleteRegistryValue(const char *)
  477. {
  478. return false;
  479. }
  480. #endif
  481. // replace replace with with as many times as it shows up in source.
  482. // write the result into source.
  483. #if defined(_WIN32) && !defined(__CYGWIN__)
  484. void cmSystemTools::ExpandRegistryValues(std::string& source)
  485. {
  486. // Regular expression to match anything inside [...] that begins in HKEY.
  487. // Note that there is a special rule for regular expressions to match a
  488. // close square-bracket inside a list delimited by square brackets.
  489. // The "[^]]" part of this expression will match any character except
  490. // a close square-bracket. The ']' character must be the first in the
  491. // list of characters inside the [^...] block of the expression.
  492. cmRegularExpression regEntry("\\[(HKEY[^]]*)\\]");
  493. // check for black line or comment
  494. while (regEntry.find(source))
  495. {
  496. // the arguments are the second match
  497. std::string key = regEntry.match(1);
  498. std::string val;
  499. if (ReadRegistryValue(key.c_str(), val))
  500. {
  501. std::string reg = "[";
  502. reg += key + "]";
  503. cmSystemTools::ReplaceString(source, reg.c_str(), val.c_str());
  504. }
  505. else
  506. {
  507. std::string reg = "[";
  508. reg += key + "]";
  509. cmSystemTools::ReplaceString(source, reg.c_str(), "/registry");
  510. }
  511. }
  512. }
  513. #else
  514. void cmSystemTools::ExpandRegistryValues(std::string&)
  515. {
  516. }
  517. #endif
  518. std::string cmSystemTools::EscapeQuotes(const char* str)
  519. {
  520. std::string result = "";
  521. for(const char* ch = str; *ch != '\0'; ++ch)
  522. {
  523. if(*ch == '"')
  524. {
  525. result += '\\';
  526. }
  527. result += *ch;
  528. }
  529. return result;
  530. }
  531. bool cmSystemTools::SameFile(const char* file1, const char* file2)
  532. {
  533. #ifdef _WIN32
  534. HANDLE hFile1, hFile2;
  535. hFile1 = CreateFile( file1,
  536. GENERIC_READ,
  537. FILE_SHARE_READ ,
  538. NULL,
  539. OPEN_EXISTING,
  540. FILE_FLAG_BACKUP_SEMANTICS,
  541. NULL
  542. );
  543. hFile2 = CreateFile( file2,
  544. GENERIC_READ,
  545. FILE_SHARE_READ,
  546. NULL,
  547. OPEN_EXISTING,
  548. FILE_FLAG_BACKUP_SEMANTICS,
  549. NULL
  550. );
  551. if( hFile1 == INVALID_HANDLE_VALUE || hFile2 == INVALID_HANDLE_VALUE)
  552. {
  553. if(hFile1 != INVALID_HANDLE_VALUE)
  554. {
  555. CloseHandle(hFile1);
  556. }
  557. if(hFile2 != INVALID_HANDLE_VALUE)
  558. {
  559. CloseHandle(hFile2);
  560. }
  561. return false;
  562. }
  563. BY_HANDLE_FILE_INFORMATION fiBuf1;
  564. BY_HANDLE_FILE_INFORMATION fiBuf2;
  565. GetFileInformationByHandle( hFile1, &fiBuf1 );
  566. GetFileInformationByHandle( hFile2, &fiBuf2 );
  567. CloseHandle(hFile1);
  568. CloseHandle(hFile2);
  569. return (fiBuf1.nFileIndexHigh == fiBuf2.nFileIndexHigh &&
  570. fiBuf1.nFileIndexLow == fiBuf2.nFileIndexLow);
  571. #else
  572. struct stat fileStat1, fileStat2;
  573. if (stat(file1, &fileStat1) == 0 && stat(file2, &fileStat2) == 0)
  574. {
  575. // see if the files are the same file
  576. // check the device inode and size
  577. if(memcmp(&fileStat2.st_dev, &fileStat1.st_dev, sizeof(fileStat1.st_dev)) == 0 &&
  578. memcmp(&fileStat2.st_ino, &fileStat1.st_ino, sizeof(fileStat1.st_ino)) == 0 &&
  579. fileStat2.st_size == fileStat1.st_size
  580. )
  581. {
  582. return true;
  583. }
  584. }
  585. return false;
  586. #endif
  587. }
  588. // return true if the file exists
  589. bool cmSystemTools::FileExists(const char* filename)
  590. {
  591. struct stat fs;
  592. if (stat(filename, &fs) != 0)
  593. {
  594. return false;
  595. }
  596. else
  597. {
  598. return true;
  599. }
  600. }
  601. // Return a capitalized string (i.e the first letter is uppercased, all other
  602. // are lowercased)
  603. std::string cmSystemTools::Capitalized(const std::string& s)
  604. {
  605. std::string n;
  606. n.resize(s.size());
  607. n[0] = toupper(s[0]);
  608. for (size_t i = 1; i < s.size(); i++)
  609. {
  610. n[i] = tolower(s[i]);
  611. }
  612. return n;
  613. }
  614. // Return a lower case string
  615. std::string cmSystemTools::LowerCase(const std::string& s)
  616. {
  617. std::string n;
  618. n.resize(s.size());
  619. for (size_t i = 0; i < s.size(); i++)
  620. {
  621. n[i] = tolower(s[i]);
  622. }
  623. return n;
  624. }
  625. // Return a lower case string
  626. std::string cmSystemTools::UpperCase(const std::string& s)
  627. {
  628. std::string n;
  629. n.resize(s.size());
  630. for (size_t i = 0; i < s.size(); i++)
  631. {
  632. n[i] = toupper(s[i]);
  633. }
  634. return n;
  635. }
  636. // convert windows slashes to unix slashes
  637. void cmSystemTools::ConvertToUnixSlashes(std::string& path)
  638. {
  639. std::string::size_type pos = 0;
  640. while((pos = path.find('\\', pos)) != std::string::npos)
  641. {
  642. path[pos] = '/';
  643. pos++;
  644. }
  645. // Remove all // from the path just like most unix shells
  646. int start_find = 0;
  647. #ifdef _WIN32
  648. // However, on windows if the first characters are both slashes,
  649. // then keep them that way, so that network paths can be handled.
  650. start_find = 1;
  651. #endif
  652. while((pos = path.find("//", start_find)) != std::string::npos)
  653. {
  654. cmSystemTools::ReplaceString(path, "//", "/");
  655. }
  656. // remove any trailing slash
  657. if(path.size() && path[path.size()-1] == '/')
  658. {
  659. path = path.substr(0, path.size()-1);
  660. }
  661. // if there is a tilda ~ then replace it with HOME
  662. if(path.find("~") == 0)
  663. {
  664. if (getenv("HOME"))
  665. {
  666. path = std::string(getenv("HOME")) + path.substr(1);
  667. }
  668. }
  669. // if there is a /tmp_mnt in a path get rid of it!
  670. // stupid sgi's
  671. if(path.find("/tmp_mnt") == 0)
  672. {
  673. path = path.substr(8);
  674. }
  675. }
  676. // change // to /, and escape any spaces in the path
  677. std::string cmSystemTools::ConvertToUnixOutputPath(const char* path)
  678. {
  679. std::string ret = path;
  680. // remove // except at the beginning might be a cygwin drive
  681. std::string::size_type pos = 1;
  682. while((pos = ret.find("//", pos)) != std::string::npos)
  683. {
  684. ret.erase(pos, 1);
  685. }
  686. // now escape spaces if there is a space in the path
  687. if(ret.find(" ") != std::string::npos)
  688. {
  689. std::string result = "";
  690. char lastch = 1;
  691. for(const char* ch = ret.c_str(); *ch != '\0'; ++ch)
  692. {
  693. // if it is already escaped then don't try to escape it again
  694. if(*ch == ' ' && lastch != '\\')
  695. {
  696. result += '\\';
  697. }
  698. result += *ch;
  699. lastch = *ch;
  700. }
  701. ret = result;
  702. }
  703. return ret;
  704. }
  705. std::string cmSystemTools::EscapeSpaces(const char* str)
  706. {
  707. #if defined(_WIN32) && !defined(__CYGWIN__)
  708. std::string result;
  709. // if there are spaces
  710. std::string temp = str;
  711. if (temp.find(" ") != std::string::npos &&
  712. temp.find("\"")==std::string::npos)
  713. {
  714. result = "\"";
  715. result += str;
  716. result += "\"";
  717. return result;
  718. }
  719. return str;
  720. #else
  721. std::string result = "";
  722. for(const char* ch = str; *ch != '\0'; ++ch)
  723. {
  724. if(*ch == ' ')
  725. {
  726. result += '\\';
  727. }
  728. result += *ch;
  729. }
  730. return result;
  731. #endif
  732. }
  733. std::string cmSystemTools::ConvertToOutputPath(const char* path)
  734. {
  735. #if defined(_WIN32) && !defined(__CYGWIN__)
  736. return cmSystemTools::ConvertToWindowsOutputPath(path);
  737. #else
  738. return cmSystemTools::ConvertToUnixOutputPath(path);
  739. #endif
  740. }
  741. // remove double slashes not at the start
  742. std::string cmSystemTools::ConvertToWindowsOutputPath(const char* path)
  743. {
  744. std::string ret = path;
  745. std::string::size_type pos = 0;
  746. // first convert all of the slashes
  747. while((pos = ret.find('/', pos)) != std::string::npos)
  748. {
  749. ret[pos] = '\\';
  750. pos++;
  751. }
  752. // check for really small paths
  753. if(ret.size() < 2)
  754. {
  755. return ret;
  756. }
  757. // now clean up a bit and remove double slashes
  758. // Only if it is not the first position in the path which is a network
  759. // path on windows
  760. pos = 1; // start at position 1
  761. if(ret[0] == '\"')
  762. {
  763. pos = 2; // if the string is already quoted then start at 2
  764. if(ret.size() < 3)
  765. {
  766. return ret;
  767. }
  768. }
  769. while((pos = ret.find("\\\\", pos)) != std::string::npos)
  770. {
  771. ret.erase(pos, 1);
  772. }
  773. // now double quote the path if it has spaces in it
  774. // and is not already double quoted
  775. if(ret.find(" ") != std::string::npos
  776. && ret[0] != '\"')
  777. {
  778. std::string result;
  779. result = "\"" + ret + "\"";
  780. ret = result;
  781. }
  782. return ret;
  783. }
  784. std::string cmSystemTools::RemoveEscapes(const char* s)
  785. {
  786. std::string result = "";
  787. for(const char* ch = s; *ch; ++ch)
  788. {
  789. if(*ch == '\\' && *(ch+1) != ';')
  790. {
  791. ++ch;
  792. switch (*ch)
  793. {
  794. case '\\': result.insert(result.end(), '\\'); break;
  795. case '"': result.insert(result.end(), '"'); break;
  796. case ' ': result.insert(result.end(), ' '); break;
  797. case 't': result.insert(result.end(), '\t'); break;
  798. case 'n': result.insert(result.end(), '\n'); break;
  799. case 'r': result.insert(result.end(), '\r'); break;
  800. case '0': result.insert(result.end(), '\0'); break;
  801. case '\0':
  802. {
  803. cmSystemTools::Error("Trailing backslash in argument:\n", s);
  804. return result;
  805. }
  806. default:
  807. {
  808. std::string chStr(1, *ch);
  809. cmSystemTools::Error("Invalid escape sequence \\", chStr.c_str(),
  810. "\nin argument ", s);
  811. }
  812. }
  813. }
  814. else
  815. {
  816. result.insert(result.end(), *ch);
  817. }
  818. }
  819. return result;
  820. }
  821. void cmSystemTools::Error(const char* m1, const char* m2,
  822. const char* m3, const char* m4)
  823. {
  824. std::string message = "CMake Error: ";
  825. if(m1)
  826. {
  827. message += m1;
  828. }
  829. if(m2)
  830. {
  831. message += m2;
  832. }
  833. if(m3)
  834. {
  835. message += m3;
  836. }
  837. if(m4)
  838. {
  839. message += m4;
  840. }
  841. cmSystemTools::s_ErrorOccured = true;
  842. cmSystemTools::Message(message.c_str(),"Error");
  843. }
  844. void cmSystemTools::SetErrorCallback(ErrorCallback f, void* clientData)
  845. {
  846. s_ErrorCallback = f;
  847. s_ErrorCallbackClientData = clientData;
  848. }
  849. void cmSystemTools::Message(const char* m1, const char *title)
  850. {
  851. if(s_DisableMessages)
  852. {
  853. return;
  854. }
  855. if(s_ErrorCallback)
  856. {
  857. (*s_ErrorCallback)(m1, title, s_DisableMessages, s_ErrorCallbackClientData);
  858. return;
  859. }
  860. else
  861. {
  862. std::cerr << m1 << std::endl << std::flush;
  863. }
  864. }
  865. bool cmSystemTools::CopyFileIfDifferent(const char* source,
  866. const char* destination)
  867. {
  868. if(cmSystemTools::FilesDiffer(source, destination))
  869. {
  870. cmSystemTools::cmCopyFile(source, destination);
  871. return true;
  872. }
  873. return false;
  874. }
  875. bool cmSystemTools::FilesDiffer(const char* source,
  876. const char* destination)
  877. {
  878. struct stat statSource;
  879. if (stat(source, &statSource) != 0)
  880. {
  881. return true;
  882. }
  883. struct stat statDestination;
  884. if (stat(destination, &statDestination) != 0)
  885. {
  886. return true;
  887. }
  888. if(statSource.st_size != statDestination.st_size)
  889. {
  890. return true;
  891. }
  892. if(statSource.st_size == 0)
  893. {
  894. return false;
  895. }
  896. #if defined(_WIN32) || defined(__CYGWIN__)
  897. std::ifstream finSource(source,
  898. std::ios::binary | std::ios::in);
  899. std::ifstream finDestination(destination,
  900. std::ios::binary | std::ios::in);
  901. #else
  902. std::ifstream finSource(source);
  903. std::ifstream finDestination(destination);
  904. #endif
  905. if(!finSource || !finDestination)
  906. {
  907. return true;
  908. }
  909. char* source_buf = new char[statSource.st_size];
  910. char* dest_buf = new char[statSource.st_size];
  911. finSource.read(source_buf, statSource.st_size);
  912. finDestination.read(dest_buf, statSource.st_size);
  913. if(statSource.st_size != static_cast<long>(finSource.gcount()) ||
  914. statSource.st_size != static_cast<long>(finDestination.gcount()))
  915. {
  916. cmOStringStream msg;
  917. msg << "FilesDiffer failed to read files (allocated: "
  918. << statSource.st_size << ", read source: " << finSource.gcount()
  919. << ", read dest: " << finDestination.gcount();
  920. cmSystemTools::Error(msg.str().c_str());
  921. delete [] source_buf;
  922. delete [] dest_buf;
  923. return false;
  924. }
  925. int ret = memcmp((const void*)source_buf,
  926. (const void*)dest_buf,
  927. statSource.st_size);
  928. delete [] dest_buf;
  929. delete [] source_buf;
  930. return ret != 0;
  931. }
  932. /**
  933. * Copy a file named by "source" to the file named by "destination".
  934. */
  935. void cmSystemTools::cmCopyFile(const char* source,
  936. const char* destination)
  937. {
  938. const int bufferSize = 4096;
  939. char buffer[bufferSize];
  940. // If destination is a directory, try to create a file with the same
  941. // name as the source in that directory.
  942. std::string new_destination;
  943. if(cmSystemTools::FileExists(destination) &&
  944. cmSystemTools::FileIsDirectory(destination))
  945. {
  946. new_destination = destination;
  947. cmSystemTools::ConvertToUnixSlashes(new_destination);
  948. new_destination += '/';
  949. std::string source_name = source;
  950. new_destination += cmSystemTools::GetFilenameName(source_name);
  951. destination = new_destination.c_str();
  952. }
  953. // Create destination directory
  954. std::string destination_dir = destination;
  955. destination_dir = cmSystemTools::GetFilenamePath(destination_dir);
  956. cmSystemTools::MakeDirectory(destination_dir.c_str());
  957. // Open files
  958. #if defined(_WIN32) || defined(__CYGWIN__)
  959. std::ifstream fin(source,
  960. std::ios::binary | std::ios::in);
  961. #else
  962. std::ifstream fin(source);
  963. #endif
  964. if(!fin)
  965. {
  966. int e = errno;
  967. std::string m = "CopyFile failed to open source file \"";
  968. m += source;
  969. m += "\"";
  970. m += " System Error: ";
  971. m += strerror(e);
  972. cmSystemTools::Error(m.c_str());
  973. return;
  974. }
  975. #if defined(_WIN32) || defined(__CYGWIN__)
  976. std::ofstream fout(destination,
  977. std::ios::binary | std::ios::out | std::ios::trunc);
  978. #else
  979. std::ofstream fout(destination,
  980. std::ios::out | std::ios::trunc);
  981. #endif
  982. if(!fout)
  983. {
  984. int e = errno;
  985. std::string m = "CopyFile failed to open destination file \"";
  986. m += destination;
  987. m += "\"";
  988. m += " System Error: ";
  989. m += strerror(e);
  990. cmSystemTools::Error(m.c_str());
  991. return;
  992. }
  993. // This copy loop is very sensitive on certain platforms with
  994. // slightly broken stream libraries (like HPUX). Normally, it is
  995. // incorrect to not check the error condition on the fin.read()
  996. // before using the data, but the fin.gcount() will be zero if an
  997. // error occurred. Therefore, the loop should be safe everywhere.
  998. while(fin)
  999. {
  1000. fin.read(buffer, bufferSize);
  1001. if(fin.gcount())
  1002. {
  1003. fout.write(buffer, fin.gcount());
  1004. }
  1005. }
  1006. // Make sure the operating system has finished writing the file
  1007. // before closing it. This will ensure the file is finished before
  1008. // the check below.
  1009. fout.flush();
  1010. fin.close();
  1011. fout.close();
  1012. // More checks.
  1013. struct stat statSource, statDestination;
  1014. statSource.st_size = 12345;
  1015. statDestination.st_size = 12345;
  1016. if(stat(source, &statSource) != 0)
  1017. {
  1018. int e = errno;
  1019. std::string m = "CopyFile failed to stat source file \"";
  1020. m += source;
  1021. m += "\"";
  1022. m += " System Error: ";
  1023. m += strerror(e);
  1024. cmSystemTools::Error(m.c_str());
  1025. }
  1026. else if(stat(destination, &statDestination) != 0)
  1027. {
  1028. int e = errno;
  1029. std::string m = "CopyFile failed to stat destination file \"";
  1030. m += source;
  1031. m += "\"";
  1032. m += " System Error: ";
  1033. m += strerror(e);
  1034. cmSystemTools::Error(m.c_str());
  1035. }
  1036. else if(statSource.st_size != statDestination.st_size)
  1037. {
  1038. cmOStringStream msg;
  1039. msg << "CopyFile failed to copy files: source \""
  1040. << source << "\", size " << statSource.st_size << ", destination \""
  1041. << destination << "\", size " << statDestination.st_size;
  1042. cmSystemTools::Error(msg.str().c_str());
  1043. }
  1044. }
  1045. // return true if the file exists
  1046. long int cmSystemTools::ModifiedTime(const char* filename)
  1047. {
  1048. struct stat fs;
  1049. if (stat(filename, &fs) != 0)
  1050. {
  1051. return 0;
  1052. }
  1053. else
  1054. {
  1055. return (long int)fs.st_mtime;
  1056. }
  1057. }
  1058. void cmSystemTools::ReportLastSystemError(const char* msg)
  1059. {
  1060. int e = errno;
  1061. std::string m = msg;
  1062. m += ": System Error: ";
  1063. m += strerror(e);
  1064. cmSystemTools::Error(m.c_str());
  1065. }
  1066. bool cmSystemTools::RemoveFile(const char* source)
  1067. {
  1068. return unlink(source) != 0 ? false : true;
  1069. }
  1070. bool cmSystemTools::IsOn(const char* val)
  1071. {
  1072. if (!val)
  1073. {
  1074. return false;
  1075. }
  1076. std::basic_string<char> v = val;
  1077. for(std::basic_string<char>::iterator c = v.begin();
  1078. c != v.end(); c++)
  1079. {
  1080. *c = toupper(*c);
  1081. }
  1082. return (v == "ON" || v == "1" || v == "YES" || v == "TRUE" || v == "Y");
  1083. }
  1084. bool cmSystemTools::IsNOTFOUND(const char* val)
  1085. {
  1086. cmRegularExpression reg("-NOTFOUND$");
  1087. if(reg.find(val))
  1088. {
  1089. return true;
  1090. }
  1091. return std::string("NOTFOUND") == val;
  1092. }
  1093. bool cmSystemTools::IsOff(const char* val)
  1094. {
  1095. if (!val || strlen(val) == 0)
  1096. {
  1097. return true;
  1098. }
  1099. std::basic_string<char> v = val;
  1100. for(std::basic_string<char>::iterator c = v.begin();
  1101. c != v.end(); c++)
  1102. {
  1103. *c = toupper(*c);
  1104. }
  1105. return (v == "OFF" || v == "0" || v == "NO" || v == "FALSE" ||
  1106. v == "N" || cmSystemTools::IsNOTFOUND(v.c_str()) || v == "IGNORE");
  1107. }
  1108. bool cmSystemTools::RunCommand(const char* command,
  1109. std::string& output,
  1110. const char* dir,
  1111. bool verbose,
  1112. int timeout)
  1113. {
  1114. int dummy;
  1115. return cmSystemTools::RunCommand(command, output, dummy,
  1116. dir, verbose, timeout);
  1117. }
  1118. #if defined(WIN32) && !defined(__CYGWIN__)
  1119. #include "cmWin32ProcessExecution.h"
  1120. // use this for shell commands like echo and dir
  1121. bool RunCommandViaWin32(const char* command,
  1122. const char* dir,
  1123. std::string& output,
  1124. int& retVal,
  1125. bool verbose,
  1126. int timeout)
  1127. {
  1128. #if defined(__BORLANDC__)
  1129. return cmWin32ProcessExecution::BorlandRunCommand(command, dir, output,
  1130. retVal,
  1131. verbose, timeout,
  1132. cmSystemTools::GetRunCommandHideConsole());
  1133. #else // Visual studio
  1134. ::SetLastError(ERROR_SUCCESS);
  1135. if ( ! command )
  1136. {
  1137. cmSystemTools::Error("No command specified");
  1138. return false;
  1139. }
  1140. cmWin32ProcessExecution resProc;
  1141. if(cmSystemTools::GetRunCommandHideConsole())
  1142. {
  1143. resProc.SetHideWindows(true);
  1144. }
  1145. if ( cmSystemTools::GetWindows9xComspecSubstitute() )
  1146. {
  1147. resProc.SetConsoleSpawn(cmSystemTools::GetWindows9xComspecSubstitute() );
  1148. }
  1149. if ( !resProc.StartProcess(command, dir, verbose) )
  1150. {
  1151. std::cout << "Problem starting command" << std::endl;
  1152. return false;
  1153. }
  1154. resProc.Wait(timeout);
  1155. output = resProc.GetOutput();
  1156. retVal = resProc.GetExitValue();
  1157. return true;
  1158. #endif
  1159. }
  1160. // use this for shell commands like echo and dir
  1161. bool RunCommandViaSystem(const char* command,
  1162. const char* dir,
  1163. std::string& output,
  1164. int& retVal,
  1165. bool verbose)
  1166. {
  1167. std::cout << "@@ " << command << std::endl;
  1168. const int BUFFER_SIZE = 4096;
  1169. char buffer[BUFFER_SIZE];
  1170. std::string commandInDir;
  1171. if(dir)
  1172. {
  1173. commandInDir = "cd ";
  1174. commandInDir += cmSystemTools::ConvertToOutputPath(dir);
  1175. commandInDir += " && ";
  1176. commandInDir += command;
  1177. }
  1178. else
  1179. {
  1180. commandInDir = command;
  1181. }
  1182. command = commandInDir.c_str();
  1183. std::string commandToFile = command;
  1184. commandToFile += " > ";
  1185. std::string tempFile;
  1186. tempFile += _tempnam(0, "cmake");
  1187. commandToFile += tempFile;
  1188. retVal = system(commandToFile.c_str());
  1189. std::ifstream fin(tempFile.c_str());
  1190. if(!fin)
  1191. {
  1192. if(verbose)
  1193. {
  1194. std::string errormsg = "RunCommand produced no output: command: \"";
  1195. errormsg += command;
  1196. errormsg += "\"";
  1197. errormsg += "\nOutput file: ";
  1198. errormsg += tempFile;
  1199. cmSystemTools::Error(errormsg.c_str());
  1200. }
  1201. fin.close();
  1202. cmSystemTools::RemoveFile(tempFile.c_str());
  1203. return false;
  1204. }
  1205. bool multiLine = false;
  1206. std::string line;
  1207. while(cmSystemTools::GetLineFromStream(fin, line))
  1208. {
  1209. output += line;
  1210. if(multiLine)
  1211. {
  1212. output += "\n";
  1213. }
  1214. multiLine = true;
  1215. }
  1216. fin.close();
  1217. cmSystemTools::RemoveFile(tempFile.c_str());
  1218. return true;
  1219. }
  1220. #else // We have popen
  1221. bool RunCommandViaPopen(const char* command,
  1222. const char* dir,
  1223. std::string& output,
  1224. int& retVal,
  1225. bool verbose,
  1226. int /*timeout*/)
  1227. {
  1228. // if only popen worked on windows.....
  1229. std::string commandInDir;
  1230. if(dir)
  1231. {
  1232. commandInDir = "cd \"";
  1233. commandInDir += dir;
  1234. commandInDir += "\" && ";
  1235. commandInDir += command;
  1236. }
  1237. else
  1238. {
  1239. commandInDir = command;
  1240. }
  1241. commandInDir += " 2>&1";
  1242. command = commandInDir.c_str();
  1243. const int BUFFER_SIZE = 4096;
  1244. char buffer[BUFFER_SIZE];
  1245. if(verbose)
  1246. {
  1247. std::cout << "running " << command << std::endl;
  1248. }
  1249. fflush(stdout);
  1250. fflush(stderr);
  1251. FILE* cpipe = popen(command, "r");
  1252. if(!cpipe)
  1253. {
  1254. return false;
  1255. }
  1256. fgets(buffer, BUFFER_SIZE, cpipe);
  1257. while(!feof(cpipe))
  1258. {
  1259. if(verbose)
  1260. {
  1261. std::cout << buffer << std::flush;
  1262. }
  1263. output += buffer;
  1264. fgets(buffer, BUFFER_SIZE, cpipe);
  1265. }
  1266. retVal = pclose(cpipe);
  1267. if (WIFEXITED(retVal))
  1268. {
  1269. retVal = WEXITSTATUS(retVal);
  1270. return true;
  1271. }
  1272. if (WIFSIGNALED(retVal))
  1273. {
  1274. retVal = WTERMSIG(retVal);
  1275. cmOStringStream error;
  1276. error << "\nProcess terminated due to ";
  1277. switch (retVal)
  1278. {
  1279. #ifdef SIGKILL
  1280. case SIGKILL:
  1281. error << "SIGKILL";
  1282. break;
  1283. #endif
  1284. #ifdef SIGFPE
  1285. case SIGFPE:
  1286. error << "SIGFPE";
  1287. break;
  1288. #endif
  1289. #ifdef SIGBUS
  1290. case SIGBUS:
  1291. error << "SIGBUS";
  1292. break;
  1293. #endif
  1294. #ifdef SIGSEGV
  1295. case SIGSEGV:
  1296. error << "SIGSEGV";
  1297. break;
  1298. #endif
  1299. default:
  1300. error << "signal " << retVal;
  1301. break;
  1302. }
  1303. output += error.str();
  1304. }
  1305. return false;
  1306. }
  1307. #endif // endif WIN32 not CYGWIN
  1308. // run a command unix uses popen (easy)
  1309. // windows uses system and ShortPath
  1310. bool cmSystemTools::RunCommand(const char* command,
  1311. std::string& output,
  1312. int &retVal,
  1313. const char* dir,
  1314. bool verbose,
  1315. int timeout)
  1316. {
  1317. if(s_DisableRunCommandOutput)
  1318. {
  1319. verbose = false;
  1320. }
  1321. #if defined(WIN32) && !defined(__CYGWIN__)
  1322. // if the command does not start with a quote, then
  1323. // try to find the program, and if the program can not be
  1324. // found use system to run the command as it must be a built in
  1325. // shell command like echo or dir
  1326. int count = 0;
  1327. if(command[0] == '\"')
  1328. {
  1329. // count the number of quotes
  1330. for(const char* s = command; *s != 0; ++s)
  1331. {
  1332. if(*s == '\"')
  1333. {
  1334. count++;
  1335. if(count > 2)
  1336. {
  1337. break;
  1338. }
  1339. }
  1340. }
  1341. // if there are more than two double quotes use
  1342. // GetShortPathName, the cmd.exe program in windows which
  1343. // is used by system fails to execute if there are more than
  1344. // one set of quotes in the arguments
  1345. if(count > 2)
  1346. {
  1347. cmRegularExpression quoted("^\"([^\"]*)\"[ \t](.*)");
  1348. if(quoted.find(command))
  1349. {
  1350. std::string shortCmd;
  1351. std::string cmd = quoted.match(1);
  1352. std::string args = quoted.match(2);
  1353. if(! cmSystemTools::FileExists(cmd.c_str()) )
  1354. {
  1355. shortCmd = cmd;
  1356. }
  1357. else if(!cmSystemTools::GetShortPath(cmd.c_str(), shortCmd))
  1358. {
  1359. cmSystemTools::Error("GetShortPath failed for " , cmd.c_str());
  1360. return false;
  1361. }
  1362. shortCmd += " ";
  1363. shortCmd += args;
  1364. //return RunCommandViaSystem(shortCmd.c_str(), dir,
  1365. // output, retVal, verbose);
  1366. //return WindowsRunCommand(shortCmd.c_str(), dir,
  1367. //output, retVal, verbose);
  1368. return RunCommandViaWin32(shortCmd.c_str(), dir,
  1369. output, retVal, verbose, timeout);
  1370. }
  1371. else
  1372. {
  1373. cmSystemTools::Error("Could not parse command line with quotes ",
  1374. command);
  1375. }
  1376. }
  1377. }
  1378. // if there is only one set of quotes or no quotes then just run the command
  1379. //return RunCommandViaSystem(command, dir, output, retVal, verbose);
  1380. //return WindowsRunCommand(command, dir, output, retVal, verbose);
  1381. return ::RunCommandViaWin32(command, dir, output, retVal, verbose, timeout);
  1382. #else
  1383. return ::RunCommandViaPopen(command, dir, output, retVal, verbose, timeout);
  1384. #endif
  1385. }
  1386. /**
  1387. * Find the file the given name. Searches the given path and then
  1388. * the system search path. Returns the full path to the file if it is
  1389. * found. Otherwise, the empty string is returned.
  1390. */
  1391. std::string cmSystemTools::FindFile(const char* name,
  1392. const std::vector<std::string>& userPaths)
  1393. {
  1394. // Add the system search path to our path.
  1395. std::vector<std::string> path = userPaths;
  1396. cmSystemTools::GetPath(path);
  1397. std::string tryPath;
  1398. for(std::vector<std::string>::const_iterator p = path.begin();
  1399. p != path.end(); ++p)
  1400. {
  1401. tryPath = *p;
  1402. tryPath += "/";
  1403. tryPath += name;
  1404. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1405. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1406. {
  1407. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1408. }
  1409. }
  1410. // Couldn't find the file.
  1411. return "";
  1412. }
  1413. /**
  1414. * Find the executable with the given name. Searches the given path and then
  1415. * the system search path. Returns the full path to the executable if it is
  1416. * found. Otherwise, the empty string is returned.
  1417. */
  1418. std::string cmSystemTools::FindProgram(const char* name,
  1419. const std::vector<std::string>& userPaths,
  1420. bool no_system_path)
  1421. {
  1422. if(!name)
  1423. {
  1424. return "";
  1425. }
  1426. // See if the executable exists as written.
  1427. if(cmSystemTools::FileExists(name) &&
  1428. !cmSystemTools::FileIsDirectory(name))
  1429. {
  1430. return cmSystemTools::CollapseFullPath(name);
  1431. }
  1432. std::string tryPath = name;
  1433. tryPath += cmSystemTools::GetExecutableExtension();
  1434. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1435. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1436. {
  1437. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1438. }
  1439. // Add the system search path to our path.
  1440. std::vector<std::string> path = userPaths;
  1441. if (!no_system_path)
  1442. {
  1443. cmSystemTools::GetPath(path);
  1444. }
  1445. for(std::vector<std::string>::const_iterator p = path.begin();
  1446. p != path.end(); ++p)
  1447. {
  1448. tryPath = *p;
  1449. tryPath += "/";
  1450. tryPath += name;
  1451. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1452. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1453. {
  1454. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1455. }
  1456. #ifdef _WIN32
  1457. tryPath += ".com";
  1458. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1459. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1460. {
  1461. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1462. }
  1463. tryPath = *p;
  1464. tryPath += "/";
  1465. tryPath += name;
  1466. #endif
  1467. tryPath += cmSystemTools::GetExecutableExtension();
  1468. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1469. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1470. {
  1471. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1472. }
  1473. }
  1474. // Couldn't find the program.
  1475. return "";
  1476. }
  1477. /**
  1478. * Find the library with the given name. Searches the given path and then
  1479. * the system search path. Returns the full path to the library if it is
  1480. * found. Otherwise, the empty string is returned.
  1481. */
  1482. std::string cmSystemTools::FindLibrary(const char* name,
  1483. const std::vector<std::string>& userPaths)
  1484. {
  1485. // See if the executable exists as written.
  1486. if(cmSystemTools::FileExists(name) &&
  1487. !cmSystemTools::FileIsDirectory(name))
  1488. {
  1489. return cmSystemTools::CollapseFullPath(name);
  1490. }
  1491. // Add the system search path to our path.
  1492. std::vector<std::string> path = userPaths;
  1493. cmSystemTools::GetPath(path);
  1494. std::string tryPath;
  1495. for(std::vector<std::string>::const_iterator p = path.begin();
  1496. p != path.end(); ++p)
  1497. {
  1498. #if defined(_WIN32) && !defined(__CYGWIN__)
  1499. tryPath = *p;
  1500. tryPath += "/";
  1501. tryPath += name;
  1502. tryPath += ".lib";
  1503. if(cmSystemTools::FileExists(tryPath.c_str()))
  1504. {
  1505. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1506. }
  1507. #else
  1508. tryPath = *p;
  1509. tryPath += "/lib";
  1510. tryPath += name;
  1511. tryPath += ".so";
  1512. if(cmSystemTools::FileExists(tryPath.c_str()))
  1513. {
  1514. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1515. }
  1516. tryPath = *p;
  1517. tryPath += "/lib";
  1518. tryPath += name;
  1519. tryPath += ".a";
  1520. if(cmSystemTools::FileExists(tryPath.c_str()))
  1521. {
  1522. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1523. }
  1524. tryPath = *p;
  1525. tryPath += "/lib";
  1526. tryPath += name;
  1527. tryPath += ".sl";
  1528. if(cmSystemTools::FileExists(tryPath.c_str()))
  1529. {
  1530. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1531. }
  1532. tryPath = *p;
  1533. tryPath += "/lib";
  1534. tryPath += name;
  1535. tryPath += ".dylib";
  1536. if(cmSystemTools::FileExists(tryPath.c_str()))
  1537. {
  1538. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1539. }
  1540. #endif
  1541. }
  1542. // Couldn't find the library.
  1543. return "";
  1544. }
  1545. bool cmSystemTools::FileIsDirectory(const char* name)
  1546. {
  1547. struct stat fs;
  1548. if(stat(name, &fs) == 0)
  1549. {
  1550. #if _WIN32
  1551. return ((fs.st_mode & _S_IFDIR) != 0);
  1552. #else
  1553. return S_ISDIR(fs.st_mode);
  1554. #endif
  1555. }
  1556. else
  1557. {
  1558. return false;
  1559. }
  1560. }
  1561. int cmSystemTools::ChangeDirectory(const char *dir)
  1562. {
  1563. return Chdir(dir);
  1564. }
  1565. std::string cmSystemTools::GetCurrentWorkingDirectory()
  1566. {
  1567. char buf[2048];
  1568. std::string path = Getcwd(buf, 2048);
  1569. return path;
  1570. }
  1571. /**
  1572. * Given the path to a program executable, get the directory part of the path with the
  1573. * file stripped off. If there is no directory part, the empty string is returned.
  1574. */
  1575. std::string cmSystemTools::GetProgramPath(const char* in_name)
  1576. {
  1577. std::string dir, file;
  1578. cmSystemTools::SplitProgramPath(in_name, dir, file);
  1579. return dir;
  1580. }
  1581. /**
  1582. * Given the path to a program executable, get the directory part of the path
  1583. * with the file stripped off. If there is no directory part, the empty
  1584. * string is returned.
  1585. */
  1586. void cmSystemTools::SplitProgramPath(const char* in_name,
  1587. std::string& dir,
  1588. std::string& file,
  1589. bool errorReport)
  1590. {
  1591. dir = in_name;
  1592. file = "";
  1593. cmSystemTools::ConvertToUnixSlashes(dir);
  1594. if(!cmSystemTools::FileIsDirectory(dir.c_str()))
  1595. {
  1596. std::string::size_type slashPos = dir.rfind("/");
  1597. if(slashPos != std::string::npos)
  1598. {
  1599. file = dir.substr(slashPos+1);
  1600. dir = dir.substr(0, slashPos);
  1601. }
  1602. else
  1603. {
  1604. file = dir;
  1605. dir = "";
  1606. }
  1607. }
  1608. if((dir != "") && !cmSystemTools::FileIsDirectory(dir.c_str()))
  1609. {
  1610. std::string oldDir = in_name;
  1611. cmSystemTools::ConvertToUnixSlashes(oldDir);
  1612. if(errorReport)
  1613. {
  1614. cmSystemTools::Error("Error splitting file name off end of path:\n",
  1615. oldDir.c_str(), "\nDirectory not found: ",
  1616. dir.c_str());
  1617. }
  1618. dir = in_name;
  1619. return;
  1620. }
  1621. }
  1622. /**
  1623. * Given a path to a file or directory, convert it to a full path.
  1624. * This collapses away relative paths relative to the cwd argument
  1625. * (which defaults to the current working directory). The full path
  1626. * is returned.
  1627. */
  1628. std::string cmSystemTools::CollapseFullPath(const char* in_relative)
  1629. {
  1630. return cmSystemTools::CollapseFullPath(in_relative, 0);
  1631. }
  1632. std::string cmSystemTools::CollapseFullPath(const char* in_relative,
  1633. const char* in_base)
  1634. {
  1635. std::string dir, file;
  1636. cmSystemTools::SplitProgramPath(in_relative, dir, file, false);
  1637. // Save original working directory.
  1638. std::string orig = cmSystemTools::GetCurrentWorkingDirectory();
  1639. // Change to base of relative path.
  1640. if(in_base)
  1641. {
  1642. Chdir(in_base);
  1643. }
  1644. #ifdef _WIN32
  1645. // Follow relative path.
  1646. if(dir != "")
  1647. {
  1648. Chdir(dir.c_str());
  1649. }
  1650. // Get the resulting directory.
  1651. std::string newDir = cmSystemTools::GetCurrentWorkingDirectory();
  1652. // Add the file back on to the directory.
  1653. cmSystemTools::ConvertToUnixSlashes(newDir);
  1654. #else
  1655. # ifdef MAXPATHLEN
  1656. char resolved_name[MAXPATHLEN];
  1657. # else
  1658. # ifdef PATH_MAX
  1659. char resolved_name[PATH_MAX];
  1660. # else
  1661. char resolved_name[5024];
  1662. # endif
  1663. # endif
  1664. // Resolve relative path.
  1665. std::string newDir;
  1666. if(dir != "")
  1667. {
  1668. realpath(dir.c_str(), resolved_name);
  1669. newDir = resolved_name;
  1670. }
  1671. else
  1672. {
  1673. newDir = cmSystemTools::GetCurrentWorkingDirectory();
  1674. }
  1675. #endif
  1676. // Restore original working directory.
  1677. Chdir(orig.c_str());
  1678. // Construct and return the full path.
  1679. std::string newPath = newDir;
  1680. if(file != "")
  1681. {
  1682. newPath += "/";
  1683. newPath += file;
  1684. }
  1685. return newPath;
  1686. }
  1687. bool cmSystemTools::Split(const char* str, std::vector<cmStdString>& lines)
  1688. {
  1689. std::string data(str);
  1690. std::string::size_type lpos = 0;
  1691. while(lpos < data.length())
  1692. {
  1693. std::string::size_type rpos = data.find_first_of("\n", lpos);
  1694. if(rpos == std::string::npos)
  1695. {
  1696. // Line ends at end of string without a newline.
  1697. lines.push_back(data.substr(lpos));
  1698. return false;
  1699. }
  1700. if((rpos > lpos) && (data[rpos-1] == '\r'))
  1701. {
  1702. // Line ends in a "\r\n" pair, remove both characters.
  1703. lines.push_back(data.substr(lpos, (rpos-1)-lpos));
  1704. }
  1705. else
  1706. {
  1707. // Line ends in a "\n", remove the character.
  1708. lines.push_back(data.substr(lpos, rpos-lpos));
  1709. }
  1710. lpos = rpos+1;
  1711. }
  1712. return true;
  1713. }
  1714. /**
  1715. * Return path of a full filename (no trailing slashes).
  1716. * Warning: returned path is converted to Unix slashes format.
  1717. */
  1718. std::string cmSystemTools::GetFilenamePath(const std::string& filename)
  1719. {
  1720. std::string fn = filename;
  1721. cmSystemTools::ConvertToUnixSlashes(fn);
  1722. std::string::size_type slash_pos = fn.rfind("/");
  1723. if(slash_pos != std::string::npos)
  1724. {
  1725. return fn.substr(0, slash_pos);
  1726. }
  1727. else
  1728. {
  1729. return "";
  1730. }
  1731. }
  1732. /**
  1733. * Return file name of a full filename (i.e. file name without path).
  1734. */
  1735. std::string cmSystemTools::GetFilenameName(const std::string& filename)
  1736. {
  1737. std::string fn = filename;
  1738. cmSystemTools::ConvertToUnixSlashes(fn);
  1739. std::string::size_type slash_pos = fn.rfind("/");
  1740. if(slash_pos != std::string::npos)
  1741. {
  1742. return fn.substr(slash_pos + 1);
  1743. }
  1744. else
  1745. {
  1746. return filename;
  1747. }
  1748. }
  1749. /**
  1750. * Return file extension of a full filename (dot included).
  1751. * Warning: this is the longest extension (for example: .tar.gz)
  1752. */
  1753. std::string cmSystemTools::GetFilenameExtension(const std::string& filename)
  1754. {
  1755. std::string name = cmSystemTools::GetFilenameName(filename);
  1756. std::string::size_type dot_pos = name.find(".");
  1757. if(dot_pos != std::string::npos)
  1758. {
  1759. return name.substr(dot_pos);
  1760. }
  1761. else
  1762. {
  1763. return "";
  1764. }
  1765. }
  1766. /**
  1767. * Return file name without extension of a full filename (i.e. without path).
  1768. * Warning: it considers the longest extension (for example: .tar.gz)
  1769. */
  1770. std::string cmSystemTools::GetFilenameWithoutExtension(const std::string& filename)
  1771. {
  1772. std::string name = cmSystemTools::GetFilenameName(filename);
  1773. std::string::size_type dot_pos = name.find(".");
  1774. if(dot_pos != std::string::npos)
  1775. {
  1776. return name.substr(0, dot_pos);
  1777. }
  1778. else
  1779. {
  1780. return name;
  1781. }
  1782. }
  1783. /**
  1784. * Return file name without extension of a full filename (i.e. without path).
  1785. * Warning: it considers the last extension (for example: removes .gz
  1786. * from .tar.gz)
  1787. */
  1788. std::string
  1789. cmSystemTools::GetFilenameWithoutLastExtension(const std::string& filename)
  1790. {
  1791. std::string name = cmSystemTools::GetFilenameName(filename);
  1792. std::string::size_type dot_pos = name.rfind(".");
  1793. if(dot_pos != std::string::npos)
  1794. {
  1795. return name.substr(0, dot_pos);
  1796. }
  1797. else
  1798. {
  1799. return name;
  1800. }
  1801. }
  1802. bool cmSystemTools::FileIsFullPath(const char* in_name)
  1803. {
  1804. std::string name = in_name;
  1805. #if defined(_WIN32)
  1806. // On Windows, the name must be at least two characters long.
  1807. if(name.length() < 2)
  1808. {
  1809. return false;
  1810. }
  1811. if(name[1] == ':')
  1812. {
  1813. return true;
  1814. }
  1815. if(name[0] == '\\')
  1816. {
  1817. return true;
  1818. }
  1819. #else
  1820. // On UNIX, the name must be at least one character long.
  1821. if(name.length() < 1)
  1822. {
  1823. return false;
  1824. }
  1825. #endif
  1826. // On UNIX, the name must begin in a '/'.
  1827. // On Windows, if the name begins in a '/', then it is a full
  1828. // network path.
  1829. if(name[0] == '/')
  1830. {
  1831. return true;
  1832. }
  1833. return false;
  1834. }
  1835. void cmSystemTools::Glob(const char *directory, const char *regexp,
  1836. std::vector<std::string>& files)
  1837. {
  1838. cmDirectory d;
  1839. cmRegularExpression reg(regexp);
  1840. if (d.Load(directory))
  1841. {
  1842. size_t numf;
  1843. unsigned int i;
  1844. numf = d.GetNumberOfFiles();
  1845. for (i = 0; i < numf; i++)
  1846. {
  1847. std::string fname = d.GetFile(i);
  1848. if (reg.find(fname))
  1849. {
  1850. files.push_back(fname);
  1851. }
  1852. }
  1853. }
  1854. }
  1855. void cmSystemTools::GlobDirs(const char *fullPath,
  1856. std::vector<std::string>& files)
  1857. {
  1858. std::string path = fullPath;
  1859. std::string::size_type pos = path.find("/*");
  1860. if(pos == std::string::npos)
  1861. {
  1862. files.push_back(fullPath);
  1863. return;
  1864. }
  1865. std::string startPath = path.substr(0, pos);
  1866. std::string finishPath = path.substr(pos+2);
  1867. cmDirectory d;
  1868. if (d.Load(startPath.c_str()))
  1869. {
  1870. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)
  1871. {
  1872. if((std::string(d.GetFile(i)) != ".")
  1873. && (std::string(d.GetFile(i)) != ".."))
  1874. {
  1875. std::string fname = startPath;
  1876. fname +="/";
  1877. fname += d.GetFile(i);
  1878. if(cmSystemTools::FileIsDirectory(fname.c_str()))
  1879. {
  1880. fname += finishPath;
  1881. cmSystemTools::GlobDirs(fname.c_str(), files);
  1882. }
  1883. }
  1884. }
  1885. }
  1886. }
  1887. void cmSystemTools::ExpandList(std::vector<std::string> const& arguments,
  1888. std::vector<std::string>& newargs)
  1889. {
  1890. std::vector<std::string>::const_iterator i;
  1891. for(i = arguments.begin();i != arguments.end(); ++i)
  1892. {
  1893. cmSystemTools::ExpandListArgument(*i, newargs);
  1894. }
  1895. }
  1896. void cmSystemTools::ExpandListArgument(const std::string& arg,
  1897. std::vector<std::string>& newargs)
  1898. {
  1899. std::string newarg;
  1900. // If argument is empty, it is an empty list.
  1901. if(arg.length() == 0)
  1902. {
  1903. return;
  1904. }
  1905. // if there are no ; in the name then just copy the current string
  1906. if(arg.find(';') == std::string::npos)
  1907. {
  1908. newargs.push_back(arg);
  1909. }
  1910. else
  1911. {
  1912. std::string::size_type start = 0;
  1913. std::string::size_type endpos = 0;
  1914. const std::string::size_type size = arg.size();
  1915. // break up ; separated sections of the string into separate strings
  1916. while(endpos != size)
  1917. {
  1918. endpos = arg.find(';', start);
  1919. if(endpos == std::string::npos)
  1920. {
  1921. endpos = arg.size();
  1922. }
  1923. else
  1924. {
  1925. // skip right over escaped ; ( \; )
  1926. while((endpos != std::string::npos)
  1927. && (endpos > 0)
  1928. && ((arg)[endpos-1] == '\\') )
  1929. {
  1930. endpos = arg.find(';', endpos+1);
  1931. }
  1932. if(endpos == std::string::npos)
  1933. {
  1934. endpos = arg.size();
  1935. }
  1936. }
  1937. std::string::size_type len = endpos - start;
  1938. if (len > 0)
  1939. {
  1940. // check for a closing ] after the start position
  1941. if(arg.find('[', start) == std::string::npos)
  1942. {
  1943. // if there is no [ in the string then keep it
  1944. newarg = arg.substr(start, len);
  1945. }
  1946. else
  1947. {
  1948. int opencount = 0;
  1949. int closecount = 0;
  1950. for(std::string::size_type j = start; j < endpos; ++j)
  1951. {
  1952. if(arg.at(j) == '[')
  1953. {
  1954. ++opencount;
  1955. }
  1956. else if (arg.at(j) == ']')
  1957. {
  1958. ++closecount;
  1959. }
  1960. }
  1961. if(opencount != closecount)
  1962. {
  1963. // skip this one
  1964. endpos = arg.find(';', endpos+1);
  1965. if(endpos == std::string::npos)
  1966. {
  1967. endpos = arg.size();
  1968. }
  1969. len = endpos - start;
  1970. }
  1971. newarg = arg.substr(start, len);
  1972. }
  1973. std::string::size_type pos = newarg.find("\\;");
  1974. if(pos != std::string::npos)
  1975. {
  1976. newarg.erase(pos, 1);
  1977. }
  1978. newargs.push_back(newarg);
  1979. }
  1980. start = endpos+1;
  1981. }
  1982. }
  1983. }
  1984. bool cmSystemTools::GetShortPath(const char* path, std::string& shortPath)
  1985. {
  1986. #if defined(WIN32) && !defined(__CYGWIN__)
  1987. const int size = int(strlen(path)) +1; // size of return
  1988. char *buffer = new char[size]; // create a buffer
  1989. char *tempPath = new char[size]; // create a buffer
  1990. int ret;
  1991. // if the path passed in has quotes around it, first remove the quotes
  1992. if (path[0] == '"' && path[strlen(path)-1] == '"')
  1993. {
  1994. strcpy(tempPath,path+1);
  1995. tempPath[strlen(tempPath)-1] = '\0';
  1996. }
  1997. else
  1998. {
  1999. strcpy(tempPath,path);
  2000. }
  2001. buffer[0] = 0;
  2002. ret = GetShortPathName(tempPath, buffer, size);
  2003. if(buffer[0] == 0 || ret > size)
  2004. {
  2005. if(ret < size)
  2006. {
  2007. LPVOID lpMsgBuf;
  2008. FormatMessage(
  2009. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  2010. FORMAT_MESSAGE_FROM_SYSTEM |
  2011. FORMAT_MESSAGE_IGNORE_INSERTS,
  2012. NULL,
  2013. GetLastError(),
  2014. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
  2015. (LPTSTR) &lpMsgBuf,
  2016. 0,
  2017. NULL
  2018. );
  2019. cmSystemTools::Error((LPCTSTR)lpMsgBuf);
  2020. LocalFree( lpMsgBuf );
  2021. }
  2022. cmSystemTools::Error("Unable to get a short path: ", path);
  2023. delete [] tempPath;
  2024. return false;
  2025. }
  2026. else
  2027. {
  2028. shortPath = buffer;
  2029. delete [] buffer;
  2030. delete [] tempPath;
  2031. return true;
  2032. }
  2033. #else
  2034. shortPath = path;
  2035. return true;
  2036. #endif
  2037. }
  2038. bool cmSystemTools::SimpleGlob(const std::string& glob,
  2039. std::vector<std::string>& files,
  2040. int type /* = 0 */)
  2041. {
  2042. files.clear();
  2043. if ( glob[glob.size()-1] != '*' )
  2044. {
  2045. return false;
  2046. }
  2047. std::string path = cmSystemTools::GetFilenamePath(glob);
  2048. std::string ppath = cmSystemTools::GetFilenameName(glob);
  2049. ppath = ppath.substr(0, ppath.size()-1);
  2050. if ( path.size() == 0 )
  2051. {
  2052. path = "/";
  2053. }
  2054. bool res = false;
  2055. cmDirectory d;
  2056. if (d.Load(path.c_str()))
  2057. {
  2058. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)
  2059. {
  2060. if((std::string(d.GetFile(i)) != ".")
  2061. && (std::string(d.GetFile(i)) != ".."))
  2062. {
  2063. std::string fname = path;
  2064. if ( path[path.size()-1] != '/' )
  2065. {
  2066. fname +="/";
  2067. }
  2068. fname += d.GetFile(i);
  2069. std::string sfname = d.GetFile(i);
  2070. if ( type > 0 && cmSystemTools::FileIsDirectory(fname.c_str()) )
  2071. {
  2072. continue;
  2073. }
  2074. if ( type < 0 && !cmSystemTools::FileIsDirectory(fname.c_str()) )
  2075. {
  2076. continue;
  2077. }
  2078. if ( sfname.size() >= ppath.size() &&
  2079. sfname.substr(0, ppath.size()) ==
  2080. ppath )
  2081. {
  2082. files.push_back(fname);
  2083. res = true;
  2084. }
  2085. }
  2086. }
  2087. }
  2088. return res;
  2089. }
  2090. cmSystemTools::FileFormat cmSystemTools::GetFileFormat(const char* cext)
  2091. {
  2092. if ( ! cext || *cext == 0 )
  2093. {
  2094. return cmSystemTools::NO_FILE_FORMAT;
  2095. }
  2096. std::string ext = cmSystemTools::LowerCase(cext);
  2097. if ( ext == "c" || ext == ".c" ) { return cmSystemTools::C_FILE_FORMAT; }
  2098. if (
  2099. ext == "C" || ext == ".C" ||
  2100. ext == "M" || ext == ".M" ||
  2101. ext == "c++" || ext == ".c++" ||
  2102. ext == "cc" || ext == ".cc" ||
  2103. ext == "cpp" || ext == ".cpp" ||
  2104. ext == "cxx" || ext == ".cxx" ||
  2105. ext == "m" || ext == ".m" ||
  2106. ext == "mm" || ext == ".mm"
  2107. ) { return cmSystemTools::CXX_FILE_FORMAT; }
  2108. if ( ext == "java" || ext == ".java" ) { return cmSystemTools::JAVA_FILE_FORMAT; }
  2109. if (
  2110. ext == "h" || ext == ".h" ||
  2111. ext == "h++" || ext == ".h++" ||
  2112. ext == "hm" || ext == ".hm" ||
  2113. ext == "hpp" || ext == ".hpp" ||
  2114. ext == "hxx" || ext == ".hxx" ||
  2115. ext == "in" || ext == ".in" ||
  2116. ext == "txx" || ext == ".txx"
  2117. ) { return cmSystemTools::HEADER_FILE_FORMAT; }
  2118. if ( ext == "rc" || ext == ".rc" ) { return cmSystemTools::RESOURCE_FILE_FORMAT; }
  2119. if ( ext == "def" || ext == ".def" ) { return cmSystemTools::DEFINITION_FILE_FORMAT; }
  2120. if ( ext == "lib" || ext == ".lib" ||
  2121. ext == "a" || ext == ".a") { return cmSystemTools::STATIC_LIBRARY_FILE_FORMAT; }
  2122. if ( ext == "o" || ext == ".o" ||
  2123. ext == "obj" || ext == ".obj") { return cmSystemTools::OBJECT_FILE_FORMAT; }
  2124. #ifdef __APPLE__
  2125. if ( ext == "dylib" || ext == ".dylib" )
  2126. { return cmSystemTools::SHARED_LIBRARY_FILE_FORMAT; }
  2127. if ( ext == "so" || ext == ".so" ||
  2128. ext == "bundle" || ext == ".bundle" )
  2129. { return cmSystemTools::MODULE_FILE_FORMAT; }
  2130. #else // __APPLE__
  2131. if ( ext == "so" || ext == ".so" ||
  2132. ext == "sl" || ext == ".sl" ||
  2133. ext == "dll" || ext == ".dll" )
  2134. { return cmSystemTools::SHARED_LIBRARY_FILE_FORMAT; }
  2135. #endif // __APPLE__
  2136. return cmSystemTools::UNKNOWN_FILE_FORMAT;
  2137. }
  2138. void cmSystemTools::SplitProgramFromArgs(const char* path,
  2139. std::string& program, std::string& args)
  2140. {
  2141. if(cmSystemTools::FileExists(path))
  2142. {
  2143. program = path;
  2144. args = "";
  2145. return;
  2146. }
  2147. std::vector<std::string> e;
  2148. std::string findProg = cmSystemTools::FindProgram(path, e);
  2149. if(findProg.size())
  2150. {
  2151. program = findProg;
  2152. args = "";
  2153. return;
  2154. }
  2155. std::string dir = path;
  2156. std::string::size_type spacePos = dir.rfind(' ');
  2157. if(spacePos == std::string::npos)
  2158. {
  2159. program = "";
  2160. args = "";
  2161. return;
  2162. }
  2163. while(spacePos != std::string::npos)
  2164. {
  2165. std::string tryProg = dir.substr(0, spacePos);
  2166. if(cmSystemTools::FileExists(tryProg.c_str()))
  2167. {
  2168. program = tryProg;
  2169. args = dir.substr(spacePos, dir.size()-spacePos);
  2170. return;
  2171. }
  2172. findProg = cmSystemTools::FindProgram(tryProg.c_str(), e);
  2173. if(findProg.size())
  2174. {
  2175. program = findProg;
  2176. args = dir.substr(spacePos, dir.size()-spacePos);
  2177. return;
  2178. }
  2179. spacePos = dir.rfind(' ', spacePos--);
  2180. }
  2181. program = "";
  2182. args = "";
  2183. }
  2184. std::string cmSystemTools::GetCurrentDateTime(const char* format)
  2185. {
  2186. char buf[1024];
  2187. time_t t;
  2188. time(&t);
  2189. strftime(buf, sizeof(buf), format, localtime(&t));
  2190. return buf;
  2191. }
  2192. std::string cmSystemTools::MakeCindentifier(const char* s)
  2193. {
  2194. std::string str(s);
  2195. if (str.find_first_of("0123456789") == 0)
  2196. {
  2197. str = "_" + str;
  2198. }
  2199. std::string permited_chars("_"
  2200. "abcdefghijklmnopqrstuvwxyz"
  2201. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  2202. "0123456789");
  2203. std::string::size_type pos = 0;
  2204. while ((pos = str.find_first_not_of(permited_chars, pos)) != std::string::npos)
  2205. {
  2206. str[pos] = '_';
  2207. }
  2208. return str;
  2209. }
  2210. // Due to a buggy stream library on the HP and another on Mac OSX, we
  2211. // need this very carefully written version of getline. Returns true
  2212. // if any data were read before the end-of-file was reached.
  2213. bool cmSystemTools::GetLineFromStream(std::istream& is, std::string& line)
  2214. {
  2215. const int bufferSize = 1024;
  2216. char buffer[bufferSize];
  2217. line = "";
  2218. bool haveData = false;
  2219. // If no characters are read from the stream, the end of file has
  2220. // been reached.
  2221. while((is.getline(buffer, bufferSize), is.gcount() > 0))
  2222. {
  2223. haveData = true;
  2224. line.append(buffer);
  2225. // If newline character was read, the gcount includes the
  2226. // character, but the buffer does not. The end of line has been
  2227. // reached.
  2228. if(strlen(buffer) == static_cast<size_t>(is.gcount()-1))
  2229. {
  2230. break;
  2231. }
  2232. // The fail bit may be set. Clear it.
  2233. is.clear(is.rdstate() & ~std::ios::failbit);
  2234. }
  2235. return haveData;
  2236. }
  2237. #if defined(_MSC_VER) && defined(_DEBUG)
  2238. # include <crtdbg.h>
  2239. # include <stdio.h>
  2240. # include <stdlib.h>
  2241. static int cmSystemToolsDebugReport(int, char* message, int*)
  2242. {
  2243. fprintf(stderr, message);
  2244. exit(1);
  2245. return 0;
  2246. }
  2247. void cmSystemTools::EnableMSVCDebugHook()
  2248. {
  2249. if(getenv("DART_TEST_FROM_DART"))
  2250. {
  2251. _CrtSetReportHook(cmSystemToolsDebugReport);
  2252. }
  2253. }
  2254. #else
  2255. void cmSystemTools::EnableMSVCDebugHook()
  2256. {
  2257. }
  2258. #endif