SystemTools.cxx 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004
  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 <ctype.h>
  20. #include <errno.h>
  21. #ifdef __QNX__
  22. # include <malloc.h> /* for malloc/free on QNX */
  23. #endif
  24. #include <stdio.h>
  25. #include <stdlib.h>
  26. #include <string.h>
  27. #include <sys/stat.h>
  28. #include <time.h>
  29. // support for realpath call
  30. #ifndef _WIN32
  31. #include <limits.h>
  32. #include <sys/param.h>
  33. #include <sys/wait.h>
  34. #include <sys/ioctl.h>
  35. #include <unistd.h>
  36. #include <termios.h>
  37. #endif
  38. #if defined(_WIN32) && (defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__))
  39. #include <io.h>
  40. #include <windows.h>
  41. #include <direct.h>
  42. #define _unlink unlink
  43. inline int Mkdir(const char* dir)
  44. {
  45. return _mkdir(dir);
  46. }
  47. inline int Rmdir(const char* dir)
  48. {
  49. return _rmdir(dir);
  50. }
  51. inline const char* Getcwd(char* buf, unsigned int len)
  52. {
  53. return _getcwd(buf, len);
  54. }
  55. inline int Chdir(const char* dir)
  56. {
  57. #if defined(__BORLANDC__)
  58. return chdir(dir);
  59. #else
  60. return _chdir(dir);
  61. #endif
  62. }
  63. inline void Realpath(const char *path, kwsys_stl::string & resolved_path)
  64. {
  65. char *ptemp;
  66. char fullpath[MAX_PATH];
  67. if( GetFullPathName(path, sizeof(fullpath), fullpath, &ptemp) )
  68. {
  69. resolved_path = fullpath;
  70. KWSYS_NAMESPACE::SystemTools::ConvertToUnixSlashes(resolved_path);
  71. }
  72. }
  73. #else
  74. #include <sys/types.h>
  75. #include <fcntl.h>
  76. #include <unistd.h>
  77. inline int Mkdir(const char* dir)
  78. {
  79. return mkdir(dir, 00777);
  80. }
  81. inline int Rmdir(const char* dir)
  82. {
  83. return rmdir(dir);
  84. }
  85. inline const char* Getcwd(char* buf, unsigned int len)
  86. {
  87. return getcwd(buf, len);
  88. }
  89. inline int Chdir(const char* dir)
  90. {
  91. return chdir(dir);
  92. }
  93. inline void Realpath(const char *path, kwsys_stl::string & resolved_path)
  94. {
  95. # ifdef MAXPATHLEN
  96. char resolved_name[MAXPATHLEN];
  97. # else
  98. # ifdef PATH_MAX
  99. char resolved_name[PATH_MAX];
  100. # else
  101. char resolved_name[5024];
  102. # endif //PATH_MAX
  103. # endif //MAXPATHLEN
  104. realpath(path, resolved_name);
  105. resolved_path = resolved_name;
  106. }
  107. #endif
  108. #if !defined(_WIN32) && defined(__COMO__)
  109. // Hack for como strict mode to avoid defining _SVID_SOURCE or _BSD_SOURCE.
  110. extern "C"
  111. {
  112. extern FILE *popen (__const char *__command, __const char *__modes) __THROW;
  113. extern int pclose (FILE *__stream) __THROW;
  114. extern char *realpath (__const char *__restrict __name,
  115. char *__restrict __resolved) __THROW;
  116. extern char *strdup (__const char *__s) __THROW;
  117. extern int putenv (char *__string) __THROW;
  118. }
  119. #endif
  120. /* Implement floattime() for various platforms */
  121. // Taken from Python 2.1.3
  122. #if defined( _WIN32 ) && !defined( __CYGWIN__ )
  123. # include <sys/timeb.h>
  124. # define HAVE_FTIME
  125. # if defined( __BORLANDC__)
  126. # define FTIME ftime
  127. # define TIMEB timeb
  128. # else // Visual studio?
  129. # define FTIME _ftime
  130. # define TIMEB _timeb
  131. # endif
  132. #elif defined( __CYGWIN__ ) || defined( __linux__ )
  133. # include <sys/time.h>
  134. # include <time.h>
  135. # define HAVE_GETTIMEOFDAY
  136. #endif
  137. namespace KWSYS_NAMESPACE
  138. {
  139. class SystemToolsTranslationMap :
  140. public kwsys_stl::map<kwsys_stl::string,kwsys_stl::string>
  141. {
  142. };
  143. double
  144. SystemTools::GetTime(void)
  145. {
  146. /* There are three ways to get the time:
  147. (1) gettimeofday() -- resolution in microseconds
  148. (2) ftime() -- resolution in milliseconds
  149. (3) time() -- resolution in seconds
  150. In all cases the return value is a float in seconds.
  151. Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
  152. fail, so we fall back on ftime() or time().
  153. Note: clock resolution does not imply clock accuracy! */
  154. #ifdef HAVE_GETTIMEOFDAY
  155. {
  156. struct timeval t;
  157. #ifdef GETTIMEOFDAY_NO_TZ
  158. if (gettimeofday(&t) == 0)
  159. return (double)t.tv_sec + t.tv_usec*0.000001;
  160. #else /* !GETTIMEOFDAY_NO_TZ */
  161. if (gettimeofday(&t, (struct timezone *)NULL) == 0)
  162. return (double)t.tv_sec + t.tv_usec*0.000001;
  163. #endif /* !GETTIMEOFDAY_NO_TZ */
  164. }
  165. #endif /* !HAVE_GETTIMEOFDAY */
  166. {
  167. #if defined(HAVE_FTIME)
  168. struct TIMEB t;
  169. ::FTIME(&t);
  170. return (double)t.time + (double)t.millitm * (double)0.001;
  171. #else /* !HAVE_FTIME */
  172. time_t secs;
  173. time(&secs);
  174. return (double)secs;
  175. #endif /* !HAVE_FTIME */
  176. }
  177. }
  178. // adds the elements of the env variable path to the arg passed in
  179. void SystemTools::GetPath(kwsys_stl::vector<kwsys_stl::string>& path, const char* env)
  180. {
  181. #if defined(_WIN32) && !defined(__CYGWIN__)
  182. const char* pathSep = ";";
  183. #else
  184. const char* pathSep = ":";
  185. #endif
  186. if(!env)
  187. {
  188. env = "PATH";
  189. }
  190. const char* cpathEnv = SystemTools::GetEnv(env);
  191. if ( !cpathEnv )
  192. {
  193. return;
  194. }
  195. kwsys_stl::string pathEnv = cpathEnv;
  196. // A hack to make the below algorithm work.
  197. if(pathEnv[pathEnv.length()-1] != ':')
  198. {
  199. pathEnv += pathSep;
  200. }
  201. kwsys_stl::string::size_type start =0;
  202. bool done = false;
  203. while(!done)
  204. {
  205. kwsys_stl::string::size_type endpos = pathEnv.find(pathSep, start);
  206. if(endpos != kwsys_stl::string::npos)
  207. {
  208. path.push_back(pathEnv.substr(start, endpos-start));
  209. start = endpos+1;
  210. }
  211. else
  212. {
  213. done = true;
  214. }
  215. }
  216. for(kwsys_stl::vector<kwsys_stl::string>::iterator i = path.begin();
  217. i != path.end(); ++i)
  218. {
  219. SystemTools::ConvertToUnixSlashes(*i);
  220. }
  221. }
  222. const char* SystemTools::GetEnv(const char* key)
  223. {
  224. return getenv(key);
  225. }
  226. bool SystemTools::GetEnv(const char* key, kwsys_stl::string& result)
  227. {
  228. const char* v = getenv(key);
  229. if(v)
  230. {
  231. result = v;
  232. return true;
  233. }
  234. else
  235. {
  236. return false;
  237. }
  238. }
  239. const char* SystemTools::GetExecutableExtension()
  240. {
  241. #if defined(_WIN32) || defined(__CYGWIN__)
  242. return ".exe";
  243. #else
  244. return "";
  245. #endif
  246. }
  247. bool SystemTools::MakeDirectory(const char* path)
  248. {
  249. if(SystemTools::FileExists(path))
  250. {
  251. return true;
  252. }
  253. kwsys_stl::string dir = path;
  254. if(dir.size() == 0)
  255. {
  256. return false;
  257. }
  258. SystemTools::ConvertToUnixSlashes(dir);
  259. kwsys_stl::string::size_type pos = dir.find(':');
  260. if(pos == kwsys_stl::string::npos)
  261. {
  262. pos = 0;
  263. }
  264. kwsys_stl::string topdir;
  265. while((pos = dir.find('/', pos)) != kwsys_stl::string::npos)
  266. {
  267. topdir = dir.substr(0, pos);
  268. Mkdir(topdir.c_str());
  269. pos++;
  270. }
  271. if(dir[dir.size()-1] == '/')
  272. {
  273. topdir = dir.substr(0, dir.size());
  274. }
  275. else
  276. {
  277. topdir = dir;
  278. }
  279. if(Mkdir(topdir.c_str()) != 0)
  280. {
  281. // There is a bug in the Borland Run time library which makes MKDIR
  282. // return EACCES when it should return EEXISTS
  283. // if it is some other error besides directory exists
  284. // then return false
  285. if( (errno != EEXIST)
  286. #ifdef __BORLANDC__
  287. && (errno != EACCES)
  288. #endif
  289. )
  290. {
  291. return false;
  292. }
  293. }
  294. return true;
  295. }
  296. // replace replace with with as many times as it shows up in source.
  297. // write the result into source.
  298. void SystemTools::ReplaceString(kwsys_stl::string& source,
  299. const char* replace,
  300. const char* with)
  301. {
  302. const char *src = source.c_str();
  303. char *searchPos = const_cast<char *>(strstr(src,replace));
  304. // get out quick if string is not found
  305. if (!searchPos)
  306. {
  307. return;
  308. }
  309. // perform replacements until done
  310. size_t replaceSize = strlen(replace);
  311. char *orig = strdup(src);
  312. char *currentPos = orig;
  313. searchPos = searchPos - src + orig;
  314. // initialize the result
  315. source.erase(source.begin(),source.end());
  316. do
  317. {
  318. *searchPos = '\0';
  319. source += currentPos;
  320. currentPos = searchPos + replaceSize;
  321. // replace
  322. source += with;
  323. searchPos = strstr(currentPos,replace);
  324. }
  325. while (searchPos);
  326. // copy any trailing text
  327. source += currentPos;
  328. free(orig);
  329. }
  330. // Read a registry value.
  331. // Example :
  332. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  333. // => will return the data of the "default" value of the key
  334. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  335. // => will return the data of the "Root" value of the key
  336. #if defined(_WIN32) && !defined(__CYGWIN__)
  337. bool SystemTools::ReadRegistryValue(const char *key, kwsys_stl::string &value)
  338. {
  339. kwsys_stl::string primary = key;
  340. kwsys_stl::string second;
  341. kwsys_stl::string valuename;
  342. size_t start = primary.find("\\");
  343. if (start == kwsys_stl::string::npos)
  344. {
  345. return false;
  346. }
  347. size_t valuenamepos = primary.find(";");
  348. if (valuenamepos != kwsys_stl::string::npos)
  349. {
  350. valuename = primary.substr(valuenamepos+1);
  351. }
  352. second = primary.substr(start+1, valuenamepos-start-1);
  353. primary = primary.substr(0, start);
  354. HKEY primaryKey = HKEY_CURRENT_USER;
  355. if (primary == "HKEY_CURRENT_USER")
  356. {
  357. primaryKey = HKEY_CURRENT_USER;
  358. }
  359. if (primary == "HKEY_CURRENT_CONFIG")
  360. {
  361. primaryKey = HKEY_CURRENT_CONFIG;
  362. }
  363. if (primary == "HKEY_CLASSES_ROOT")
  364. {
  365. primaryKey = HKEY_CLASSES_ROOT;
  366. }
  367. if (primary == "HKEY_LOCAL_MACHINE")
  368. {
  369. primaryKey = HKEY_LOCAL_MACHINE;
  370. }
  371. if (primary == "HKEY_USERS")
  372. {
  373. primaryKey = HKEY_USERS;
  374. }
  375. HKEY hKey;
  376. if(RegOpenKeyEx(primaryKey,
  377. second.c_str(),
  378. 0,
  379. KEY_READ,
  380. &hKey) != ERROR_SUCCESS)
  381. {
  382. return false;
  383. }
  384. else
  385. {
  386. DWORD dwType, dwSize;
  387. dwSize = 1023;
  388. char data[1024];
  389. if(RegQueryValueEx(hKey,
  390. (LPTSTR)valuename.c_str(),
  391. NULL,
  392. &dwType,
  393. (BYTE *)data,
  394. &dwSize) == ERROR_SUCCESS)
  395. {
  396. if (dwType == REG_SZ)
  397. {
  398. value = data;
  399. RegCloseKey(hKey);
  400. return true;
  401. }
  402. }
  403. }
  404. return false;
  405. }
  406. #else
  407. bool SystemTools::ReadRegistryValue(const char *, kwsys_stl::string &)
  408. {
  409. return false;
  410. }
  411. #endif
  412. // Write a registry value.
  413. // Example :
  414. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  415. // => will set the data of the "default" value of the key
  416. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  417. // => will set the data of the "Root" value of the key
  418. #if defined(_WIN32) && !defined(__CYGWIN__)
  419. bool SystemTools::WriteRegistryValue(const char *key, const char *value)
  420. {
  421. kwsys_stl::string primary = key;
  422. kwsys_stl::string second;
  423. kwsys_stl::string valuename;
  424. size_t start = primary.find("\\");
  425. if (start == kwsys_stl::string::npos)
  426. {
  427. return false;
  428. }
  429. size_t valuenamepos = primary.find(";");
  430. if (valuenamepos != kwsys_stl::string::npos)
  431. {
  432. valuename = primary.substr(valuenamepos+1);
  433. }
  434. second = primary.substr(start+1, valuenamepos-start-1);
  435. primary = primary.substr(0, start);
  436. HKEY primaryKey = HKEY_CURRENT_USER;
  437. if (primary == "HKEY_CURRENT_USER")
  438. {
  439. primaryKey = HKEY_CURRENT_USER;
  440. }
  441. if (primary == "HKEY_CURRENT_CONFIG")
  442. {
  443. primaryKey = HKEY_CURRENT_CONFIG;
  444. }
  445. if (primary == "HKEY_CLASSES_ROOT")
  446. {
  447. primaryKey = HKEY_CLASSES_ROOT;
  448. }
  449. if (primary == "HKEY_LOCAL_MACHINE")
  450. {
  451. primaryKey = HKEY_LOCAL_MACHINE;
  452. }
  453. if (primary == "HKEY_USERS")
  454. {
  455. primaryKey = HKEY_USERS;
  456. }
  457. HKEY hKey;
  458. DWORD dwDummy;
  459. if(RegCreateKeyEx(primaryKey,
  460. second.c_str(),
  461. 0,
  462. "",
  463. REG_OPTION_NON_VOLATILE,
  464. KEY_WRITE,
  465. NULL,
  466. &hKey,
  467. &dwDummy) != ERROR_SUCCESS)
  468. {
  469. return false;
  470. }
  471. if(RegSetValueEx(hKey,
  472. (LPTSTR)valuename.c_str(),
  473. 0,
  474. REG_SZ,
  475. (CONST BYTE *)value,
  476. (DWORD)(strlen(value) + 1)) == ERROR_SUCCESS)
  477. {
  478. return true;
  479. }
  480. return false;
  481. }
  482. #else
  483. bool SystemTools::WriteRegistryValue(const char *, const char *)
  484. {
  485. return false;
  486. }
  487. #endif
  488. // Delete a registry value.
  489. // Example :
  490. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  491. // => will delete the data of the "default" value of the key
  492. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  493. // => will delete the data of the "Root" value of the key
  494. #if defined(_WIN32) && !defined(__CYGWIN__)
  495. bool SystemTools::DeleteRegistryValue(const char *key)
  496. {
  497. kwsys_stl::string primary = key;
  498. kwsys_stl::string second;
  499. kwsys_stl::string valuename;
  500. size_t start = primary.find("\\");
  501. if (start == kwsys_stl::string::npos)
  502. {
  503. return false;
  504. }
  505. size_t valuenamepos = primary.find(";");
  506. if (valuenamepos != kwsys_stl::string::npos)
  507. {
  508. valuename = primary.substr(valuenamepos+1);
  509. }
  510. second = primary.substr(start+1, valuenamepos-start-1);
  511. primary = primary.substr(0, start);
  512. HKEY primaryKey = HKEY_CURRENT_USER;
  513. if (primary == "HKEY_CURRENT_USER")
  514. {
  515. primaryKey = HKEY_CURRENT_USER;
  516. }
  517. if (primary == "HKEY_CURRENT_CONFIG")
  518. {
  519. primaryKey = HKEY_CURRENT_CONFIG;
  520. }
  521. if (primary == "HKEY_CLASSES_ROOT")
  522. {
  523. primaryKey = HKEY_CLASSES_ROOT;
  524. }
  525. if (primary == "HKEY_LOCAL_MACHINE")
  526. {
  527. primaryKey = HKEY_LOCAL_MACHINE;
  528. }
  529. if (primary == "HKEY_USERS")
  530. {
  531. primaryKey = HKEY_USERS;
  532. }
  533. HKEY hKey;
  534. if(RegOpenKeyEx(primaryKey,
  535. second.c_str(),
  536. 0,
  537. KEY_WRITE,
  538. &hKey) != ERROR_SUCCESS)
  539. {
  540. return false;
  541. }
  542. else
  543. {
  544. if(RegDeleteValue(hKey,
  545. (LPTSTR)valuename.c_str()) == ERROR_SUCCESS)
  546. {
  547. RegCloseKey(hKey);
  548. return true;
  549. }
  550. }
  551. return false;
  552. }
  553. #else
  554. bool SystemTools::DeleteRegistryValue(const char *)
  555. {
  556. return false;
  557. }
  558. #endif
  559. bool SystemTools::SameFile(const char* file1, const char* file2)
  560. {
  561. #ifdef _WIN32
  562. HANDLE hFile1, hFile2;
  563. hFile1 = CreateFile( file1,
  564. GENERIC_READ,
  565. FILE_SHARE_READ ,
  566. NULL,
  567. OPEN_EXISTING,
  568. FILE_FLAG_BACKUP_SEMANTICS,
  569. NULL
  570. );
  571. hFile2 = CreateFile( file2,
  572. GENERIC_READ,
  573. FILE_SHARE_READ,
  574. NULL,
  575. OPEN_EXISTING,
  576. FILE_FLAG_BACKUP_SEMANTICS,
  577. NULL
  578. );
  579. if( hFile1 == INVALID_HANDLE_VALUE || hFile2 == INVALID_HANDLE_VALUE)
  580. {
  581. if(hFile1 != INVALID_HANDLE_VALUE)
  582. {
  583. CloseHandle(hFile1);
  584. }
  585. if(hFile2 != INVALID_HANDLE_VALUE)
  586. {
  587. CloseHandle(hFile2);
  588. }
  589. return false;
  590. }
  591. BY_HANDLE_FILE_INFORMATION fiBuf1;
  592. BY_HANDLE_FILE_INFORMATION fiBuf2;
  593. GetFileInformationByHandle( hFile1, &fiBuf1 );
  594. GetFileInformationByHandle( hFile2, &fiBuf2 );
  595. CloseHandle(hFile1);
  596. CloseHandle(hFile2);
  597. return (fiBuf1.dwVolumeSerialNumber == fiBuf2.dwVolumeSerialNumber &&
  598. fiBuf1.nFileIndexHigh == fiBuf2.nFileIndexHigh &&
  599. fiBuf1.nFileIndexLow == fiBuf2.nFileIndexLow);
  600. #else
  601. struct stat fileStat1, fileStat2;
  602. if (stat(file1, &fileStat1) == 0 && stat(file2, &fileStat2) == 0)
  603. {
  604. // see if the files are the same file
  605. // check the device inode and size
  606. if(memcmp(&fileStat2.st_dev, &fileStat1.st_dev, sizeof(fileStat1.st_dev)) == 0 &&
  607. memcmp(&fileStat2.st_ino, &fileStat1.st_ino, sizeof(fileStat1.st_ino)) == 0 &&
  608. fileStat2.st_size == fileStat1.st_size
  609. )
  610. {
  611. return true;
  612. }
  613. }
  614. return false;
  615. #endif
  616. }
  617. // return true if the file exists
  618. bool SystemTools::FileExists(const char* filename)
  619. {
  620. #ifdef _MSC_VER
  621. # define access _access
  622. #endif
  623. #ifndef R_OK
  624. # define R_OK 04
  625. #endif
  626. if ( access(filename, R_OK) != 0 )
  627. {
  628. return false;
  629. }
  630. else
  631. {
  632. return true;
  633. }
  634. }
  635. bool SystemTools::FileTimeCompare(const char* f1, const char* f2,
  636. int* result)
  637. {
  638. // Default to same time.
  639. *result = 0;
  640. #if !defined(_WIN32) || defined(__CYGWIN__)
  641. // POSIX version. Use stat function to get file modification time.
  642. struct stat s1;
  643. if(stat(f1, &s1) != 0)
  644. {
  645. return false;
  646. }
  647. struct stat s2;
  648. if(stat(f2, &s2) != 0)
  649. {
  650. return false;
  651. }
  652. # if KWSYS_STAT_HAS_ST_MTIM
  653. // Compare using nanosecond resolution.
  654. if(s1.st_mtim.tv_sec < s2.st_mtim.tv_sec)
  655. {
  656. *result = -1;
  657. }
  658. else if(s1.st_mtim.tv_sec > s2.st_mtim.tv_sec)
  659. {
  660. *result = 1;
  661. }
  662. else if(s1.st_mtim.tv_nsec < s2.st_mtim.tv_nsec)
  663. {
  664. *result = -1;
  665. }
  666. else if(s1.st_mtim.tv_nsec > s2.st_mtim.tv_nsec)
  667. {
  668. *result = 1;
  669. }
  670. # else
  671. // Compare using 1 second resolution.
  672. if(s1.st_mtime < s2.st_mtime)
  673. {
  674. *result = -1;
  675. }
  676. else if(s1.st_mtime > s2.st_mtime)
  677. {
  678. *result = 1;
  679. }
  680. # endif
  681. #else
  682. // Windows version. Create file handles and get the modification times.
  683. HANDLE hf1 = CreateFile(f1, GENERIC_READ, FILE_SHARE_READ,
  684. NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS,
  685. NULL);
  686. if(hf1 == INVALID_HANDLE_VALUE)
  687. {
  688. return false;
  689. }
  690. FILETIME tf1;
  691. if(!GetFileTime(hf1, 0, 0, &tf1))
  692. {
  693. CloseHandle(hf1);
  694. return false;
  695. }
  696. CloseHandle(hf1);
  697. HANDLE hf2 = CreateFile(f2, GENERIC_READ, FILE_SHARE_READ,
  698. NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS,
  699. NULL);
  700. if(hf2 == INVALID_HANDLE_VALUE)
  701. {
  702. return false;
  703. }
  704. FILETIME tf2;
  705. if(!GetFileTime(hf2, 0, 0, &tf2))
  706. {
  707. CloseHandle(hf2);
  708. return false;
  709. }
  710. CloseHandle(hf2);
  711. // Compare the file times using resolution provided by system call.
  712. *result = (int)CompareFileTime(&tf1, &tf2);
  713. #endif
  714. return true;
  715. }
  716. // Return a capitalized string (i.e the first letter is uppercased, all other
  717. // are lowercased)
  718. kwsys_stl::string SystemTools::Capitalized(const kwsys_stl::string& s)
  719. {
  720. kwsys_stl::string n;
  721. if(s.size() == 0)
  722. {
  723. return n;
  724. }
  725. n.resize(s.size());
  726. n[0] = static_cast<kwsys_stl::string::value_type>(toupper(s[0]));
  727. for (size_t i = 1; i < s.size(); i++)
  728. {
  729. n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
  730. }
  731. return n;
  732. }
  733. // Return capitalized words
  734. kwsys_stl::string SystemTools::CapitalizedWords(const kwsys_stl::string& s)
  735. {
  736. kwsys_stl::string n(s);
  737. for (size_t i = 0; i < s.size(); i++)
  738. {
  739. if (isalpha(s[i]) && (i == 0 || isspace(s[i - 1])))
  740. {
  741. n[i] = static_cast<kwsys_stl::string::value_type>(toupper(s[i]));
  742. }
  743. }
  744. return n;
  745. }
  746. // Return uncapitalized words
  747. kwsys_stl::string SystemTools::UnCapitalizedWords(const kwsys_stl::string& s)
  748. {
  749. kwsys_stl::string n(s);
  750. for (size_t i = 0; i < s.size(); i++)
  751. {
  752. if (isalpha(s[i]) && (i == 0 || isspace(s[i - 1])))
  753. {
  754. n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
  755. }
  756. }
  757. return n;
  758. }
  759. kwsys_stl::string SystemTools::AddSpaceBetweenCapitalizedWords(
  760. const kwsys_stl::string& s)
  761. {
  762. kwsys_stl::string n;
  763. if (s.size())
  764. {
  765. n.reserve(s.size());
  766. n += s[0];
  767. for (size_t i = 1; i < s.size(); i++)
  768. {
  769. if (isupper(s[i]) && !isspace(s[i - 1]) && !isupper(s[i - 1]))
  770. {
  771. n += ' ';
  772. }
  773. n += s[i];
  774. }
  775. }
  776. return n;
  777. }
  778. char* SystemTools::AppendStrings(const char* str1, const char* str2)
  779. {
  780. if (!str1)
  781. {
  782. return SystemTools::DuplicateString(str2);
  783. }
  784. if (!str2)
  785. {
  786. return SystemTools::DuplicateString(str1);
  787. }
  788. size_t len1 = strlen(str1);
  789. char *newstr = new char[len1 + strlen(str2) + 1];
  790. if (!newstr)
  791. {
  792. return 0;
  793. }
  794. strcpy(newstr, str1);
  795. strcat(newstr + len1, str2);
  796. return newstr;
  797. }
  798. char* SystemTools::AppendStrings(
  799. const char* str1, const char* str2, const char* str3)
  800. {
  801. if (!str1)
  802. {
  803. return SystemTools::AppendStrings(str2, str3);
  804. }
  805. if (!str2)
  806. {
  807. return SystemTools::AppendStrings(str1, str3);
  808. }
  809. if (!str3)
  810. {
  811. return SystemTools::AppendStrings(str1, str2);
  812. }
  813. size_t len1 = strlen(str1), len2 = strlen(str2);
  814. char *newstr = new char[len1 + len2 + strlen(str3) + 1];
  815. if (!newstr)
  816. {
  817. return 0;
  818. }
  819. strcpy(newstr, str1);
  820. strcat(newstr + len1, str2);
  821. strcat(newstr + len1 + len2, str3);
  822. return newstr;
  823. }
  824. // Return a lower case string
  825. kwsys_stl::string SystemTools::LowerCase(const kwsys_stl::string& s)
  826. {
  827. kwsys_stl::string n;
  828. n.resize(s.size());
  829. for (size_t i = 0; i < s.size(); i++)
  830. {
  831. n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
  832. }
  833. return n;
  834. }
  835. // Return a lower case string
  836. kwsys_stl::string SystemTools::UpperCase(const kwsys_stl::string& s)
  837. {
  838. kwsys_stl::string n;
  839. n.resize(s.size());
  840. for (size_t i = 0; i < s.size(); i++)
  841. {
  842. n[i] = static_cast<kwsys_stl::string::value_type>(toupper(s[i]));
  843. }
  844. return n;
  845. }
  846. // Count char in string
  847. size_t SystemTools::CountChar(const char* str, char c)
  848. {
  849. size_t count = 0;
  850. if (str)
  851. {
  852. while (*str)
  853. {
  854. if (*str == c)
  855. {
  856. ++count;
  857. }
  858. ++str;
  859. }
  860. }
  861. return count;
  862. }
  863. // Remove chars in string
  864. char* SystemTools::RemoveChars(const char* str, const char *toremove)
  865. {
  866. if (!str)
  867. {
  868. return NULL;
  869. }
  870. char *clean_str = new char [strlen(str) + 1];
  871. char *ptr = clean_str;
  872. while (*str)
  873. {
  874. const char *str2 = toremove;
  875. while (*str2 && *str != *str2)
  876. {
  877. ++str2;
  878. }
  879. if (!*str2)
  880. {
  881. *ptr++ = *str;
  882. }
  883. ++str;
  884. }
  885. *ptr = '\0';
  886. return clean_str;
  887. }
  888. // Remove chars in string
  889. char* SystemTools::RemoveCharsButUpperHex(const char* str)
  890. {
  891. if (!str)
  892. {
  893. return 0;
  894. }
  895. char *clean_str = new char [strlen(str) + 1];
  896. char *ptr = clean_str;
  897. while (*str)
  898. {
  899. if ((*str >= '0' && *str <= '9') || (*str >= 'A' && *str <= 'H'))
  900. {
  901. *ptr++ = *str;
  902. }
  903. ++str;
  904. }
  905. *ptr = '\0';
  906. return clean_str;
  907. }
  908. // Replace chars in string
  909. char* SystemTools::ReplaceChars(char* str, const char *toreplace, char replacement)
  910. {
  911. if (str)
  912. {
  913. char *ptr = str;
  914. while (*ptr)
  915. {
  916. const char *ptr2 = toreplace;
  917. while (*ptr2)
  918. {
  919. if (*ptr == *ptr2)
  920. {
  921. *ptr = replacement;
  922. }
  923. ++ptr2;
  924. }
  925. ++ptr;
  926. }
  927. }
  928. return str;
  929. }
  930. // Returns if string starts with another string
  931. bool SystemTools::StringStartsWith(const char* str1, const char* str2)
  932. {
  933. if (!str1 || !str2)
  934. {
  935. return false;
  936. }
  937. size_t len1 = strlen(str1), len2 = strlen(str2);
  938. return len1 >= len2 && !strncmp(str1, str2, len2) ? true : false;
  939. }
  940. // Returns if string ends with another string
  941. bool SystemTools::StringEndsWith(const char* str1, const char* str2)
  942. {
  943. if (!str1 || !str2)
  944. {
  945. return false;
  946. }
  947. size_t len1 = strlen(str1), len2 = strlen(str2);
  948. return len1 >= len2 && !strncmp(str1 + (len1 - len2), str2, len2) ? true : false;
  949. }
  950. // Returns a pointer to the last occurence of str2 in str1
  951. const char* SystemTools::FindLastString(const char* str1, const char* str2)
  952. {
  953. if (!str1 || !str2)
  954. {
  955. return NULL;
  956. }
  957. size_t len1 = strlen(str1), len2 = strlen(str2);
  958. if (len1 >= len2)
  959. {
  960. const char *ptr = str1 + len1 - len2;
  961. do
  962. {
  963. if (!strncmp(ptr, str2, len2))
  964. {
  965. return ptr;
  966. }
  967. } while (ptr-- != str1);
  968. }
  969. return NULL;
  970. }
  971. // Duplicate string
  972. char* SystemTools::DuplicateString(const char* str)
  973. {
  974. if (str)
  975. {
  976. char *newstr = new char [strlen(str) + 1];
  977. return strcpy(newstr, str);
  978. }
  979. return NULL;
  980. }
  981. // Return a cropped string
  982. kwsys_stl::string SystemTools::CropString(const kwsys_stl::string& s,
  983. size_t max_len)
  984. {
  985. if (!s.size() || max_len == 0 || max_len >= s.size())
  986. {
  987. return s;
  988. }
  989. kwsys_stl::string n;
  990. n.reserve(max_len);
  991. size_t middle = max_len / 2;
  992. n += s.substr(0, middle);
  993. n += s.substr(s.size() - (max_len - middle), kwsys_stl::string::npos);
  994. if (max_len > 2)
  995. {
  996. n[middle] = '.';
  997. if (max_len > 3)
  998. {
  999. n[middle - 1] = '.';
  1000. if (max_len > 4)
  1001. {
  1002. n[middle + 1] = '.';
  1003. }
  1004. }
  1005. }
  1006. return n;
  1007. }
  1008. // convert windows slashes to unix slashes
  1009. void SystemTools::ConvertToUnixSlashes(kwsys_stl::string& path)
  1010. {
  1011. kwsys_stl::string::size_type pos = 0;
  1012. while((pos = path.find('\\', pos)) != kwsys_stl::string::npos)
  1013. {
  1014. // make sure we don't convert an escaped space to a unix slash
  1015. if(pos < path.size()-1)
  1016. {
  1017. if(path[pos+1] != ' ')
  1018. {
  1019. path[pos] = '/';
  1020. }
  1021. }
  1022. pos++;
  1023. }
  1024. // Remove all // from the path just like most unix shells
  1025. int start_find;
  1026. #ifdef _WIN32
  1027. // However, on windows if the first characters are both slashes,
  1028. // then keep them that way, so that network paths can be handled.
  1029. start_find = 1;
  1030. #else
  1031. start_find = 0;
  1032. #endif
  1033. while((pos = path.find("//", start_find)) != kwsys_stl::string::npos)
  1034. {
  1035. SystemTools::ReplaceString(path, "//", "/");
  1036. }
  1037. // remove any trailing slash
  1038. if(path.size() > 1 && path[path.size()-1] == '/')
  1039. {
  1040. path = path.substr(0, path.size()-1);
  1041. }
  1042. // if there is a tilda ~ then replace it with HOME
  1043. if(path.find("~") == 0)
  1044. {
  1045. if (getenv("HOME"))
  1046. {
  1047. path = kwsys_stl::string(getenv("HOME")) + path.substr(1);
  1048. }
  1049. }
  1050. }
  1051. // change // to /, and escape any spaces in the path
  1052. kwsys_stl::string SystemTools::ConvertToUnixOutputPath(const char* path)
  1053. {
  1054. kwsys_stl::string ret = path;
  1055. // remove // except at the beginning might be a cygwin drive
  1056. kwsys_stl::string::size_type pos = 1;
  1057. while((pos = ret.find("//", pos)) != kwsys_stl::string::npos)
  1058. {
  1059. ret.erase(pos, 1);
  1060. }
  1061. // now escape spaces if there is a space in the path
  1062. if(ret.find(" ") != kwsys_stl::string::npos)
  1063. {
  1064. kwsys_stl::string result = "";
  1065. char lastch = 1;
  1066. for(const char* ch = ret.c_str(); *ch != '\0'; ++ch)
  1067. {
  1068. // if it is already escaped then don't try to escape it again
  1069. if(*ch == ' ' && lastch != '\\')
  1070. {
  1071. result += '\\';
  1072. }
  1073. result += *ch;
  1074. lastch = *ch;
  1075. }
  1076. ret = result;
  1077. }
  1078. return ret;
  1079. }
  1080. kwsys_stl::string SystemTools::ConvertToOutputPath(const char* path)
  1081. {
  1082. #if defined(_WIN32) && !defined(__CYGWIN__)
  1083. return SystemTools::ConvertToWindowsOutputPath(path);
  1084. #else
  1085. return SystemTools::ConvertToUnixOutputPath(path);
  1086. #endif
  1087. }
  1088. // remove double slashes not at the start
  1089. kwsys_stl::string SystemTools::ConvertToWindowsOutputPath(const char* path)
  1090. {
  1091. kwsys_stl::string ret = path;
  1092. kwsys_stl::string::size_type pos = 0;
  1093. // first convert all of the slashes
  1094. while((pos = ret.find('/', pos)) != kwsys_stl::string::npos)
  1095. {
  1096. ret[pos] = '\\';
  1097. pos++;
  1098. }
  1099. // check for really small paths
  1100. if(ret.size() < 2)
  1101. {
  1102. return ret;
  1103. }
  1104. // now clean up a bit and remove double slashes
  1105. // Only if it is not the first position in the path which is a network
  1106. // path on windows
  1107. pos = 1; // start at position 1
  1108. if(ret[0] == '\"')
  1109. {
  1110. pos = 2; // if the string is already quoted then start at 2
  1111. if(ret.size() < 3)
  1112. {
  1113. return ret;
  1114. }
  1115. }
  1116. while((pos = ret.find("\\\\", pos)) != kwsys_stl::string::npos)
  1117. {
  1118. ret.erase(pos, 1);
  1119. }
  1120. // now double quote the path if it has spaces in it
  1121. // and is not already double quoted
  1122. if(ret.find(" ") != kwsys_stl::string::npos
  1123. && ret[0] != '\"')
  1124. {
  1125. kwsys_stl::string result;
  1126. result = "\"" + ret + "\"";
  1127. ret = result;
  1128. }
  1129. return ret;
  1130. }
  1131. bool SystemTools::CopyFileIfDifferent(const char* source,
  1132. const char* destination)
  1133. {
  1134. if(SystemTools::FilesDiffer(source, destination))
  1135. {
  1136. return SystemTools::CopyFileAlways(source, destination);
  1137. }
  1138. return true;
  1139. }
  1140. bool SystemTools::FilesDiffer(const char* source,
  1141. const char* destination)
  1142. {
  1143. struct stat statSource;
  1144. if (stat(source, &statSource) != 0)
  1145. {
  1146. return true;
  1147. }
  1148. struct stat statDestination;
  1149. if (stat(destination, &statDestination) != 0)
  1150. {
  1151. return true;
  1152. }
  1153. if(statSource.st_size != statDestination.st_size)
  1154. {
  1155. return true;
  1156. }
  1157. if(statSource.st_size == 0)
  1158. {
  1159. return false;
  1160. }
  1161. #if defined(_WIN32) || defined(__CYGWIN__)
  1162. kwsys_ios::ifstream finSource(source, (kwsys_ios::ios::binary |
  1163. kwsys_ios::ios::in));
  1164. kwsys_ios::ifstream finDestination(destination, (kwsys_ios::ios::binary |
  1165. kwsys_ios::ios::in));
  1166. #else
  1167. kwsys_ios::ifstream finSource(source);
  1168. kwsys_ios::ifstream finDestination(destination);
  1169. #endif
  1170. if(!finSource || !finDestination)
  1171. {
  1172. return true;
  1173. }
  1174. char* source_buf = new char[statSource.st_size];
  1175. char* dest_buf = new char[statSource.st_size];
  1176. finSource.read(source_buf, statSource.st_size);
  1177. finDestination.read(dest_buf, statSource.st_size);
  1178. if(statSource.st_size != static_cast<long>(finSource.gcount()) ||
  1179. statSource.st_size != static_cast<long>(finDestination.gcount()))
  1180. {
  1181. // Failed to read files.
  1182. delete [] source_buf;
  1183. delete [] dest_buf;
  1184. return true;
  1185. }
  1186. int ret = memcmp((const void*)source_buf,
  1187. (const void*)dest_buf,
  1188. statSource.st_size);
  1189. delete [] dest_buf;
  1190. delete [] source_buf;
  1191. return ret != 0;
  1192. }
  1193. /**
  1194. * Copy a file named by "source" to the file named by "destination".
  1195. */
  1196. bool SystemTools::CopyFileAlways(const char* source, const char* destination)
  1197. {
  1198. // If files are the same do not copy
  1199. if ( SystemTools::SameFile(source, destination) )
  1200. {
  1201. return true;
  1202. }
  1203. mode_t perm = 0;
  1204. bool perms = SystemTools::GetPermissions(source, perm);
  1205. const int bufferSize = 4096;
  1206. char buffer[bufferSize];
  1207. // If destination is a directory, try to create a file with the same
  1208. // name as the source in that directory.
  1209. kwsys_stl::string new_destination;
  1210. if(SystemTools::FileExists(destination) &&
  1211. SystemTools::FileIsDirectory(destination))
  1212. {
  1213. new_destination = destination;
  1214. SystemTools::ConvertToUnixSlashes(new_destination);
  1215. new_destination += '/';
  1216. kwsys_stl::string source_name = source;
  1217. new_destination += SystemTools::GetFilenameName(source_name);
  1218. destination = new_destination.c_str();
  1219. }
  1220. // Create destination directory
  1221. kwsys_stl::string destination_dir = destination;
  1222. destination_dir = SystemTools::GetFilenamePath(destination_dir);
  1223. SystemTools::MakeDirectory(destination_dir.c_str());
  1224. // Open files
  1225. #if defined(_WIN32) || defined(__CYGWIN__)
  1226. kwsys_ios::ifstream fin(source,
  1227. kwsys_ios::ios::binary | kwsys_ios::ios::in);
  1228. #else
  1229. kwsys_ios::ifstream fin(source);
  1230. #endif
  1231. if(!fin)
  1232. {
  1233. return false;
  1234. }
  1235. // try and remove the destination file so that read only destination files
  1236. // can be written to.
  1237. // If the remove fails continue so that files in read only directories
  1238. // that do not allow file removal can be modified.
  1239. SystemTools::RemoveFile(destination);
  1240. #if defined(_WIN32) || defined(__CYGWIN__)
  1241. kwsys_ios::ofstream fout(destination,
  1242. kwsys_ios::ios::binary | kwsys_ios::ios::out | kwsys_ios::ios::trunc);
  1243. #else
  1244. kwsys_ios::ofstream fout(destination,
  1245. kwsys_ios::ios::out | kwsys_ios::ios::trunc);
  1246. #endif
  1247. if(!fout)
  1248. {
  1249. return false;
  1250. }
  1251. // This copy loop is very sensitive on certain platforms with
  1252. // slightly broken stream libraries (like HPUX). Normally, it is
  1253. // incorrect to not check the error condition on the fin.read()
  1254. // before using the data, but the fin.gcount() will be zero if an
  1255. // error occurred. Therefore, the loop should be safe everywhere.
  1256. while(fin)
  1257. {
  1258. fin.read(buffer, bufferSize);
  1259. if(fin.gcount())
  1260. {
  1261. fout.write(buffer, fin.gcount());
  1262. }
  1263. }
  1264. // Make sure the operating system has finished writing the file
  1265. // before closing it. This will ensure the file is finished before
  1266. // the check below.
  1267. fout.flush();
  1268. fin.close();
  1269. fout.close();
  1270. // More checks.
  1271. struct stat statSource, statDestination;
  1272. statSource.st_size = 12345;
  1273. statDestination.st_size = 12345;
  1274. if(stat(source, &statSource) != 0)
  1275. {
  1276. return false;
  1277. }
  1278. else if(stat(destination, &statDestination) != 0)
  1279. {
  1280. return false;
  1281. }
  1282. else if(statSource.st_size != statDestination.st_size)
  1283. {
  1284. return false;
  1285. }
  1286. if ( perms )
  1287. {
  1288. if ( !SystemTools::SetPermissions(destination, perm) )
  1289. {
  1290. return false;
  1291. }
  1292. }
  1293. return true;
  1294. }
  1295. /**
  1296. * Copy a directory content from "source" directory to the directory named by
  1297. * "destination".
  1298. */
  1299. bool SystemTools::CopyADirectory(const char* source, const char* destination)
  1300. {
  1301. Directory dir;
  1302. dir.Load(source);
  1303. size_t fileNum;
  1304. if ( !SystemTools::MakeDirectory(destination) )
  1305. {
  1306. return false;
  1307. }
  1308. for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum)
  1309. {
  1310. if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".") &&
  1311. strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".."))
  1312. {
  1313. kwsys_stl::string fullPath = source;
  1314. fullPath += "/";
  1315. fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
  1316. if(SystemTools::FileIsDirectory(fullPath.c_str()))
  1317. {
  1318. kwsys_stl::string fullDestPath = destination;
  1319. fullDestPath += "/";
  1320. fullDestPath += dir.GetFile(static_cast<unsigned long>(fileNum));
  1321. if (!SystemTools::CopyADirectory(fullPath.c_str(), fullDestPath.c_str()))
  1322. {
  1323. return false;
  1324. }
  1325. }
  1326. else
  1327. {
  1328. if(!SystemTools::CopyFileAlways(fullPath.c_str(), destination))
  1329. {
  1330. return false;
  1331. }
  1332. }
  1333. }
  1334. }
  1335. return true;
  1336. }
  1337. // return size of file; also returns zero if no file exists
  1338. unsigned long SystemTools::FileLength(const char* filename)
  1339. {
  1340. struct stat fs;
  1341. if (stat(filename, &fs) != 0)
  1342. {
  1343. return 0;
  1344. }
  1345. else
  1346. {
  1347. return static_cast<unsigned long>(fs.st_size);
  1348. }
  1349. }
  1350. int SystemTools::Strucmp(const char *s1, const char *s2)
  1351. {
  1352. // lifted from Graphvis http://www.graphviz.org
  1353. while ((*s1 != '\0')
  1354. && (tolower(*s1) == tolower(*s2)))
  1355. {
  1356. s1++;
  1357. s2++;
  1358. }
  1359. return tolower(*s1) - tolower(*s2);
  1360. }
  1361. // return file's modified time
  1362. long int SystemTools::ModifiedTime(const char* filename)
  1363. {
  1364. struct stat fs;
  1365. if (stat(filename, &fs) != 0)
  1366. {
  1367. return 0;
  1368. }
  1369. else
  1370. {
  1371. return (long int)fs.st_mtime;
  1372. }
  1373. }
  1374. // return file's creation time
  1375. long int SystemTools::CreationTime(const char* filename)
  1376. {
  1377. struct stat fs;
  1378. if (stat(filename, &fs) != 0)
  1379. {
  1380. return 0;
  1381. }
  1382. else
  1383. {
  1384. return fs.st_ctime >= 0 ? (long int)fs.st_ctime : 0;
  1385. }
  1386. }
  1387. bool SystemTools::ConvertDateMacroString(const char *str, time_t *tmt)
  1388. {
  1389. if (!str || !tmt || strlen(str) < 12)
  1390. {
  1391. return false;
  1392. }
  1393. struct tm tmt2;
  1394. // __DATE__
  1395. // The compilation date of the current source file. The date is a string
  1396. // literal of the form Mmm dd yyyy. The month name Mmm is the same as for
  1397. // dates generated by the library function asctime declared in TIME.H.
  1398. // index: 012345678901
  1399. // format: Mmm dd yyyy
  1400. // example: Dec 19 2003
  1401. static char month_names[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
  1402. char buffer[12];
  1403. strcpy(buffer, str);
  1404. buffer[3] = 0;
  1405. char *ptr = strstr(month_names, buffer);
  1406. if (!ptr)
  1407. {
  1408. return false;
  1409. }
  1410. int month = (ptr - month_names) / 3;
  1411. int day = atoi(buffer + 4);
  1412. int year = atoi(buffer + 7);
  1413. tmt2.tm_isdst = -1;
  1414. tmt2.tm_hour = 0;
  1415. tmt2.tm_min = 0;
  1416. tmt2.tm_sec = 0;
  1417. tmt2.tm_wday = 0;
  1418. tmt2.tm_yday = 0;
  1419. tmt2.tm_mday = day;
  1420. tmt2.tm_mon = month;
  1421. tmt2.tm_year = year - 1900;
  1422. *tmt = mktime(&tmt2);
  1423. return true;
  1424. }
  1425. bool SystemTools::ConvertTimeStampMacroString(const char *str, time_t *tmt)
  1426. {
  1427. if (!str || !tmt || strlen(str) < 27)
  1428. {
  1429. return false;
  1430. }
  1431. struct tm tmt2;
  1432. // __TIMESTAMP__
  1433. // The date and time of the last modification of the current source file,
  1434. // expressed as a string literal in the form Ddd Mmm Date hh:mm:ss yyyy,
  1435. /// where Ddd is the abbreviated day of the week and Date is an integer
  1436. // from 1 to 31.
  1437. // index: 0123456789
  1438. // 0123456789
  1439. // 0123456789
  1440. // format: Ddd Mmm Date hh:mm:ss yyyy
  1441. // example: Fri Dec 19 14:34:58 2003
  1442. static char month_names[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
  1443. char buffer[27];
  1444. strcpy(buffer, str);
  1445. buffer[7] = 0;
  1446. char *ptr = strstr(month_names, buffer + 4);
  1447. if (!ptr)
  1448. {
  1449. return false;
  1450. }
  1451. int month = (ptr - month_names) / 3;
  1452. int day = atoi(buffer + 8);
  1453. int hour = atoi(buffer + 11);
  1454. int min = atoi(buffer + 14);
  1455. int sec = atoi(buffer + 17);
  1456. int year = atoi(buffer + 20);
  1457. tmt2.tm_isdst = -1;
  1458. tmt2.tm_hour = hour;
  1459. tmt2.tm_min = min;
  1460. tmt2.tm_sec = sec;
  1461. tmt2.tm_wday = 0;
  1462. tmt2.tm_yday = 0;
  1463. tmt2.tm_mday = day;
  1464. tmt2.tm_mon = month;
  1465. tmt2.tm_year = year - 1900;
  1466. *tmt = mktime(&tmt2);
  1467. return true;
  1468. }
  1469. kwsys_stl::string SystemTools::GetLastSystemError()
  1470. {
  1471. int e = errno;
  1472. return strerror(e);
  1473. }
  1474. bool SystemTools::RemoveFile(const char* source)
  1475. {
  1476. #ifdef _WIN32
  1477. mode_t mode;
  1478. if ( !SystemTools::GetPermissions(source, mode) )
  1479. {
  1480. return false;
  1481. }
  1482. /* Win32 unlink is stupid --- it fails if the file is read-only */
  1483. SystemTools::SetPermissions(source, S_IWRITE);
  1484. #endif
  1485. bool res = unlink(source) != 0 ? false : true;
  1486. #ifdef _WIN32
  1487. if ( !res )
  1488. {
  1489. SystemTools::SetPermissions(source, mode);
  1490. }
  1491. #endif
  1492. return res;
  1493. }
  1494. bool SystemTools::RemoveADirectory(const char* source)
  1495. {
  1496. Directory dir;
  1497. dir.Load(source);
  1498. size_t fileNum;
  1499. for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum)
  1500. {
  1501. if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".") &&
  1502. strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".."))
  1503. {
  1504. kwsys_stl::string fullPath = source;
  1505. fullPath += "/";
  1506. fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
  1507. if(SystemTools::FileIsDirectory(fullPath.c_str()))
  1508. {
  1509. if (!SystemTools::RemoveADirectory(fullPath.c_str()))
  1510. {
  1511. return false;
  1512. }
  1513. }
  1514. else
  1515. {
  1516. if(!SystemTools::RemoveFile(fullPath.c_str()))
  1517. {
  1518. return false;
  1519. }
  1520. }
  1521. }
  1522. }
  1523. return (Rmdir(source) == 0);
  1524. }
  1525. /**
  1526. * Find the file the given name. Searches the given path and then
  1527. * the system search path. Returns the full path to the file if it is
  1528. * found. Otherwise, the empty string is returned.
  1529. */
  1530. kwsys_stl::string SystemTools
  1531. ::FindFile(const char* name,
  1532. const kwsys_stl::vector<kwsys_stl::string>& userPaths)
  1533. {
  1534. // Add the system search path to our path first
  1535. kwsys_stl::vector<kwsys_stl::string> path;
  1536. SystemTools::GetPath(path, "CMAKE_FILE_PATH");
  1537. SystemTools::GetPath(path);
  1538. // now add the additional paths
  1539. path.insert(path.end(), userPaths.begin(), userPaths.end());
  1540. // now look for the file
  1541. kwsys_stl::string tryPath;
  1542. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator p = path.begin();
  1543. p != path.end(); ++p)
  1544. {
  1545. tryPath = *p;
  1546. tryPath += "/";
  1547. tryPath += name;
  1548. if(SystemTools::FileExists(tryPath.c_str()) &&
  1549. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1550. {
  1551. return SystemTools::CollapseFullPath(tryPath.c_str());
  1552. }
  1553. }
  1554. // Couldn't find the file.
  1555. return "";
  1556. }
  1557. /**
  1558. * Find the executable with the given name. Searches the given path and then
  1559. * the system search path. Returns the full path to the executable if it is
  1560. * found. Otherwise, the empty string is returned.
  1561. */
  1562. kwsys_stl::string SystemTools::FindProgram(
  1563. const char* name,
  1564. const kwsys_stl::vector<kwsys_stl::string>& userPaths,
  1565. bool no_system_path)
  1566. {
  1567. if(!name)
  1568. {
  1569. return "";
  1570. }
  1571. // See if the executable exists as written.
  1572. if(SystemTools::FileExists(name) &&
  1573. !SystemTools::FileIsDirectory(name))
  1574. {
  1575. return SystemTools::CollapseFullPath(name);
  1576. }
  1577. kwsys_stl::string tryPath = name;
  1578. tryPath += SystemTools::GetExecutableExtension();
  1579. if(SystemTools::FileExists(tryPath.c_str()) &&
  1580. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1581. {
  1582. return SystemTools::CollapseFullPath(tryPath.c_str());
  1583. }
  1584. kwsys_stl::vector<kwsys_stl::string> path;
  1585. SystemTools::GetPath(path, "CMAKE_PROGRAM_PATH");
  1586. // Add the system search path to our path.
  1587. if (!no_system_path)
  1588. {
  1589. SystemTools::GetPath(path);
  1590. }
  1591. // now add the additional paths
  1592. path.insert(path.end(), userPaths.begin(), userPaths.end());
  1593. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator p = path.begin();
  1594. p != path.end(); ++p)
  1595. {
  1596. tryPath = *p;
  1597. tryPath += "/";
  1598. tryPath += name;
  1599. if(SystemTools::FileExists(tryPath.c_str()) &&
  1600. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1601. {
  1602. return SystemTools::CollapseFullPath(tryPath.c_str());
  1603. }
  1604. #ifdef _WIN32
  1605. tryPath += ".com";
  1606. if(SystemTools::FileExists(tryPath.c_str()) &&
  1607. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1608. {
  1609. return SystemTools::CollapseFullPath(tryPath.c_str());
  1610. }
  1611. tryPath = *p;
  1612. tryPath += "/";
  1613. tryPath += name;
  1614. #endif
  1615. tryPath += SystemTools::GetExecutableExtension();
  1616. if(SystemTools::FileExists(tryPath.c_str()) &&
  1617. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1618. {
  1619. return SystemTools::CollapseFullPath(tryPath.c_str());
  1620. }
  1621. }
  1622. // Couldn't find the program.
  1623. return "";
  1624. }
  1625. /**
  1626. * Find the library with the given name. Searches the given path and then
  1627. * the system search path. Returns the full path to the library if it is
  1628. * found. Otherwise, the empty string is returned.
  1629. */
  1630. kwsys_stl::string SystemTools
  1631. ::FindLibrary(const char* name,
  1632. const kwsys_stl::vector<kwsys_stl::string>& userPaths)
  1633. {
  1634. // See if the executable exists as written.
  1635. if(SystemTools::FileExists(name) &&
  1636. !SystemTools::FileIsDirectory(name))
  1637. {
  1638. return SystemTools::CollapseFullPath(name);
  1639. }
  1640. // Add the system search path to our path.
  1641. kwsys_stl::vector<kwsys_stl::string> path;
  1642. SystemTools::GetPath(path);
  1643. // now add the additional paths
  1644. path.insert(path.end(), userPaths.begin(), userPaths.end());
  1645. kwsys_stl::string tryPath;
  1646. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator p = path.begin();
  1647. p != path.end(); ++p)
  1648. {
  1649. #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__MINGW32__)
  1650. tryPath = *p;
  1651. tryPath += "/";
  1652. tryPath += name;
  1653. tryPath += ".lib";
  1654. if(SystemTools::FileExists(tryPath.c_str())
  1655. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1656. {
  1657. return SystemTools::CollapseFullPath(tryPath.c_str());
  1658. }
  1659. #else
  1660. tryPath = *p;
  1661. tryPath += "/lib";
  1662. tryPath += name;
  1663. tryPath += ".so";
  1664. if(SystemTools::FileExists(tryPath.c_str())
  1665. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1666. {
  1667. return SystemTools::CollapseFullPath(tryPath.c_str());
  1668. }
  1669. tryPath = *p;
  1670. tryPath += "/lib";
  1671. tryPath += name;
  1672. tryPath += ".a";
  1673. if(SystemTools::FileExists(tryPath.c_str())
  1674. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1675. {
  1676. return SystemTools::CollapseFullPath(tryPath.c_str());
  1677. }
  1678. tryPath = *p;
  1679. tryPath += "/lib";
  1680. tryPath += name;
  1681. tryPath += ".sl";
  1682. if(SystemTools::FileExists(tryPath.c_str())
  1683. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1684. {
  1685. return SystemTools::CollapseFullPath(tryPath.c_str());
  1686. }
  1687. tryPath = *p;
  1688. tryPath += "/lib";
  1689. tryPath += name;
  1690. tryPath += ".dylib";
  1691. if(SystemTools::FileExists(tryPath.c_str())
  1692. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1693. {
  1694. return SystemTools::CollapseFullPath(tryPath.c_str());
  1695. }
  1696. tryPath = *p;
  1697. tryPath += "/lib";
  1698. tryPath += name;
  1699. tryPath += ".dll";
  1700. if(SystemTools::FileExists(tryPath.c_str())
  1701. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1702. {
  1703. return SystemTools::CollapseFullPath(tryPath.c_str());
  1704. }
  1705. #endif
  1706. }
  1707. // Couldn't find the library.
  1708. return "";
  1709. }
  1710. bool SystemTools::FileIsDirectory(const char* name)
  1711. {
  1712. struct stat fs;
  1713. if(stat(name, &fs) == 0)
  1714. {
  1715. #if _WIN32
  1716. return ((fs.st_mode & _S_IFDIR) != 0);
  1717. #else
  1718. return S_ISDIR(fs.st_mode);
  1719. #endif
  1720. }
  1721. else
  1722. {
  1723. return false;
  1724. }
  1725. }
  1726. int SystemTools::ChangeDirectory(const char *dir)
  1727. {
  1728. return Chdir(dir);
  1729. }
  1730. kwsys_stl::string SystemTools::GetCurrentWorkingDirectory()
  1731. {
  1732. char buf[2048];
  1733. const char* cwd = Getcwd(buf, 2048);
  1734. kwsys_stl::string path;
  1735. if ( cwd )
  1736. {
  1737. path = cwd;
  1738. }
  1739. return SystemTools::CollapseFullPath(path.c_str());
  1740. }
  1741. kwsys_stl::string SystemTools::GetProgramPath(const char* in_name)
  1742. {
  1743. kwsys_stl::string dir, file;
  1744. SystemTools::SplitProgramPath(in_name, dir, file);
  1745. return dir;
  1746. }
  1747. bool SystemTools::SplitProgramPath(const char* in_name,
  1748. kwsys_stl::string& dir,
  1749. kwsys_stl::string& file,
  1750. bool)
  1751. {
  1752. dir = in_name;
  1753. file = "";
  1754. SystemTools::ConvertToUnixSlashes(dir);
  1755. if(!SystemTools::FileIsDirectory(dir.c_str()))
  1756. {
  1757. kwsys_stl::string::size_type slashPos = dir.rfind("/");
  1758. if(slashPos != kwsys_stl::string::npos)
  1759. {
  1760. file = dir.substr(slashPos+1);
  1761. dir = dir.substr(0, slashPos);
  1762. }
  1763. else
  1764. {
  1765. file = dir;
  1766. dir = "";
  1767. }
  1768. }
  1769. if(!(dir == "") && !SystemTools::FileIsDirectory(dir.c_str()))
  1770. {
  1771. kwsys_stl::string oldDir = in_name;
  1772. SystemTools::ConvertToUnixSlashes(oldDir);
  1773. dir = in_name;
  1774. return false;
  1775. }
  1776. return true;
  1777. }
  1778. bool SystemTools::FindProgramPath(const char* argv0,
  1779. kwsys_stl::string& pathOut,
  1780. kwsys_stl::string& errorMsg,
  1781. const char* exeName,
  1782. const char* buildDir,
  1783. const char* installPrefix )
  1784. {
  1785. kwsys_stl::vector<kwsys_stl::string> failures;
  1786. kwsys_stl::string self = argv0;
  1787. SystemTools::ConvertToUnixSlashes(self);
  1788. failures.push_back(argv0);
  1789. self = SystemTools::FindProgram(self.c_str());
  1790. if(!SystemTools::FileExists(self.c_str()))
  1791. {
  1792. if(buildDir)
  1793. {
  1794. kwsys_stl::string intdir = ".";
  1795. #ifdef CMAKE_INTDIR
  1796. intdir = CMAKE_INTDIR;
  1797. #endif
  1798. self = buildDir;
  1799. self += "/bin/";
  1800. self += intdir;
  1801. self += "/";
  1802. self += exeName;
  1803. self += SystemTools::GetExecutableExtension();
  1804. }
  1805. }
  1806. if(installPrefix)
  1807. {
  1808. if(!SystemTools::FileExists(self.c_str()))
  1809. {
  1810. failures.push_back(self);
  1811. self = installPrefix;
  1812. self += "/bin/";
  1813. self += exeName;
  1814. }
  1815. }
  1816. if(!SystemTools::FileExists(self.c_str()))
  1817. {
  1818. failures.push_back(self);
  1819. kwsys_ios::ostringstream msg;
  1820. msg << "Can not find the command line program " << exeName << "\n";
  1821. msg << " argv[0] = \"" << argv0 << "\"\n";
  1822. msg << " Attempted paths:\n";
  1823. kwsys_stl::vector<kwsys_stl::string>::iterator i;
  1824. for(i=failures.begin(); i != failures.end(); ++i)
  1825. {
  1826. msg << " \"" << i->c_str() << "\"\n";
  1827. }
  1828. errorMsg = msg.str();
  1829. return false;
  1830. }
  1831. pathOut = self;
  1832. return true;
  1833. }
  1834. kwsys_stl::string SystemTools::CollapseFullPath(const char* in_relative)
  1835. {
  1836. return SystemTools::CollapseFullPath(in_relative, 0);
  1837. }
  1838. void SystemTools::AddTranslationPath(const char * a, const char * b)
  1839. {
  1840. kwsys_stl::string path_a = a;
  1841. kwsys_stl::string path_b = b;
  1842. SystemTools::ConvertToUnixSlashes(path_a);
  1843. SystemTools::ConvertToUnixSlashes(path_b);
  1844. // First check this is a directory path, since we don't want the table to
  1845. // grow too fat
  1846. if( SystemTools::FileIsDirectory( path_a.c_str() ) )
  1847. {
  1848. // Make sure the path is a full path and does not contain no '..'
  1849. if( SystemTools::FileIsFullPath(path_b.c_str()) && path_b.find("..")
  1850. == kwsys_stl::string::npos )
  1851. {
  1852. // Before inserting make sure path ends with '/'
  1853. if(path_a.size() && path_a[path_a.size() -1] != '/')
  1854. {
  1855. path_a += '/';
  1856. }
  1857. if(path_b.size() && path_b[path_b.size() -1] != '/')
  1858. {
  1859. path_b += '/';
  1860. }
  1861. if( !(path_a == path_b) )
  1862. {
  1863. SystemTools::TranslationMap->insert(
  1864. SystemToolsTranslationMap::value_type(path_a, path_b));
  1865. }
  1866. }
  1867. }
  1868. }
  1869. void SystemTools::AddKeepPath(const char* dir)
  1870. {
  1871. kwsys_stl::string cdir = SystemTools::CollapseFullPath(dir);
  1872. SystemTools::AddTranslationPath(cdir.c_str(), dir);
  1873. }
  1874. void SystemTools::CheckTranslationPath(kwsys_stl::string & path)
  1875. {
  1876. // Do not translate paths that are too short to have meaningful
  1877. // translations.
  1878. if(path.size() < 2)
  1879. {
  1880. return;
  1881. }
  1882. // Always add a trailing slash before translation. It does not
  1883. // matter if this adds an extra slash, but we do not want to
  1884. // translate part of a directory (like the foo part of foo-dir).
  1885. path += "/";
  1886. // In case a file was specified we still have to go through this:
  1887. // Now convert any path found in the table back to the one desired:
  1888. kwsys_stl::map<kwsys_stl::string,kwsys_stl::string>::const_iterator it;
  1889. for(it = SystemTools::TranslationMap->begin();
  1890. it != SystemTools::TranslationMap->end();
  1891. ++it )
  1892. {
  1893. // We need to check of the path is a substring of the other path
  1894. if(path.find( it->first ) == 0)
  1895. {
  1896. path = path.replace( 0, it->first.size(), it->second);
  1897. }
  1898. }
  1899. // Remove the trailing slash we added before.
  1900. path.erase(path.end()-1, path.end());
  1901. }
  1902. void
  1903. SystemToolsAppendComponents(
  1904. kwsys_stl::vector<kwsys_stl::string>& out_components,
  1905. kwsys_stl::vector<kwsys_stl::string>::const_iterator first,
  1906. kwsys_stl::vector<kwsys_stl::string>::const_iterator last)
  1907. {
  1908. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator i = first;
  1909. i != last; ++i)
  1910. {
  1911. if(*i == "..")
  1912. {
  1913. if(out_components.begin() != out_components.end())
  1914. {
  1915. out_components.erase(out_components.end()-1, out_components.end());
  1916. }
  1917. }
  1918. else if(*i != "." && *i != "")
  1919. {
  1920. out_components.push_back(*i);
  1921. }
  1922. }
  1923. }
  1924. kwsys_stl::string SystemTools::CollapseFullPath(const char* in_path,
  1925. const char* in_base)
  1926. {
  1927. // Collect the output path components.
  1928. kwsys_stl::vector<kwsys_stl::string> out_components;
  1929. // Split the input path components.
  1930. kwsys_stl::vector<kwsys_stl::string> path_components;
  1931. SystemTools::SplitPath(in_path, path_components);
  1932. // If the input path is relative, start with a base path.
  1933. if(path_components[0].length() == 0)
  1934. {
  1935. kwsys_stl::vector<kwsys_stl::string> base_components;
  1936. if(in_base)
  1937. {
  1938. // Use the given base path.
  1939. SystemTools::SplitPath(in_base, base_components);
  1940. }
  1941. else
  1942. {
  1943. // Use the current working directory as a base path.
  1944. char buf[2048];
  1945. if(const char* cwd = Getcwd(buf, 2048))
  1946. {
  1947. SystemTools::SplitPath(cwd, base_components);
  1948. }
  1949. else
  1950. {
  1951. // ??
  1952. }
  1953. }
  1954. // Append base path components to the output path.
  1955. out_components.push_back(base_components[0]);
  1956. SystemToolsAppendComponents(out_components,
  1957. base_components.begin()+1,
  1958. base_components.end());
  1959. }
  1960. // Append input path components to the output path.
  1961. SystemToolsAppendComponents(out_components,
  1962. path_components.begin(),
  1963. path_components.end());
  1964. // Transform the path back to a string.
  1965. kwsys_stl::string newPath = SystemTools::JoinPath(out_components);
  1966. // Update the translation table with this potentially new path.
  1967. SystemTools::AddTranslationPath(newPath.c_str(), in_path);
  1968. SystemTools::CheckTranslationPath(newPath);
  1969. // Return the reconstructed path.
  1970. return newPath;
  1971. }
  1972. //----------------------------------------------------------------------------
  1973. void SystemTools::SplitPath(const char* p,
  1974. kwsys_stl::vector<kwsys_stl::string>& components)
  1975. {
  1976. components.clear();
  1977. // Identify the root component.
  1978. const char* c = p;
  1979. if(c[0] == '/' && c[1] == '/')
  1980. {
  1981. // Network path.
  1982. components.push_back("//");
  1983. c += 2;
  1984. }
  1985. else if(c[0] == '/')
  1986. {
  1987. // Unix path.
  1988. components.push_back("/");
  1989. c += 1;
  1990. }
  1991. else if(c[0] && c[1] == ':' && c[2] == '/')
  1992. {
  1993. // Windows path.
  1994. kwsys_stl::string root = "_:/";
  1995. root[0] = c[0];
  1996. components.push_back(root);
  1997. c += 3;
  1998. }
  1999. else if(c[0] && c[1] == ':')
  2000. {
  2001. // Path relative to a windows drive working directory.
  2002. kwsys_stl::string root = "_:";
  2003. root[0] = c[0];
  2004. components.push_back(root);
  2005. c += 2;
  2006. }
  2007. else
  2008. {
  2009. // Relative path.
  2010. components.push_back("");
  2011. }
  2012. // Parse the remaining components.
  2013. const char* first = c;
  2014. const char* last = first;
  2015. for(;*last; ++last)
  2016. {
  2017. if(*last == '/')
  2018. {
  2019. // End of a component. Save it.
  2020. components.push_back(kwsys_stl::string(first, last-first));
  2021. first = last+1;
  2022. }
  2023. }
  2024. // Save the last component unless there were no components.
  2025. if(last != c)
  2026. {
  2027. components.push_back(kwsys_stl::string(first, last-first));
  2028. }
  2029. }
  2030. //----------------------------------------------------------------------------
  2031. kwsys_stl::string
  2032. SystemTools::JoinPath(const kwsys_stl::vector<kwsys_stl::string>& components)
  2033. {
  2034. kwsys_stl::string result;
  2035. if(components.size() > 0)
  2036. {
  2037. result += components[0];
  2038. }
  2039. if(components.size() > 1)
  2040. {
  2041. result += components[1];
  2042. }
  2043. for(unsigned int i=2; i < components.size(); ++i)
  2044. {
  2045. result += "/";
  2046. result += components[i];
  2047. }
  2048. return result;
  2049. }
  2050. //----------------------------------------------------------------------------
  2051. bool SystemTools::ComparePath(const char* c1, const char* c2)
  2052. {
  2053. #if defined(_WIN32) || defined(__APPLE__)
  2054. return SystemTools::Strucmp(c1, c2) == 0;
  2055. #else
  2056. return strcmp(c1, c2) == 0;
  2057. #endif
  2058. }
  2059. bool SystemTools::Split(const char* str, kwsys_stl::vector<kwsys_stl::string>& lines)
  2060. {
  2061. kwsys_stl::string data(str);
  2062. kwsys_stl::string::size_type lpos = 0;
  2063. while(lpos < data.length())
  2064. {
  2065. kwsys_stl::string::size_type rpos = data.find_first_of("\n", lpos);
  2066. if(rpos == kwsys_stl::string::npos)
  2067. {
  2068. // Line ends at end of string without a newline.
  2069. lines.push_back(data.substr(lpos));
  2070. return false;
  2071. }
  2072. if((rpos > lpos) && (data[rpos-1] == '\r'))
  2073. {
  2074. // Line ends in a "\r\n" pair, remove both characters.
  2075. lines.push_back(data.substr(lpos, (rpos-1)-lpos));
  2076. }
  2077. else
  2078. {
  2079. // Line ends in a "\n", remove the character.
  2080. lines.push_back(data.substr(lpos, rpos-lpos));
  2081. }
  2082. lpos = rpos+1;
  2083. }
  2084. return true;
  2085. }
  2086. /**
  2087. * Return path of a full filename (no trailing slashes).
  2088. * Warning: returned path is converted to Unix slashes format.
  2089. */
  2090. kwsys_stl::string SystemTools::GetFilenamePath(const kwsys_stl::string& filename)
  2091. {
  2092. kwsys_stl::string fn = filename;
  2093. SystemTools::ConvertToUnixSlashes(fn);
  2094. kwsys_stl::string::size_type slash_pos = fn.rfind("/");
  2095. if(slash_pos != kwsys_stl::string::npos)
  2096. {
  2097. return fn.substr(0, slash_pos);
  2098. }
  2099. else
  2100. {
  2101. return "";
  2102. }
  2103. }
  2104. /**
  2105. * Return file name of a full filename (i.e. file name without path).
  2106. */
  2107. kwsys_stl::string SystemTools::GetFilenameName(const kwsys_stl::string& filename)
  2108. {
  2109. kwsys_stl::string fn = filename;
  2110. SystemTools::ConvertToUnixSlashes(fn);
  2111. kwsys_stl::string::size_type slash_pos = fn.rfind("/");
  2112. if(slash_pos != kwsys_stl::string::npos)
  2113. {
  2114. return fn.substr(slash_pos + 1);
  2115. }
  2116. else
  2117. {
  2118. return filename;
  2119. }
  2120. }
  2121. /**
  2122. * Return file extension of a full filename (dot included).
  2123. * Warning: this is the longest extension (for example: .tar.gz)
  2124. */
  2125. kwsys_stl::string SystemTools::GetFilenameExtension(const kwsys_stl::string& filename)
  2126. {
  2127. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  2128. kwsys_stl::string::size_type dot_pos = name.find(".");
  2129. if(dot_pos != kwsys_stl::string::npos)
  2130. {
  2131. return name.substr(dot_pos);
  2132. }
  2133. else
  2134. {
  2135. return "";
  2136. }
  2137. }
  2138. /**
  2139. * Return file extension of a full filename (dot included).
  2140. * Warning: this is the shortest extension (for example: .tar.gz)
  2141. */
  2142. kwsys_stl::string SystemTools::GetFilenameLastExtension(const kwsys_stl::string& filename)
  2143. {
  2144. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  2145. kwsys_stl::string::size_type dot_pos = name.rfind(".");
  2146. if(dot_pos != kwsys_stl::string::npos)
  2147. {
  2148. return name.substr(dot_pos);
  2149. }
  2150. else
  2151. {
  2152. return "";
  2153. }
  2154. }
  2155. /**
  2156. * Return file name without extension of a full filename (i.e. without path).
  2157. * Warning: it considers the longest extension (for example: .tar.gz)
  2158. */
  2159. kwsys_stl::string SystemTools::GetFilenameWithoutExtension(const kwsys_stl::string& filename)
  2160. {
  2161. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  2162. kwsys_stl::string::size_type dot_pos = name.find(".");
  2163. if(dot_pos != kwsys_stl::string::npos)
  2164. {
  2165. return name.substr(0, dot_pos);
  2166. }
  2167. else
  2168. {
  2169. return name;
  2170. }
  2171. }
  2172. /**
  2173. * Return file name without extension of a full filename (i.e. without path).
  2174. * Warning: it considers the last extension (for example: removes .gz
  2175. * from .tar.gz)
  2176. */
  2177. kwsys_stl::string
  2178. SystemTools::GetFilenameWithoutLastExtension(const kwsys_stl::string& filename)
  2179. {
  2180. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  2181. kwsys_stl::string::size_type dot_pos = name.rfind(".");
  2182. if(dot_pos != kwsys_stl::string::npos)
  2183. {
  2184. return name.substr(0, dot_pos);
  2185. }
  2186. else
  2187. {
  2188. return name;
  2189. }
  2190. }
  2191. bool SystemTools::FileHasSignature(const char *filename,
  2192. const char *signature,
  2193. long offset)
  2194. {
  2195. if (!filename || !signature)
  2196. {
  2197. return false;
  2198. }
  2199. FILE *fp;
  2200. fp = fopen(filename, "rb");
  2201. if (!fp)
  2202. {
  2203. return false;
  2204. }
  2205. fseek(fp, offset, SEEK_SET);
  2206. bool res = false;
  2207. size_t signature_len = strlen(signature);
  2208. char *buffer = new char [signature_len];
  2209. if (fread(buffer, 1, signature_len, fp) == signature_len)
  2210. {
  2211. res = (!strncmp(buffer, signature, signature_len) ? true : false);
  2212. }
  2213. delete [] buffer;
  2214. fclose(fp);
  2215. return res;
  2216. }
  2217. bool SystemTools::LocateFileInDir(const char *filename,
  2218. const char *dir,
  2219. kwsys_stl::string& filename_found,
  2220. int try_filename_dirs)
  2221. {
  2222. if (!filename || !dir)
  2223. {
  2224. return false;
  2225. }
  2226. // Get the basename of 'filename'
  2227. kwsys_stl::string filename_base = SystemTools::GetFilenameName(filename);
  2228. // Check if 'dir' is really a directory
  2229. // If win32 and matches something like C:, accept it as a dir
  2230. kwsys_stl::string real_dir;
  2231. if (!SystemTools::FileIsDirectory(dir))
  2232. {
  2233. #if _WIN32
  2234. size_t dir_len = strlen(dir);
  2235. if (dir_len < 2 || dir[dir_len - 1] != ':')
  2236. {
  2237. #endif
  2238. real_dir = SystemTools::GetFilenamePath(dir);
  2239. dir = real_dir.c_str();
  2240. #if _WIN32
  2241. }
  2242. #endif
  2243. }
  2244. // Try to find the file in 'dir'
  2245. bool res = false;
  2246. if (filename_base.size() && dir)
  2247. {
  2248. size_t dir_len = strlen(dir);
  2249. int need_slash =
  2250. (dir_len && dir[dir_len - 1] != '/' && dir[dir_len - 1] != '\\');
  2251. kwsys_stl::string temp = dir;
  2252. if (need_slash)
  2253. {
  2254. temp += "/";
  2255. }
  2256. temp += filename_base;
  2257. if (SystemTools::FileExists(filename_found.c_str()))
  2258. {
  2259. res = true;
  2260. filename_found = temp;
  2261. }
  2262. // If not found, we can try harder by appending part of the file to
  2263. // to the directory to look inside.
  2264. // Example: if we were looking for /foo/bar/yo.txt in /d1/d2, then
  2265. // try to find yo.txt in /d1/d2/bar, then /d1/d2/foo/bar, etc.
  2266. else if (try_filename_dirs)
  2267. {
  2268. kwsys_stl::string filename_dir(filename);
  2269. kwsys_stl::string filename_dir_base;
  2270. kwsys_stl::string filename_dir_bases;
  2271. do
  2272. {
  2273. filename_dir = SystemTools::GetFilenamePath(filename_dir);
  2274. filename_dir_base = SystemTools::GetFilenameName(filename_dir);
  2275. #if _WIN32
  2276. if (!filename_dir_base.size() ||
  2277. filename_dir_base[filename_dir_base.size() - 1] == ':')
  2278. #else
  2279. if (!filename_dir_base.size())
  2280. #endif
  2281. {
  2282. break;
  2283. }
  2284. filename_dir_bases = filename_dir_base + "/" + filename_dir_bases;
  2285. temp = dir;
  2286. if (need_slash)
  2287. {
  2288. temp += "/";
  2289. }
  2290. temp += filename_dir_bases;
  2291. res = SystemTools::LocateFileInDir(
  2292. filename_base.c_str(), temp.c_str(), filename_found, 0);
  2293. } while (!res && filename_dir_base.size());
  2294. }
  2295. }
  2296. return res;
  2297. }
  2298. bool SystemTools::FileIsFullPath(const char* in_name)
  2299. {
  2300. kwsys_stl::string name = in_name;
  2301. #if defined(_WIN32) || defined(__CYGWIN__)
  2302. // On Windows, the name must be at least two characters long.
  2303. if(name.length() < 2)
  2304. {
  2305. return false;
  2306. }
  2307. if(name[1] == ':')
  2308. {
  2309. return true;
  2310. }
  2311. if(name[0] == '\\')
  2312. {
  2313. return true;
  2314. }
  2315. #else
  2316. // On UNIX, the name must be at least one character long.
  2317. if(name.length() < 1)
  2318. {
  2319. return false;
  2320. }
  2321. #endif
  2322. // On UNIX, the name must begin in a '/'.
  2323. // On Windows, if the name begins in a '/', then it is a full
  2324. // network path.
  2325. if(name[0] == '/')
  2326. {
  2327. return true;
  2328. }
  2329. return false;
  2330. }
  2331. bool SystemTools::GetShortPath(const char* path, kwsys_stl::string& shortPath)
  2332. {
  2333. #if defined(WIN32) && !defined(__CYGWIN__)
  2334. const int size = int(strlen(path)) +1; // size of return
  2335. char *buffer = new char[size]; // create a buffer
  2336. char *tempPath = new char[size]; // create a buffer
  2337. int ret;
  2338. // if the path passed in has quotes around it, first remove the quotes
  2339. if (path[0] == '"' && path[strlen(path)-1] == '"')
  2340. {
  2341. strcpy(tempPath,path+1);
  2342. tempPath[strlen(tempPath)-1] = '\0';
  2343. }
  2344. else
  2345. {
  2346. strcpy(tempPath,path);
  2347. }
  2348. buffer[0] = 0;
  2349. ret = GetShortPathName(tempPath, buffer, size);
  2350. if(buffer[0] == 0 || ret > size)
  2351. {
  2352. delete [] buffer;
  2353. delete [] tempPath;
  2354. return false;
  2355. }
  2356. else
  2357. {
  2358. shortPath = buffer;
  2359. delete [] buffer;
  2360. delete [] tempPath;
  2361. return true;
  2362. }
  2363. #else
  2364. shortPath = path;
  2365. return true;
  2366. #endif
  2367. }
  2368. void SystemTools::SplitProgramFromArgs(const char* path,
  2369. kwsys_stl::string& program, kwsys_stl::string& args)
  2370. {
  2371. // see if this is a full path to a program
  2372. // if so then set program to path and args to nothing
  2373. if(SystemTools::FileExists(path))
  2374. {
  2375. program = path;
  2376. args = "";
  2377. return;
  2378. }
  2379. // Try to find the program in the path, note the program
  2380. // may have spaces in its name so we have to look for it
  2381. kwsys_stl::vector<kwsys_stl::string> e;
  2382. kwsys_stl::string findProg = SystemTools::FindProgram(path, e);
  2383. if(findProg.size())
  2384. {
  2385. program = findProg;
  2386. args = "";
  2387. return;
  2388. }
  2389. // Now try and peel off space separated chunks from the end of the string
  2390. // so the largest path possible is found allowing for spaces in the path
  2391. kwsys_stl::string dir = path;
  2392. kwsys_stl::string::size_type spacePos = dir.rfind(' ');
  2393. while(spacePos != kwsys_stl::string::npos)
  2394. {
  2395. kwsys_stl::string tryProg = dir.substr(0, spacePos);
  2396. // See if the file exists
  2397. if(SystemTools::FileExists(tryProg.c_str()))
  2398. {
  2399. program = tryProg;
  2400. // remove trailing spaces from program
  2401. kwsys_stl::string::size_type pos = program.size()-1;
  2402. while(program[pos] == ' ')
  2403. {
  2404. program.erase(pos);
  2405. pos--;
  2406. }
  2407. args = dir.substr(spacePos, dir.size()-spacePos);
  2408. return;
  2409. }
  2410. // Now try and find the the program in the path
  2411. findProg = SystemTools::FindProgram(tryProg.c_str(), e);
  2412. if(findProg.size())
  2413. {
  2414. program = findProg;
  2415. // remove trailing spaces from program
  2416. kwsys_stl::string::size_type pos = program.size()-1;
  2417. while(program[pos] == ' ')
  2418. {
  2419. program.erase(pos);
  2420. pos--;
  2421. }
  2422. args = dir.substr(spacePos, dir.size()-spacePos);
  2423. return;
  2424. }
  2425. // move past the space for the next search
  2426. spacePos--;
  2427. spacePos = dir.rfind(' ', spacePos);
  2428. }
  2429. program = "";
  2430. args = "";
  2431. }
  2432. kwsys_stl::string SystemTools::GetCurrentDateTime(const char* format)
  2433. {
  2434. char buf[1024];
  2435. time_t t;
  2436. time(&t);
  2437. strftime(buf, sizeof(buf), format, localtime(&t));
  2438. return buf;
  2439. }
  2440. kwsys_stl::string SystemTools::MakeCindentifier(const char* s)
  2441. {
  2442. kwsys_stl::string str(s);
  2443. if (str.find_first_of("0123456789") == 0)
  2444. {
  2445. str = "_" + str;
  2446. }
  2447. kwsys_stl::string permited_chars("_"
  2448. "abcdefghijklmnopqrstuvwxyz"
  2449. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  2450. "0123456789");
  2451. kwsys_stl::string::size_type pos = 0;
  2452. while ((pos = str.find_first_not_of(permited_chars, pos)) != kwsys_stl::string::npos)
  2453. {
  2454. str[pos] = '_';
  2455. }
  2456. return str;
  2457. }
  2458. // Due to a buggy stream library on the HP and another on Mac OSX, we
  2459. // need this very carefully written version of getline. Returns true
  2460. // if any data were read before the end-of-file was reached.
  2461. bool SystemTools::GetLineFromStream(kwsys_ios::istream& is, kwsys_stl::string& line,
  2462. bool *has_newline /* = 0 */)
  2463. {
  2464. const int bufferSize = 1024;
  2465. char buffer[bufferSize];
  2466. line = "";
  2467. bool haveData = false;
  2468. if ( has_newline )
  2469. {
  2470. *has_newline = false;
  2471. }
  2472. // If no characters are read from the stream, the end of file has
  2473. // been reached.
  2474. while((is.getline(buffer, bufferSize), is.gcount() > 0))
  2475. {
  2476. haveData = true;
  2477. line.append(buffer);
  2478. // If newline character was read, the gcount includes the
  2479. // character, but the buffer does not. The end of line has been
  2480. // reached.
  2481. if(strlen(buffer) < static_cast<size_t>(is.gcount()))
  2482. {
  2483. if ( has_newline )
  2484. {
  2485. *has_newline = true;
  2486. }
  2487. break;
  2488. }
  2489. // The fail bit may be set. Clear it.
  2490. is.clear(is.rdstate() & ~kwsys_ios::ios::failbit);
  2491. }
  2492. return haveData;
  2493. }
  2494. int SystemTools::GetTerminalWidth()
  2495. {
  2496. int width = -1;
  2497. #ifndef _WIN32
  2498. struct winsize ws;
  2499. char *columns; /* Unix98 environment variable */
  2500. if(ioctl(1, TIOCGWINSZ, &ws) != -1 && ws.ws_col>0 && ws.ws_row>0)
  2501. {
  2502. width = ws.ws_col;
  2503. }
  2504. if(!isatty(STDOUT_FILENO))
  2505. {
  2506. width = -1;
  2507. }
  2508. columns = getenv("COLUMNS");
  2509. if(columns && *columns)
  2510. {
  2511. long t;
  2512. char *endptr;
  2513. t = strtol(columns, &endptr, 0);
  2514. if(endptr && !*endptr && (t>0) && (t<1000))
  2515. {
  2516. width = (int)t;
  2517. }
  2518. }
  2519. if ( width < 9 )
  2520. {
  2521. width = -1;
  2522. }
  2523. #endif
  2524. return width;
  2525. }
  2526. bool SystemTools::GetPermissions(const char* file, mode_t& mode)
  2527. {
  2528. if ( !file )
  2529. {
  2530. return false;
  2531. }
  2532. struct stat st;
  2533. if ( stat(file, &st) < 0 )
  2534. {
  2535. return false;
  2536. }
  2537. mode = st.st_mode;
  2538. return true;
  2539. }
  2540. bool SystemTools::SetPermissions(const char* file, mode_t mode)
  2541. {
  2542. if ( !file )
  2543. {
  2544. return false;
  2545. }
  2546. if ( !SystemTools::FileExists(file) )
  2547. {
  2548. return false;
  2549. }
  2550. if ( chmod(file, mode) < 0 )
  2551. {
  2552. return false;
  2553. }
  2554. return true;
  2555. }
  2556. kwsys_stl::string SystemTools::GetParentDirectory(const char* fileOrDir)
  2557. {
  2558. if ( !fileOrDir || !*fileOrDir )
  2559. {
  2560. return "";
  2561. }
  2562. kwsys_stl::string res = fileOrDir;
  2563. SystemTools::ConvertToUnixSlashes(res);
  2564. kwsys_stl::string::size_type cc = res.size()-1;
  2565. if ( res[cc] == '/' )
  2566. {
  2567. cc --;
  2568. }
  2569. for ( ; cc > 0; cc -- )
  2570. {
  2571. if ( res[cc] == '/' )
  2572. {
  2573. break;
  2574. }
  2575. }
  2576. return res.substr(0, cc);
  2577. }
  2578. bool SystemTools::IsSubDirectory(const char* cSubdir, const char* cDir)
  2579. {
  2580. kwsys_stl::string subdir = cSubdir;
  2581. kwsys_stl::string dir = cDir;
  2582. SystemTools::ConvertToUnixSlashes(dir);
  2583. kwsys_stl::string path = subdir;
  2584. do
  2585. {
  2586. path = SystemTools::GetParentDirectory(path.c_str());
  2587. if ( dir == path )
  2588. {
  2589. return true;
  2590. }
  2591. }
  2592. while ( path.size() > dir.size() );
  2593. return false;
  2594. }
  2595. kwsys_stl::string SystemTools::FileExistsInParentDirectories(const char* fname,
  2596. const char* directory, const char* toplevel)
  2597. {
  2598. kwsys_stl::string file = fname;
  2599. SystemTools::ConvertToUnixSlashes(file);
  2600. kwsys_stl::string dir = directory;
  2601. SystemTools::ConvertToUnixSlashes(dir);
  2602. while ( !dir.empty() )
  2603. {
  2604. kwsys_stl::string path = dir + "/" + file;
  2605. if ( SystemTools::FileExists(path.c_str()) )
  2606. {
  2607. return path;
  2608. }
  2609. if ( dir.size() < strlen(toplevel) )
  2610. {
  2611. break;
  2612. }
  2613. dir = SystemTools::GetParentDirectory(dir.c_str());
  2614. }
  2615. return "";
  2616. }
  2617. void SystemTools::Delay(unsigned int msec)
  2618. {
  2619. #ifdef _WIN32
  2620. Sleep(msec);
  2621. #else
  2622. usleep(msec * 1000);
  2623. #endif
  2624. }
  2625. // These must NOT be initialized. Default initialization to zero is
  2626. // necessary.
  2627. unsigned int SystemToolsManagerCount;
  2628. SystemToolsTranslationMap *SystemTools::TranslationMap;
  2629. // SystemToolsManager manages the SystemTools singleton.
  2630. // SystemToolsManager should be included in any translation unit
  2631. // that will use SystemTools or that implements the singleton
  2632. // pattern. It makes sure that the SystemTools singleton is created
  2633. // before and destroyed after all other singletons in CMake.
  2634. SystemToolsManager::SystemToolsManager()
  2635. {
  2636. if(++SystemToolsManagerCount == 1)
  2637. {
  2638. SystemTools::ClassInitialize();
  2639. }
  2640. }
  2641. SystemToolsManager::~SystemToolsManager()
  2642. {
  2643. if(--SystemToolsManagerCount == 0)
  2644. {
  2645. SystemTools::ClassFinalize();
  2646. }
  2647. }
  2648. void SystemTools::ClassInitialize()
  2649. {
  2650. // Allocate the translation map first.
  2651. SystemTools::TranslationMap = new SystemToolsTranslationMap;
  2652. // Add some special translation paths for unix. These are not added
  2653. // for windows because drive letters need to be maintained. Also,
  2654. // there are not sym-links and mount points on windows anyway.
  2655. #if !defined(_WIN32) || defined(__CYGWIN__)
  2656. // Work-around an SGI problem by always adding this mapping:
  2657. SystemTools::AddTranslationPath("/tmp_mnt/", "/");
  2658. // The tmp path is frequently a logical path so always keep it:
  2659. SystemTools::AddKeepPath("/tmp/");
  2660. // If the current working directory is a logical path then keep the
  2661. // logical name.
  2662. if(const char* pwd = getenv("PWD"))
  2663. {
  2664. char buf[2048];
  2665. if(const char* cwd = Getcwd(buf, 2048))
  2666. {
  2667. kwsys_stl::string pwd_path;
  2668. Realpath(pwd, pwd_path);
  2669. if(cwd == pwd_path && strcmp(cwd, pwd) != 0)
  2670. {
  2671. // The current working directory is a logical path. Split
  2672. // both the logical and physical paths into their components.
  2673. kwsys_stl::vector<kwsys_stl::string> cwd_components;
  2674. kwsys_stl::vector<kwsys_stl::string> pwd_components;
  2675. SystemTools::SplitPath(cwd, cwd_components);
  2676. SystemTools::SplitPath(pwd, pwd_components);
  2677. // Remove the common ending of the paths to leave only the
  2678. // part that changes under the logical mapping.
  2679. kwsys_stl::vector<kwsys_stl::string>::iterator ic = cwd_components.end();
  2680. kwsys_stl::vector<kwsys_stl::string>::iterator ip = pwd_components.end();
  2681. for(;ip != pwd_components.begin() && ic != cwd_components.begin() &&
  2682. *(ip-1) == *(ic-1); --ip,--ic);
  2683. cwd_components.erase(ic, cwd_components.end());
  2684. pwd_components.erase(ip, pwd_components.end());
  2685. // Reconstruct the string versions of the part of the path
  2686. // that changed.
  2687. kwsys_stl::string cwd_changed = SystemTools::JoinPath(cwd_components);
  2688. kwsys_stl::string pwd_changed = SystemTools::JoinPath(pwd_components);
  2689. // Add the translation to keep the logical path name.
  2690. if(!cwd_changed.empty() && !pwd_changed.empty())
  2691. {
  2692. SystemTools::AddTranslationPath(cwd_changed.c_str(),
  2693. pwd_changed.c_str());
  2694. }
  2695. }
  2696. }
  2697. }
  2698. #endif
  2699. }
  2700. void SystemTools::ClassFinalize()
  2701. {
  2702. delete SystemTools::TranslationMap;
  2703. }
  2704. } // namespace KWSYS_NAMESPACE
  2705. #if defined(_MSC_VER) && defined(_DEBUG)
  2706. # include <crtdbg.h>
  2707. # include <stdio.h>
  2708. # include <stdlib.h>
  2709. namespace KWSYS_NAMESPACE
  2710. {
  2711. static int SystemToolsDebugReport(int, char* message, int*)
  2712. {
  2713. fprintf(stderr, message);
  2714. exit(1);
  2715. }
  2716. void SystemTools::EnableMSVCDebugHook()
  2717. {
  2718. if(getenv("DART_TEST_FROM_DART"))
  2719. {
  2720. _CrtSetReportHook(SystemToolsDebugReport);
  2721. }
  2722. }
  2723. } // namespace KWSYS_NAMESPACE
  2724. #else
  2725. namespace KWSYS_NAMESPACE
  2726. {
  2727. void SystemTools::EnableMSVCDebugHook() {}
  2728. } // namespace KWSYS_NAMESPACE
  2729. #endif