cmSystemTools.cxx 61 KB

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