SystemTools.cxx 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912
  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. bool SystemTools::FileTimeCompare(const char* f1, const char* f2,
  635. int* result)
  636. {
  637. // Default to same time.
  638. *result = 0;
  639. #if !defined(_WIN32) || defined(__CYGWIN__)
  640. // POSIX version. Use stat function to get file modification time.
  641. struct stat s1;
  642. if(stat(f1, &s1) != 0)
  643. {
  644. return false;
  645. }
  646. struct stat s2;
  647. if(stat(f2, &s2) != 0)
  648. {
  649. return false;
  650. }
  651. # if KWSYS_STAT_HAS_ST_MTIM
  652. // Compare using nanosecond resolution.
  653. if(s1.st_mtim.tv_sec < s2.st_mtim.tv_sec)
  654. {
  655. *result = -1;
  656. }
  657. else if(s1.st_mtim.tv_sec > s2.st_mtim.tv_sec)
  658. {
  659. *result = 1;
  660. }
  661. else if(s1.st_mtim.tv_nsec < s2.st_mtim.tv_nsec)
  662. {
  663. *result = -1;
  664. }
  665. else if(s1.st_mtim.tv_nsec > s2.st_mtim.tv_nsec)
  666. {
  667. *result = 1;
  668. }
  669. # else
  670. // Compare using 1 second resolution.
  671. if(s1.st_mtime < s2.st_mtime)
  672. {
  673. *result = -1;
  674. }
  675. else if(s1.st_mtime > s2.st_mtime)
  676. {
  677. *result = 1;
  678. }
  679. # endif
  680. #else
  681. // Windows version. Create file handles and get the modification times.
  682. HANDLE hf1 = CreateFile(f1, GENERIC_READ, FILE_SHARE_READ,
  683. NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS,
  684. NULL);
  685. if(hf1 == INVALID_HANDLE_VALUE)
  686. {
  687. return false;
  688. }
  689. FILETIME tf1;
  690. if(!GetFileTime(hf1, 0, 0, &tf1))
  691. {
  692. CloseHandle(hf1);
  693. return false;
  694. }
  695. CloseHandle(hf1);
  696. HANDLE hf2 = CreateFile(f2, GENERIC_READ, FILE_SHARE_READ,
  697. NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS,
  698. NULL);
  699. if(hf2 == INVALID_HANDLE_VALUE)
  700. {
  701. return false;
  702. }
  703. FILETIME tf2;
  704. if(!GetFileTime(hf2, 0, 0, &tf2))
  705. {
  706. CloseHandle(hf2);
  707. return false;
  708. }
  709. CloseHandle(hf2);
  710. // Compare the file times using resolution provided by system call.
  711. *result = (int)CompareFileTime(&tf1, &tf2);
  712. #endif
  713. return true;
  714. }
  715. // Return a capitalized string (i.e the first letter is uppercased, all other
  716. // are lowercased)
  717. kwsys_stl::string SystemTools::Capitalized(const kwsys_stl::string& s)
  718. {
  719. kwsys_stl::string n;
  720. if(s.size() == 0)
  721. {
  722. return n;
  723. }
  724. n.resize(s.size());
  725. n[0] = static_cast<kwsys_stl::string::value_type>(toupper(s[0]));
  726. for (size_t i = 1; i < s.size(); i++)
  727. {
  728. n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
  729. }
  730. return n;
  731. }
  732. // Return capitalized words
  733. kwsys_stl::string SystemTools::CapitalizedWords(const kwsys_stl::string& s)
  734. {
  735. kwsys_stl::string n(s);
  736. for (size_t i = 0; i < s.size(); i++)
  737. {
  738. if (isalpha(s[i]) && (i == 0 || isspace(s[i - 1])))
  739. {
  740. n[i] = static_cast<kwsys_stl::string::value_type>(toupper(s[i]));
  741. }
  742. }
  743. return n;
  744. }
  745. // Return uncapitalized words
  746. kwsys_stl::string SystemTools::UnCapitalizedWords(const kwsys_stl::string& s)
  747. {
  748. kwsys_stl::string n(s);
  749. for (size_t i = 0; i < s.size(); i++)
  750. {
  751. if (isalpha(s[i]) && (i == 0 || isspace(s[i - 1])))
  752. {
  753. n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
  754. }
  755. }
  756. return n;
  757. }
  758. // Return a lower case string
  759. kwsys_stl::string SystemTools::LowerCase(const kwsys_stl::string& s)
  760. {
  761. kwsys_stl::string n;
  762. n.resize(s.size());
  763. for (size_t i = 0; i < s.size(); i++)
  764. {
  765. n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
  766. }
  767. return n;
  768. }
  769. // Return a lower case string
  770. kwsys_stl::string SystemTools::UpperCase(const kwsys_stl::string& s)
  771. {
  772. kwsys_stl::string n;
  773. n.resize(s.size());
  774. for (size_t i = 0; i < s.size(); i++)
  775. {
  776. n[i] = static_cast<kwsys_stl::string::value_type>(toupper(s[i]));
  777. }
  778. return n;
  779. }
  780. // Count char in string
  781. size_t SystemTools::CountChar(const char* str, char c)
  782. {
  783. size_t count = 0;
  784. if (str)
  785. {
  786. while (*str)
  787. {
  788. if (*str == c)
  789. {
  790. ++count;
  791. }
  792. ++str;
  793. }
  794. }
  795. return count;
  796. }
  797. // Remove chars in string
  798. char* SystemTools::RemoveChars(const char* str, const char *toremove)
  799. {
  800. if (!str)
  801. {
  802. return NULL;
  803. }
  804. char *clean_str = new char [strlen(str) + 1];
  805. char *ptr = clean_str;
  806. while (*str)
  807. {
  808. const char *str2 = toremove;
  809. while (*str2 && *str != *str2)
  810. {
  811. ++str2;
  812. }
  813. if (!*str2)
  814. {
  815. *ptr++ = *str;
  816. }
  817. ++str;
  818. }
  819. *ptr = '\0';
  820. return clean_str;
  821. }
  822. // Remove chars in string
  823. char* SystemTools::RemoveCharsButUpperHex(const char* str)
  824. {
  825. if (!str)
  826. {
  827. return 0;
  828. }
  829. char *clean_str = new char [strlen(str) + 1];
  830. char *ptr = clean_str;
  831. while (*str)
  832. {
  833. if ((*str >= '0' && *str <= '9') || (*str >= 'A' && *str <= 'H'))
  834. {
  835. *ptr++ = *str;
  836. }
  837. ++str;
  838. }
  839. *ptr = '\0';
  840. return clean_str;
  841. }
  842. // Replace chars in string
  843. char* SystemTools::ReplaceChars(char* str, const char *toreplace, char replacement)
  844. {
  845. if (str)
  846. {
  847. char *ptr = str;
  848. while (*ptr)
  849. {
  850. const char *ptr2 = toreplace;
  851. while (*ptr2)
  852. {
  853. if (*ptr == *ptr2)
  854. {
  855. *ptr = replacement;
  856. }
  857. ++ptr2;
  858. }
  859. ++ptr;
  860. }
  861. }
  862. return str;
  863. }
  864. // Returns if string starts with another string
  865. bool vtkString::StringStartsWith(const char* str1, const char* str2)
  866. {
  867. if (!str1 || !str2)
  868. {
  869. return false;
  870. }
  871. size_t len1 = strlen(str1), len2 = strlen(str2);
  872. return len1 >= len2 && !strncmp(str1, str2, len2) ? true : false
  873. }
  874. // Returns if string ends with another string
  875. bool vtkString::StringEndsWith(const char* str1, const char* str2)
  876. {
  877. if (!str1 || !str2)
  878. {
  879. return false;
  880. }
  881. size_t len1 = strlen(str1), len2 = strlen(str2);
  882. return len1 >= len2 && !strncmp(str1 + (len1 - len2), str2, len2) ? true : false;
  883. }
  884. // Returns a pointer to the last occurence of str2 in str1
  885. const char* SystemTools::FindLastString(const char* str1, const char* str2)
  886. {
  887. if (!str1 || !str2)
  888. {
  889. return NULL;
  890. }
  891. size_t len1 = strlen(str1), len2 = strlen(str2);
  892. if (len1 >= len2)
  893. {
  894. const char *ptr = str1 + len1 - len2;
  895. do
  896. {
  897. if (!strncmp(ptr, str2, len2))
  898. {
  899. return ptr;
  900. }
  901. } while (ptr-- != str1);
  902. }
  903. return NULL;
  904. }
  905. // Duplicate string
  906. char* SystemTools::DuplicateString(const char* str)
  907. {
  908. if (str)
  909. {
  910. char *newstr = new char [strlen(str) + 1];
  911. return strcpy(newstr, str);
  912. }
  913. return NULL;
  914. }
  915. // Return a cropped string
  916. kwsys_stl::string SystemTools::CropString(const kwsys_stl::string& s,
  917. size_t max_len)
  918. {
  919. if (!s.size() || max_len == 0 || max_len >= s.size())
  920. {
  921. return s;
  922. }
  923. kwsys_stl::string n;
  924. n.reserve(max_len);
  925. size_t middle = max_len / 2;
  926. n += s.substr(0, middle);
  927. n += s.substr(s.size() - (max_len - middle), kwsys_stl::string::npos);
  928. if (max_len > 2)
  929. {
  930. n[middle] = '.';
  931. if (max_len > 3)
  932. {
  933. n[middle - 1] = '.';
  934. if (max_len > 4)
  935. {
  936. n[middle + 1] = '.';
  937. }
  938. }
  939. }
  940. return n;
  941. }
  942. // convert windows slashes to unix slashes
  943. void SystemTools::ConvertToUnixSlashes(kwsys_stl::string& path)
  944. {
  945. kwsys_stl::string::size_type pos = 0;
  946. while((pos = path.find('\\', pos)) != kwsys_stl::string::npos)
  947. {
  948. // make sure we don't convert an escaped space to a unix slash
  949. if(pos < path.size()-1)
  950. {
  951. if(path[pos+1] != ' ')
  952. {
  953. path[pos] = '/';
  954. }
  955. }
  956. pos++;
  957. }
  958. // Remove all // from the path just like most unix shells
  959. int start_find;
  960. #ifdef _WIN32
  961. // However, on windows if the first characters are both slashes,
  962. // then keep them that way, so that network paths can be handled.
  963. start_find = 1;
  964. #else
  965. start_find = 0;
  966. #endif
  967. while((pos = path.find("//", start_find)) != kwsys_stl::string::npos)
  968. {
  969. SystemTools::ReplaceString(path, "//", "/");
  970. }
  971. // remove any trailing slash
  972. if(path.size() > 1 && path[path.size()-1] == '/')
  973. {
  974. path = path.substr(0, path.size()-1);
  975. }
  976. // if there is a tilda ~ then replace it with HOME
  977. if(path.find("~") == 0)
  978. {
  979. if (getenv("HOME"))
  980. {
  981. path = kwsys_stl::string(getenv("HOME")) + path.substr(1);
  982. }
  983. }
  984. }
  985. // change // to /, and escape any spaces in the path
  986. kwsys_stl::string SystemTools::ConvertToUnixOutputPath(const char* path)
  987. {
  988. kwsys_stl::string ret = path;
  989. // remove // except at the beginning might be a cygwin drive
  990. kwsys_stl::string::size_type pos = 1;
  991. while((pos = ret.find("//", pos)) != kwsys_stl::string::npos)
  992. {
  993. ret.erase(pos, 1);
  994. }
  995. // now escape spaces if there is a space in the path
  996. if(ret.find(" ") != kwsys_stl::string::npos)
  997. {
  998. kwsys_stl::string result = "";
  999. char lastch = 1;
  1000. for(const char* ch = ret.c_str(); *ch != '\0'; ++ch)
  1001. {
  1002. // if it is already escaped then don't try to escape it again
  1003. if(*ch == ' ' && lastch != '\\')
  1004. {
  1005. result += '\\';
  1006. }
  1007. result += *ch;
  1008. lastch = *ch;
  1009. }
  1010. ret = result;
  1011. }
  1012. return ret;
  1013. }
  1014. kwsys_stl::string SystemTools::ConvertToOutputPath(const char* path)
  1015. {
  1016. #if defined(_WIN32) && !defined(__CYGWIN__)
  1017. return SystemTools::ConvertToWindowsOutputPath(path);
  1018. #else
  1019. return SystemTools::ConvertToUnixOutputPath(path);
  1020. #endif
  1021. }
  1022. // remove double slashes not at the start
  1023. kwsys_stl::string SystemTools::ConvertToWindowsOutputPath(const char* path)
  1024. {
  1025. kwsys_stl::string ret = path;
  1026. kwsys_stl::string::size_type pos = 0;
  1027. // first convert all of the slashes
  1028. while((pos = ret.find('/', pos)) != kwsys_stl::string::npos)
  1029. {
  1030. ret[pos] = '\\';
  1031. pos++;
  1032. }
  1033. // check for really small paths
  1034. if(ret.size() < 2)
  1035. {
  1036. return ret;
  1037. }
  1038. // now clean up a bit and remove double slashes
  1039. // Only if it is not the first position in the path which is a network
  1040. // path on windows
  1041. pos = 1; // start at position 1
  1042. if(ret[0] == '\"')
  1043. {
  1044. pos = 2; // if the string is already quoted then start at 2
  1045. if(ret.size() < 3)
  1046. {
  1047. return ret;
  1048. }
  1049. }
  1050. while((pos = ret.find("\\\\", pos)) != kwsys_stl::string::npos)
  1051. {
  1052. ret.erase(pos, 1);
  1053. }
  1054. // now double quote the path if it has spaces in it
  1055. // and is not already double quoted
  1056. if(ret.find(" ") != kwsys_stl::string::npos
  1057. && ret[0] != '\"')
  1058. {
  1059. kwsys_stl::string result;
  1060. result = "\"" + ret + "\"";
  1061. ret = result;
  1062. }
  1063. return ret;
  1064. }
  1065. bool SystemTools::CopyFileIfDifferent(const char* source,
  1066. const char* destination)
  1067. {
  1068. if(SystemTools::FilesDiffer(source, destination))
  1069. {
  1070. return SystemTools::CopyFileAlways(source, destination);
  1071. }
  1072. return true;
  1073. }
  1074. bool SystemTools::FilesDiffer(const char* source,
  1075. const char* destination)
  1076. {
  1077. struct stat statSource;
  1078. if (stat(source, &statSource) != 0)
  1079. {
  1080. return true;
  1081. }
  1082. struct stat statDestination;
  1083. if (stat(destination, &statDestination) != 0)
  1084. {
  1085. return true;
  1086. }
  1087. if(statSource.st_size != statDestination.st_size)
  1088. {
  1089. return true;
  1090. }
  1091. if(statSource.st_size == 0)
  1092. {
  1093. return false;
  1094. }
  1095. #if defined(_WIN32) || defined(__CYGWIN__)
  1096. kwsys_ios::ifstream finSource(source, (kwsys_ios::ios::binary |
  1097. kwsys_ios::ios::in));
  1098. kwsys_ios::ifstream finDestination(destination, (kwsys_ios::ios::binary |
  1099. kwsys_ios::ios::in));
  1100. #else
  1101. kwsys_ios::ifstream finSource(source);
  1102. kwsys_ios::ifstream finDestination(destination);
  1103. #endif
  1104. if(!finSource || !finDestination)
  1105. {
  1106. return true;
  1107. }
  1108. char* source_buf = new char[statSource.st_size];
  1109. char* dest_buf = new char[statSource.st_size];
  1110. finSource.read(source_buf, statSource.st_size);
  1111. finDestination.read(dest_buf, statSource.st_size);
  1112. if(statSource.st_size != static_cast<long>(finSource.gcount()) ||
  1113. statSource.st_size != static_cast<long>(finDestination.gcount()))
  1114. {
  1115. // Failed to read files.
  1116. delete [] source_buf;
  1117. delete [] dest_buf;
  1118. return true;
  1119. }
  1120. int ret = memcmp((const void*)source_buf,
  1121. (const void*)dest_buf,
  1122. statSource.st_size);
  1123. delete [] dest_buf;
  1124. delete [] source_buf;
  1125. return ret != 0;
  1126. }
  1127. /**
  1128. * Copy a file named by "source" to the file named by "destination".
  1129. */
  1130. bool SystemTools::CopyFileAlways(const char* source, const char* destination)
  1131. {
  1132. // If files are the same do not copy
  1133. if ( SystemTools::SameFile(source, destination) )
  1134. {
  1135. return true;
  1136. }
  1137. mode_t perm = 0;
  1138. bool perms = SystemTools::GetPermissions(source, perm);
  1139. const int bufferSize = 4096;
  1140. char buffer[bufferSize];
  1141. // If destination is a directory, try to create a file with the same
  1142. // name as the source in that directory.
  1143. kwsys_stl::string new_destination;
  1144. if(SystemTools::FileExists(destination) &&
  1145. SystemTools::FileIsDirectory(destination))
  1146. {
  1147. new_destination = destination;
  1148. SystemTools::ConvertToUnixSlashes(new_destination);
  1149. new_destination += '/';
  1150. kwsys_stl::string source_name = source;
  1151. new_destination += SystemTools::GetFilenameName(source_name);
  1152. destination = new_destination.c_str();
  1153. }
  1154. // Create destination directory
  1155. kwsys_stl::string destination_dir = destination;
  1156. destination_dir = SystemTools::GetFilenamePath(destination_dir);
  1157. SystemTools::MakeDirectory(destination_dir.c_str());
  1158. // Open files
  1159. #if defined(_WIN32) || defined(__CYGWIN__)
  1160. kwsys_ios::ifstream fin(source,
  1161. kwsys_ios::ios::binary | kwsys_ios::ios::in);
  1162. #else
  1163. kwsys_ios::ifstream fin(source);
  1164. #endif
  1165. if(!fin)
  1166. {
  1167. return false;
  1168. }
  1169. // try and remove the destination file so that read only destination files
  1170. // can be written to.
  1171. // If the remove fails continue so that files in read only directories
  1172. // that do not allow file removal can be modified.
  1173. SystemTools::RemoveFile(destination);
  1174. #if defined(_WIN32) || defined(__CYGWIN__)
  1175. kwsys_ios::ofstream fout(destination,
  1176. kwsys_ios::ios::binary | kwsys_ios::ios::out | kwsys_ios::ios::trunc);
  1177. #else
  1178. kwsys_ios::ofstream fout(destination,
  1179. kwsys_ios::ios::out | kwsys_ios::ios::trunc);
  1180. #endif
  1181. if(!fout)
  1182. {
  1183. return false;
  1184. }
  1185. // This copy loop is very sensitive on certain platforms with
  1186. // slightly broken stream libraries (like HPUX). Normally, it is
  1187. // incorrect to not check the error condition on the fin.read()
  1188. // before using the data, but the fin.gcount() will be zero if an
  1189. // error occurred. Therefore, the loop should be safe everywhere.
  1190. while(fin)
  1191. {
  1192. fin.read(buffer, bufferSize);
  1193. if(fin.gcount())
  1194. {
  1195. fout.write(buffer, fin.gcount());
  1196. }
  1197. }
  1198. // Make sure the operating system has finished writing the file
  1199. // before closing it. This will ensure the file is finished before
  1200. // the check below.
  1201. fout.flush();
  1202. fin.close();
  1203. fout.close();
  1204. // More checks.
  1205. struct stat statSource, statDestination;
  1206. statSource.st_size = 12345;
  1207. statDestination.st_size = 12345;
  1208. if(stat(source, &statSource) != 0)
  1209. {
  1210. return false;
  1211. }
  1212. else if(stat(destination, &statDestination) != 0)
  1213. {
  1214. return false;
  1215. }
  1216. else if(statSource.st_size != statDestination.st_size)
  1217. {
  1218. return false;
  1219. }
  1220. if ( perms )
  1221. {
  1222. if ( !SystemTools::SetPermissions(destination, perm) )
  1223. {
  1224. return false;
  1225. }
  1226. }
  1227. return true;
  1228. }
  1229. /**
  1230. * Copy a directory content from "source" directory to the directory named by
  1231. * "destination".
  1232. */
  1233. bool SystemTools::CopyADirectory(const char* source, const char* destination)
  1234. {
  1235. Directory dir;
  1236. dir.Load(source);
  1237. size_t fileNum;
  1238. if ( !SystemTools::MakeDirectory(destination) )
  1239. {
  1240. return false;
  1241. }
  1242. for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum)
  1243. {
  1244. if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".") &&
  1245. strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".."))
  1246. {
  1247. kwsys_stl::string fullPath = source;
  1248. fullPath += "/";
  1249. fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
  1250. if(SystemTools::FileIsDirectory(fullPath.c_str()))
  1251. {
  1252. kwsys_stl::string fullDestPath = destination;
  1253. fullDestPath += "/";
  1254. fullDestPath += dir.GetFile(static_cast<unsigned long>(fileNum));
  1255. if (!SystemTools::CopyADirectory(fullPath.c_str(), fullDestPath.c_str()))
  1256. {
  1257. return false;
  1258. }
  1259. }
  1260. else
  1261. {
  1262. if(!SystemTools::CopyFileAlways(fullPath.c_str(), destination))
  1263. {
  1264. return false;
  1265. }
  1266. }
  1267. }
  1268. }
  1269. return true;
  1270. }
  1271. // return size of file; also returns zero if no file exists
  1272. unsigned long SystemTools::FileLength(const char* filename)
  1273. {
  1274. struct stat fs;
  1275. if (stat(filename, &fs) != 0)
  1276. {
  1277. return 0;
  1278. }
  1279. else
  1280. {
  1281. return fs.st_size;
  1282. }
  1283. }
  1284. int SystemTools::Strucmp(const char *s1, const char *s2)
  1285. {
  1286. // lifted from Graphvis http://www.graphviz.org
  1287. while ((*s1 != '\0')
  1288. && (tolower(*s1) == tolower(*s2)))
  1289. {
  1290. s1++;
  1291. s2++;
  1292. }
  1293. return tolower(*s1) - tolower(*s2);
  1294. }
  1295. // return file's modified time
  1296. long int SystemTools::ModifiedTime(const char* filename)
  1297. {
  1298. struct stat fs;
  1299. if (stat(filename, &fs) != 0)
  1300. {
  1301. return 0;
  1302. }
  1303. else
  1304. {
  1305. return (long int)fs.st_mtime;
  1306. }
  1307. }
  1308. // return file's creation time
  1309. long int SystemTools::CreationTime(const char* filename)
  1310. {
  1311. struct stat fs;
  1312. if (stat(filename, &fs) != 0)
  1313. {
  1314. return 0;
  1315. }
  1316. else
  1317. {
  1318. return fs.st_ctime >= 0 ? (long int)fs.st_ctime : 0;
  1319. }
  1320. }
  1321. bool SystemTools::ConvertDateMacroString(const char *str, time_t *tmt)
  1322. {
  1323. if (!str || !tmt || strlen(str) < 12)
  1324. {
  1325. return false;
  1326. }
  1327. struct tm tmt2;
  1328. // __DATE__
  1329. // The compilation date of the current source file. The date is a string
  1330. // literal of the form Mmm dd yyyy. The month name Mmm is the same as for
  1331. // dates generated by the library function asctime declared in TIME.H.
  1332. // index: 012345678901
  1333. // format: Mmm dd yyyy
  1334. // example: Dec 19 2003
  1335. static char month_names[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
  1336. char buffer[12];
  1337. strcpy(buffer, str);
  1338. buffer[3] = 0;
  1339. char *ptr = strstr(month_names, buffer);
  1340. if (!ptr)
  1341. {
  1342. return false;
  1343. }
  1344. int month = (ptr - month_names) / 3;
  1345. int day = atoi(buffer + 4);
  1346. int year = atoi(buffer + 7);
  1347. tmt2.tm_isdst = -1;
  1348. tmt2.tm_hour = 0;
  1349. tmt2.tm_min = 0;
  1350. tmt2.tm_sec = 0;
  1351. tmt2.tm_wday = 0;
  1352. tmt2.tm_yday = 0;
  1353. tmt2.tm_mday = day;
  1354. tmt2.tm_mon = month;
  1355. tmt2.tm_year = year - 1900;
  1356. *tmt = mktime(&tmt2);
  1357. return true;
  1358. }
  1359. bool SystemTools::ConvertTimeStampMacroString(const char *str, time_t *tmt)
  1360. {
  1361. if (!str || !tmt || strlen(str) < 27)
  1362. {
  1363. return false;
  1364. }
  1365. struct tm tmt2;
  1366. // __TIMESTAMP__
  1367. // The date and time of the last modification of the current source file,
  1368. // expressed as a string literal in the form Ddd Mmm Date hh:mm:ss yyyy,
  1369. /// where Ddd is the abbreviated day of the week and Date is an integer
  1370. // from 1 to 31.
  1371. // index: 0123456789
  1372. // 0123456789
  1373. // 0123456789
  1374. // format: Ddd Mmm Date hh:mm:ss yyyy
  1375. // example: Fri Dec 19 14:34:58 2003
  1376. static char month_names[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
  1377. char buffer[27];
  1378. strcpy(buffer, str);
  1379. buffer[7] = 0;
  1380. char *ptr = strstr(month_names, buffer + 4);
  1381. if (!ptr)
  1382. {
  1383. return false;
  1384. }
  1385. int month = (ptr - month_names) / 3;
  1386. int day = atoi(buffer + 8);
  1387. int hour = atoi(buffer + 11);
  1388. int min = atoi(buffer + 14);
  1389. int sec = atoi(buffer + 17);
  1390. int year = atoi(buffer + 20);
  1391. tmt2.tm_isdst = -1;
  1392. tmt2.tm_hour = hour;
  1393. tmt2.tm_min = min;
  1394. tmt2.tm_sec = sec;
  1395. tmt2.tm_wday = 0;
  1396. tmt2.tm_yday = 0;
  1397. tmt2.tm_mday = day;
  1398. tmt2.tm_mon = month;
  1399. tmt2.tm_year = year - 1900;
  1400. *tmt = mktime(&tmt2);
  1401. return true;
  1402. }
  1403. kwsys_stl::string SystemTools::GetLastSystemError()
  1404. {
  1405. int e = errno;
  1406. return strerror(e);
  1407. }
  1408. bool SystemTools::RemoveFile(const char* source)
  1409. {
  1410. #ifdef _WIN32
  1411. mode_t mode;
  1412. if ( !SystemTools::GetPermissions(source, mode) )
  1413. {
  1414. return false;
  1415. }
  1416. /* Win32 unlink is stupid --- it fails if the file is read-only */
  1417. SystemTools::SetPermissions(source, S_IWRITE);
  1418. #endif
  1419. bool res = unlink(source) != 0 ? false : true;
  1420. #ifdef _WIN32
  1421. if ( !res )
  1422. {
  1423. SystemTools::SetPermissions(source, mode);
  1424. }
  1425. #endif
  1426. return res;
  1427. }
  1428. bool SystemTools::RemoveADirectory(const char* source)
  1429. {
  1430. Directory dir;
  1431. dir.Load(source);
  1432. size_t fileNum;
  1433. for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum)
  1434. {
  1435. if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".") &&
  1436. strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".."))
  1437. {
  1438. kwsys_stl::string fullPath = source;
  1439. fullPath += "/";
  1440. fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
  1441. if(SystemTools::FileIsDirectory(fullPath.c_str()))
  1442. {
  1443. if (!SystemTools::RemoveADirectory(fullPath.c_str()))
  1444. {
  1445. return false;
  1446. }
  1447. }
  1448. else
  1449. {
  1450. if(!SystemTools::RemoveFile(fullPath.c_str()))
  1451. {
  1452. return false;
  1453. }
  1454. }
  1455. }
  1456. }
  1457. return (Rmdir(source) == 0);
  1458. }
  1459. /**
  1460. * Find the file the given name. Searches the given path and then
  1461. * the system search path. Returns the full path to the file if it is
  1462. * found. Otherwise, the empty string is returned.
  1463. */
  1464. kwsys_stl::string SystemTools
  1465. ::FindFile(const char* name,
  1466. const kwsys_stl::vector<kwsys_stl::string>& userPaths)
  1467. {
  1468. // Add the system search path to our path first
  1469. kwsys_stl::vector<kwsys_stl::string> path;
  1470. SystemTools::GetPath(path, "CMAKE_FILE_PATH");
  1471. SystemTools::GetPath(path);
  1472. // now add the additional paths
  1473. path.insert(path.end(), userPaths.begin(), userPaths.end());
  1474. // now look for the file
  1475. kwsys_stl::string tryPath;
  1476. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator p = path.begin();
  1477. p != path.end(); ++p)
  1478. {
  1479. tryPath = *p;
  1480. tryPath += "/";
  1481. tryPath += name;
  1482. if(SystemTools::FileExists(tryPath.c_str()) &&
  1483. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1484. {
  1485. return SystemTools::CollapseFullPath(tryPath.c_str());
  1486. }
  1487. }
  1488. // Couldn't find the file.
  1489. return "";
  1490. }
  1491. /**
  1492. * Find the executable with the given name. Searches the given path and then
  1493. * the system search path. Returns the full path to the executable if it is
  1494. * found. Otherwise, the empty string is returned.
  1495. */
  1496. kwsys_stl::string SystemTools::FindProgram(
  1497. const char* name,
  1498. const kwsys_stl::vector<kwsys_stl::string>& userPaths,
  1499. bool no_system_path)
  1500. {
  1501. if(!name)
  1502. {
  1503. return "";
  1504. }
  1505. // See if the executable exists as written.
  1506. if(SystemTools::FileExists(name) &&
  1507. !SystemTools::FileIsDirectory(name))
  1508. {
  1509. return SystemTools::CollapseFullPath(name);
  1510. }
  1511. kwsys_stl::string tryPath = name;
  1512. tryPath += SystemTools::GetExecutableExtension();
  1513. if(SystemTools::FileExists(tryPath.c_str()) &&
  1514. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1515. {
  1516. return SystemTools::CollapseFullPath(tryPath.c_str());
  1517. }
  1518. kwsys_stl::vector<kwsys_stl::string> path;
  1519. SystemTools::GetPath(path, "CMAKE_PROGRAM_PATH");
  1520. // Add the system search path to our path.
  1521. if (!no_system_path)
  1522. {
  1523. SystemTools::GetPath(path);
  1524. }
  1525. // now add the additional paths
  1526. path.insert(path.end(), userPaths.begin(), userPaths.end());
  1527. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator p = path.begin();
  1528. p != path.end(); ++p)
  1529. {
  1530. tryPath = *p;
  1531. tryPath += "/";
  1532. tryPath += name;
  1533. if(SystemTools::FileExists(tryPath.c_str()) &&
  1534. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1535. {
  1536. return SystemTools::CollapseFullPath(tryPath.c_str());
  1537. }
  1538. #ifdef _WIN32
  1539. tryPath += ".com";
  1540. if(SystemTools::FileExists(tryPath.c_str()) &&
  1541. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1542. {
  1543. return SystemTools::CollapseFullPath(tryPath.c_str());
  1544. }
  1545. tryPath = *p;
  1546. tryPath += "/";
  1547. tryPath += name;
  1548. #endif
  1549. tryPath += SystemTools::GetExecutableExtension();
  1550. if(SystemTools::FileExists(tryPath.c_str()) &&
  1551. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1552. {
  1553. return SystemTools::CollapseFullPath(tryPath.c_str());
  1554. }
  1555. }
  1556. // Couldn't find the program.
  1557. return "";
  1558. }
  1559. /**
  1560. * Find the library with the given name. Searches the given path and then
  1561. * the system search path. Returns the full path to the library if it is
  1562. * found. Otherwise, the empty string is returned.
  1563. */
  1564. kwsys_stl::string SystemTools
  1565. ::FindLibrary(const char* name,
  1566. const kwsys_stl::vector<kwsys_stl::string>& userPaths)
  1567. {
  1568. // See if the executable exists as written.
  1569. if(SystemTools::FileExists(name) &&
  1570. !SystemTools::FileIsDirectory(name))
  1571. {
  1572. return SystemTools::CollapseFullPath(name);
  1573. }
  1574. // Add the system search path to our path.
  1575. kwsys_stl::vector<kwsys_stl::string> path;
  1576. SystemTools::GetPath(path);
  1577. // now add the additional paths
  1578. path.insert(path.end(), userPaths.begin(), userPaths.end());
  1579. kwsys_stl::string tryPath;
  1580. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator p = path.begin();
  1581. p != path.end(); ++p)
  1582. {
  1583. #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__MINGW32__)
  1584. tryPath = *p;
  1585. tryPath += "/";
  1586. tryPath += name;
  1587. tryPath += ".lib";
  1588. if(SystemTools::FileExists(tryPath.c_str())
  1589. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1590. {
  1591. return SystemTools::CollapseFullPath(tryPath.c_str());
  1592. }
  1593. #else
  1594. tryPath = *p;
  1595. tryPath += "/lib";
  1596. tryPath += name;
  1597. tryPath += ".so";
  1598. if(SystemTools::FileExists(tryPath.c_str())
  1599. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1600. {
  1601. return SystemTools::CollapseFullPath(tryPath.c_str());
  1602. }
  1603. tryPath = *p;
  1604. tryPath += "/lib";
  1605. tryPath += name;
  1606. tryPath += ".a";
  1607. if(SystemTools::FileExists(tryPath.c_str())
  1608. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1609. {
  1610. return SystemTools::CollapseFullPath(tryPath.c_str());
  1611. }
  1612. tryPath = *p;
  1613. tryPath += "/lib";
  1614. tryPath += name;
  1615. tryPath += ".sl";
  1616. if(SystemTools::FileExists(tryPath.c_str())
  1617. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1618. {
  1619. return SystemTools::CollapseFullPath(tryPath.c_str());
  1620. }
  1621. tryPath = *p;
  1622. tryPath += "/lib";
  1623. tryPath += name;
  1624. tryPath += ".dylib";
  1625. if(SystemTools::FileExists(tryPath.c_str())
  1626. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1627. {
  1628. return SystemTools::CollapseFullPath(tryPath.c_str());
  1629. }
  1630. tryPath = *p;
  1631. tryPath += "/lib";
  1632. tryPath += name;
  1633. tryPath += ".dll";
  1634. if(SystemTools::FileExists(tryPath.c_str())
  1635. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1636. {
  1637. return SystemTools::CollapseFullPath(tryPath.c_str());
  1638. }
  1639. #endif
  1640. }
  1641. // Couldn't find the library.
  1642. return "";
  1643. }
  1644. bool SystemTools::FileIsDirectory(const char* name)
  1645. {
  1646. struct stat fs;
  1647. if(stat(name, &fs) == 0)
  1648. {
  1649. #if _WIN32
  1650. return ((fs.st_mode & _S_IFDIR) != 0);
  1651. #else
  1652. return S_ISDIR(fs.st_mode);
  1653. #endif
  1654. }
  1655. else
  1656. {
  1657. return false;
  1658. }
  1659. }
  1660. int SystemTools::ChangeDirectory(const char *dir)
  1661. {
  1662. return Chdir(dir);
  1663. }
  1664. kwsys_stl::string SystemTools::GetCurrentWorkingDirectory()
  1665. {
  1666. char buf[2048];
  1667. const char* cwd = Getcwd(buf, 2048);
  1668. kwsys_stl::string path;
  1669. if ( cwd )
  1670. {
  1671. path = cwd;
  1672. }
  1673. return SystemTools::CollapseFullPath(path.c_str());
  1674. }
  1675. kwsys_stl::string SystemTools::GetProgramPath(const char* in_name)
  1676. {
  1677. kwsys_stl::string dir, file;
  1678. SystemTools::SplitProgramPath(in_name, dir, file);
  1679. return dir;
  1680. }
  1681. bool SystemTools::SplitProgramPath(const char* in_name,
  1682. kwsys_stl::string& dir,
  1683. kwsys_stl::string& file,
  1684. bool)
  1685. {
  1686. dir = in_name;
  1687. file = "";
  1688. SystemTools::ConvertToUnixSlashes(dir);
  1689. if(!SystemTools::FileIsDirectory(dir.c_str()))
  1690. {
  1691. kwsys_stl::string::size_type slashPos = dir.rfind("/");
  1692. if(slashPos != kwsys_stl::string::npos)
  1693. {
  1694. file = dir.substr(slashPos+1);
  1695. dir = dir.substr(0, slashPos);
  1696. }
  1697. else
  1698. {
  1699. file = dir;
  1700. dir = "";
  1701. }
  1702. }
  1703. if(!(dir == "") && !SystemTools::FileIsDirectory(dir.c_str()))
  1704. {
  1705. kwsys_stl::string oldDir = in_name;
  1706. SystemTools::ConvertToUnixSlashes(oldDir);
  1707. dir = in_name;
  1708. return false;
  1709. }
  1710. return true;
  1711. }
  1712. bool SystemTools::FindProgramPath(const char* argv0,
  1713. kwsys_stl::string& pathOut,
  1714. kwsys_stl::string& errorMsg,
  1715. const char* exeName,
  1716. const char* buildDir,
  1717. const char* installPrefix )
  1718. {
  1719. kwsys_stl::vector<kwsys_stl::string> failures;
  1720. kwsys_stl::string self = argv0;
  1721. SystemTools::ConvertToUnixSlashes(self);
  1722. failures.push_back(argv0);
  1723. self = SystemTools::FindProgram(self.c_str());
  1724. if(!SystemTools::FileExists(self.c_str()))
  1725. {
  1726. if(buildDir)
  1727. {
  1728. kwsys_stl::string intdir = ".";
  1729. #ifdef CMAKE_INTDIR
  1730. intdir = CMAKE_INTDIR;
  1731. #endif
  1732. self = buildDir;
  1733. self += "/bin/";
  1734. self += intdir;
  1735. self += "/";
  1736. self += exeName;
  1737. self += SystemTools::GetExecutableExtension();
  1738. }
  1739. }
  1740. if(installPrefix)
  1741. {
  1742. if(!SystemTools::FileExists(self.c_str()))
  1743. {
  1744. failures.push_back(self);
  1745. self = installPrefix;
  1746. self += "/bin/";
  1747. self += exeName;
  1748. }
  1749. }
  1750. if(!SystemTools::FileExists(self.c_str()))
  1751. {
  1752. failures.push_back(self);
  1753. kwsys_ios::ostringstream msg;
  1754. msg << "Can not find the command line program " << exeName << "\n";
  1755. msg << " argv[0] = \"" << argv0 << "\"\n";
  1756. msg << " Attempted paths:\n";
  1757. kwsys_stl::vector<kwsys_stl::string>::iterator i;
  1758. for(i=failures.begin(); i != failures.end(); ++i)
  1759. {
  1760. msg << " \"" << i->c_str() << "\"\n";
  1761. }
  1762. errorMsg = msg.str();
  1763. return false;
  1764. }
  1765. pathOut = self;
  1766. return true;
  1767. }
  1768. kwsys_stl::string SystemTools::CollapseFullPath(const char* in_relative)
  1769. {
  1770. return SystemTools::CollapseFullPath(in_relative, 0);
  1771. }
  1772. void SystemTools::AddTranslationPath(const char * a, const char * b)
  1773. {
  1774. kwsys_stl::string path_a = a;
  1775. kwsys_stl::string path_b = b;
  1776. SystemTools::ConvertToUnixSlashes(path_a);
  1777. SystemTools::ConvertToUnixSlashes(path_b);
  1778. // First check this is a directory path, since we don't want the table to
  1779. // grow too fat
  1780. if( SystemTools::FileIsDirectory( path_a.c_str() ) )
  1781. {
  1782. // Make sure the path is a full path and does not contain no '..'
  1783. if( SystemTools::FileIsFullPath(path_b.c_str()) && path_b.find("..")
  1784. == kwsys_stl::string::npos )
  1785. {
  1786. // Before inserting make sure path ends with '/'
  1787. if(path_a.size() && path_a[path_a.size() -1] != '/')
  1788. {
  1789. path_a += '/';
  1790. }
  1791. if(path_b.size() && path_b[path_b.size() -1] != '/')
  1792. {
  1793. path_b += '/';
  1794. }
  1795. if( !(path_a == path_b) )
  1796. {
  1797. SystemTools::TranslationMap->insert(
  1798. SystemToolsTranslationMap::value_type(path_a, path_b));
  1799. }
  1800. }
  1801. }
  1802. }
  1803. void SystemTools::AddKeepPath(const char* dir)
  1804. {
  1805. kwsys_stl::string cdir = SystemTools::CollapseFullPath(dir);
  1806. SystemTools::AddTranslationPath(cdir.c_str(), dir);
  1807. }
  1808. void SystemTools::CheckTranslationPath(kwsys_stl::string & path)
  1809. {
  1810. // Do not translate paths that are too short to have meaningful
  1811. // translations.
  1812. if(path.size() < 2)
  1813. {
  1814. return;
  1815. }
  1816. // Always add a trailing slash before translation. It does not
  1817. // matter if this adds an extra slash, but we do not want to
  1818. // translate part of a directory (like the foo part of foo-dir).
  1819. path += "/";
  1820. // In case a file was specified we still have to go through this:
  1821. // Now convert any path found in the table back to the one desired:
  1822. kwsys_stl::map<kwsys_stl::string,kwsys_stl::string>::const_iterator it;
  1823. for(it = SystemTools::TranslationMap->begin();
  1824. it != SystemTools::TranslationMap->end();
  1825. ++it )
  1826. {
  1827. // We need to check of the path is a substring of the other path
  1828. if(path.find( it->first ) == 0)
  1829. {
  1830. path = path.replace( 0, it->first.size(), it->second);
  1831. }
  1832. }
  1833. // Remove the trailing slash we added before.
  1834. path.erase(path.end()-1, path.end());
  1835. }
  1836. kwsys_stl::string SystemTools::CollapseFullPath(const char* in_relative,
  1837. const char* in_base)
  1838. {
  1839. kwsys_stl::string orig;
  1840. // Change to base of relative path.
  1841. if(in_base)
  1842. {
  1843. // Save original working directory.
  1844. orig = SystemTools::GetCurrentWorkingDirectory();
  1845. Chdir(in_base);
  1846. }
  1847. kwsys_stl::string dir, file;
  1848. SystemTools::SplitProgramPath(in_relative, dir, file, false);
  1849. if(dir.size() == 0 &&
  1850. in_relative && strlen(in_relative) > 0 &&
  1851. in_relative[0] == '/')
  1852. {
  1853. dir = "/";
  1854. }
  1855. // Resolve relative path.
  1856. kwsys_stl::string newDir;
  1857. if(!(dir == ""))
  1858. {
  1859. Realpath(dir.c_str(), newDir);
  1860. }
  1861. else
  1862. {
  1863. newDir = SystemTools::GetCurrentWorkingDirectory();
  1864. }
  1865. if(in_base)
  1866. {
  1867. // Restore original working directory.
  1868. Chdir(orig.c_str());
  1869. }
  1870. // Construct and return the full path.
  1871. kwsys_stl::string newPath = newDir;
  1872. if(!(file == ""))
  1873. {
  1874. if(!(newDir.size() == 1 && newDir[0] == '/'))
  1875. {
  1876. newPath += "/";
  1877. }
  1878. newPath += file;
  1879. }
  1880. // Now we need to update the translation table with this potentially new path
  1881. SystemTools::AddTranslationPath(newPath.c_str(), in_relative);
  1882. SystemTools::CheckTranslationPath(newPath);
  1883. return newPath;
  1884. }
  1885. //----------------------------------------------------------------------------
  1886. void SystemTools::SplitPath(const char* p,
  1887. kwsys_stl::vector<kwsys_stl::string>& components)
  1888. {
  1889. components.clear();
  1890. // Identify the root component.
  1891. const char* c = p;
  1892. if(c[0] == '/' && c[1] == '/')
  1893. {
  1894. // Network path.
  1895. components.push_back("//");
  1896. c += 2;
  1897. }
  1898. else if(c[0] == '/')
  1899. {
  1900. // Unix path.
  1901. components.push_back("/");
  1902. c += 1;
  1903. }
  1904. else if(c[0] && c[1] == ':' && c[2] == '/')
  1905. {
  1906. // Windows path.
  1907. kwsys_stl::string root = "_:/";
  1908. root[0] = c[0];
  1909. components.push_back(root);
  1910. c += 3;
  1911. }
  1912. else if(c[0] && c[1] == ':')
  1913. {
  1914. // Path relative to a windows drive working directory.
  1915. kwsys_stl::string root = "_:";
  1916. root[0] = c[0];
  1917. components.push_back(root);
  1918. c += 2;
  1919. }
  1920. else
  1921. {
  1922. // Relative path.
  1923. components.push_back("");
  1924. }
  1925. // Parse the remaining components.
  1926. const char* first = c;
  1927. const char* last = first;
  1928. for(;*last; ++last)
  1929. {
  1930. if(*last == '/')
  1931. {
  1932. // End of a component. Save it.
  1933. components.push_back(kwsys_stl::string(first, last-first));
  1934. first = last+1;
  1935. }
  1936. }
  1937. // Save the last component unless there were no components.
  1938. if(last != c)
  1939. {
  1940. components.push_back(kwsys_stl::string(first, last-first));
  1941. }
  1942. }
  1943. //----------------------------------------------------------------------------
  1944. kwsys_stl::string
  1945. SystemTools::JoinPath(const kwsys_stl::vector<kwsys_stl::string>& components)
  1946. {
  1947. kwsys_stl::string result;
  1948. if(components.size() > 0)
  1949. {
  1950. result += components[0];
  1951. }
  1952. if(components.size() > 1)
  1953. {
  1954. result += components[1];
  1955. }
  1956. for(unsigned int i=2; i < components.size(); ++i)
  1957. {
  1958. result += "/";
  1959. result += components[i];
  1960. }
  1961. return result;
  1962. }
  1963. //----------------------------------------------------------------------------
  1964. bool SystemTools::ComparePath(const char* c1, const char* c2)
  1965. {
  1966. #if defined(_WIN32) || defined(__APPLE__)
  1967. return SystemTools::Strucmp(c1, c2) == 0;
  1968. #else
  1969. return strcmp(c1, c2) == 0;
  1970. #endif
  1971. }
  1972. bool SystemTools::Split(const char* str, kwsys_stl::vector<kwsys_stl::string>& lines)
  1973. {
  1974. kwsys_stl::string data(str);
  1975. kwsys_stl::string::size_type lpos = 0;
  1976. while(lpos < data.length())
  1977. {
  1978. kwsys_stl::string::size_type rpos = data.find_first_of("\n", lpos);
  1979. if(rpos == kwsys_stl::string::npos)
  1980. {
  1981. // Line ends at end of string without a newline.
  1982. lines.push_back(data.substr(lpos));
  1983. return false;
  1984. }
  1985. if((rpos > lpos) && (data[rpos-1] == '\r'))
  1986. {
  1987. // Line ends in a "\r\n" pair, remove both characters.
  1988. lines.push_back(data.substr(lpos, (rpos-1)-lpos));
  1989. }
  1990. else
  1991. {
  1992. // Line ends in a "\n", remove the character.
  1993. lines.push_back(data.substr(lpos, rpos-lpos));
  1994. }
  1995. lpos = rpos+1;
  1996. }
  1997. return true;
  1998. }
  1999. /**
  2000. * Return path of a full filename (no trailing slashes).
  2001. * Warning: returned path is converted to Unix slashes format.
  2002. */
  2003. kwsys_stl::string SystemTools::GetFilenamePath(const kwsys_stl::string& filename)
  2004. {
  2005. kwsys_stl::string fn = filename;
  2006. SystemTools::ConvertToUnixSlashes(fn);
  2007. kwsys_stl::string::size_type slash_pos = fn.rfind("/");
  2008. if(slash_pos != kwsys_stl::string::npos)
  2009. {
  2010. return fn.substr(0, slash_pos);
  2011. }
  2012. else
  2013. {
  2014. return "";
  2015. }
  2016. }
  2017. /**
  2018. * Return file name of a full filename (i.e. file name without path).
  2019. */
  2020. kwsys_stl::string SystemTools::GetFilenameName(const kwsys_stl::string& filename)
  2021. {
  2022. kwsys_stl::string fn = filename;
  2023. SystemTools::ConvertToUnixSlashes(fn);
  2024. kwsys_stl::string::size_type slash_pos = fn.rfind("/");
  2025. if(slash_pos != kwsys_stl::string::npos)
  2026. {
  2027. return fn.substr(slash_pos + 1);
  2028. }
  2029. else
  2030. {
  2031. return filename;
  2032. }
  2033. }
  2034. /**
  2035. * Return file extension of a full filename (dot included).
  2036. * Warning: this is the longest extension (for example: .tar.gz)
  2037. */
  2038. kwsys_stl::string SystemTools::GetFilenameExtension(const kwsys_stl::string& filename)
  2039. {
  2040. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  2041. kwsys_stl::string::size_type dot_pos = name.find(".");
  2042. if(dot_pos != kwsys_stl::string::npos)
  2043. {
  2044. return name.substr(dot_pos);
  2045. }
  2046. else
  2047. {
  2048. return "";
  2049. }
  2050. }
  2051. /**
  2052. * Return file extension of a full filename (dot included).
  2053. * Warning: this is the shortest extension (for example: .tar.gz)
  2054. */
  2055. kwsys_stl::string SystemTools::GetFilenameLastExtension(const kwsys_stl::string& filename)
  2056. {
  2057. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  2058. kwsys_stl::string::size_type dot_pos = name.rfind(".");
  2059. if(dot_pos != kwsys_stl::string::npos)
  2060. {
  2061. return name.substr(dot_pos);
  2062. }
  2063. else
  2064. {
  2065. return "";
  2066. }
  2067. }
  2068. /**
  2069. * Return file name without extension of a full filename (i.e. without path).
  2070. * Warning: it considers the longest extension (for example: .tar.gz)
  2071. */
  2072. kwsys_stl::string SystemTools::GetFilenameWithoutExtension(const kwsys_stl::string& filename)
  2073. {
  2074. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  2075. kwsys_stl::string::size_type dot_pos = name.find(".");
  2076. if(dot_pos != kwsys_stl::string::npos)
  2077. {
  2078. return name.substr(0, dot_pos);
  2079. }
  2080. else
  2081. {
  2082. return name;
  2083. }
  2084. }
  2085. /**
  2086. * Return file name without extension of a full filename (i.e. without path).
  2087. * Warning: it considers the last extension (for example: removes .gz
  2088. * from .tar.gz)
  2089. */
  2090. kwsys_stl::string
  2091. SystemTools::GetFilenameWithoutLastExtension(const kwsys_stl::string& filename)
  2092. {
  2093. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  2094. kwsys_stl::string::size_type dot_pos = name.rfind(".");
  2095. if(dot_pos != kwsys_stl::string::npos)
  2096. {
  2097. return name.substr(0, dot_pos);
  2098. }
  2099. else
  2100. {
  2101. return name;
  2102. }
  2103. }
  2104. bool SystemTools::FileHasSignature(const char *filename,
  2105. const char *signature,
  2106. unsigned long offset)
  2107. {
  2108. if (!filename || !signature)
  2109. {
  2110. return false;
  2111. }
  2112. FILE *fp;
  2113. fp = fopen(filename, "rb");
  2114. if (!fp)
  2115. {
  2116. return false;
  2117. }
  2118. fseek(fp, offset, SEEK_SET);
  2119. bool res = false;
  2120. size_t signature_len = strlen(signature);
  2121. char *buffer = new char [signature_len];
  2122. if (fread(buffer, 1, signature_len, fp) == signature_len)
  2123. {
  2124. res = (!strncmp(buffer, signature, signature_len) ? true : false);
  2125. }
  2126. delete [] buffer;
  2127. fclose(fp);
  2128. return res;
  2129. }
  2130. bool SystemTools::LocateFileInDir(const char *filename,
  2131. const char *dir,
  2132. kwsys_stl::string& filename_found,
  2133. int try_filename_dirs)
  2134. {
  2135. if (!filename || !dir)
  2136. {
  2137. return false;
  2138. }
  2139. // Get the basename of 'filename'
  2140. kwsys_stl::string filename_base = SystemTools::GetFilenameName(filename);
  2141. // Check if 'dir' is really a directory
  2142. // If win32 and matches something like C:, accept it as a dir
  2143. kwsys_stl::string real_dir;
  2144. if (!SystemTools::FileIsDirectory(dir))
  2145. {
  2146. #if _WIN32
  2147. size_t dir_len = strlen(dir);
  2148. if (dir_len < 2 || dir[dir_len - 1] != ':')
  2149. {
  2150. #endif
  2151. real_dir = SystemTools::GetFilenamePath(dir);
  2152. dir = real_dir.c_str();
  2153. #if _WIN32
  2154. }
  2155. #endif
  2156. }
  2157. // Try to find the file in 'dir'
  2158. bool res = false;
  2159. if (filename_base.size() && dir)
  2160. {
  2161. size_t dir_len = strlen(dir);
  2162. int need_slash =
  2163. (dir_len && dir[dir_len - 1] != '/' && dir[dir_len - 1] != '\\');
  2164. kwsys_stl::string temp = dir;
  2165. if (need_slash)
  2166. {
  2167. temp += "/";
  2168. }
  2169. temp += filename_base;
  2170. if (SystemTools::FileExists(filename_found.c_str()))
  2171. {
  2172. res = true;
  2173. filename_found = temp;
  2174. }
  2175. // If not found, we can try harder by appending part of the file to
  2176. // to the directory to look inside.
  2177. // Example: if we were looking for /foo/bar/yo.txt in /d1/d2, then
  2178. // try to find yo.txt in /d1/d2/bar, then /d1/d2/foo/bar, etc.
  2179. else if (try_filename_dirs)
  2180. {
  2181. kwsys_stl::string filename_dir(filename);
  2182. kwsys_stl::string filename_dir_base;
  2183. kwsys_stl::string filename_dir_bases;
  2184. do
  2185. {
  2186. filename_dir = SystemTools::GetFilenamePath(filename_dir);
  2187. filename_dir_base = SystemTools::GetFilenameName(filename_dir);
  2188. #if _WIN32
  2189. if (!filename_dir_base.size() ||
  2190. filename_dir_base[filename_dir_base.size() - 1] == ':')
  2191. #else
  2192. if (!filename_dir_base.size())
  2193. #endif
  2194. {
  2195. break;
  2196. }
  2197. filename_dir_bases = filename_dir_base + "/" + filename_dir_bases;
  2198. temp = dir;
  2199. if (need_slash)
  2200. {
  2201. temp += "/";
  2202. }
  2203. temp += filename_dir_bases;
  2204. res = SystemTools::LocateFileInDir(
  2205. filename_base.c_str(), temp.c_str(), filename_found, 0);
  2206. } while (!res && filename_dir_base.size());
  2207. }
  2208. }
  2209. return res;
  2210. }
  2211. bool SystemTools::FileIsFullPath(const char* in_name)
  2212. {
  2213. kwsys_stl::string name = in_name;
  2214. #if defined(_WIN32) || defined(__CYGWIN__)
  2215. // On Windows, the name must be at least two characters long.
  2216. if(name.length() < 2)
  2217. {
  2218. return false;
  2219. }
  2220. if(name[1] == ':')
  2221. {
  2222. return true;
  2223. }
  2224. if(name[0] == '\\')
  2225. {
  2226. return true;
  2227. }
  2228. #else
  2229. // On UNIX, the name must be at least one character long.
  2230. if(name.length() < 1)
  2231. {
  2232. return false;
  2233. }
  2234. #endif
  2235. // On UNIX, the name must begin in a '/'.
  2236. // On Windows, if the name begins in a '/', then it is a full
  2237. // network path.
  2238. if(name[0] == '/')
  2239. {
  2240. return true;
  2241. }
  2242. return false;
  2243. }
  2244. bool SystemTools::GetShortPath(const char* path, kwsys_stl::string& shortPath)
  2245. {
  2246. #if defined(WIN32) && !defined(__CYGWIN__)
  2247. const int size = int(strlen(path)) +1; // size of return
  2248. char *buffer = new char[size]; // create a buffer
  2249. char *tempPath = new char[size]; // create a buffer
  2250. int ret;
  2251. // if the path passed in has quotes around it, first remove the quotes
  2252. if (path[0] == '"' && path[strlen(path)-1] == '"')
  2253. {
  2254. strcpy(tempPath,path+1);
  2255. tempPath[strlen(tempPath)-1] = '\0';
  2256. }
  2257. else
  2258. {
  2259. strcpy(tempPath,path);
  2260. }
  2261. buffer[0] = 0;
  2262. ret = GetShortPathName(tempPath, buffer, size);
  2263. if(buffer[0] == 0 || ret > size)
  2264. {
  2265. delete [] buffer;
  2266. delete [] tempPath;
  2267. return false;
  2268. }
  2269. else
  2270. {
  2271. shortPath = buffer;
  2272. delete [] buffer;
  2273. delete [] tempPath;
  2274. return true;
  2275. }
  2276. #else
  2277. shortPath = path;
  2278. return true;
  2279. #endif
  2280. }
  2281. void SystemTools::SplitProgramFromArgs(const char* path,
  2282. kwsys_stl::string& program, kwsys_stl::string& args)
  2283. {
  2284. // see if this is a full path to a program
  2285. // if so then set program to path and args to nothing
  2286. if(SystemTools::FileExists(path))
  2287. {
  2288. program = path;
  2289. args = "";
  2290. return;
  2291. }
  2292. // Try to find the program in the path, note the program
  2293. // may have spaces in its name so we have to look for it
  2294. kwsys_stl::vector<kwsys_stl::string> e;
  2295. kwsys_stl::string findProg = SystemTools::FindProgram(path, e);
  2296. if(findProg.size())
  2297. {
  2298. program = findProg;
  2299. args = "";
  2300. return;
  2301. }
  2302. // Now try and peel off space separated chunks from the end of the string
  2303. // so the largest path possible is found allowing for spaces in the path
  2304. kwsys_stl::string dir = path;
  2305. kwsys_stl::string::size_type spacePos = dir.rfind(' ');
  2306. while(spacePos != kwsys_stl::string::npos)
  2307. {
  2308. kwsys_stl::string tryProg = dir.substr(0, spacePos);
  2309. // See if the file exists
  2310. if(SystemTools::FileExists(tryProg.c_str()))
  2311. {
  2312. program = tryProg;
  2313. // remove trailing spaces from program
  2314. kwsys_stl::string::size_type pos = program.size()-1;
  2315. while(program[pos] == ' ')
  2316. {
  2317. program.erase(pos);
  2318. pos--;
  2319. }
  2320. args = dir.substr(spacePos, dir.size()-spacePos);
  2321. return;
  2322. }
  2323. // Now try and find the the program in the path
  2324. findProg = SystemTools::FindProgram(tryProg.c_str(), e);
  2325. if(findProg.size())
  2326. {
  2327. program = findProg;
  2328. // remove trailing spaces from program
  2329. kwsys_stl::string::size_type pos = program.size()-1;
  2330. while(program[pos] == ' ')
  2331. {
  2332. program.erase(pos);
  2333. pos--;
  2334. }
  2335. args = dir.substr(spacePos, dir.size()-spacePos);
  2336. return;
  2337. }
  2338. // move past the space for the next search
  2339. spacePos--;
  2340. spacePos = dir.rfind(' ', spacePos);
  2341. }
  2342. program = "";
  2343. args = "";
  2344. }
  2345. kwsys_stl::string SystemTools::GetCurrentDateTime(const char* format)
  2346. {
  2347. char buf[1024];
  2348. time_t t;
  2349. time(&t);
  2350. strftime(buf, sizeof(buf), format, localtime(&t));
  2351. return buf;
  2352. }
  2353. kwsys_stl::string SystemTools::MakeCindentifier(const char* s)
  2354. {
  2355. kwsys_stl::string str(s);
  2356. if (str.find_first_of("0123456789") == 0)
  2357. {
  2358. str = "_" + str;
  2359. }
  2360. kwsys_stl::string permited_chars("_"
  2361. "abcdefghijklmnopqrstuvwxyz"
  2362. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  2363. "0123456789");
  2364. kwsys_stl::string::size_type pos = 0;
  2365. while ((pos = str.find_first_not_of(permited_chars, pos)) != kwsys_stl::string::npos)
  2366. {
  2367. str[pos] = '_';
  2368. }
  2369. return str;
  2370. }
  2371. // Due to a buggy stream library on the HP and another on Mac OSX, we
  2372. // need this very carefully written version of getline. Returns true
  2373. // if any data were read before the end-of-file was reached.
  2374. bool SystemTools::GetLineFromStream(kwsys_ios::istream& is, kwsys_stl::string& line,
  2375. bool *has_newline /* = 0 */)
  2376. {
  2377. const int bufferSize = 1024;
  2378. char buffer[bufferSize];
  2379. line = "";
  2380. bool haveData = false;
  2381. if ( has_newline )
  2382. {
  2383. *has_newline = false;
  2384. }
  2385. // If no characters are read from the stream, the end of file has
  2386. // been reached.
  2387. while((is.getline(buffer, bufferSize), is.gcount() > 0))
  2388. {
  2389. haveData = true;
  2390. line.append(buffer);
  2391. // If newline character was read, the gcount includes the
  2392. // character, but the buffer does not. The end of line has been
  2393. // reached.
  2394. if(strlen(buffer) < static_cast<size_t>(is.gcount()))
  2395. {
  2396. if ( has_newline )
  2397. {
  2398. *has_newline = true;
  2399. }
  2400. break;
  2401. }
  2402. // The fail bit may be set. Clear it.
  2403. is.clear(is.rdstate() & ~kwsys_ios::ios::failbit);
  2404. }
  2405. return haveData;
  2406. }
  2407. int SystemTools::GetTerminalWidth()
  2408. {
  2409. int width = -1;
  2410. #ifndef _WIN32
  2411. struct winsize ws;
  2412. char *columns; /* Unix98 environment variable */
  2413. if(ioctl(1, TIOCGWINSZ, &ws) != -1 && ws.ws_col>0 && ws.ws_row>0)
  2414. {
  2415. width = ws.ws_col;
  2416. }
  2417. if(!isatty(STDOUT_FILENO))
  2418. {
  2419. width = -1;
  2420. }
  2421. columns = getenv("COLUMNS");
  2422. if(columns && *columns)
  2423. {
  2424. long t;
  2425. char *endptr;
  2426. t = strtol(columns, &endptr, 0);
  2427. if(endptr && !*endptr && (t>0) && (t<1000))
  2428. {
  2429. width = (int)t;
  2430. }
  2431. }
  2432. if ( width < 9 )
  2433. {
  2434. width = -1;
  2435. }
  2436. #endif
  2437. return width;
  2438. }
  2439. bool SystemTools::GetPermissions(const char* file, mode_t& mode)
  2440. {
  2441. if ( !file )
  2442. {
  2443. return false;
  2444. }
  2445. struct stat st;
  2446. if ( stat(file, &st) < 0 )
  2447. {
  2448. return false;
  2449. }
  2450. mode = st.st_mode;
  2451. return true;
  2452. }
  2453. bool SystemTools::SetPermissions(const char* file, mode_t mode)
  2454. {
  2455. if ( !file )
  2456. {
  2457. return false;
  2458. }
  2459. if ( !SystemTools::FileExists(file) )
  2460. {
  2461. return false;
  2462. }
  2463. if ( chmod(file, mode) < 0 )
  2464. {
  2465. return false;
  2466. }
  2467. return true;
  2468. }
  2469. kwsys_stl::string SystemTools::GetParentDirectory(const char* fileOrDir)
  2470. {
  2471. if ( !fileOrDir || !*fileOrDir )
  2472. {
  2473. return "";
  2474. }
  2475. kwsys_stl::string res = fileOrDir;
  2476. SystemTools::ConvertToUnixSlashes(res);
  2477. kwsys_stl::string::size_type cc = res.size()-1;
  2478. if ( res[cc] == '/' )
  2479. {
  2480. cc --;
  2481. }
  2482. for ( ; cc > 0; cc -- )
  2483. {
  2484. if ( res[cc] == '/' )
  2485. {
  2486. break;
  2487. }
  2488. }
  2489. return res.substr(0, cc);
  2490. }
  2491. bool SystemTools::IsSubDirectory(const char* cSubdir, const char* cDir)
  2492. {
  2493. kwsys_stl::string subdir = cSubdir;
  2494. kwsys_stl::string dir = cDir;
  2495. SystemTools::ConvertToUnixSlashes(dir);
  2496. kwsys_stl::string path = subdir;
  2497. do
  2498. {
  2499. path = SystemTools::GetParentDirectory(path.c_str());
  2500. if ( dir == path )
  2501. {
  2502. return true;
  2503. }
  2504. }
  2505. while ( path.size() > dir.size() );
  2506. return false;
  2507. }
  2508. kwsys_stl::string SystemTools::FileExistsInParentDirectories(const char* fname,
  2509. const char* directory, const char* toplevel)
  2510. {
  2511. kwsys_stl::string file = fname;
  2512. SystemTools::ConvertToUnixSlashes(file);
  2513. kwsys_stl::string dir = directory;
  2514. SystemTools::ConvertToUnixSlashes(dir);
  2515. while ( !dir.empty() )
  2516. {
  2517. kwsys_stl::string path = dir + "/" + file;
  2518. if ( SystemTools::FileExists(path.c_str()) )
  2519. {
  2520. return path;
  2521. }
  2522. if ( dir.size() < strlen(toplevel) )
  2523. {
  2524. break;
  2525. }
  2526. dir = SystemTools::GetParentDirectory(dir.c_str());
  2527. }
  2528. return "";
  2529. }
  2530. void SystemTools::Delay(unsigned int msec)
  2531. {
  2532. #ifdef _WIN32
  2533. Sleep(msec);
  2534. #else
  2535. usleep(msec * 1000);
  2536. #endif
  2537. }
  2538. // These must NOT be initialized. Default initialization to zero is
  2539. // necessary.
  2540. unsigned int SystemToolsManagerCount;
  2541. SystemToolsTranslationMap *SystemTools::TranslationMap;
  2542. // SystemToolsManager manages the SystemTools singleton.
  2543. // SystemToolsManager should be included in any translation unit
  2544. // that will use SystemTools or that implements the singleton
  2545. // pattern. It makes sure that the SystemTools singleton is created
  2546. // before and destroyed after all other singletons in CMake.
  2547. SystemToolsManager::SystemToolsManager()
  2548. {
  2549. if(++SystemToolsManagerCount == 1)
  2550. {
  2551. SystemTools::ClassInitialize();
  2552. }
  2553. }
  2554. SystemToolsManager::~SystemToolsManager()
  2555. {
  2556. if(--SystemToolsManagerCount == 0)
  2557. {
  2558. SystemTools::ClassFinalize();
  2559. }
  2560. }
  2561. void SystemTools::ClassInitialize()
  2562. {
  2563. // Allocate the translation map first.
  2564. SystemTools::TranslationMap = new SystemToolsTranslationMap;
  2565. // Add some special translation paths for unix. These are not added
  2566. // for windows because drive letters need to be maintained. Also,
  2567. // there are not sym-links and mount points on windows anyway.
  2568. #if !defined(_WIN32) || defined(__CYGWIN__)
  2569. // Work-around an SGI problem by always adding this mapping:
  2570. SystemTools::AddTranslationPath("/tmp_mnt/", "/");
  2571. // The tmp path is frequently a logical path so always keep it:
  2572. SystemTools::AddKeepPath("/tmp/");
  2573. // If the current working directory is a logical path then keep the
  2574. // logical name.
  2575. if(const char* pwd = getenv("PWD"))
  2576. {
  2577. char buf[2048];
  2578. if(const char* cwd = Getcwd(buf, 2048))
  2579. {
  2580. kwsys_stl::string pwd_path;
  2581. Realpath(pwd, pwd_path);
  2582. if(cwd == pwd_path && strcmp(cwd, pwd) != 0)
  2583. {
  2584. // The current working directory is a logical path. Split
  2585. // both the logical and physical paths into their components.
  2586. kwsys_stl::vector<kwsys_stl::string> cwd_components;
  2587. kwsys_stl::vector<kwsys_stl::string> pwd_components;
  2588. SystemTools::SplitPath(cwd, cwd_components);
  2589. SystemTools::SplitPath(pwd, pwd_components);
  2590. // Remove the common ending of the paths to leave only the
  2591. // part that changes under the logical mapping.
  2592. kwsys_stl::vector<kwsys_stl::string>::iterator ic = cwd_components.end();
  2593. kwsys_stl::vector<kwsys_stl::string>::iterator ip = pwd_components.end();
  2594. for(;ip != pwd_components.begin() && ic != cwd_components.begin() &&
  2595. *(ip-1) == *(ic-1); --ip,--ic);
  2596. cwd_components.erase(ic, cwd_components.end());
  2597. pwd_components.erase(ip, pwd_components.end());
  2598. // Reconstruct the string versions of the part of the path
  2599. // that changed.
  2600. kwsys_stl::string cwd_changed = SystemTools::JoinPath(cwd_components);
  2601. kwsys_stl::string pwd_changed = SystemTools::JoinPath(pwd_components);
  2602. // Add the translation to keep the logical path name.
  2603. if(!cwd_changed.empty() && !pwd_changed.empty())
  2604. {
  2605. SystemTools::AddTranslationPath(cwd_changed.c_str(),
  2606. pwd_changed.c_str());
  2607. }
  2608. }
  2609. }
  2610. }
  2611. #endif
  2612. }
  2613. void SystemTools::ClassFinalize()
  2614. {
  2615. delete SystemTools::TranslationMap;
  2616. }
  2617. } // namespace KWSYS_NAMESPACE
  2618. #if defined(_MSC_VER) && defined(_DEBUG)
  2619. # include <crtdbg.h>
  2620. # include <stdio.h>
  2621. # include <stdlib.h>
  2622. namespace KWSYS_NAMESPACE
  2623. {
  2624. static int SystemToolsDebugReport(int, char* message, int*)
  2625. {
  2626. fprintf(stderr, message);
  2627. exit(1);
  2628. }
  2629. void SystemTools::EnableMSVCDebugHook()
  2630. {
  2631. if(getenv("DART_TEST_FROM_DART"))
  2632. {
  2633. _CrtSetReportHook(SystemToolsDebugReport);
  2634. }
  2635. }
  2636. } // namespace KWSYS_NAMESPACE
  2637. #else
  2638. namespace KWSYS_NAMESPACE
  2639. {
  2640. void SystemTools::EnableMSVCDebugHook() {}
  2641. } // namespace KWSYS_NAMESPACE
  2642. #endif