SystemTools.cxx 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962
  1. /*=========================================================================
  2. Program: KWSys - Kitware System Library
  3. Module: $RCSfile$
  4. Copyright (c) Kitware, Inc., Insight Consortium. All rights reserved.
  5. See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
  6. This software is distributed WITHOUT ANY WARRANTY; without even
  7. the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  8. PURPOSE. See the above copyright notices for more information.
  9. =========================================================================*/
  10. #include "kwsysPrivate.h"
  11. #include KWSYS_HEADER(SystemTools.hxx)
  12. #include KWSYS_HEADER(Directory.hxx)
  13. #include KWSYS_HEADER(ios/iostream)
  14. #include KWSYS_HEADER(ios/fstream)
  15. #include KWSYS_HEADER(ios/sstream)
  16. #ifdef _MSC_VER
  17. # pragma warning (disable: 4786)
  18. #endif
  19. #include <stdio.h>
  20. #include <sys/stat.h>
  21. #include <ctype.h>
  22. #include <errno.h>
  23. #include <time.h>
  24. // support for realpath call
  25. #ifndef _WIN32
  26. #include <limits.h>
  27. #include <stdlib.h>
  28. #include <sys/param.h>
  29. #include <sys/wait.h>
  30. #include <sys/ioctl.h>
  31. #include <unistd.h>
  32. #include <termios.h>
  33. #endif
  34. #if defined(_WIN32) && (defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__))
  35. #include <io.h>
  36. #include <stdio.h>
  37. #include <stdlib.h>
  38. #include <string.h>
  39. #include <windows.h>
  40. #include <direct.h>
  41. #define _unlink unlink
  42. inline int Mkdir(const char* dir)
  43. {
  44. return _mkdir(dir);
  45. }
  46. inline int Rmdir(const char* dir)
  47. {
  48. return _rmdir(dir);
  49. }
  50. inline const char* Getcwd(char* buf, unsigned int len)
  51. {
  52. return _getcwd(buf, len);
  53. }
  54. inline int Chdir(const char* dir)
  55. {
  56. #if defined(__BORLANDC__)
  57. return chdir(dir);
  58. #else
  59. return _chdir(dir);
  60. #endif
  61. }
  62. #else
  63. #include <sys/types.h>
  64. #include <fcntl.h>
  65. #include <unistd.h>
  66. inline int Mkdir(const char* dir)
  67. {
  68. return mkdir(dir, 00777);
  69. }
  70. inline int Rmdir(const char* dir)
  71. {
  72. return rmdir(dir);
  73. }
  74. inline const char* Getcwd(char* buf, unsigned int len)
  75. {
  76. return getcwd(buf, len);
  77. }
  78. inline int Chdir(const char* dir)
  79. {
  80. return chdir(dir);
  81. }
  82. #endif
  83. #if !defined(_WIN32) && defined(__COMO__)
  84. // Hack for como strict mode to avoid defining _SVID_SOURCE or _BSD_SOURCE.
  85. extern "C"
  86. {
  87. extern FILE *popen (__const char *__command, __const char *__modes) __THROW;
  88. extern int pclose (FILE *__stream) __THROW;
  89. extern char *realpath (__const char *__restrict __name,
  90. char *__restrict __resolved) __THROW;
  91. extern char *strdup (__const char *__s) __THROW;
  92. extern int putenv (char *__string) __THROW;
  93. }
  94. #endif
  95. /* Implement floattime() for various platforms */
  96. // Taken from Python 2.1.3
  97. #if defined( _WIN32 ) && !defined( __CYGWIN__ )
  98. # include <sys/timeb.h>
  99. # define HAVE_FTIME
  100. # if defined( __BORLANDC__)
  101. # define FTIME ftime
  102. # define TIMEB timeb
  103. # else // Visual studio?
  104. # define FTIME _ftime
  105. # define TIMEB _timeb
  106. # endif
  107. #elif defined( __CYGWIN__ ) || defined( __linux__ )
  108. # include <sys/time.h>
  109. # include <time.h>
  110. # define HAVE_GETTIMEOFDAY
  111. #endif
  112. namespace KWSYS_NAMESPACE
  113. {
  114. double
  115. SystemTools::GetTime(void)
  116. {
  117. /* There are three ways to get the time:
  118. (1) gettimeofday() -- resolution in microseconds
  119. (2) ftime() -- resolution in milliseconds
  120. (3) time() -- resolution in seconds
  121. In all cases the return value is a float in seconds.
  122. Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
  123. fail, so we fall back on ftime() or time().
  124. Note: clock resolution does not imply clock accuracy! */
  125. #ifdef HAVE_GETTIMEOFDAY
  126. {
  127. struct timeval t;
  128. #ifdef GETTIMEOFDAY_NO_TZ
  129. if (gettimeofday(&t) == 0)
  130. return (double)t.tv_sec + t.tv_usec*0.000001;
  131. #else /* !GETTIMEOFDAY_NO_TZ */
  132. if (gettimeofday(&t, (struct timezone *)NULL) == 0)
  133. return (double)t.tv_sec + t.tv_usec*0.000001;
  134. #endif /* !GETTIMEOFDAY_NO_TZ */
  135. }
  136. #endif /* !HAVE_GETTIMEOFDAY */
  137. {
  138. #if defined(HAVE_FTIME)
  139. struct TIMEB t;
  140. ::FTIME(&t);
  141. return (double)t.time + (double)t.millitm * (double)0.001;
  142. #else /* !HAVE_FTIME */
  143. time_t secs;
  144. time(&secs);
  145. return (double)secs;
  146. #endif /* !HAVE_FTIME */
  147. }
  148. }
  149. // adds the elements of the env variable path to the arg passed in
  150. void SystemTools::GetPath(kwsys_stl::vector<kwsys_stl::string>& path, const char* env)
  151. {
  152. #if defined(_WIN32) && !defined(__CYGWIN__)
  153. const char* pathSep = ";";
  154. #else
  155. const char* pathSep = ":";
  156. #endif
  157. if(!env)
  158. {
  159. env = "PATH";
  160. }
  161. const char* cpathEnv = SystemTools::GetEnv(env);
  162. if ( !cpathEnv )
  163. {
  164. return;
  165. }
  166. kwsys_stl::string pathEnv = cpathEnv;
  167. // A hack to make the below algorithm work.
  168. if(pathEnv[pathEnv.length()-1] != ':')
  169. {
  170. pathEnv += pathSep;
  171. }
  172. kwsys_stl::string::size_type start =0;
  173. bool done = false;
  174. while(!done)
  175. {
  176. kwsys_stl::string::size_type endpos = pathEnv.find(pathSep, start);
  177. if(endpos != kwsys_stl::string::npos)
  178. {
  179. path.push_back(pathEnv.substr(start, endpos-start));
  180. start = endpos+1;
  181. }
  182. else
  183. {
  184. done = true;
  185. }
  186. }
  187. for(kwsys_stl::vector<kwsys_stl::string>::iterator i = path.begin();
  188. i != path.end(); ++i)
  189. {
  190. SystemTools::ConvertToUnixSlashes(*i);
  191. }
  192. }
  193. const char* SystemTools::GetEnv(const char* key)
  194. {
  195. return getenv(key);
  196. }
  197. bool SystemTools::GetEnv(const char* key, kwsys_stl::string& result)
  198. {
  199. const char* v = getenv(key);
  200. if(v)
  201. {
  202. result = v;
  203. return true;
  204. }
  205. else
  206. {
  207. return false;
  208. }
  209. }
  210. const char* SystemTools::GetExecutableExtension()
  211. {
  212. #if defined(_WIN32) || defined(__CYGWIN__)
  213. return ".exe";
  214. #else
  215. return "";
  216. #endif
  217. }
  218. bool SystemTools::MakeDirectory(const char* path)
  219. {
  220. if(SystemTools::FileExists(path))
  221. {
  222. return true;
  223. }
  224. kwsys_stl::string dir = path;
  225. if(dir.size() == 0)
  226. {
  227. return false;
  228. }
  229. SystemTools::ConvertToUnixSlashes(dir);
  230. kwsys_stl::string::size_type pos = dir.find(':');
  231. if(pos == kwsys_stl::string::npos)
  232. {
  233. pos = 0;
  234. }
  235. kwsys_stl::string topdir;
  236. while((pos = dir.find('/', pos)) != kwsys_stl::string::npos)
  237. {
  238. topdir = dir.substr(0, pos);
  239. Mkdir(topdir.c_str());
  240. pos++;
  241. }
  242. if(dir[dir.size()-1] == '/')
  243. {
  244. topdir = dir.substr(0, dir.size());
  245. }
  246. else
  247. {
  248. topdir = dir;
  249. }
  250. if(Mkdir(topdir.c_str()) != 0)
  251. {
  252. // There is a bug in the Borland Run time library which makes MKDIR
  253. // return EACCES when it should return EEXISTS
  254. // if it is some other error besides directory exists
  255. // then return false
  256. if( (errno != EEXIST)
  257. #ifdef __BORLANDC__
  258. && (errno != EACCES)
  259. #endif
  260. )
  261. {
  262. return false;
  263. }
  264. }
  265. return true;
  266. }
  267. // replace replace with with as many times as it shows up in source.
  268. // write the result into source.
  269. void SystemTools::ReplaceString(kwsys_stl::string& source,
  270. const char* replace,
  271. const char* with)
  272. {
  273. const char *src = source.c_str();
  274. char *searchPos = const_cast<char *>(strstr(src,replace));
  275. // get out quick if string is not found
  276. if (!searchPos)
  277. {
  278. return;
  279. }
  280. // perform replacements until done
  281. size_t replaceSize = strlen(replace);
  282. char *orig = strdup(src);
  283. char *currentPos = orig;
  284. searchPos = searchPos - src + orig;
  285. // initialize the result
  286. source.erase(source.begin(),source.end());
  287. do
  288. {
  289. *searchPos = '\0';
  290. source += currentPos;
  291. currentPos = searchPos + replaceSize;
  292. // replace
  293. source += with;
  294. searchPos = strstr(currentPos,replace);
  295. }
  296. while (searchPos);
  297. // copy any trailing text
  298. source += currentPos;
  299. free(orig);
  300. }
  301. // Read a registry value.
  302. // Example :
  303. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  304. // => will return the data of the "default" value of the key
  305. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  306. // => will return the data of the "Root" value of the key
  307. #if defined(_WIN32) && !defined(__CYGWIN__)
  308. bool SystemTools::ReadRegistryValue(const char *key, kwsys_stl::string &value)
  309. {
  310. kwsys_stl::string primary = key;
  311. kwsys_stl::string second;
  312. kwsys_stl::string valuename;
  313. size_t start = primary.find("\\");
  314. if (start == kwsys_stl::string::npos)
  315. {
  316. return false;
  317. }
  318. size_t valuenamepos = primary.find(";");
  319. if (valuenamepos != kwsys_stl::string::npos)
  320. {
  321. valuename = primary.substr(valuenamepos+1);
  322. }
  323. second = primary.substr(start+1, valuenamepos-start-1);
  324. primary = primary.substr(0, start);
  325. HKEY primaryKey = HKEY_CURRENT_USER;
  326. if (primary == "HKEY_CURRENT_USER")
  327. {
  328. primaryKey = HKEY_CURRENT_USER;
  329. }
  330. if (primary == "HKEY_CURRENT_CONFIG")
  331. {
  332. primaryKey = HKEY_CURRENT_CONFIG;
  333. }
  334. if (primary == "HKEY_CLASSES_ROOT")
  335. {
  336. primaryKey = HKEY_CLASSES_ROOT;
  337. }
  338. if (primary == "HKEY_LOCAL_MACHINE")
  339. {
  340. primaryKey = HKEY_LOCAL_MACHINE;
  341. }
  342. if (primary == "HKEY_USERS")
  343. {
  344. primaryKey = HKEY_USERS;
  345. }
  346. HKEY hKey;
  347. if(RegOpenKeyEx(primaryKey,
  348. second.c_str(),
  349. 0,
  350. KEY_READ,
  351. &hKey) != ERROR_SUCCESS)
  352. {
  353. return false;
  354. }
  355. else
  356. {
  357. DWORD dwType, dwSize;
  358. dwSize = 1023;
  359. char data[1024];
  360. if(RegQueryValueEx(hKey,
  361. (LPTSTR)valuename.c_str(),
  362. NULL,
  363. &dwType,
  364. (BYTE *)data,
  365. &dwSize) == ERROR_SUCCESS)
  366. {
  367. if (dwType == REG_SZ)
  368. {
  369. value = data;
  370. RegCloseKey(hKey);
  371. return true;
  372. }
  373. }
  374. }
  375. return false;
  376. }
  377. #else
  378. bool SystemTools::ReadRegistryValue(const char *, kwsys_stl::string &)
  379. {
  380. return false;
  381. }
  382. #endif
  383. // Write a registry value.
  384. // Example :
  385. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  386. // => will set the data of the "default" value of the key
  387. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  388. // => will set the data of the "Root" value of the key
  389. #if defined(_WIN32) && !defined(__CYGWIN__)
  390. bool SystemTools::WriteRegistryValue(const char *key, const char *value)
  391. {
  392. kwsys_stl::string primary = key;
  393. kwsys_stl::string second;
  394. kwsys_stl::string valuename;
  395. size_t start = primary.find("\\");
  396. if (start == kwsys_stl::string::npos)
  397. {
  398. return false;
  399. }
  400. size_t valuenamepos = primary.find(";");
  401. if (valuenamepos != kwsys_stl::string::npos)
  402. {
  403. valuename = primary.substr(valuenamepos+1);
  404. }
  405. second = primary.substr(start+1, valuenamepos-start-1);
  406. primary = primary.substr(0, start);
  407. HKEY primaryKey = HKEY_CURRENT_USER;
  408. if (primary == "HKEY_CURRENT_USER")
  409. {
  410. primaryKey = HKEY_CURRENT_USER;
  411. }
  412. if (primary == "HKEY_CURRENT_CONFIG")
  413. {
  414. primaryKey = HKEY_CURRENT_CONFIG;
  415. }
  416. if (primary == "HKEY_CLASSES_ROOT")
  417. {
  418. primaryKey = HKEY_CLASSES_ROOT;
  419. }
  420. if (primary == "HKEY_LOCAL_MACHINE")
  421. {
  422. primaryKey = HKEY_LOCAL_MACHINE;
  423. }
  424. if (primary == "HKEY_USERS")
  425. {
  426. primaryKey = HKEY_USERS;
  427. }
  428. HKEY hKey;
  429. DWORD dwDummy;
  430. if(RegCreateKeyEx(primaryKey,
  431. second.c_str(),
  432. 0,
  433. "",
  434. REG_OPTION_NON_VOLATILE,
  435. KEY_WRITE,
  436. NULL,
  437. &hKey,
  438. &dwDummy) != ERROR_SUCCESS)
  439. {
  440. return false;
  441. }
  442. if(RegSetValueEx(hKey,
  443. (LPTSTR)valuename.c_str(),
  444. 0,
  445. REG_SZ,
  446. (CONST BYTE *)value,
  447. (DWORD)(strlen(value) + 1)) == ERROR_SUCCESS)
  448. {
  449. return true;
  450. }
  451. return false;
  452. }
  453. #else
  454. bool SystemTools::WriteRegistryValue(const char *, const char *)
  455. {
  456. return false;
  457. }
  458. #endif
  459. // Delete a registry value.
  460. // Example :
  461. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  462. // => will delete the data of the "default" value of the key
  463. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  464. // => will delete the data of the "Root" value of the key
  465. #if defined(_WIN32) && !defined(__CYGWIN__)
  466. bool SystemTools::DeleteRegistryValue(const char *key)
  467. {
  468. kwsys_stl::string primary = key;
  469. kwsys_stl::string second;
  470. kwsys_stl::string valuename;
  471. size_t start = primary.find("\\");
  472. if (start == kwsys_stl::string::npos)
  473. {
  474. return false;
  475. }
  476. size_t valuenamepos = primary.find(";");
  477. if (valuenamepos != kwsys_stl::string::npos)
  478. {
  479. valuename = primary.substr(valuenamepos+1);
  480. }
  481. second = primary.substr(start+1, valuenamepos-start-1);
  482. primary = primary.substr(0, start);
  483. HKEY primaryKey = HKEY_CURRENT_USER;
  484. if (primary == "HKEY_CURRENT_USER")
  485. {
  486. primaryKey = HKEY_CURRENT_USER;
  487. }
  488. if (primary == "HKEY_CURRENT_CONFIG")
  489. {
  490. primaryKey = HKEY_CURRENT_CONFIG;
  491. }
  492. if (primary == "HKEY_CLASSES_ROOT")
  493. {
  494. primaryKey = HKEY_CLASSES_ROOT;
  495. }
  496. if (primary == "HKEY_LOCAL_MACHINE")
  497. {
  498. primaryKey = HKEY_LOCAL_MACHINE;
  499. }
  500. if (primary == "HKEY_USERS")
  501. {
  502. primaryKey = HKEY_USERS;
  503. }
  504. HKEY hKey;
  505. if(RegOpenKeyEx(primaryKey,
  506. second.c_str(),
  507. 0,
  508. KEY_WRITE,
  509. &hKey) != ERROR_SUCCESS)
  510. {
  511. return false;
  512. }
  513. else
  514. {
  515. if(RegDeleteValue(hKey,
  516. (LPTSTR)valuename.c_str()) == ERROR_SUCCESS)
  517. {
  518. RegCloseKey(hKey);
  519. return true;
  520. }
  521. }
  522. return false;
  523. }
  524. #else
  525. bool SystemTools::DeleteRegistryValue(const char *)
  526. {
  527. return false;
  528. }
  529. #endif
  530. bool SystemTools::SameFile(const char* file1, const char* file2)
  531. {
  532. #ifdef _WIN32
  533. HANDLE hFile1, hFile2;
  534. hFile1 = CreateFile( file1,
  535. GENERIC_READ,
  536. FILE_SHARE_READ ,
  537. NULL,
  538. OPEN_EXISTING,
  539. FILE_FLAG_BACKUP_SEMANTICS,
  540. NULL
  541. );
  542. hFile2 = CreateFile( file2,
  543. GENERIC_READ,
  544. FILE_SHARE_READ,
  545. NULL,
  546. OPEN_EXISTING,
  547. FILE_FLAG_BACKUP_SEMANTICS,
  548. NULL
  549. );
  550. if( hFile1 == INVALID_HANDLE_VALUE || hFile2 == INVALID_HANDLE_VALUE)
  551. {
  552. if(hFile1 != INVALID_HANDLE_VALUE)
  553. {
  554. CloseHandle(hFile1);
  555. }
  556. if(hFile2 != INVALID_HANDLE_VALUE)
  557. {
  558. CloseHandle(hFile2);
  559. }
  560. return false;
  561. }
  562. BY_HANDLE_FILE_INFORMATION fiBuf1;
  563. BY_HANDLE_FILE_INFORMATION fiBuf2;
  564. GetFileInformationByHandle( hFile1, &fiBuf1 );
  565. GetFileInformationByHandle( hFile2, &fiBuf2 );
  566. CloseHandle(hFile1);
  567. CloseHandle(hFile2);
  568. return (fiBuf1.dwVolumeSerialNumber == fiBuf2.dwVolumeSerialNumber &&
  569. fiBuf1.nFileIndexHigh == fiBuf2.nFileIndexHigh &&
  570. fiBuf1.nFileIndexLow == fiBuf2.nFileIndexLow);
  571. #else
  572. struct stat fileStat1, fileStat2;
  573. if (stat(file1, &fileStat1) == 0 && stat(file2, &fileStat2) == 0)
  574. {
  575. // see if the files are the same file
  576. // check the device inode and size
  577. if(memcmp(&fileStat2.st_dev, &fileStat1.st_dev, sizeof(fileStat1.st_dev)) == 0 &&
  578. memcmp(&fileStat2.st_ino, &fileStat1.st_ino, sizeof(fileStat1.st_ino)) == 0 &&
  579. fileStat2.st_size == fileStat1.st_size
  580. )
  581. {
  582. return true;
  583. }
  584. }
  585. return false;
  586. #endif
  587. }
  588. // return true if the file exists
  589. bool SystemTools::FileExists(const char* filename)
  590. {
  591. #ifdef _MSC_VER
  592. # define access _access
  593. #endif
  594. #ifndef R_OK
  595. # define R_OK 04
  596. #endif
  597. if ( access(filename, R_OK) != 0 )
  598. {
  599. return false;
  600. }
  601. else
  602. {
  603. return true;
  604. }
  605. }
  606. // Return a capitalized string (i.e the first letter is uppercased, all other
  607. // are lowercased)
  608. kwsys_stl::string SystemTools::Capitalized(const kwsys_stl::string& s)
  609. {
  610. kwsys_stl::string n;
  611. if(s.size() == 0)
  612. {
  613. return n;
  614. }
  615. n.resize(s.size());
  616. n[0] = static_cast<kwsys_stl::string::value_type>(toupper(s[0]));
  617. for (size_t i = 1; i < s.size(); i++)
  618. {
  619. n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
  620. }
  621. return n;
  622. }
  623. // Return a lower case string
  624. kwsys_stl::string SystemTools::LowerCase(const kwsys_stl::string& s)
  625. {
  626. kwsys_stl::string n;
  627. n.resize(s.size());
  628. for (size_t i = 0; i < s.size(); i++)
  629. {
  630. n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
  631. }
  632. return n;
  633. }
  634. // Return a lower case string
  635. kwsys_stl::string SystemTools::UpperCase(const kwsys_stl::string& s)
  636. {
  637. kwsys_stl::string n;
  638. n.resize(s.size());
  639. for (size_t i = 0; i < s.size(); i++)
  640. {
  641. n[i] = static_cast<kwsys_stl::string::value_type>(toupper(s[i]));
  642. }
  643. return n;
  644. }
  645. // convert windows slashes to unix slashes
  646. void SystemTools::ConvertToUnixSlashes(kwsys_stl::string& path)
  647. {
  648. kwsys_stl::string::size_type pos = 0;
  649. while((pos = path.find('\\', pos)) != kwsys_stl::string::npos)
  650. {
  651. // make sure we don't convert an escaped space to a unix slash
  652. if(pos < path.size()-2)
  653. {
  654. if(path[pos+1] != ' ')
  655. {
  656. path[pos] = '/';
  657. }
  658. }
  659. pos++;
  660. }
  661. // Remove all // from the path just like most unix shells
  662. int start_find;
  663. #ifdef _WIN32
  664. // However, on windows if the first characters are both slashes,
  665. // then keep them that way, so that network paths can be handled.
  666. start_find = 1;
  667. #else
  668. start_find = 0;
  669. #endif
  670. while((pos = path.find("//", start_find)) != kwsys_stl::string::npos)
  671. {
  672. SystemTools::ReplaceString(path, "//", "/");
  673. }
  674. // remove any trailing slash
  675. if(path.size() > 1 && path[path.size()-1] == '/')
  676. {
  677. path = path.substr(0, path.size()-1);
  678. }
  679. // if there is a tilda ~ then replace it with HOME
  680. if(path.find("~") == 0)
  681. {
  682. if (getenv("HOME"))
  683. {
  684. path = kwsys_stl::string(getenv("HOME")) + path.substr(1);
  685. }
  686. }
  687. // if there is a /tmp_mnt in a path get rid of it!
  688. if(path.find("/tmp_mnt") == 0)
  689. {
  690. path = path.substr(8);
  691. }
  692. }
  693. // change // to /, and escape any spaces in the path
  694. kwsys_stl::string SystemTools::ConvertToUnixOutputPath(const char* path)
  695. {
  696. kwsys_stl::string ret = path;
  697. // remove // except at the beginning might be a cygwin drive
  698. kwsys_stl::string::size_type pos = 1;
  699. while((pos = ret.find("//", pos)) != kwsys_stl::string::npos)
  700. {
  701. ret.erase(pos, 1);
  702. }
  703. // now escape spaces if there is a space in the path
  704. if(ret.find(" ") != kwsys_stl::string::npos)
  705. {
  706. kwsys_stl::string result = "";
  707. char lastch = 1;
  708. for(const char* ch = ret.c_str(); *ch != '\0'; ++ch)
  709. {
  710. // if it is already escaped then don't try to escape it again
  711. if(*ch == ' ' && lastch != '\\')
  712. {
  713. result += '\\';
  714. }
  715. result += *ch;
  716. lastch = *ch;
  717. }
  718. ret = result;
  719. }
  720. return ret;
  721. }
  722. kwsys_stl::string SystemTools::ConvertToOutputPath(const char* path)
  723. {
  724. #if defined(_WIN32) && !defined(__CYGWIN__)
  725. return SystemTools::ConvertToWindowsOutputPath(path);
  726. #else
  727. return SystemTools::ConvertToUnixOutputPath(path);
  728. #endif
  729. }
  730. // remove double slashes not at the start
  731. kwsys_stl::string SystemTools::ConvertToWindowsOutputPath(const char* path)
  732. {
  733. kwsys_stl::string ret = path;
  734. kwsys_stl::string::size_type pos = 0;
  735. // first convert all of the slashes
  736. while((pos = ret.find('/', pos)) != kwsys_stl::string::npos)
  737. {
  738. ret[pos] = '\\';
  739. pos++;
  740. }
  741. // check for really small paths
  742. if(ret.size() < 2)
  743. {
  744. return ret;
  745. }
  746. // now clean up a bit and remove double slashes
  747. // Only if it is not the first position in the path which is a network
  748. // path on windows
  749. pos = 1; // start at position 1
  750. if(ret[0] == '\"')
  751. {
  752. pos = 2; // if the string is already quoted then start at 2
  753. if(ret.size() < 3)
  754. {
  755. return ret;
  756. }
  757. }
  758. while((pos = ret.find("\\\\", pos)) != kwsys_stl::string::npos)
  759. {
  760. ret.erase(pos, 1);
  761. }
  762. // now double quote the path if it has spaces in it
  763. // and is not already double quoted
  764. if(ret.find(" ") != kwsys_stl::string::npos
  765. && ret[0] != '\"')
  766. {
  767. kwsys_stl::string result;
  768. result = "\"" + ret + "\"";
  769. ret = result;
  770. }
  771. return ret;
  772. }
  773. bool SystemTools::CopyFileIfDifferent(const char* source,
  774. const char* destination)
  775. {
  776. if(SystemTools::FilesDiffer(source, destination))
  777. {
  778. return SystemTools::CopyFileAlways(source, destination);
  779. }
  780. return true;
  781. }
  782. bool SystemTools::FilesDiffer(const char* source,
  783. const char* destination)
  784. {
  785. struct stat statSource;
  786. if (stat(source, &statSource) != 0)
  787. {
  788. return true;
  789. }
  790. struct stat statDestination;
  791. if (stat(destination, &statDestination) != 0)
  792. {
  793. return true;
  794. }
  795. if(statSource.st_size != statDestination.st_size)
  796. {
  797. return true;
  798. }
  799. if(statSource.st_size == 0)
  800. {
  801. return false;
  802. }
  803. #if defined(_WIN32) || defined(__CYGWIN__)
  804. kwsys_ios::ifstream finSource(source, (kwsys_ios::ios::binary |
  805. kwsys_ios::ios::in));
  806. kwsys_ios::ifstream finDestination(destination, (kwsys_ios::ios::binary |
  807. kwsys_ios::ios::in));
  808. #else
  809. kwsys_ios::ifstream finSource(source);
  810. kwsys_ios::ifstream finDestination(destination);
  811. #endif
  812. if(!finSource || !finDestination)
  813. {
  814. return true;
  815. }
  816. char* source_buf = new char[statSource.st_size];
  817. char* dest_buf = new char[statSource.st_size];
  818. finSource.read(source_buf, statSource.st_size);
  819. finDestination.read(dest_buf, statSource.st_size);
  820. if(statSource.st_size != static_cast<long>(finSource.gcount()) ||
  821. statSource.st_size != static_cast<long>(finDestination.gcount()))
  822. {
  823. // Failed to read files.
  824. delete [] source_buf;
  825. delete [] dest_buf;
  826. return true;
  827. }
  828. int ret = memcmp((const void*)source_buf,
  829. (const void*)dest_buf,
  830. statSource.st_size);
  831. delete [] dest_buf;
  832. delete [] source_buf;
  833. return ret != 0;
  834. }
  835. /**
  836. * Copy a file named by "source" to the file named by "destination".
  837. */
  838. bool SystemTools::CopyFileAlways(const char* source, const char* destination)
  839. {
  840. // If files are the same do not copy
  841. if ( SystemTools::SameFile(source, destination) )
  842. {
  843. return true;
  844. }
  845. mode_t perm = 0;
  846. bool perms = SystemTools::GetPermissions(source, perm);
  847. const int bufferSize = 4096;
  848. char buffer[bufferSize];
  849. // If destination is a directory, try to create a file with the same
  850. // name as the source in that directory.
  851. kwsys_stl::string new_destination;
  852. if(SystemTools::FileExists(destination) &&
  853. SystemTools::FileIsDirectory(destination))
  854. {
  855. new_destination = destination;
  856. SystemTools::ConvertToUnixSlashes(new_destination);
  857. new_destination += '/';
  858. kwsys_stl::string source_name = source;
  859. new_destination += SystemTools::GetFilenameName(source_name);
  860. destination = new_destination.c_str();
  861. }
  862. // Create destination directory
  863. kwsys_stl::string destination_dir = destination;
  864. destination_dir = SystemTools::GetFilenamePath(destination_dir);
  865. SystemTools::MakeDirectory(destination_dir.c_str());
  866. // Open files
  867. #if defined(_WIN32) || defined(__CYGWIN__)
  868. kwsys_ios::ifstream fin(source,
  869. kwsys_ios::ios::binary | kwsys_ios::ios::in);
  870. #else
  871. kwsys_ios::ifstream fin(source);
  872. #endif
  873. if(!fin)
  874. {
  875. return false;
  876. }
  877. if ( SystemTools::FileExists(destination) && !SystemTools::RemoveFile(destination) )
  878. {
  879. return false;
  880. }
  881. #if defined(_WIN32) || defined(__CYGWIN__)
  882. kwsys_ios::ofstream fout(destination,
  883. kwsys_ios::ios::binary | kwsys_ios::ios::out | kwsys_ios::ios::trunc);
  884. #else
  885. kwsys_ios::ofstream fout(destination,
  886. kwsys_ios::ios::out | kwsys_ios::ios::trunc);
  887. #endif
  888. if(!fout)
  889. {
  890. return false;
  891. }
  892. // This copy loop is very sensitive on certain platforms with
  893. // slightly broken stream libraries (like HPUX). Normally, it is
  894. // incorrect to not check the error condition on the fin.read()
  895. // before using the data, but the fin.gcount() will be zero if an
  896. // error occurred. Therefore, the loop should be safe everywhere.
  897. while(fin)
  898. {
  899. fin.read(buffer, bufferSize);
  900. if(fin.gcount())
  901. {
  902. fout.write(buffer, fin.gcount());
  903. }
  904. }
  905. // Make sure the operating system has finished writing the file
  906. // before closing it. This will ensure the file is finished before
  907. // the check below.
  908. fout.flush();
  909. fin.close();
  910. fout.close();
  911. // More checks.
  912. struct stat statSource, statDestination;
  913. statSource.st_size = 12345;
  914. statDestination.st_size = 12345;
  915. if(stat(source, &statSource) != 0)
  916. {
  917. return false;
  918. }
  919. else if(stat(destination, &statDestination) != 0)
  920. {
  921. return false;
  922. }
  923. else if(statSource.st_size != statDestination.st_size)
  924. {
  925. return false;
  926. }
  927. if ( perms )
  928. {
  929. if ( !SystemTools::SetPermissions(destination, perm) )
  930. {
  931. return false;
  932. }
  933. }
  934. return true;
  935. }
  936. // return size of file; also returns zero if no file exists
  937. unsigned long SystemTools::FileLength(const char* filename)
  938. {
  939. struct stat fs;
  940. if (stat(filename, &fs) != 0)
  941. {
  942. return 0;
  943. }
  944. else
  945. {
  946. return fs.st_size;
  947. }
  948. }
  949. int SystemTools::Strucmp(const char *s1, const char *s2)
  950. {
  951. // lifted from Graphvis http://www.graphviz.org
  952. while ((*s1 != '\0')
  953. && (tolower(*s1) == tolower(*s2)))
  954. {
  955. s1++;
  956. s2++;
  957. }
  958. return tolower(*s1) - tolower(*s2);
  959. }
  960. // return true if the file exists
  961. long int SystemTools::ModifiedTime(const char* filename)
  962. {
  963. struct stat fs;
  964. if (stat(filename, &fs) != 0)
  965. {
  966. return 0;
  967. }
  968. else
  969. {
  970. return (long int)fs.st_mtime;
  971. }
  972. }
  973. kwsys_stl::string SystemTools::GetLastSystemError()
  974. {
  975. int e = errno;
  976. return strerror(e);
  977. }
  978. bool SystemTools::RemoveFile(const char* source)
  979. {
  980. return unlink(source) != 0 ? false : true;
  981. }
  982. bool SystemTools::RemoveADirectory(const char* source)
  983. {
  984. Directory dir;
  985. dir.Load(source);
  986. size_t fileNum;
  987. for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum)
  988. {
  989. if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".") &&
  990. strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".."))
  991. {
  992. kwsys_stl::string fullPath = source;
  993. fullPath += "/";
  994. fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
  995. if(SystemTools::FileIsDirectory(fullPath.c_str()))
  996. {
  997. if (!SystemTools::RemoveADirectory(fullPath.c_str()))
  998. {
  999. return false;
  1000. }
  1001. }
  1002. else
  1003. {
  1004. if(!SystemTools::RemoveFile(fullPath.c_str()))
  1005. {
  1006. return false;
  1007. }
  1008. }
  1009. }
  1010. }
  1011. return (Rmdir(source) == 0);
  1012. }
  1013. /**
  1014. * Find the file the given name. Searches the given path and then
  1015. * the system search path. Returns the full path to the file if it is
  1016. * found. Otherwise, the empty string is returned.
  1017. */
  1018. kwsys_stl::string SystemTools::FindFile(const char* name,
  1019. const kwsys_stl::vector<kwsys_stl::string>& userPaths)
  1020. {
  1021. // Add the system search path to our path first
  1022. kwsys_stl::vector<kwsys_stl::string> path;
  1023. SystemTools::GetPath(path, "CMAKE_FILE_PATH");
  1024. SystemTools::GetPath(path);
  1025. // now add the additional paths
  1026. path.insert(path.end(), userPaths.begin(), userPaths.end());
  1027. // now look for the file
  1028. kwsys_stl::string tryPath;
  1029. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator p = path.begin();
  1030. p != path.end(); ++p)
  1031. {
  1032. tryPath = *p;
  1033. tryPath += "/";
  1034. tryPath += name;
  1035. if(SystemTools::FileExists(tryPath.c_str()) &&
  1036. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1037. {
  1038. return SystemTools::CollapseFullPath(tryPath.c_str());
  1039. }
  1040. }
  1041. // Couldn't find the file.
  1042. return "";
  1043. }
  1044. /**
  1045. * Find the executable with the given name. Searches the given path and then
  1046. * the system search path. Returns the full path to the executable if it is
  1047. * found. Otherwise, the empty string is returned.
  1048. */
  1049. kwsys_stl::string SystemTools::FindProgram(
  1050. const char* name,
  1051. const kwsys_stl::vector<kwsys_stl::string>& userPaths,
  1052. bool no_system_path)
  1053. {
  1054. if(!name)
  1055. {
  1056. return "";
  1057. }
  1058. // See if the executable exists as written.
  1059. if(SystemTools::FileExists(name) &&
  1060. !SystemTools::FileIsDirectory(name))
  1061. {
  1062. return SystemTools::CollapseFullPath(name);
  1063. }
  1064. kwsys_stl::string tryPath = name;
  1065. tryPath += SystemTools::GetExecutableExtension();
  1066. if(SystemTools::FileExists(tryPath.c_str()) &&
  1067. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1068. {
  1069. return SystemTools::CollapseFullPath(tryPath.c_str());
  1070. }
  1071. kwsys_stl::vector<kwsys_stl::string> path;
  1072. SystemTools::GetPath(path, "CMAKE_PROGRAM_PATH");
  1073. // Add the system search path to our path.
  1074. if (!no_system_path)
  1075. {
  1076. SystemTools::GetPath(path);
  1077. }
  1078. // now add the additional paths
  1079. path.insert(path.end(), userPaths.begin(), userPaths.end());
  1080. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator p = path.begin();
  1081. p != path.end(); ++p)
  1082. {
  1083. tryPath = *p;
  1084. tryPath += "/";
  1085. tryPath += name;
  1086. if(SystemTools::FileExists(tryPath.c_str()) &&
  1087. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1088. {
  1089. return SystemTools::CollapseFullPath(tryPath.c_str());
  1090. }
  1091. #ifdef _WIN32
  1092. tryPath += ".com";
  1093. if(SystemTools::FileExists(tryPath.c_str()) &&
  1094. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1095. {
  1096. return SystemTools::CollapseFullPath(tryPath.c_str());
  1097. }
  1098. tryPath = *p;
  1099. tryPath += "/";
  1100. tryPath += name;
  1101. #endif
  1102. tryPath += SystemTools::GetExecutableExtension();
  1103. if(SystemTools::FileExists(tryPath.c_str()) &&
  1104. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1105. {
  1106. return SystemTools::CollapseFullPath(tryPath.c_str());
  1107. }
  1108. }
  1109. // Couldn't find the program.
  1110. return "";
  1111. }
  1112. /**
  1113. * Find the library with the given name. Searches the given path and then
  1114. * the system search path. Returns the full path to the library if it is
  1115. * found. Otherwise, the empty string is returned.
  1116. */
  1117. kwsys_stl::string SystemTools::FindLibrary(const char* name,
  1118. const kwsys_stl::vector<kwsys_stl::string>& userPaths)
  1119. {
  1120. // See if the executable exists as written.
  1121. if(SystemTools::FileExists(name) &&
  1122. !SystemTools::FileIsDirectory(name))
  1123. {
  1124. return SystemTools::CollapseFullPath(name);
  1125. }
  1126. // Add the system search path to our path.
  1127. kwsys_stl::vector<kwsys_stl::string> path;
  1128. SystemTools::GetPath(path);
  1129. // now add the additional paths
  1130. path.insert(path.end(), userPaths.begin(), userPaths.end());
  1131. kwsys_stl::string tryPath;
  1132. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator p = path.begin();
  1133. p != path.end(); ++p)
  1134. {
  1135. #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__MINGW32__)
  1136. tryPath = *p;
  1137. tryPath += "/";
  1138. tryPath += name;
  1139. tryPath += ".lib";
  1140. if(SystemTools::FileExists(tryPath.c_str())
  1141. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1142. {
  1143. return SystemTools::CollapseFullPath(tryPath.c_str());
  1144. }
  1145. #else
  1146. tryPath = *p;
  1147. tryPath += "/lib";
  1148. tryPath += name;
  1149. tryPath += ".so";
  1150. if(SystemTools::FileExists(tryPath.c_str())
  1151. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1152. {
  1153. return SystemTools::CollapseFullPath(tryPath.c_str());
  1154. }
  1155. tryPath = *p;
  1156. tryPath += "/lib";
  1157. tryPath += name;
  1158. tryPath += ".a";
  1159. if(SystemTools::FileExists(tryPath.c_str())
  1160. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1161. {
  1162. return SystemTools::CollapseFullPath(tryPath.c_str());
  1163. }
  1164. tryPath = *p;
  1165. tryPath += "/lib";
  1166. tryPath += name;
  1167. tryPath += ".sl";
  1168. if(SystemTools::FileExists(tryPath.c_str())
  1169. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1170. {
  1171. return SystemTools::CollapseFullPath(tryPath.c_str());
  1172. }
  1173. tryPath = *p;
  1174. tryPath += "/lib";
  1175. tryPath += name;
  1176. tryPath += ".dylib";
  1177. if(SystemTools::FileExists(tryPath.c_str())
  1178. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1179. {
  1180. return SystemTools::CollapseFullPath(tryPath.c_str());
  1181. }
  1182. tryPath = *p;
  1183. tryPath += "/lib";
  1184. tryPath += name;
  1185. tryPath += ".dll";
  1186. if(SystemTools::FileExists(tryPath.c_str())
  1187. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1188. {
  1189. return SystemTools::CollapseFullPath(tryPath.c_str());
  1190. }
  1191. #endif
  1192. }
  1193. // Couldn't find the library.
  1194. return "";
  1195. }
  1196. bool SystemTools::FileIsDirectory(const char* name)
  1197. {
  1198. struct stat fs;
  1199. if(stat(name, &fs) == 0)
  1200. {
  1201. #if _WIN32
  1202. return ((fs.st_mode & _S_IFDIR) != 0);
  1203. #else
  1204. return S_ISDIR(fs.st_mode);
  1205. #endif
  1206. }
  1207. else
  1208. {
  1209. return false;
  1210. }
  1211. }
  1212. int SystemTools::ChangeDirectory(const char *dir)
  1213. {
  1214. return Chdir(dir);
  1215. }
  1216. kwsys_stl::string SystemTools::GetCurrentWorkingDirectory()
  1217. {
  1218. char buf[2048];
  1219. const char* cwd = Getcwd(buf, 2048);
  1220. kwsys_stl::string path;
  1221. if ( cwd )
  1222. {
  1223. path = cwd;
  1224. }
  1225. return path;
  1226. }
  1227. kwsys_stl::string SystemTools::GetProgramPath(const char* in_name)
  1228. {
  1229. kwsys_stl::string dir, file;
  1230. SystemTools::SplitProgramPath(in_name, dir, file);
  1231. return dir;
  1232. }
  1233. bool SystemTools::SplitProgramPath(const char* in_name,
  1234. kwsys_stl::string& dir,
  1235. kwsys_stl::string& file,
  1236. bool)
  1237. {
  1238. dir = in_name;
  1239. file = "";
  1240. SystemTools::ConvertToUnixSlashes(dir);
  1241. if(!SystemTools::FileIsDirectory(dir.c_str()))
  1242. {
  1243. kwsys_stl::string::size_type slashPos = dir.rfind("/");
  1244. if(slashPos != kwsys_stl::string::npos)
  1245. {
  1246. file = dir.substr(slashPos+1);
  1247. dir = dir.substr(0, slashPos);
  1248. }
  1249. else
  1250. {
  1251. file = dir;
  1252. dir = "";
  1253. }
  1254. }
  1255. if(!(dir == "") && !SystemTools::FileIsDirectory(dir.c_str()))
  1256. {
  1257. kwsys_stl::string oldDir = in_name;
  1258. SystemTools::ConvertToUnixSlashes(oldDir);
  1259. dir = in_name;
  1260. return false;
  1261. }
  1262. return true;
  1263. }
  1264. bool SystemTools::FindProgramPath(const char* argv0,
  1265. kwsys_stl::string& pathOut,
  1266. kwsys_stl::string& errorMsg,
  1267. const char* exeName,
  1268. const char* buildDir,
  1269. const char* installPrefix )
  1270. {
  1271. kwsys_stl::vector<kwsys_stl::string> failures;
  1272. kwsys_stl::string self = argv0;
  1273. SystemTools::ConvertToUnixSlashes(self);
  1274. failures.push_back(argv0);
  1275. self = SystemTools::FindProgram(self.c_str());
  1276. if(!SystemTools::FileExists(self.c_str()))
  1277. {
  1278. if(buildDir)
  1279. {
  1280. kwsys_stl::string intdir = ".";
  1281. #ifdef CMAKE_INTDIR
  1282. intdir = CMAKE_INTDIR;
  1283. #endif
  1284. self = buildDir;
  1285. self += "/bin/";
  1286. self += intdir;
  1287. self += "/";
  1288. self += exeName;
  1289. self += SystemTools::GetExecutableExtension();
  1290. }
  1291. }
  1292. if(installPrefix)
  1293. {
  1294. if(!SystemTools::FileExists(self.c_str()))
  1295. {
  1296. failures.push_back(self);
  1297. self = installPrefix;
  1298. self += "/bin/";
  1299. self += exeName;
  1300. }
  1301. }
  1302. if(!SystemTools::FileExists(self.c_str()))
  1303. {
  1304. failures.push_back(self);
  1305. kwsys_ios::ostringstream msg;
  1306. msg << "Can not find the command line program " << exeName << "\n";
  1307. msg << " argv[0] = \"" << argv0 << "\"\n";
  1308. msg << " Attempted paths:\n";
  1309. kwsys_stl::vector<kwsys_stl::string>::iterator i;
  1310. for(i=failures.begin(); i != failures.end(); ++i)
  1311. {
  1312. msg << " \"" << i->c_str() << "\"\n";
  1313. }
  1314. errorMsg = msg.str();
  1315. return false;
  1316. }
  1317. pathOut = self;
  1318. return true;
  1319. }
  1320. kwsys_stl::string SystemTools::CollapseFullPath(const char* in_relative)
  1321. {
  1322. return SystemTools::CollapseFullPath(in_relative, 0);
  1323. }
  1324. kwsys_stl::string SystemTools::CollapseFullPath(const char* in_relative,
  1325. const char* in_base)
  1326. {
  1327. // Save original working directory.
  1328. kwsys_stl::string orig = SystemTools::GetCurrentWorkingDirectory();
  1329. // Change to base of relative path.
  1330. if(in_base)
  1331. {
  1332. Chdir(in_base);
  1333. }
  1334. kwsys_stl::string dir, file;
  1335. SystemTools::SplitProgramPath(in_relative, dir, file, false);
  1336. if(dir.size() == 0 &&
  1337. in_relative && strlen(in_relative) > 0 &&
  1338. in_relative[0] == '/')
  1339. {
  1340. dir = "/";
  1341. }
  1342. #ifdef _WIN32
  1343. // Follow relative path.
  1344. if(!(dir == ""))
  1345. {
  1346. Chdir(dir.c_str());
  1347. }
  1348. // Get the resulting directory.
  1349. kwsys_stl::string newDir = SystemTools::GetCurrentWorkingDirectory();
  1350. // Add the file back on to the directory.
  1351. SystemTools::ConvertToUnixSlashes(newDir);
  1352. #else
  1353. # ifdef MAXPATHLEN
  1354. char resolved_name[MAXPATHLEN];
  1355. # else
  1356. # ifdef PATH_MAX
  1357. char resolved_name[PATH_MAX];
  1358. # else
  1359. char resolved_name[5024];
  1360. # endif
  1361. # endif
  1362. // Resolve relative path.
  1363. kwsys_stl::string newDir;
  1364. if(!(dir == ""))
  1365. {
  1366. realpath(dir.c_str(), resolved_name);
  1367. newDir = resolved_name;
  1368. }
  1369. else
  1370. {
  1371. newDir = SystemTools::GetCurrentWorkingDirectory();
  1372. }
  1373. // if there is a /tmp_mnt in a path get rid of it!
  1374. if(newDir.find("/tmp_mnt") == 0)
  1375. {
  1376. newDir = newDir.substr(8);
  1377. }
  1378. #endif
  1379. // Restore original working directory.
  1380. Chdir(orig.c_str());
  1381. // Construct and return the full path.
  1382. kwsys_stl::string newPath = newDir;
  1383. if(!(file == ""))
  1384. {
  1385. if(!(newDir.size() == 1 && newDir[0] == '/'))
  1386. {
  1387. newPath += "/";
  1388. }
  1389. newPath += file;
  1390. }
  1391. return newPath;
  1392. }
  1393. bool SystemTools::Split(const char* str, kwsys_stl::vector<kwsys_stl::string>& lines)
  1394. {
  1395. kwsys_stl::string data(str);
  1396. kwsys_stl::string::size_type lpos = 0;
  1397. while(lpos < data.length())
  1398. {
  1399. kwsys_stl::string::size_type rpos = data.find_first_of("\n", lpos);
  1400. if(rpos == kwsys_stl::string::npos)
  1401. {
  1402. // Line ends at end of string without a newline.
  1403. lines.push_back(data.substr(lpos));
  1404. return false;
  1405. }
  1406. if((rpos > lpos) && (data[rpos-1] == '\r'))
  1407. {
  1408. // Line ends in a "\r\n" pair, remove both characters.
  1409. lines.push_back(data.substr(lpos, (rpos-1)-lpos));
  1410. }
  1411. else
  1412. {
  1413. // Line ends in a "\n", remove the character.
  1414. lines.push_back(data.substr(lpos, rpos-lpos));
  1415. }
  1416. lpos = rpos+1;
  1417. }
  1418. return true;
  1419. }
  1420. /**
  1421. * Return path of a full filename (no trailing slashes).
  1422. * Warning: returned path is converted to Unix slashes format.
  1423. */
  1424. kwsys_stl::string SystemTools::GetFilenamePath(const kwsys_stl::string& filename)
  1425. {
  1426. kwsys_stl::string fn = filename;
  1427. SystemTools::ConvertToUnixSlashes(fn);
  1428. kwsys_stl::string::size_type slash_pos = fn.rfind("/");
  1429. if(slash_pos != kwsys_stl::string::npos)
  1430. {
  1431. return fn.substr(0, slash_pos);
  1432. }
  1433. else
  1434. {
  1435. return "";
  1436. }
  1437. }
  1438. /**
  1439. * Return file name of a full filename (i.e. file name without path).
  1440. */
  1441. kwsys_stl::string SystemTools::GetFilenameName(const kwsys_stl::string& filename)
  1442. {
  1443. kwsys_stl::string fn = filename;
  1444. SystemTools::ConvertToUnixSlashes(fn);
  1445. kwsys_stl::string::size_type slash_pos = fn.rfind("/");
  1446. if(slash_pos != kwsys_stl::string::npos)
  1447. {
  1448. return fn.substr(slash_pos + 1);
  1449. }
  1450. else
  1451. {
  1452. return filename;
  1453. }
  1454. }
  1455. /**
  1456. * Return file extension of a full filename (dot included).
  1457. * Warning: this is the longest extension (for example: .tar.gz)
  1458. */
  1459. kwsys_stl::string SystemTools::GetFilenameExtension(const kwsys_stl::string& filename)
  1460. {
  1461. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  1462. kwsys_stl::string::size_type dot_pos = name.find(".");
  1463. if(dot_pos != kwsys_stl::string::npos)
  1464. {
  1465. return name.substr(dot_pos);
  1466. }
  1467. else
  1468. {
  1469. return "";
  1470. }
  1471. }
  1472. /**
  1473. * Return file extension of a full filename (dot included).
  1474. * Warning: this is the shortest extension (for example: .tar.gz)
  1475. */
  1476. kwsys_stl::string SystemTools::GetFilenameLastExtension(const kwsys_stl::string& filename)
  1477. {
  1478. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  1479. kwsys_stl::string::size_type dot_pos = name.rfind(".");
  1480. if(dot_pos != kwsys_stl::string::npos)
  1481. {
  1482. return name.substr(dot_pos);
  1483. }
  1484. else
  1485. {
  1486. return "";
  1487. }
  1488. }
  1489. /**
  1490. * Return file name without extension of a full filename (i.e. without path).
  1491. * Warning: it considers the longest extension (for example: .tar.gz)
  1492. */
  1493. kwsys_stl::string SystemTools::GetFilenameWithoutExtension(const kwsys_stl::string& filename)
  1494. {
  1495. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  1496. kwsys_stl::string::size_type dot_pos = name.find(".");
  1497. if(dot_pos != kwsys_stl::string::npos)
  1498. {
  1499. return name.substr(0, dot_pos);
  1500. }
  1501. else
  1502. {
  1503. return name;
  1504. }
  1505. }
  1506. /**
  1507. * Return file name without extension of a full filename (i.e. without path).
  1508. * Warning: it considers the last extension (for example: removes .gz
  1509. * from .tar.gz)
  1510. */
  1511. kwsys_stl::string
  1512. SystemTools::GetFilenameWithoutLastExtension(const kwsys_stl::string& filename)
  1513. {
  1514. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  1515. kwsys_stl::string::size_type dot_pos = name.rfind(".");
  1516. if(dot_pos != kwsys_stl::string::npos)
  1517. {
  1518. return name.substr(0, dot_pos);
  1519. }
  1520. else
  1521. {
  1522. return name;
  1523. }
  1524. }
  1525. bool SystemTools::FileIsFullPath(const char* in_name)
  1526. {
  1527. kwsys_stl::string name = in_name;
  1528. #if defined(_WIN32) || defined(__CYGWIN__)
  1529. // On Windows, the name must be at least two characters long.
  1530. if(name.length() < 2)
  1531. {
  1532. return false;
  1533. }
  1534. if(name[1] == ':')
  1535. {
  1536. return true;
  1537. }
  1538. if(name[0] == '\\')
  1539. {
  1540. return true;
  1541. }
  1542. #else
  1543. // On UNIX, the name must be at least one character long.
  1544. if(name.length() < 1)
  1545. {
  1546. return false;
  1547. }
  1548. #endif
  1549. // On UNIX, the name must begin in a '/'.
  1550. // On Windows, if the name begins in a '/', then it is a full
  1551. // network path.
  1552. if(name[0] == '/')
  1553. {
  1554. return true;
  1555. }
  1556. return false;
  1557. }
  1558. bool SystemTools::GetShortPath(const char* path, kwsys_stl::string& shortPath)
  1559. {
  1560. #if defined(WIN32) && !defined(__CYGWIN__)
  1561. const int size = int(strlen(path)) +1; // size of return
  1562. char *buffer = new char[size]; // create a buffer
  1563. char *tempPath = new char[size]; // create a buffer
  1564. int ret;
  1565. // if the path passed in has quotes around it, first remove the quotes
  1566. if (path[0] == '"' && path[strlen(path)-1] == '"')
  1567. {
  1568. strcpy(tempPath,path+1);
  1569. tempPath[strlen(tempPath)-1] = '\0';
  1570. }
  1571. else
  1572. {
  1573. strcpy(tempPath,path);
  1574. }
  1575. buffer[0] = 0;
  1576. ret = GetShortPathName(tempPath, buffer, size);
  1577. if(buffer[0] == 0 || ret > size)
  1578. {
  1579. delete [] buffer;
  1580. delete [] tempPath;
  1581. return false;
  1582. }
  1583. else
  1584. {
  1585. shortPath = buffer;
  1586. delete [] buffer;
  1587. delete [] tempPath;
  1588. return true;
  1589. }
  1590. #else
  1591. shortPath = path;
  1592. return true;
  1593. #endif
  1594. }
  1595. void SystemTools::SplitProgramFromArgs(const char* path,
  1596. kwsys_stl::string& program, kwsys_stl::string& args)
  1597. {
  1598. if(SystemTools::FileExists(path))
  1599. {
  1600. program = path;
  1601. args = "";
  1602. return;
  1603. }
  1604. kwsys_stl::vector<kwsys_stl::string> e;
  1605. kwsys_stl::string findProg = SystemTools::FindProgram(path, e);
  1606. if(findProg.size())
  1607. {
  1608. program = findProg;
  1609. args = "";
  1610. return;
  1611. }
  1612. kwsys_stl::string dir = path;
  1613. kwsys_stl::string::size_type spacePos = dir.rfind(' ');
  1614. if(spacePos == kwsys_stl::string::npos)
  1615. {
  1616. program = "";
  1617. args = "";
  1618. return;
  1619. }
  1620. while(spacePos != kwsys_stl::string::npos)
  1621. {
  1622. kwsys_stl::string tryProg = dir.substr(0, spacePos);
  1623. if(SystemTools::FileExists(tryProg.c_str()))
  1624. {
  1625. program = tryProg;
  1626. args = dir.substr(spacePos, dir.size()-spacePos);
  1627. return;
  1628. }
  1629. findProg = SystemTools::FindProgram(tryProg.c_str(), e);
  1630. if(findProg.size())
  1631. {
  1632. program = findProg;
  1633. args = dir.substr(spacePos, dir.size()-spacePos);
  1634. return;
  1635. }
  1636. spacePos = dir.rfind(' ', spacePos--);
  1637. }
  1638. program = "";
  1639. args = "";
  1640. }
  1641. kwsys_stl::string SystemTools::GetCurrentDateTime(const char* format)
  1642. {
  1643. char buf[1024];
  1644. time_t t;
  1645. time(&t);
  1646. strftime(buf, sizeof(buf), format, localtime(&t));
  1647. return buf;
  1648. }
  1649. kwsys_stl::string SystemTools::MakeCindentifier(const char* s)
  1650. {
  1651. kwsys_stl::string str(s);
  1652. if (str.find_first_of("0123456789") == 0)
  1653. {
  1654. str = "_" + str;
  1655. }
  1656. kwsys_stl::string permited_chars("_"
  1657. "abcdefghijklmnopqrstuvwxyz"
  1658. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  1659. "0123456789");
  1660. kwsys_stl::string::size_type pos = 0;
  1661. while ((pos = str.find_first_not_of(permited_chars, pos)) != kwsys_stl::string::npos)
  1662. {
  1663. str[pos] = '_';
  1664. }
  1665. return str;
  1666. }
  1667. // Due to a buggy stream library on the HP and another on Mac OSX, we
  1668. // need this very carefully written version of getline. Returns true
  1669. // if any data were read before the end-of-file was reached.
  1670. bool SystemTools::GetLineFromStream(kwsys_ios::istream& is, kwsys_stl::string& line,
  1671. bool *has_newline /* = 0 */)
  1672. {
  1673. const int bufferSize = 1024;
  1674. char buffer[bufferSize];
  1675. line = "";
  1676. bool haveData = false;
  1677. if ( has_newline )
  1678. {
  1679. *has_newline = false;
  1680. }
  1681. // If no characters are read from the stream, the end of file has
  1682. // been reached.
  1683. while((is.getline(buffer, bufferSize), is.gcount() > 0))
  1684. {
  1685. haveData = true;
  1686. line.append(buffer);
  1687. // If newline character was read, the gcount includes the
  1688. // character, but the buffer does not. The end of line has been
  1689. // reached.
  1690. if(strlen(buffer) < static_cast<size_t>(is.gcount()))
  1691. {
  1692. if ( has_newline )
  1693. {
  1694. *has_newline = true;
  1695. }
  1696. break;
  1697. }
  1698. // The fail bit may be set. Clear it.
  1699. is.clear(is.rdstate() & ~kwsys_ios::ios::failbit);
  1700. }
  1701. return haveData;
  1702. }
  1703. int SystemTools::GetTerminalWidth()
  1704. {
  1705. int width = -1;
  1706. #ifndef _WIN32
  1707. struct winsize ws;
  1708. char *columns; /* Unix98 environment variable */
  1709. if(ioctl(1, TIOCGWINSZ, &ws) != -1 && ws.ws_col>0 && ws.ws_row>0)
  1710. {
  1711. width = ws.ws_col;
  1712. }
  1713. if(!isatty(STDOUT_FILENO))
  1714. {
  1715. width = -1;
  1716. }
  1717. columns = getenv("COLUMNS");
  1718. if(columns && *columns)
  1719. {
  1720. long t;
  1721. char *endptr;
  1722. t = strtol(columns, &endptr, 0);
  1723. if(endptr && !*endptr && (t>0) && (t<1000))
  1724. {
  1725. width = (int)t;
  1726. }
  1727. }
  1728. if ( width < 9 )
  1729. {
  1730. width = -1;
  1731. }
  1732. #endif
  1733. return width;
  1734. }
  1735. bool SystemTools::GetPermissions(const char* file, mode_t& mode)
  1736. {
  1737. if ( !file )
  1738. {
  1739. return false;
  1740. }
  1741. struct stat st;
  1742. if ( stat(file, &st) < 0 )
  1743. {
  1744. return false;
  1745. }
  1746. mode = st.st_mode;
  1747. return true;
  1748. }
  1749. bool SystemTools::SetPermissions(const char* file, mode_t mode)
  1750. {
  1751. if ( !file )
  1752. {
  1753. return false;
  1754. }
  1755. if ( !SystemTools::FileExists(file) )
  1756. {
  1757. return false;
  1758. }
  1759. if ( chmod(file, mode) < 0 )
  1760. {
  1761. return false;
  1762. }
  1763. return true;
  1764. }
  1765. } // namespace KWSYS_NAMESPACE
  1766. #if defined(_MSC_VER) && defined(_DEBUG)
  1767. # include <crtdbg.h>
  1768. # include <stdio.h>
  1769. # include <stdlib.h>
  1770. namespace KWSYS_NAMESPACE
  1771. {
  1772. static int SystemToolsDebugReport(int, char* message, int*)
  1773. {
  1774. fprintf(stderr, message);
  1775. exit(1);
  1776. }
  1777. void SystemTools::EnableMSVCDebugHook()
  1778. {
  1779. if(getenv("DART_TEST_FROM_DART"))
  1780. {
  1781. _CrtSetReportHook(SystemToolsDebugReport);
  1782. }
  1783. }
  1784. } // namespace KWSYS_NAMESPACE
  1785. #else
  1786. namespace KWSYS_NAMESPACE
  1787. {
  1788. void SystemTools::EnableMSVCDebugHook() {}
  1789. } // namespace KWSYS_NAMESPACE
  1790. #endif