SystemTools.cxx 57 KB

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