cmSystemTools.cxx 61 KB

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