SystemTools.cxx 49 KB

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