SystemTools.cxx 90 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787
  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. // Work-around CMake dependency scanning limitation. This must
  17. // duplicate the above list of headers.
  18. #if 0
  19. # include "SystemTools.hxx.in"
  20. # include "Directory.hxx.in"
  21. # include "kwsys_ios_iostream.h.in"
  22. # include "kwsys_ios_fstream.h.in"
  23. # include "kwsys_ios_sstream.h.in"
  24. #endif
  25. #ifdef _MSC_VER
  26. # pragma warning (disable: 4786)
  27. #endif
  28. #if defined(__sgi) && !defined(__GNUC__)
  29. # pragma set woff 1375 /* base class destructor not virtual */
  30. #endif
  31. #include <ctype.h>
  32. #include <errno.h>
  33. #ifdef __QNX__
  34. # include <malloc.h> /* for malloc/free on QNX */
  35. #endif
  36. #include <stdio.h>
  37. #include <stdlib.h>
  38. #include <string.h>
  39. #include <sys/stat.h>
  40. #include <time.h>
  41. // support for realpath call
  42. #ifndef _WIN32
  43. #include <limits.h>
  44. #include <sys/param.h>
  45. #include <sys/wait.h>
  46. #include <sys/ioctl.h>
  47. #include <unistd.h>
  48. #include <termios.h>
  49. #endif
  50. // Windows API. Some parts used even on cygwin.
  51. #if defined(_WIN32)
  52. # include <windows.h>
  53. #endif
  54. // This is a hack to prevent warnings about these functions being
  55. // declared but not referenced.
  56. #if defined(__sgi) && !defined(__GNUC__)
  57. # include <sys/termios.h>
  58. namespace KWSYS_NAMESPACE
  59. {
  60. class SystemToolsHack
  61. {
  62. public:
  63. enum
  64. {
  65. Ref1 = sizeof(cfgetospeed(0)),
  66. Ref2 = sizeof(cfgetispeed(0)),
  67. Ref3 = sizeof(tcgetattr(0, 0)),
  68. Ref4 = sizeof(tcsetattr(0, 0, 0)),
  69. Ref5 = sizeof(cfsetospeed(0,0)),
  70. Ref6 = sizeof(cfsetispeed(0,0))
  71. };
  72. };
  73. }
  74. #endif
  75. #if defined(_WIN32) && (defined(_MSC_VER) || defined(__WATCOMC__) ||defined(__BORLANDC__) || defined(__MINGW32__))
  76. #include <io.h>
  77. #include <direct.h>
  78. #define _unlink unlink
  79. #endif
  80. /* The maximum length of a file name. */
  81. #if defined(PATH_MAX)
  82. # define KWSYS_SYSTEMTOOLS_MAXPATH PATH_MAX
  83. #elif defined(MAXPATHLEN)
  84. # define KWSYS_SYSTEMTOOLS_MAXPATH MAXPATHLEN
  85. #else
  86. # define KWSYS_SYSTEMTOOLS_MAXPATH 16384
  87. #endif
  88. #if defined(__WATCOMC__)
  89. #include <direct.h>
  90. #define _mkdir mkdir
  91. #define _rmdir rmdir
  92. #define _getcwd getcwd
  93. #define _chdir chdir
  94. #endif
  95. #if defined(_WIN32) && (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__BORLANDC__) || defined(__MINGW32__))
  96. inline int Mkdir(const char* dir)
  97. {
  98. return _mkdir(dir);
  99. }
  100. inline int Rmdir(const char* dir)
  101. {
  102. return _rmdir(dir);
  103. }
  104. inline const char* Getcwd(char* buf, unsigned int len)
  105. {
  106. return _getcwd(buf, len);
  107. }
  108. inline int Chdir(const char* dir)
  109. {
  110. #if defined(__BORLANDC__)
  111. return chdir(dir);
  112. #else
  113. return _chdir(dir);
  114. #endif
  115. }
  116. inline void Realpath(const char *path, kwsys_stl::string & resolved_path)
  117. {
  118. char *ptemp;
  119. char fullpath[MAX_PATH];
  120. if( GetFullPathName(path, sizeof(fullpath), fullpath, &ptemp) )
  121. {
  122. resolved_path = fullpath;
  123. KWSYS_NAMESPACE::SystemTools::ConvertToUnixSlashes(resolved_path);
  124. }
  125. }
  126. #else
  127. #include <sys/types.h>
  128. #include <fcntl.h>
  129. #include <unistd.h>
  130. inline int Mkdir(const char* dir)
  131. {
  132. return mkdir(dir, 00777);
  133. }
  134. inline int Rmdir(const char* dir)
  135. {
  136. return rmdir(dir);
  137. }
  138. inline const char* Getcwd(char* buf, unsigned int len)
  139. {
  140. return getcwd(buf, len);
  141. }
  142. inline int Chdir(const char* dir)
  143. {
  144. return chdir(dir);
  145. }
  146. inline void Realpath(const char *path, kwsys_stl::string & resolved_path)
  147. {
  148. char resolved_name[KWSYS_SYSTEMTOOLS_MAXPATH];
  149. realpath(path, resolved_name);
  150. resolved_path = resolved_name;
  151. }
  152. #endif
  153. #if !defined(_WIN32) && defined(__COMO__)
  154. // Hack for como strict mode to avoid defining _SVID_SOURCE or _BSD_SOURCE.
  155. extern "C"
  156. {
  157. extern FILE *popen (__const char *__command, __const char *__modes) __THROW;
  158. extern int pclose (FILE *__stream) __THROW;
  159. extern char *realpath (__const char *__restrict __name,
  160. char *__restrict __resolved) __THROW;
  161. extern char *strdup (__const char *__s) __THROW;
  162. extern int putenv (char *__string) __THROW;
  163. }
  164. #endif
  165. /* Implement floattime() for various platforms */
  166. // Taken from Python 2.1.3
  167. #if defined( _WIN32 ) && !defined( __CYGWIN__ )
  168. # include <sys/timeb.h>
  169. # define HAVE_FTIME
  170. # if defined( __BORLANDC__)
  171. # define FTIME ftime
  172. # define TIMEB timeb
  173. # else // Visual studio?
  174. # define FTIME _ftime
  175. # define TIMEB _timeb
  176. # endif
  177. #elif defined( __CYGWIN__ ) || defined( __linux__ )
  178. # include <sys/time.h>
  179. # include <time.h>
  180. # define HAVE_GETTIMEOFDAY
  181. #endif
  182. namespace KWSYS_NAMESPACE
  183. {
  184. class SystemToolsTranslationMap :
  185. public kwsys_stl::map<kwsys_stl::string,kwsys_stl::string>
  186. {
  187. };
  188. double
  189. SystemTools::GetTime(void)
  190. {
  191. /* There are three ways to get the time:
  192. (1) gettimeofday() -- resolution in microseconds
  193. (2) ftime() -- resolution in milliseconds
  194. (3) time() -- resolution in seconds
  195. In all cases the return value is a float in seconds.
  196. Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
  197. fail, so we fall back on ftime() or time().
  198. Note: clock resolution does not imply clock accuracy! */
  199. #ifdef HAVE_GETTIMEOFDAY
  200. {
  201. struct timeval t;
  202. #ifdef GETTIMEOFDAY_NO_TZ
  203. if (gettimeofday(&t) == 0)
  204. return (double)t.tv_sec + t.tv_usec*0.000001;
  205. #else /* !GETTIMEOFDAY_NO_TZ */
  206. if (gettimeofday(&t, (struct timezone *)NULL) == 0)
  207. return (double)t.tv_sec + t.tv_usec*0.000001;
  208. #endif /* !GETTIMEOFDAY_NO_TZ */
  209. }
  210. #endif /* !HAVE_GETTIMEOFDAY */
  211. {
  212. #if defined(HAVE_FTIME)
  213. struct TIMEB t;
  214. ::FTIME(&t);
  215. return (double)t.time + (double)t.millitm * (double)0.001;
  216. #else /* !HAVE_FTIME */
  217. time_t secs;
  218. time(&secs);
  219. return (double)secs;
  220. #endif /* !HAVE_FTIME */
  221. }
  222. }
  223. // adds the elements of the env variable path to the arg passed in
  224. void SystemTools::GetPath(kwsys_stl::vector<kwsys_stl::string>& path, const char* env)
  225. {
  226. #if defined(_WIN32) && !defined(__CYGWIN__)
  227. const char* pathSep = ";";
  228. #else
  229. const char* pathSep = ":";
  230. #endif
  231. if(!env)
  232. {
  233. env = "PATH";
  234. }
  235. const char* cpathEnv = SystemTools::GetEnv(env);
  236. if ( !cpathEnv )
  237. {
  238. return;
  239. }
  240. kwsys_stl::string pathEnv = cpathEnv;
  241. // A hack to make the below algorithm work.
  242. if(pathEnv[pathEnv.length()-1] != ':')
  243. {
  244. pathEnv += pathSep;
  245. }
  246. kwsys_stl::string::size_type start =0;
  247. bool done = false;
  248. while(!done)
  249. {
  250. kwsys_stl::string::size_type endpos = pathEnv.find(pathSep, start);
  251. if(endpos != kwsys_stl::string::npos)
  252. {
  253. path.push_back(pathEnv.substr(start, endpos-start));
  254. start = endpos+1;
  255. }
  256. else
  257. {
  258. done = true;
  259. }
  260. }
  261. for(kwsys_stl::vector<kwsys_stl::string>::iterator i = path.begin();
  262. i != path.end(); ++i)
  263. {
  264. SystemTools::ConvertToUnixSlashes(*i);
  265. }
  266. }
  267. const char* SystemTools::GetEnv(const char* key)
  268. {
  269. return getenv(key);
  270. }
  271. bool SystemTools::GetEnv(const char* key, kwsys_stl::string& result)
  272. {
  273. const char* v = getenv(key);
  274. if(v)
  275. {
  276. result = v;
  277. return true;
  278. }
  279. else
  280. {
  281. return false;
  282. }
  283. }
  284. const char* SystemTools::GetExecutableExtension()
  285. {
  286. #if defined(_WIN32) || defined(__CYGWIN__)
  287. return ".exe";
  288. #else
  289. return "";
  290. #endif
  291. }
  292. bool SystemTools::MakeDirectory(const char* path)
  293. {
  294. if(SystemTools::FileExists(path))
  295. {
  296. return true;
  297. }
  298. kwsys_stl::string dir = path;
  299. if(dir.size() == 0)
  300. {
  301. return false;
  302. }
  303. SystemTools::ConvertToUnixSlashes(dir);
  304. kwsys_stl::string::size_type pos = dir.find(':');
  305. if(pos == kwsys_stl::string::npos)
  306. {
  307. pos = 0;
  308. }
  309. kwsys_stl::string topdir;
  310. while((pos = dir.find('/', pos)) != kwsys_stl::string::npos)
  311. {
  312. topdir = dir.substr(0, pos);
  313. Mkdir(topdir.c_str());
  314. pos++;
  315. }
  316. if(dir[dir.size()-1] == '/')
  317. {
  318. topdir = dir.substr(0, dir.size());
  319. }
  320. else
  321. {
  322. topdir = dir;
  323. }
  324. if(Mkdir(topdir.c_str()) != 0)
  325. {
  326. // There is a bug in the Borland Run time library which makes MKDIR
  327. // return EACCES when it should return EEXISTS
  328. // if it is some other error besides directory exists
  329. // then return false
  330. if( (errno != EEXIST)
  331. #ifdef __BORLANDC__
  332. && (errno != EACCES)
  333. #endif
  334. )
  335. {
  336. return false;
  337. }
  338. }
  339. return true;
  340. }
  341. // replace replace with with as many times as it shows up in source.
  342. // write the result into source.
  343. void SystemTools::ReplaceString(kwsys_stl::string& source,
  344. const char* replace,
  345. const char* with)
  346. {
  347. const char *src = source.c_str();
  348. char *searchPos = const_cast<char *>(strstr(src,replace));
  349. // get out quick if string is not found
  350. if (!searchPos)
  351. {
  352. return;
  353. }
  354. // perform replacements until done
  355. size_t replaceSize = strlen(replace);
  356. char *orig = strdup(src);
  357. char *currentPos = orig;
  358. searchPos = searchPos - src + orig;
  359. // initialize the result
  360. source.erase(source.begin(),source.end());
  361. do
  362. {
  363. *searchPos = '\0';
  364. source += currentPos;
  365. currentPos = searchPos + replaceSize;
  366. // replace
  367. source += with;
  368. searchPos = strstr(currentPos,replace);
  369. }
  370. while (searchPos);
  371. // copy any trailing text
  372. source += currentPos;
  373. free(orig);
  374. }
  375. // Read a registry value.
  376. // Example :
  377. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  378. // => will return the data of the "default" value of the key
  379. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  380. // => will return the data of the "Root" value of the key
  381. #if defined(_WIN32) && !defined(__CYGWIN__)
  382. bool SystemTools::ReadRegistryValue(const char *key, kwsys_stl::string &value)
  383. {
  384. kwsys_stl::string primary = key;
  385. kwsys_stl::string second;
  386. kwsys_stl::string valuename;
  387. size_t start = primary.find("\\");
  388. if (start == kwsys_stl::string::npos)
  389. {
  390. return false;
  391. }
  392. size_t valuenamepos = primary.find(";");
  393. if (valuenamepos != kwsys_stl::string::npos)
  394. {
  395. valuename = primary.substr(valuenamepos+1);
  396. }
  397. second = primary.substr(start+1, valuenamepos-start-1);
  398. primary = primary.substr(0, start);
  399. HKEY primaryKey = HKEY_CURRENT_USER;
  400. if (primary == "HKEY_CURRENT_USER")
  401. {
  402. primaryKey = HKEY_CURRENT_USER;
  403. }
  404. if (primary == "HKEY_CURRENT_CONFIG")
  405. {
  406. primaryKey = HKEY_CURRENT_CONFIG;
  407. }
  408. if (primary == "HKEY_CLASSES_ROOT")
  409. {
  410. primaryKey = HKEY_CLASSES_ROOT;
  411. }
  412. if (primary == "HKEY_LOCAL_MACHINE")
  413. {
  414. primaryKey = HKEY_LOCAL_MACHINE;
  415. }
  416. if (primary == "HKEY_USERS")
  417. {
  418. primaryKey = HKEY_USERS;
  419. }
  420. HKEY hKey;
  421. if(RegOpenKeyEx(primaryKey,
  422. second.c_str(),
  423. 0,
  424. KEY_READ,
  425. &hKey) != ERROR_SUCCESS)
  426. {
  427. return false;
  428. }
  429. else
  430. {
  431. DWORD dwType, dwSize;
  432. dwSize = 1023;
  433. char data[1024];
  434. if(RegQueryValueEx(hKey,
  435. (LPTSTR)valuename.c_str(),
  436. NULL,
  437. &dwType,
  438. (BYTE *)data,
  439. &dwSize) == ERROR_SUCCESS)
  440. {
  441. if (dwType == REG_SZ)
  442. {
  443. value = data;
  444. RegCloseKey(hKey);
  445. return true;
  446. }
  447. }
  448. }
  449. return false;
  450. }
  451. #else
  452. bool SystemTools::ReadRegistryValue(const char *, kwsys_stl::string &)
  453. {
  454. return false;
  455. }
  456. #endif
  457. // Write a registry value.
  458. // Example :
  459. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  460. // => will set the data of the "default" value of the key
  461. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  462. // => will set the data of the "Root" value of the key
  463. #if defined(_WIN32) && !defined(__CYGWIN__)
  464. bool SystemTools::WriteRegistryValue(const char *key, const char *value)
  465. {
  466. kwsys_stl::string primary = key;
  467. kwsys_stl::string second;
  468. kwsys_stl::string valuename;
  469. size_t start = primary.find("\\");
  470. if (start == kwsys_stl::string::npos)
  471. {
  472. return false;
  473. }
  474. size_t valuenamepos = primary.find(";");
  475. if (valuenamepos != kwsys_stl::string::npos)
  476. {
  477. valuename = primary.substr(valuenamepos+1);
  478. }
  479. second = primary.substr(start+1, valuenamepos-start-1);
  480. primary = primary.substr(0, start);
  481. HKEY primaryKey = HKEY_CURRENT_USER;
  482. if (primary == "HKEY_CURRENT_USER")
  483. {
  484. primaryKey = HKEY_CURRENT_USER;
  485. }
  486. if (primary == "HKEY_CURRENT_CONFIG")
  487. {
  488. primaryKey = HKEY_CURRENT_CONFIG;
  489. }
  490. if (primary == "HKEY_CLASSES_ROOT")
  491. {
  492. primaryKey = HKEY_CLASSES_ROOT;
  493. }
  494. if (primary == "HKEY_LOCAL_MACHINE")
  495. {
  496. primaryKey = HKEY_LOCAL_MACHINE;
  497. }
  498. if (primary == "HKEY_USERS")
  499. {
  500. primaryKey = HKEY_USERS;
  501. }
  502. HKEY hKey;
  503. DWORD dwDummy;
  504. if(RegCreateKeyEx(primaryKey,
  505. second.c_str(),
  506. 0,
  507. "",
  508. REG_OPTION_NON_VOLATILE,
  509. KEY_WRITE,
  510. NULL,
  511. &hKey,
  512. &dwDummy) != ERROR_SUCCESS)
  513. {
  514. return false;
  515. }
  516. if(RegSetValueEx(hKey,
  517. (LPTSTR)valuename.c_str(),
  518. 0,
  519. REG_SZ,
  520. (CONST BYTE *)value,
  521. (DWORD)(strlen(value) + 1)) == ERROR_SUCCESS)
  522. {
  523. return true;
  524. }
  525. return false;
  526. }
  527. #else
  528. bool SystemTools::WriteRegistryValue(const char *, const char *)
  529. {
  530. return false;
  531. }
  532. #endif
  533. // Delete a registry value.
  534. // Example :
  535. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  536. // => will delete the data of the "default" value of the key
  537. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  538. // => will delete the data of the "Root" value of the key
  539. #if defined(_WIN32) && !defined(__CYGWIN__)
  540. bool SystemTools::DeleteRegistryValue(const char *key)
  541. {
  542. kwsys_stl::string primary = key;
  543. kwsys_stl::string second;
  544. kwsys_stl::string valuename;
  545. size_t start = primary.find("\\");
  546. if (start == kwsys_stl::string::npos)
  547. {
  548. return false;
  549. }
  550. size_t valuenamepos = primary.find(";");
  551. if (valuenamepos != kwsys_stl::string::npos)
  552. {
  553. valuename = primary.substr(valuenamepos+1);
  554. }
  555. second = primary.substr(start+1, valuenamepos-start-1);
  556. primary = primary.substr(0, start);
  557. HKEY primaryKey = HKEY_CURRENT_USER;
  558. if (primary == "HKEY_CURRENT_USER")
  559. {
  560. primaryKey = HKEY_CURRENT_USER;
  561. }
  562. if (primary == "HKEY_CURRENT_CONFIG")
  563. {
  564. primaryKey = HKEY_CURRENT_CONFIG;
  565. }
  566. if (primary == "HKEY_CLASSES_ROOT")
  567. {
  568. primaryKey = HKEY_CLASSES_ROOT;
  569. }
  570. if (primary == "HKEY_LOCAL_MACHINE")
  571. {
  572. primaryKey = HKEY_LOCAL_MACHINE;
  573. }
  574. if (primary == "HKEY_USERS")
  575. {
  576. primaryKey = HKEY_USERS;
  577. }
  578. HKEY hKey;
  579. if(RegOpenKeyEx(primaryKey,
  580. second.c_str(),
  581. 0,
  582. KEY_WRITE,
  583. &hKey) != ERROR_SUCCESS)
  584. {
  585. return false;
  586. }
  587. else
  588. {
  589. if(RegDeleteValue(hKey,
  590. (LPTSTR)valuename.c_str()) == ERROR_SUCCESS)
  591. {
  592. RegCloseKey(hKey);
  593. return true;
  594. }
  595. }
  596. return false;
  597. }
  598. #else
  599. bool SystemTools::DeleteRegistryValue(const char *)
  600. {
  601. return false;
  602. }
  603. #endif
  604. bool SystemTools::SameFile(const char* file1, const char* file2)
  605. {
  606. #ifdef _WIN32
  607. HANDLE hFile1, hFile2;
  608. hFile1 = CreateFile( file1,
  609. GENERIC_READ,
  610. FILE_SHARE_READ ,
  611. NULL,
  612. OPEN_EXISTING,
  613. FILE_FLAG_BACKUP_SEMANTICS,
  614. NULL
  615. );
  616. hFile2 = CreateFile( file2,
  617. GENERIC_READ,
  618. FILE_SHARE_READ,
  619. NULL,
  620. OPEN_EXISTING,
  621. FILE_FLAG_BACKUP_SEMANTICS,
  622. NULL
  623. );
  624. if( hFile1 == INVALID_HANDLE_VALUE || hFile2 == INVALID_HANDLE_VALUE)
  625. {
  626. if(hFile1 != INVALID_HANDLE_VALUE)
  627. {
  628. CloseHandle(hFile1);
  629. }
  630. if(hFile2 != INVALID_HANDLE_VALUE)
  631. {
  632. CloseHandle(hFile2);
  633. }
  634. return false;
  635. }
  636. BY_HANDLE_FILE_INFORMATION fiBuf1;
  637. BY_HANDLE_FILE_INFORMATION fiBuf2;
  638. GetFileInformationByHandle( hFile1, &fiBuf1 );
  639. GetFileInformationByHandle( hFile2, &fiBuf2 );
  640. CloseHandle(hFile1);
  641. CloseHandle(hFile2);
  642. return (fiBuf1.dwVolumeSerialNumber == fiBuf2.dwVolumeSerialNumber &&
  643. fiBuf1.nFileIndexHigh == fiBuf2.nFileIndexHigh &&
  644. fiBuf1.nFileIndexLow == fiBuf2.nFileIndexLow);
  645. #else
  646. struct stat fileStat1, fileStat2;
  647. if (stat(file1, &fileStat1) == 0 && stat(file2, &fileStat2) == 0)
  648. {
  649. // see if the files are the same file
  650. // check the device inode and size
  651. if(memcmp(&fileStat2.st_dev, &fileStat1.st_dev, sizeof(fileStat1.st_dev)) == 0 &&
  652. memcmp(&fileStat2.st_ino, &fileStat1.st_ino, sizeof(fileStat1.st_ino)) == 0 &&
  653. fileStat2.st_size == fileStat1.st_size
  654. )
  655. {
  656. return true;
  657. }
  658. }
  659. return false;
  660. #endif
  661. }
  662. // return true if the file exists
  663. bool SystemTools::FileExists(const char* filename)
  664. {
  665. #ifdef _MSC_VER
  666. # define access _access
  667. #endif
  668. #ifndef R_OK
  669. # define R_OK 04
  670. #endif
  671. if ( access(filename, R_OK) != 0 )
  672. {
  673. return false;
  674. }
  675. else
  676. {
  677. return true;
  678. }
  679. }
  680. bool SystemTools::FileTimeCompare(const char* f1, const char* f2,
  681. int* result)
  682. {
  683. // Default to same time.
  684. *result = 0;
  685. #if !defined(_WIN32) || defined(__CYGWIN__)
  686. // POSIX version. Use stat function to get file modification time.
  687. struct stat s1;
  688. if(stat(f1, &s1) != 0)
  689. {
  690. return false;
  691. }
  692. struct stat s2;
  693. if(stat(f2, &s2) != 0)
  694. {
  695. return false;
  696. }
  697. # if KWSYS_STAT_HAS_ST_MTIM
  698. // Compare using nanosecond resolution.
  699. if(s1.st_mtim.tv_sec < s2.st_mtim.tv_sec)
  700. {
  701. *result = -1;
  702. }
  703. else if(s1.st_mtim.tv_sec > s2.st_mtim.tv_sec)
  704. {
  705. *result = 1;
  706. }
  707. else if(s1.st_mtim.tv_nsec < s2.st_mtim.tv_nsec)
  708. {
  709. *result = -1;
  710. }
  711. else if(s1.st_mtim.tv_nsec > s2.st_mtim.tv_nsec)
  712. {
  713. *result = 1;
  714. }
  715. # else
  716. // Compare using 1 second resolution.
  717. if(s1.st_mtime < s2.st_mtime)
  718. {
  719. *result = -1;
  720. }
  721. else if(s1.st_mtime > s2.st_mtime)
  722. {
  723. *result = 1;
  724. }
  725. # endif
  726. #else
  727. // Windows version. Get the modification time from extended file attributes.
  728. WIN32_FILE_ATTRIBUTE_DATA f1d;
  729. WIN32_FILE_ATTRIBUTE_DATA f2d;
  730. if(!GetFileAttributesEx(f1, GetFileExInfoStandard, &f1d))
  731. {
  732. return false;
  733. }
  734. if(!GetFileAttributesEx(f2, GetFileExInfoStandard, &f2d))
  735. {
  736. return false;
  737. }
  738. // Compare the file times using resolution provided by system call.
  739. *result = (int)CompareFileTime(&f1d.ftLastWriteTime, &f2d.ftLastWriteTime);
  740. #endif
  741. return true;
  742. }
  743. // Return a capitalized string (i.e the first letter is uppercased, all other
  744. // are lowercased)
  745. kwsys_stl::string SystemTools::Capitalized(const kwsys_stl::string& s)
  746. {
  747. kwsys_stl::string n;
  748. if(s.size() == 0)
  749. {
  750. return n;
  751. }
  752. n.resize(s.size());
  753. n[0] = static_cast<kwsys_stl::string::value_type>(toupper(s[0]));
  754. for (size_t i = 1; i < s.size(); i++)
  755. {
  756. n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
  757. }
  758. return n;
  759. }
  760. // Return capitalized words
  761. kwsys_stl::string SystemTools::CapitalizedWords(const kwsys_stl::string& s)
  762. {
  763. kwsys_stl::string n(s);
  764. for (size_t i = 0; i < s.size(); i++)
  765. {
  766. if (isalpha(s[i]) && (i == 0 || isspace(s[i - 1])))
  767. {
  768. n[i] = static_cast<kwsys_stl::string::value_type>(toupper(s[i]));
  769. }
  770. }
  771. return n;
  772. }
  773. // Return uncapitalized words
  774. kwsys_stl::string SystemTools::UnCapitalizedWords(const kwsys_stl::string& s)
  775. {
  776. kwsys_stl::string n(s);
  777. for (size_t i = 0; i < s.size(); i++)
  778. {
  779. if (isalpha(s[i]) && (i == 0 || isspace(s[i - 1])))
  780. {
  781. n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
  782. }
  783. }
  784. return n;
  785. }
  786. kwsys_stl::string SystemTools::AddSpaceBetweenCapitalizedWords(
  787. const kwsys_stl::string& s)
  788. {
  789. kwsys_stl::string n;
  790. if (s.size())
  791. {
  792. n.reserve(s.size());
  793. n += s[0];
  794. for (size_t i = 1; i < s.size(); i++)
  795. {
  796. if (isupper(s[i]) && !isspace(s[i - 1]) && !isupper(s[i - 1]))
  797. {
  798. n += ' ';
  799. }
  800. n += s[i];
  801. }
  802. }
  803. return n;
  804. }
  805. char* SystemTools::AppendStrings(const char* str1, const char* str2)
  806. {
  807. if (!str1)
  808. {
  809. return SystemTools::DuplicateString(str2);
  810. }
  811. if (!str2)
  812. {
  813. return SystemTools::DuplicateString(str1);
  814. }
  815. size_t len1 = strlen(str1);
  816. char *newstr = new char[len1 + strlen(str2) + 1];
  817. if (!newstr)
  818. {
  819. return 0;
  820. }
  821. strcpy(newstr, str1);
  822. strcat(newstr + len1, str2);
  823. return newstr;
  824. }
  825. char* SystemTools::AppendStrings(
  826. const char* str1, const char* str2, const char* str3)
  827. {
  828. if (!str1)
  829. {
  830. return SystemTools::AppendStrings(str2, str3);
  831. }
  832. if (!str2)
  833. {
  834. return SystemTools::AppendStrings(str1, str3);
  835. }
  836. if (!str3)
  837. {
  838. return SystemTools::AppendStrings(str1, str2);
  839. }
  840. size_t len1 = strlen(str1), len2 = strlen(str2);
  841. char *newstr = new char[len1 + len2 + strlen(str3) + 1];
  842. if (!newstr)
  843. {
  844. return 0;
  845. }
  846. strcpy(newstr, str1);
  847. strcat(newstr + len1, str2);
  848. strcat(newstr + len1 + len2, str3);
  849. return newstr;
  850. }
  851. // Return a lower case string
  852. kwsys_stl::string SystemTools::LowerCase(const kwsys_stl::string& s)
  853. {
  854. kwsys_stl::string n;
  855. n.resize(s.size());
  856. for (size_t i = 0; i < s.size(); i++)
  857. {
  858. n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
  859. }
  860. return n;
  861. }
  862. // Return a lower case string
  863. kwsys_stl::string SystemTools::UpperCase(const kwsys_stl::string& s)
  864. {
  865. kwsys_stl::string n;
  866. n.resize(s.size());
  867. for (size_t i = 0; i < s.size(); i++)
  868. {
  869. n[i] = static_cast<kwsys_stl::string::value_type>(toupper(s[i]));
  870. }
  871. return n;
  872. }
  873. // Count char in string
  874. size_t SystemTools::CountChar(const char* str, char c)
  875. {
  876. size_t count = 0;
  877. if (str)
  878. {
  879. while (*str)
  880. {
  881. if (*str == c)
  882. {
  883. ++count;
  884. }
  885. ++str;
  886. }
  887. }
  888. return count;
  889. }
  890. // Remove chars in string
  891. char* SystemTools::RemoveChars(const char* str, const char *toremove)
  892. {
  893. if (!str)
  894. {
  895. return NULL;
  896. }
  897. char *clean_str = new char [strlen(str) + 1];
  898. char *ptr = clean_str;
  899. while (*str)
  900. {
  901. const char *str2 = toremove;
  902. while (*str2 && *str != *str2)
  903. {
  904. ++str2;
  905. }
  906. if (!*str2)
  907. {
  908. *ptr++ = *str;
  909. }
  910. ++str;
  911. }
  912. *ptr = '\0';
  913. return clean_str;
  914. }
  915. // Remove chars in string
  916. char* SystemTools::RemoveCharsButUpperHex(const char* str)
  917. {
  918. if (!str)
  919. {
  920. return 0;
  921. }
  922. char *clean_str = new char [strlen(str) + 1];
  923. char *ptr = clean_str;
  924. while (*str)
  925. {
  926. if ((*str >= '0' && *str <= '9') || (*str >= 'A' && *str <= 'H'))
  927. {
  928. *ptr++ = *str;
  929. }
  930. ++str;
  931. }
  932. *ptr = '\0';
  933. return clean_str;
  934. }
  935. // Replace chars in string
  936. char* SystemTools::ReplaceChars(char* str, const char *toreplace, char replacement)
  937. {
  938. if (str)
  939. {
  940. char *ptr = str;
  941. while (*ptr)
  942. {
  943. const char *ptr2 = toreplace;
  944. while (*ptr2)
  945. {
  946. if (*ptr == *ptr2)
  947. {
  948. *ptr = replacement;
  949. }
  950. ++ptr2;
  951. }
  952. ++ptr;
  953. }
  954. }
  955. return str;
  956. }
  957. // Returns if string starts with another string
  958. bool SystemTools::StringStartsWith(const char* str1, const char* str2)
  959. {
  960. if (!str1 || !str2)
  961. {
  962. return false;
  963. }
  964. size_t len1 = strlen(str1), len2 = strlen(str2);
  965. return len1 >= len2 && !strncmp(str1, str2, len2) ? true : false;
  966. }
  967. // Returns if string ends with another string
  968. bool SystemTools::StringEndsWith(const char* str1, const char* str2)
  969. {
  970. if (!str1 || !str2)
  971. {
  972. return false;
  973. }
  974. size_t len1 = strlen(str1), len2 = strlen(str2);
  975. return len1 >= len2 && !strncmp(str1 + (len1 - len2), str2, len2) ? true : false;
  976. }
  977. // Returns a pointer to the last occurence of str2 in str1
  978. const char* SystemTools::FindLastString(const char* str1, const char* str2)
  979. {
  980. if (!str1 || !str2)
  981. {
  982. return NULL;
  983. }
  984. size_t len1 = strlen(str1), len2 = strlen(str2);
  985. if (len1 >= len2)
  986. {
  987. const char *ptr = str1 + len1 - len2;
  988. do
  989. {
  990. if (!strncmp(ptr, str2, len2))
  991. {
  992. return ptr;
  993. }
  994. } while (ptr-- != str1);
  995. }
  996. return NULL;
  997. }
  998. // Duplicate string
  999. char* SystemTools::DuplicateString(const char* str)
  1000. {
  1001. if (str)
  1002. {
  1003. char *newstr = new char [strlen(str) + 1];
  1004. return strcpy(newstr, str);
  1005. }
  1006. return NULL;
  1007. }
  1008. // Return a cropped string
  1009. kwsys_stl::string SystemTools::CropString(const kwsys_stl::string& s,
  1010. size_t max_len)
  1011. {
  1012. if (!s.size() || max_len == 0 || max_len >= s.size())
  1013. {
  1014. return s;
  1015. }
  1016. kwsys_stl::string n;
  1017. n.reserve(max_len);
  1018. size_t middle = max_len / 2;
  1019. n += s.substr(0, middle);
  1020. n += s.substr(s.size() - (max_len - middle), kwsys_stl::string::npos);
  1021. if (max_len > 2)
  1022. {
  1023. n[middle] = '.';
  1024. if (max_len > 3)
  1025. {
  1026. n[middle - 1] = '.';
  1027. if (max_len > 4)
  1028. {
  1029. n[middle + 1] = '.';
  1030. }
  1031. }
  1032. }
  1033. return n;
  1034. }
  1035. //----------------------------------------------------------------------------
  1036. int SystemTools::EstimateFormatLength(const char *format, va_list ap)
  1037. {
  1038. if (!format)
  1039. {
  1040. return 0;
  1041. }
  1042. // Quick-hack attempt at estimating the length of the string.
  1043. // Should never under-estimate.
  1044. // Start with the length of the format string itself.
  1045. int length = strlen(format);
  1046. // Increase the length for every argument in the format.
  1047. const char* cur = format;
  1048. while(*cur)
  1049. {
  1050. if(*cur++ == '%')
  1051. {
  1052. // Skip "%%" since it doesn't correspond to a va_arg.
  1053. if(*cur != '%')
  1054. {
  1055. while(!int(isalpha(*cur)))
  1056. {
  1057. ++cur;
  1058. }
  1059. switch (*cur)
  1060. {
  1061. case 's':
  1062. {
  1063. // Check the length of the string.
  1064. char* s = va_arg(ap, char*);
  1065. if(s)
  1066. {
  1067. length += strlen(s);
  1068. }
  1069. } break;
  1070. case 'e':
  1071. case 'f':
  1072. case 'g':
  1073. {
  1074. // Assume the argument contributes no more than 64 characters.
  1075. length += 64;
  1076. // Eat the argument.
  1077. static_cast<void>(va_arg(ap, double));
  1078. } break;
  1079. default:
  1080. {
  1081. // Assume the argument contributes no more than 64 characters.
  1082. length += 64;
  1083. // Eat the argument.
  1084. static_cast<void>(va_arg(ap, int));
  1085. } break;
  1086. }
  1087. }
  1088. // Move past the characters just tested.
  1089. ++cur;
  1090. }
  1091. }
  1092. return length;
  1093. }
  1094. kwsys_stl::string SystemTools::EscapeChars(
  1095. const char *str,
  1096. const char *chars_to_escape,
  1097. char escape_char)
  1098. {
  1099. kwsys_stl::string n;
  1100. if (str)
  1101. {
  1102. if (!chars_to_escape | !*chars_to_escape)
  1103. {
  1104. n.append(str);
  1105. }
  1106. else
  1107. {
  1108. n.reserve(strlen(str));
  1109. while (*str)
  1110. {
  1111. const char *ptr = chars_to_escape;
  1112. while (*ptr)
  1113. {
  1114. if (*str == *ptr)
  1115. {
  1116. n += escape_char;
  1117. break;
  1118. }
  1119. ++ptr;
  1120. }
  1121. n += *str;
  1122. ++str;
  1123. }
  1124. }
  1125. }
  1126. return n;
  1127. }
  1128. // convert windows slashes to unix slashes
  1129. void SystemTools::ConvertToUnixSlashes(kwsys_stl::string& path)
  1130. {
  1131. const char* pathCString = path.c_str();
  1132. bool hasDoubleSlash = false;
  1133. const char* pos0 = pathCString;
  1134. const char* pos1 = pathCString+1;
  1135. for (kwsys_stl::string::size_type pos = 0; *pos0; ++ pos )
  1136. {
  1137. // make sure we don't convert an escaped space to a unix slash
  1138. if ( *pos0 == '\\' && *pos1 != ' ' )
  1139. {
  1140. path[pos] = '/';
  1141. }
  1142. // Also, reuse the loop to check for slash followed by another slash
  1143. if ( !hasDoubleSlash && *pos1 &&
  1144. *pos1 == '/' && *(pos1+1) == '/' )
  1145. {
  1146. #ifdef _WIN32
  1147. // However, on windows if the first characters are both slashes,
  1148. // then keep them that way, so that network paths can be handled.
  1149. if ( pos > 0)
  1150. {
  1151. hasDoubleSlash = true;
  1152. }
  1153. #else
  1154. hasDoubleSlash = true;
  1155. #endif
  1156. }
  1157. pos0 ++;
  1158. pos1 ++;
  1159. }
  1160. if ( hasDoubleSlash )
  1161. {
  1162. SystemTools::ReplaceString(path, "//", "/");
  1163. }
  1164. // remove any trailing slash
  1165. if(!path.empty())
  1166. {
  1167. // if there is a tilda ~ then replace it with HOME
  1168. pathCString = path.c_str();
  1169. if(*pathCString == '~')
  1170. {
  1171. const char* homeEnv = SystemTools::GetEnv("HOME");
  1172. if (homeEnv)
  1173. {
  1174. path.replace(0,1,homeEnv);
  1175. }
  1176. }
  1177. pathCString = path.c_str();
  1178. if (*(pathCString+(path.size()-1)) == '/')
  1179. {
  1180. path = path.substr(0, path.size()-1);
  1181. }
  1182. }
  1183. }
  1184. // change // to /, and escape any spaces in the path
  1185. kwsys_stl::string SystemTools::ConvertToUnixOutputPath(const char* path)
  1186. {
  1187. kwsys_stl::string ret = path;
  1188. // remove // except at the beginning might be a cygwin drive
  1189. kwsys_stl::string::size_type pos=0;
  1190. while((pos = ret.find("//", pos)) != kwsys_stl::string::npos)
  1191. {
  1192. ret.erase(pos, 1);
  1193. }
  1194. // now escape spaces if there is a space in the path
  1195. if(ret.find(" ") != kwsys_stl::string::npos)
  1196. {
  1197. kwsys_stl::string result = "";
  1198. char lastch = 1;
  1199. for(const char* ch = ret.c_str(); *ch != '\0'; ++ch)
  1200. {
  1201. // if it is already escaped then don't try to escape it again
  1202. if(*ch == ' ' && lastch != '\\')
  1203. {
  1204. result += '\\';
  1205. }
  1206. result += *ch;
  1207. lastch = *ch;
  1208. }
  1209. ret = result;
  1210. }
  1211. return ret;
  1212. }
  1213. kwsys_stl::string SystemTools::ConvertToOutputPath(const char* path)
  1214. {
  1215. #if defined(_WIN32) && !defined(__CYGWIN__)
  1216. return SystemTools::ConvertToWindowsOutputPath(path);
  1217. #else
  1218. return SystemTools::ConvertToUnixOutputPath(path);
  1219. #endif
  1220. }
  1221. // remove double slashes not at the start
  1222. kwsys_stl::string SystemTools::ConvertToWindowsOutputPath(const char* path)
  1223. {
  1224. kwsys_stl::string ret;
  1225. // make it big enough for all of path and double quotes
  1226. ret.reserve(strlen(path)+3);
  1227. // put path into the string
  1228. ret.insert(0,path);
  1229. kwsys_stl::string::size_type pos = 0;
  1230. // first convert all of the slashes
  1231. while((pos = ret.find('/', pos)) != kwsys_stl::string::npos)
  1232. {
  1233. ret[pos] = '\\';
  1234. pos++;
  1235. }
  1236. // check for really small paths
  1237. if(ret.size() < 2)
  1238. {
  1239. return ret;
  1240. }
  1241. // now clean up a bit and remove double slashes
  1242. // Only if it is not the first position in the path which is a network
  1243. // path on windows
  1244. pos = 1; // start at position 1
  1245. if(ret[0] == '\"')
  1246. {
  1247. pos = 2; // if the string is already quoted then start at 2
  1248. if(ret.size() < 3)
  1249. {
  1250. return ret;
  1251. }
  1252. }
  1253. while((pos = ret.find("\\\\", pos)) != kwsys_stl::string::npos)
  1254. {
  1255. ret.erase(pos, 1);
  1256. }
  1257. // now double quote the path if it has spaces in it
  1258. // and is not already double quoted
  1259. if(ret.find(' ') != kwsys_stl::string::npos
  1260. && ret[0] != '\"')
  1261. {
  1262. ret.insert(static_cast<kwsys_stl::string::size_type>(0),
  1263. static_cast<kwsys_stl::string::size_type>(1), '\"');
  1264. ret.append(1, '\"');
  1265. }
  1266. return ret;
  1267. }
  1268. bool SystemTools::CopyFileIfDifferent(const char* source,
  1269. const char* destination)
  1270. {
  1271. if(SystemTools::FilesDiffer(source, destination))
  1272. {
  1273. return SystemTools::CopyFileAlways(source, destination);
  1274. }
  1275. return true;
  1276. }
  1277. bool SystemTools::FilesDiffer(const char* source,
  1278. const char* destination)
  1279. {
  1280. struct stat statSource;
  1281. if (stat(source, &statSource) != 0)
  1282. {
  1283. return true;
  1284. }
  1285. struct stat statDestination;
  1286. if (stat(destination, &statDestination) != 0)
  1287. {
  1288. return true;
  1289. }
  1290. if(statSource.st_size != statDestination.st_size)
  1291. {
  1292. return true;
  1293. }
  1294. if(statSource.st_size == 0)
  1295. {
  1296. return false;
  1297. }
  1298. #if defined(_WIN32) || defined(__CYGWIN__)
  1299. kwsys_ios::ifstream finSource(source, (kwsys_ios::ios::binary |
  1300. kwsys_ios::ios::in));
  1301. kwsys_ios::ifstream finDestination(destination, (kwsys_ios::ios::binary |
  1302. kwsys_ios::ios::in));
  1303. #else
  1304. kwsys_ios::ifstream finSource(source);
  1305. kwsys_ios::ifstream finDestination(destination);
  1306. #endif
  1307. if(!finSource || !finDestination)
  1308. {
  1309. return true;
  1310. }
  1311. char* source_buf = new char[statSource.st_size];
  1312. char* dest_buf = new char[statSource.st_size];
  1313. finSource.read(source_buf, statSource.st_size);
  1314. finDestination.read(dest_buf, statSource.st_size);
  1315. if(statSource.st_size != static_cast<long>(finSource.gcount()) ||
  1316. statSource.st_size != static_cast<long>(finDestination.gcount()))
  1317. {
  1318. // Failed to read files.
  1319. delete [] source_buf;
  1320. delete [] dest_buf;
  1321. return true;
  1322. }
  1323. int ret = memcmp((const void*)source_buf,
  1324. (const void*)dest_buf,
  1325. statSource.st_size);
  1326. delete [] dest_buf;
  1327. delete [] source_buf;
  1328. return ret != 0;
  1329. }
  1330. /**
  1331. * Copy a file named by "source" to the file named by "destination".
  1332. */
  1333. bool SystemTools::CopyFileAlways(const char* source, const char* destination)
  1334. {
  1335. // If files are the same do not copy
  1336. if ( SystemTools::SameFile(source, destination) )
  1337. {
  1338. return true;
  1339. }
  1340. mode_t perm = 0;
  1341. bool perms = SystemTools::GetPermissions(source, perm);
  1342. const int bufferSize = 4096;
  1343. char buffer[bufferSize];
  1344. // If destination is a directory, try to create a file with the same
  1345. // name as the source in that directory.
  1346. kwsys_stl::string new_destination;
  1347. if(SystemTools::FileExists(destination) &&
  1348. SystemTools::FileIsDirectory(destination))
  1349. {
  1350. new_destination = destination;
  1351. SystemTools::ConvertToUnixSlashes(new_destination);
  1352. new_destination += '/';
  1353. kwsys_stl::string source_name = source;
  1354. new_destination += SystemTools::GetFilenameName(source_name);
  1355. destination = new_destination.c_str();
  1356. }
  1357. // Create destination directory
  1358. kwsys_stl::string destination_dir = destination;
  1359. destination_dir = SystemTools::GetFilenamePath(destination_dir);
  1360. SystemTools::MakeDirectory(destination_dir.c_str());
  1361. // Open files
  1362. #if defined(_WIN32) || defined(__CYGWIN__)
  1363. kwsys_ios::ifstream fin(source,
  1364. kwsys_ios::ios::binary | kwsys_ios::ios::in);
  1365. #else
  1366. kwsys_ios::ifstream fin(source);
  1367. #endif
  1368. if(!fin)
  1369. {
  1370. return false;
  1371. }
  1372. // try and remove the destination file so that read only destination files
  1373. // can be written to.
  1374. // If the remove fails continue so that files in read only directories
  1375. // that do not allow file removal can be modified.
  1376. SystemTools::RemoveFile(destination);
  1377. #if defined(_WIN32) || defined(__CYGWIN__)
  1378. kwsys_ios::ofstream fout(destination,
  1379. kwsys_ios::ios::binary | kwsys_ios::ios::out | kwsys_ios::ios::trunc);
  1380. #else
  1381. kwsys_ios::ofstream fout(destination,
  1382. kwsys_ios::ios::out | kwsys_ios::ios::trunc);
  1383. #endif
  1384. if(!fout)
  1385. {
  1386. return false;
  1387. }
  1388. // This copy loop is very sensitive on certain platforms with
  1389. // slightly broken stream libraries (like HPUX). Normally, it is
  1390. // incorrect to not check the error condition on the fin.read()
  1391. // before using the data, but the fin.gcount() will be zero if an
  1392. // error occurred. Therefore, the loop should be safe everywhere.
  1393. while(fin)
  1394. {
  1395. fin.read(buffer, bufferSize);
  1396. if(fin.gcount())
  1397. {
  1398. fout.write(buffer, fin.gcount());
  1399. }
  1400. }
  1401. // Make sure the operating system has finished writing the file
  1402. // before closing it. This will ensure the file is finished before
  1403. // the check below.
  1404. fout.flush();
  1405. fin.close();
  1406. fout.close();
  1407. // More checks.
  1408. struct stat statSource, statDestination;
  1409. statSource.st_size = 12345;
  1410. statDestination.st_size = 12345;
  1411. if(stat(source, &statSource) != 0)
  1412. {
  1413. return false;
  1414. }
  1415. else if(stat(destination, &statDestination) != 0)
  1416. {
  1417. return false;
  1418. }
  1419. else if(statSource.st_size != statDestination.st_size)
  1420. {
  1421. return false;
  1422. }
  1423. if ( perms )
  1424. {
  1425. if ( !SystemTools::SetPermissions(destination, perm) )
  1426. {
  1427. return false;
  1428. }
  1429. }
  1430. return true;
  1431. }
  1432. /**
  1433. * Copy a directory content from "source" directory to the directory named by
  1434. * "destination".
  1435. */
  1436. bool SystemTools::CopyADirectory(const char* source, const char* destination)
  1437. {
  1438. Directory dir;
  1439. dir.Load(source);
  1440. size_t fileNum;
  1441. if ( !SystemTools::MakeDirectory(destination) )
  1442. {
  1443. return false;
  1444. }
  1445. for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum)
  1446. {
  1447. if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".") &&
  1448. strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".."))
  1449. {
  1450. kwsys_stl::string fullPath = source;
  1451. fullPath += "/";
  1452. fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
  1453. if(SystemTools::FileIsDirectory(fullPath.c_str()))
  1454. {
  1455. kwsys_stl::string fullDestPath = destination;
  1456. fullDestPath += "/";
  1457. fullDestPath += dir.GetFile(static_cast<unsigned long>(fileNum));
  1458. if (!SystemTools::CopyADirectory(fullPath.c_str(), fullDestPath.c_str()))
  1459. {
  1460. return false;
  1461. }
  1462. }
  1463. else
  1464. {
  1465. if(!SystemTools::CopyFileAlways(fullPath.c_str(), destination))
  1466. {
  1467. return false;
  1468. }
  1469. }
  1470. }
  1471. }
  1472. return true;
  1473. }
  1474. // return size of file; also returns zero if no file exists
  1475. unsigned long SystemTools::FileLength(const char* filename)
  1476. {
  1477. struct stat fs;
  1478. if (stat(filename, &fs) != 0)
  1479. {
  1480. return 0;
  1481. }
  1482. else
  1483. {
  1484. return static_cast<unsigned long>(fs.st_size);
  1485. }
  1486. }
  1487. int SystemTools::Strucmp(const char *s1, const char *s2)
  1488. {
  1489. // lifted from Graphvis http://www.graphviz.org
  1490. while ((*s1 != '\0')
  1491. && (tolower(*s1) == tolower(*s2)))
  1492. {
  1493. s1++;
  1494. s2++;
  1495. }
  1496. return tolower(*s1) - tolower(*s2);
  1497. }
  1498. // return file's modified time
  1499. long int SystemTools::ModifiedTime(const char* filename)
  1500. {
  1501. struct stat fs;
  1502. if (stat(filename, &fs) != 0)
  1503. {
  1504. return 0;
  1505. }
  1506. else
  1507. {
  1508. return (long int)fs.st_mtime;
  1509. }
  1510. }
  1511. // return file's creation time
  1512. long int SystemTools::CreationTime(const char* filename)
  1513. {
  1514. struct stat fs;
  1515. if (stat(filename, &fs) != 0)
  1516. {
  1517. return 0;
  1518. }
  1519. else
  1520. {
  1521. return fs.st_ctime >= 0 ? (long int)fs.st_ctime : 0;
  1522. }
  1523. }
  1524. bool SystemTools::ConvertDateMacroString(const char *str, time_t *tmt)
  1525. {
  1526. if (!str || !tmt || strlen(str) < 12)
  1527. {
  1528. return false;
  1529. }
  1530. struct tm tmt2;
  1531. // __DATE__
  1532. // The compilation date of the current source file. The date is a string
  1533. // literal of the form Mmm dd yyyy. The month name Mmm is the same as for
  1534. // dates generated by the library function asctime declared in TIME.H.
  1535. // index: 012345678901
  1536. // format: Mmm dd yyyy
  1537. // example: Dec 19 2003
  1538. static char month_names[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
  1539. char buffer[12];
  1540. strcpy(buffer, str);
  1541. buffer[3] = 0;
  1542. char *ptr = strstr(month_names, buffer);
  1543. if (!ptr)
  1544. {
  1545. return false;
  1546. }
  1547. int month = (ptr - month_names) / 3;
  1548. int day = atoi(buffer + 4);
  1549. int year = atoi(buffer + 7);
  1550. tmt2.tm_isdst = -1;
  1551. tmt2.tm_hour = 0;
  1552. tmt2.tm_min = 0;
  1553. tmt2.tm_sec = 0;
  1554. tmt2.tm_wday = 0;
  1555. tmt2.tm_yday = 0;
  1556. tmt2.tm_mday = day;
  1557. tmt2.tm_mon = month;
  1558. tmt2.tm_year = year - 1900;
  1559. *tmt = mktime(&tmt2);
  1560. return true;
  1561. }
  1562. bool SystemTools::ConvertTimeStampMacroString(const char *str, time_t *tmt)
  1563. {
  1564. if (!str || !tmt || strlen(str) < 27)
  1565. {
  1566. return false;
  1567. }
  1568. struct tm tmt2;
  1569. // __TIMESTAMP__
  1570. // The date and time of the last modification of the current source file,
  1571. // expressed as a string literal in the form Ddd Mmm Date hh:mm:ss yyyy,
  1572. /// where Ddd is the abbreviated day of the week and Date is an integer
  1573. // from 1 to 31.
  1574. // index: 0123456789
  1575. // 0123456789
  1576. // 0123456789
  1577. // format: Ddd Mmm Date hh:mm:ss yyyy
  1578. // example: Fri Dec 19 14:34:58 2003
  1579. static char month_names[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
  1580. char buffer[27];
  1581. strcpy(buffer, str);
  1582. buffer[7] = 0;
  1583. char *ptr = strstr(month_names, buffer + 4);
  1584. if (!ptr)
  1585. {
  1586. return false;
  1587. }
  1588. int month = (ptr - month_names) / 3;
  1589. int day = atoi(buffer + 8);
  1590. int hour = atoi(buffer + 11);
  1591. int min = atoi(buffer + 14);
  1592. int sec = atoi(buffer + 17);
  1593. int year = atoi(buffer + 20);
  1594. tmt2.tm_isdst = -1;
  1595. tmt2.tm_hour = hour;
  1596. tmt2.tm_min = min;
  1597. tmt2.tm_sec = sec;
  1598. tmt2.tm_wday = 0;
  1599. tmt2.tm_yday = 0;
  1600. tmt2.tm_mday = day;
  1601. tmt2.tm_mon = month;
  1602. tmt2.tm_year = year - 1900;
  1603. *tmt = mktime(&tmt2);
  1604. return true;
  1605. }
  1606. kwsys_stl::string SystemTools::GetLastSystemError()
  1607. {
  1608. int e = errno;
  1609. return strerror(e);
  1610. }
  1611. bool SystemTools::RemoveFile(const char* source)
  1612. {
  1613. #ifdef _WIN32
  1614. mode_t mode;
  1615. if ( !SystemTools::GetPermissions(source, mode) )
  1616. {
  1617. return false;
  1618. }
  1619. /* Win32 unlink is stupid --- it fails if the file is read-only */
  1620. SystemTools::SetPermissions(source, S_IWRITE);
  1621. #endif
  1622. bool res = unlink(source) != 0 ? false : true;
  1623. #ifdef _WIN32
  1624. if ( !res )
  1625. {
  1626. SystemTools::SetPermissions(source, mode);
  1627. }
  1628. #endif
  1629. return res;
  1630. }
  1631. bool SystemTools::RemoveADirectory(const char* source)
  1632. {
  1633. Directory dir;
  1634. dir.Load(source);
  1635. size_t fileNum;
  1636. for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum)
  1637. {
  1638. if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".") &&
  1639. strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".."))
  1640. {
  1641. kwsys_stl::string fullPath = source;
  1642. fullPath += "/";
  1643. fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
  1644. if(SystemTools::FileIsDirectory(fullPath.c_str()) &&
  1645. !SystemTools::FileIsSymlink(fullPath.c_str()))
  1646. {
  1647. if (!SystemTools::RemoveADirectory(fullPath.c_str()))
  1648. {
  1649. return false;
  1650. }
  1651. }
  1652. else
  1653. {
  1654. if(!SystemTools::RemoveFile(fullPath.c_str()))
  1655. {
  1656. return false;
  1657. }
  1658. }
  1659. }
  1660. }
  1661. return (Rmdir(source) == 0);
  1662. }
  1663. /**
  1664. */
  1665. size_t SystemTools::GetMaximumFilePathLength()
  1666. {
  1667. return KWSYS_SYSTEMTOOLS_MAXPATH;
  1668. }
  1669. /**
  1670. * Find the file the given name. Searches the given path and then
  1671. * the system search path. Returns the full path to the file if it is
  1672. * found. Otherwise, the empty string is returned.
  1673. */
  1674. kwsys_stl::string SystemTools
  1675. ::FindFile(const char* name,
  1676. const kwsys_stl::vector<kwsys_stl::string>& userPaths)
  1677. {
  1678. // Add the system search path to our path first
  1679. kwsys_stl::vector<kwsys_stl::string> path;
  1680. SystemTools::GetPath(path, "CMAKE_FILE_PATH");
  1681. SystemTools::GetPath(path);
  1682. // now add the additional paths
  1683. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator i = userPaths.begin();
  1684. i != userPaths.end(); ++i)
  1685. {
  1686. path.push_back(*i);
  1687. }
  1688. // now look for the file
  1689. kwsys_stl::string tryPath;
  1690. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator p = path.begin();
  1691. p != path.end(); ++p)
  1692. {
  1693. tryPath = *p;
  1694. tryPath += "/";
  1695. tryPath += name;
  1696. if(SystemTools::FileExists(tryPath.c_str()) &&
  1697. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1698. {
  1699. return SystemTools::CollapseFullPath(tryPath.c_str());
  1700. }
  1701. }
  1702. // Couldn't find the file.
  1703. return "";
  1704. }
  1705. /**
  1706. * Find the executable with the given name. Searches the given path and then
  1707. * the system search path. Returns the full path to the executable if it is
  1708. * found. Otherwise, the empty string is returned.
  1709. */
  1710. kwsys_stl::string SystemTools::FindProgram(
  1711. const char* name,
  1712. const kwsys_stl::vector<kwsys_stl::string>& userPaths,
  1713. bool no_system_path)
  1714. {
  1715. if(!name)
  1716. {
  1717. return "";
  1718. }
  1719. // See if the executable exists as written.
  1720. if(SystemTools::FileExists(name) &&
  1721. !SystemTools::FileIsDirectory(name))
  1722. {
  1723. return SystemTools::CollapseFullPath(name);
  1724. }
  1725. kwsys_stl::string tryPath = name;
  1726. tryPath += SystemTools::GetExecutableExtension();
  1727. if(SystemTools::FileExists(tryPath.c_str()) &&
  1728. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1729. {
  1730. return SystemTools::CollapseFullPath(tryPath.c_str());
  1731. }
  1732. kwsys_stl::vector<kwsys_stl::string> path;
  1733. SystemTools::GetPath(path, "CMAKE_PROGRAM_PATH");
  1734. // Add the system search path to our path.
  1735. if (!no_system_path)
  1736. {
  1737. SystemTools::GetPath(path);
  1738. }
  1739. // now add the additional paths
  1740. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator i = userPaths.begin();
  1741. i != userPaths.end(); ++i)
  1742. {
  1743. path.push_back(*i);
  1744. }
  1745. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator p = path.begin();
  1746. p != path.end(); ++p)
  1747. {
  1748. tryPath = *p;
  1749. tryPath += "/";
  1750. tryPath += name;
  1751. if(SystemTools::FileExists(tryPath.c_str()) &&
  1752. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1753. {
  1754. return SystemTools::CollapseFullPath(tryPath.c_str());
  1755. }
  1756. #ifdef _WIN32
  1757. tryPath += ".com";
  1758. if(SystemTools::FileExists(tryPath.c_str()) &&
  1759. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1760. {
  1761. return SystemTools::CollapseFullPath(tryPath.c_str());
  1762. }
  1763. tryPath = *p;
  1764. tryPath += "/";
  1765. tryPath += name;
  1766. #endif
  1767. tryPath += SystemTools::GetExecutableExtension();
  1768. if(SystemTools::FileExists(tryPath.c_str()) &&
  1769. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1770. {
  1771. return SystemTools::CollapseFullPath(tryPath.c_str());
  1772. }
  1773. }
  1774. // Couldn't find the program.
  1775. return "";
  1776. }
  1777. kwsys_stl::string SystemTools::FindProgram(
  1778. const kwsys_stl::vector<kwsys_stl::string>& names,
  1779. const kwsys_stl::vector<kwsys_stl::string>& path,
  1780. bool noSystemPath)
  1781. {
  1782. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator it = names.begin();
  1783. it != names.end() ; ++it)
  1784. {
  1785. // Try to find the program.
  1786. kwsys_stl::string result = SystemTools::FindProgram(it->c_str(),
  1787. path,
  1788. noSystemPath);
  1789. if ( !result.empty() )
  1790. {
  1791. return result;
  1792. }
  1793. }
  1794. return "";
  1795. }
  1796. /**
  1797. * Find the library with the given name. Searches the given path and then
  1798. * the system search path. Returns the full path to the library if it is
  1799. * found. Otherwise, the empty string is returned.
  1800. */
  1801. kwsys_stl::string SystemTools
  1802. ::FindLibrary(const char* name,
  1803. const kwsys_stl::vector<kwsys_stl::string>& userPaths)
  1804. {
  1805. // See if the executable exists as written.
  1806. if(SystemTools::FileExists(name) &&
  1807. !SystemTools::FileIsDirectory(name))
  1808. {
  1809. return SystemTools::CollapseFullPath(name);
  1810. }
  1811. // Add the system search path to our path.
  1812. kwsys_stl::vector<kwsys_stl::string> path;
  1813. SystemTools::GetPath(path);
  1814. // now add the additional paths
  1815. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator i = userPaths.begin();
  1816. i != userPaths.end(); ++i)
  1817. {
  1818. path.push_back(*i);
  1819. }
  1820. kwsys_stl::string tryPath;
  1821. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator p = path.begin();
  1822. p != path.end(); ++p)
  1823. {
  1824. #if defined(__APPLE__)
  1825. tryPath = *p;
  1826. tryPath += "/";
  1827. tryPath += name;
  1828. tryPath += ".framework";
  1829. if(SystemTools::FileExists(tryPath.c_str())
  1830. && SystemTools::FileIsDirectory(tryPath.c_str()))
  1831. {
  1832. return SystemTools::CollapseFullPath(tryPath.c_str());
  1833. }
  1834. #endif
  1835. #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__MINGW32__)
  1836. tryPath = *p;
  1837. tryPath += "/";
  1838. tryPath += name;
  1839. tryPath += ".lib";
  1840. if(SystemTools::FileExists(tryPath.c_str())
  1841. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1842. {
  1843. return SystemTools::CollapseFullPath(tryPath.c_str());
  1844. }
  1845. #else
  1846. tryPath = *p;
  1847. tryPath += "/lib";
  1848. tryPath += name;
  1849. tryPath += ".so";
  1850. if(SystemTools::FileExists(tryPath.c_str())
  1851. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1852. {
  1853. return SystemTools::CollapseFullPath(tryPath.c_str());
  1854. }
  1855. tryPath = *p;
  1856. tryPath += "/lib";
  1857. tryPath += name;
  1858. tryPath += ".a";
  1859. if(SystemTools::FileExists(tryPath.c_str())
  1860. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1861. {
  1862. return SystemTools::CollapseFullPath(tryPath.c_str());
  1863. }
  1864. tryPath = *p;
  1865. tryPath += "/lib";
  1866. tryPath += name;
  1867. tryPath += ".sl";
  1868. if(SystemTools::FileExists(tryPath.c_str())
  1869. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1870. {
  1871. return SystemTools::CollapseFullPath(tryPath.c_str());
  1872. }
  1873. tryPath = *p;
  1874. tryPath += "/lib";
  1875. tryPath += name;
  1876. tryPath += ".dylib";
  1877. if(SystemTools::FileExists(tryPath.c_str())
  1878. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1879. {
  1880. return SystemTools::CollapseFullPath(tryPath.c_str());
  1881. }
  1882. tryPath = *p;
  1883. tryPath += "/lib";
  1884. tryPath += name;
  1885. tryPath += ".dll";
  1886. if(SystemTools::FileExists(tryPath.c_str())
  1887. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1888. {
  1889. return SystemTools::CollapseFullPath(tryPath.c_str());
  1890. }
  1891. #endif
  1892. }
  1893. // Couldn't find the library.
  1894. return "";
  1895. }
  1896. bool SystemTools::FileIsDirectory(const char* name)
  1897. {
  1898. struct stat fs;
  1899. if(stat(name, &fs) == 0)
  1900. {
  1901. #if _WIN32
  1902. return ((fs.st_mode & _S_IFDIR) != 0);
  1903. #else
  1904. return S_ISDIR(fs.st_mode);
  1905. #endif
  1906. }
  1907. else
  1908. {
  1909. return false;
  1910. }
  1911. }
  1912. bool SystemTools::FileIsSymlink(const char* name)
  1913. {
  1914. #if _WIN32
  1915. (void)name;
  1916. return false;
  1917. #else
  1918. struct stat fs;
  1919. if(lstat(name, &fs) == 0)
  1920. {
  1921. return S_ISLNK(fs.st_mode);
  1922. }
  1923. else
  1924. {
  1925. return false;
  1926. }
  1927. #endif
  1928. }
  1929. int SystemTools::ChangeDirectory(const char *dir)
  1930. {
  1931. return Chdir(dir);
  1932. }
  1933. kwsys_stl::string SystemTools::GetCurrentWorkingDirectory(bool collapse)
  1934. {
  1935. char buf[2048];
  1936. const char* cwd = Getcwd(buf, 2048);
  1937. kwsys_stl::string path;
  1938. if ( cwd )
  1939. {
  1940. path = cwd;
  1941. }
  1942. if(collapse)
  1943. {
  1944. return SystemTools::CollapseFullPath(path.c_str());
  1945. }
  1946. return path;
  1947. }
  1948. kwsys_stl::string SystemTools::GetProgramPath(const char* in_name)
  1949. {
  1950. kwsys_stl::string dir, file;
  1951. SystemTools::SplitProgramPath(in_name, dir, file);
  1952. return dir;
  1953. }
  1954. bool SystemTools::SplitProgramPath(const char* in_name,
  1955. kwsys_stl::string& dir,
  1956. kwsys_stl::string& file,
  1957. bool)
  1958. {
  1959. dir = in_name;
  1960. file = "";
  1961. SystemTools::ConvertToUnixSlashes(dir);
  1962. if(!SystemTools::FileIsDirectory(dir.c_str()))
  1963. {
  1964. kwsys_stl::string::size_type slashPos = dir.rfind("/");
  1965. if(slashPos != kwsys_stl::string::npos)
  1966. {
  1967. file = dir.substr(slashPos+1);
  1968. dir = dir.substr(0, slashPos);
  1969. }
  1970. else
  1971. {
  1972. file = dir;
  1973. dir = "";
  1974. }
  1975. }
  1976. if(!(dir == "") && !SystemTools::FileIsDirectory(dir.c_str()))
  1977. {
  1978. kwsys_stl::string oldDir = in_name;
  1979. SystemTools::ConvertToUnixSlashes(oldDir);
  1980. dir = in_name;
  1981. return false;
  1982. }
  1983. return true;
  1984. }
  1985. bool SystemTools::FindProgramPath(const char* argv0,
  1986. kwsys_stl::string& pathOut,
  1987. kwsys_stl::string& errorMsg,
  1988. const char* exeName,
  1989. const char* buildDir,
  1990. const char* installPrefix )
  1991. {
  1992. kwsys_stl::vector<kwsys_stl::string> failures;
  1993. kwsys_stl::string self = argv0;
  1994. SystemTools::ConvertToUnixSlashes(self);
  1995. failures.push_back(argv0);
  1996. self = SystemTools::FindProgram(self.c_str());
  1997. if(!SystemTools::FileExists(self.c_str()))
  1998. {
  1999. if(buildDir)
  2000. {
  2001. kwsys_stl::string intdir = ".";
  2002. #ifdef CMAKE_INTDIR
  2003. intdir = CMAKE_INTDIR;
  2004. #endif
  2005. self = buildDir;
  2006. self += "/bin/";
  2007. self += intdir;
  2008. self += "/";
  2009. self += exeName;
  2010. self += SystemTools::GetExecutableExtension();
  2011. }
  2012. }
  2013. if(installPrefix)
  2014. {
  2015. if(!SystemTools::FileExists(self.c_str()))
  2016. {
  2017. failures.push_back(self);
  2018. self = installPrefix;
  2019. self += "/bin/";
  2020. self += exeName;
  2021. }
  2022. }
  2023. if(!SystemTools::FileExists(self.c_str()))
  2024. {
  2025. failures.push_back(self);
  2026. kwsys_ios::ostringstream msg;
  2027. msg << "Can not find the command line program " << exeName << "\n";
  2028. msg << " argv[0] = \"" << argv0 << "\"\n";
  2029. msg << " Attempted paths:\n";
  2030. kwsys_stl::vector<kwsys_stl::string>::iterator i;
  2031. for(i=failures.begin(); i != failures.end(); ++i)
  2032. {
  2033. msg << " \"" << i->c_str() << "\"\n";
  2034. }
  2035. errorMsg = msg.str();
  2036. return false;
  2037. }
  2038. pathOut = self;
  2039. return true;
  2040. }
  2041. kwsys_stl::string SystemTools::CollapseFullPath(const char* in_relative)
  2042. {
  2043. return SystemTools::CollapseFullPath(in_relative, 0);
  2044. }
  2045. void SystemTools::AddTranslationPath(const char * a, const char * b)
  2046. {
  2047. kwsys_stl::string path_a = a;
  2048. kwsys_stl::string path_b = b;
  2049. SystemTools::ConvertToUnixSlashes(path_a);
  2050. SystemTools::ConvertToUnixSlashes(path_b);
  2051. // First check this is a directory path, since we don't want the table to
  2052. // grow too fat
  2053. if( SystemTools::FileIsDirectory( path_a.c_str() ) )
  2054. {
  2055. // Make sure the path is a full path and does not contain no '..'
  2056. if( SystemTools::FileIsFullPath(path_b.c_str()) && path_b.find("..")
  2057. == kwsys_stl::string::npos )
  2058. {
  2059. // Before inserting make sure path ends with '/'
  2060. if(path_a.size() && path_a[path_a.size() -1] != '/')
  2061. {
  2062. path_a += '/';
  2063. }
  2064. if(path_b.size() && path_b[path_b.size() -1] != '/')
  2065. {
  2066. path_b += '/';
  2067. }
  2068. if( !(path_a == path_b) )
  2069. {
  2070. SystemTools::TranslationMap->insert(
  2071. SystemToolsTranslationMap::value_type(path_a, path_b));
  2072. }
  2073. }
  2074. }
  2075. }
  2076. void SystemTools::AddKeepPath(const char* dir)
  2077. {
  2078. kwsys_stl::string cdir = SystemTools::CollapseFullPath(dir);
  2079. SystemTools::AddTranslationPath(cdir.c_str(), dir);
  2080. }
  2081. void SystemTools::CheckTranslationPath(kwsys_stl::string & path)
  2082. {
  2083. // Do not translate paths that are too short to have meaningful
  2084. // translations.
  2085. if(path.size() < 2)
  2086. {
  2087. return;
  2088. }
  2089. // Always add a trailing slash before translation. It does not
  2090. // matter if this adds an extra slash, but we do not want to
  2091. // translate part of a directory (like the foo part of foo-dir).
  2092. path += "/";
  2093. // In case a file was specified we still have to go through this:
  2094. // Now convert any path found in the table back to the one desired:
  2095. kwsys_stl::map<kwsys_stl::string,kwsys_stl::string>::const_iterator it;
  2096. for(it = SystemTools::TranslationMap->begin();
  2097. it != SystemTools::TranslationMap->end();
  2098. ++it )
  2099. {
  2100. // We need to check of the path is a substring of the other path
  2101. if(path.find( it->first ) == 0)
  2102. {
  2103. path = path.replace( 0, it->first.size(), it->second);
  2104. }
  2105. }
  2106. // Remove the trailing slash we added before.
  2107. path.erase(path.end()-1, path.end());
  2108. }
  2109. void
  2110. SystemToolsAppendComponents(
  2111. kwsys_stl::vector<kwsys_stl::string>& out_components,
  2112. kwsys_stl::vector<kwsys_stl::string>::const_iterator first,
  2113. kwsys_stl::vector<kwsys_stl::string>::const_iterator last)
  2114. {
  2115. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator i = first;
  2116. i != last; ++i)
  2117. {
  2118. if(*i == "..")
  2119. {
  2120. if(out_components.begin() != out_components.end())
  2121. {
  2122. out_components.erase(out_components.end()-1, out_components.end());
  2123. }
  2124. }
  2125. else if(!(*i == ".") && !(*i == ""))
  2126. {
  2127. out_components.push_back(*i);
  2128. }
  2129. }
  2130. }
  2131. kwsys_stl::string SystemTools::CollapseFullPath(const char* in_path,
  2132. const char* in_base)
  2133. {
  2134. // Collect the output path components.
  2135. kwsys_stl::vector<kwsys_stl::string> out_components;
  2136. // Split the input path components.
  2137. kwsys_stl::vector<kwsys_stl::string> path_components;
  2138. SystemTools::SplitPath(in_path, path_components);
  2139. // If the input path is relative, start with a base path.
  2140. if(path_components[0].length() == 0)
  2141. {
  2142. kwsys_stl::vector<kwsys_stl::string> base_components;
  2143. if(in_base)
  2144. {
  2145. // Use the given base path.
  2146. SystemTools::SplitPath(in_base, base_components);
  2147. }
  2148. else
  2149. {
  2150. // Use the current working directory as a base path.
  2151. char buf[2048];
  2152. if(const char* cwd = Getcwd(buf, 2048))
  2153. {
  2154. SystemTools::SplitPath(cwd, base_components);
  2155. }
  2156. else
  2157. {
  2158. // ??
  2159. }
  2160. }
  2161. // Append base path components to the output path.
  2162. out_components.push_back(base_components[0]);
  2163. SystemToolsAppendComponents(out_components,
  2164. base_components.begin()+1,
  2165. base_components.end());
  2166. }
  2167. // Append input path components to the output path.
  2168. SystemToolsAppendComponents(out_components,
  2169. path_components.begin(),
  2170. path_components.end());
  2171. // Transform the path back to a string.
  2172. kwsys_stl::string newPath = SystemTools::JoinPath(out_components);
  2173. // Update the translation table with this potentially new path.
  2174. SystemTools::AddTranslationPath(newPath.c_str(), in_path);
  2175. SystemTools::CheckTranslationPath(newPath);
  2176. #ifdef _WIN32
  2177. newPath = SystemTools::GetActualCaseForPath(newPath.c_str());
  2178. #endif
  2179. // Return the reconstructed path.
  2180. return newPath;
  2181. }
  2182. // OK, some fun stuff to get the actual case of a given path.
  2183. // Basically, you just need to call ShortPath, then GetLongPathName,
  2184. // However, GetLongPathName is not implemented on windows NT and 95,
  2185. // so we have to simulate it on those versions
  2186. #ifdef _WIN32
  2187. int OldWindowsGetLongPath(kwsys_stl::string const& shortPath,
  2188. kwsys_stl::string& longPath )
  2189. {
  2190. kwsys_stl::string::size_type iFound = shortPath.rfind('/');
  2191. if (iFound > 1 && iFound != shortPath.npos)
  2192. {
  2193. // recurse to peel off components
  2194. //
  2195. if (OldWindowsGetLongPath(shortPath.substr(0, iFound), longPath) > 0)
  2196. {
  2197. longPath += '/';
  2198. if (shortPath[1] != '/')
  2199. {
  2200. WIN32_FIND_DATA findData;
  2201. // append the long component name to the path
  2202. //
  2203. if (INVALID_HANDLE_VALUE != ::FindFirstFile
  2204. (shortPath.c_str(), &findData))
  2205. {
  2206. longPath += findData.cFileName;
  2207. }
  2208. else
  2209. {
  2210. // if FindFirstFile fails, return the error code
  2211. //
  2212. longPath = "";
  2213. return 0;
  2214. }
  2215. }
  2216. }
  2217. }
  2218. else
  2219. {
  2220. longPath = shortPath;
  2221. }
  2222. return longPath.size();
  2223. }
  2224. int PortableGetLongPathName(const char* pathIn,
  2225. kwsys_stl::string & longPath)
  2226. {
  2227. kwsys_stl::string shortPath;
  2228. if(!SystemTools::GetShortPath(pathIn, shortPath))
  2229. {
  2230. return 0;
  2231. }
  2232. HMODULE lh = LoadLibrary("Kernel32.dll");
  2233. if(lh)
  2234. {
  2235. FARPROC proc = GetProcAddress(lh, "GetLongPathNameA");
  2236. if(proc)
  2237. {
  2238. typedef DWORD (WINAPI * GetLongFunctionPtr) (LPCSTR,LPSTR,DWORD);
  2239. GetLongFunctionPtr func = (GetLongFunctionPtr)proc;
  2240. char buffer[MAX_PATH+1];
  2241. int len = (*func)(shortPath.c_str(), buffer, MAX_PATH+1);
  2242. if(len == 0 || len > MAX_PATH+1)
  2243. {
  2244. FreeLibrary(lh);
  2245. return 0;
  2246. }
  2247. longPath = buffer;
  2248. FreeLibrary(lh);
  2249. return len;
  2250. }
  2251. FreeLibrary(lh);
  2252. }
  2253. return OldWindowsGetLongPath(shortPath.c_str(), longPath);
  2254. }
  2255. #endif
  2256. //----------------------------------------------------------------------------
  2257. kwsys_stl::string SystemTools::GetActualCaseForPath(const char* p)
  2258. {
  2259. #ifndef _WIN32
  2260. return p;
  2261. #else
  2262. kwsys_stl::string shortPath;
  2263. if(!SystemTools::GetShortPath(p, shortPath))
  2264. {
  2265. return p;
  2266. }
  2267. kwsys_stl::string longPath;
  2268. int len = PortableGetLongPathName(shortPath.c_str(), longPath);
  2269. if(len == 0 || len > MAX_PATH+1)
  2270. {
  2271. return p;
  2272. }
  2273. return longPath;
  2274. #endif
  2275. }
  2276. //----------------------------------------------------------------------------
  2277. void SystemTools::SplitPath(const char* p,
  2278. kwsys_stl::vector<kwsys_stl::string>& components)
  2279. {
  2280. components.clear();
  2281. // Identify the root component.
  2282. const char* c = p;
  2283. if((c[0] == '/' && c[1] == '/') || (c[0] == '\\' && c[1] == '\\'))
  2284. {
  2285. // Network path.
  2286. components.push_back("//");
  2287. c += 2;
  2288. }
  2289. else if(c[0] == '/')
  2290. {
  2291. // Unix path.
  2292. components.push_back("/");
  2293. c += 1;
  2294. }
  2295. else if(c[0] && c[1] == ':' && (c[2] == '/' || c[2] == '\\'))
  2296. {
  2297. // Windows path.
  2298. kwsys_stl::string root = "_:/";
  2299. root[0] = c[0];
  2300. components.push_back(root);
  2301. c += 3;
  2302. }
  2303. else if(c[0] && c[1] == ':')
  2304. {
  2305. // Path relative to a windows drive working directory.
  2306. kwsys_stl::string root = "_:";
  2307. root[0] = c[0];
  2308. components.push_back(root);
  2309. c += 2;
  2310. }
  2311. else
  2312. {
  2313. // Relative path.
  2314. components.push_back("");
  2315. }
  2316. // Parse the remaining components.
  2317. const char* first = c;
  2318. const char* last = first;
  2319. for(;*last; ++last)
  2320. {
  2321. if(*last == '/' || *last == '\\')
  2322. {
  2323. // End of a component. Save it.
  2324. components.push_back(kwsys_stl::string(first, last-first));
  2325. first = last+1;
  2326. }
  2327. }
  2328. // Save the last component unless there were no components.
  2329. if(last != c)
  2330. {
  2331. components.push_back(kwsys_stl::string(first, last-first));
  2332. }
  2333. }
  2334. //----------------------------------------------------------------------------
  2335. kwsys_stl::string
  2336. SystemTools::JoinPath(const kwsys_stl::vector<kwsys_stl::string>& components)
  2337. {
  2338. kwsys_stl::string result;
  2339. if(components.size() > 0)
  2340. {
  2341. result += components[0];
  2342. }
  2343. if(components.size() > 1)
  2344. {
  2345. result += components[1];
  2346. }
  2347. for(unsigned int i=2; i < components.size(); ++i)
  2348. {
  2349. result += "/";
  2350. result += components[i];
  2351. }
  2352. return result;
  2353. }
  2354. //----------------------------------------------------------------------------
  2355. bool SystemTools::ComparePath(const char* c1, const char* c2)
  2356. {
  2357. #if defined(_WIN32) || defined(__APPLE__)
  2358. return SystemTools::Strucmp(c1, c2) == 0;
  2359. #else
  2360. return strcmp(c1, c2) == 0;
  2361. #endif
  2362. }
  2363. //----------------------------------------------------------------------------
  2364. bool SystemTools::Split(const char* str, kwsys_stl::vector<kwsys_stl::string>& lines, char separator)
  2365. {
  2366. kwsys_stl::string data(str);
  2367. kwsys_stl::string::size_type lpos = 0;
  2368. while(lpos < data.length())
  2369. {
  2370. kwsys_stl::string::size_type rpos = data.find_first_of(separator, lpos);
  2371. if(rpos == kwsys_stl::string::npos)
  2372. {
  2373. // Line ends at end of string without a newline.
  2374. lines.push_back(data.substr(lpos));
  2375. return false;
  2376. }
  2377. else
  2378. {
  2379. // Line ends in a "\n", remove the character.
  2380. lines.push_back(data.substr(lpos, rpos-lpos));
  2381. }
  2382. lpos = rpos+1;
  2383. }
  2384. return true;
  2385. }
  2386. //----------------------------------------------------------------------------
  2387. bool SystemTools::Split(const char* str, kwsys_stl::vector<kwsys_stl::string>& lines)
  2388. {
  2389. kwsys_stl::string data(str);
  2390. kwsys_stl::string::size_type lpos = 0;
  2391. while(lpos < data.length())
  2392. {
  2393. kwsys_stl::string::size_type rpos = data.find_first_of("\n", lpos);
  2394. if(rpos == kwsys_stl::string::npos)
  2395. {
  2396. // Line ends at end of string without a newline.
  2397. lines.push_back(data.substr(lpos));
  2398. return false;
  2399. }
  2400. if((rpos > lpos) && (data[rpos-1] == '\r'))
  2401. {
  2402. // Line ends in a "\r\n" pair, remove both characters.
  2403. lines.push_back(data.substr(lpos, (rpos-1)-lpos));
  2404. }
  2405. else
  2406. {
  2407. // Line ends in a "\n", remove the character.
  2408. lines.push_back(data.substr(lpos, rpos-lpos));
  2409. }
  2410. lpos = rpos+1;
  2411. }
  2412. return true;
  2413. }
  2414. /**
  2415. * Return path of a full filename (no trailing slashes).
  2416. * Warning: returned path is converted to Unix slashes format.
  2417. */
  2418. kwsys_stl::string SystemTools::GetFilenamePath(const kwsys_stl::string& filename)
  2419. {
  2420. kwsys_stl::string fn = filename;
  2421. SystemTools::ConvertToUnixSlashes(fn);
  2422. kwsys_stl::string::size_type slash_pos = fn.rfind("/");
  2423. if(slash_pos != kwsys_stl::string::npos)
  2424. {
  2425. return fn.substr(0, slash_pos);
  2426. }
  2427. else
  2428. {
  2429. return "";
  2430. }
  2431. }
  2432. /**
  2433. * Return file name of a full filename (i.e. file name without path).
  2434. */
  2435. kwsys_stl::string SystemTools::GetFilenameName(const kwsys_stl::string& filename)
  2436. {
  2437. #if defined(_WIN32)
  2438. kwsys_stl::string::size_type slash_pos = filename.find_last_of("/\\");
  2439. #else
  2440. kwsys_stl::string::size_type slash_pos = filename.find_last_of("/");
  2441. #endif
  2442. if(slash_pos != kwsys_stl::string::npos)
  2443. {
  2444. return filename.substr(slash_pos + 1);
  2445. }
  2446. else
  2447. {
  2448. return filename;
  2449. }
  2450. }
  2451. /**
  2452. * Return file extension of a full filename (dot included).
  2453. * Warning: this is the longest extension (for example: .tar.gz)
  2454. */
  2455. kwsys_stl::string SystemTools::GetFilenameExtension(const kwsys_stl::string& filename)
  2456. {
  2457. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  2458. kwsys_stl::string::size_type dot_pos = name.find(".");
  2459. if(dot_pos != kwsys_stl::string::npos)
  2460. {
  2461. return name.substr(dot_pos);
  2462. }
  2463. else
  2464. {
  2465. return "";
  2466. }
  2467. }
  2468. /**
  2469. * Return file extension of a full filename (dot included).
  2470. * Warning: this is the shortest extension (for example: .tar.gz)
  2471. */
  2472. kwsys_stl::string SystemTools::GetFilenameLastExtension(const kwsys_stl::string& filename)
  2473. {
  2474. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  2475. kwsys_stl::string::size_type dot_pos = name.rfind(".");
  2476. if(dot_pos != kwsys_stl::string::npos)
  2477. {
  2478. return name.substr(dot_pos);
  2479. }
  2480. else
  2481. {
  2482. return "";
  2483. }
  2484. }
  2485. /**
  2486. * Return file name without extension of a full filename (i.e. without path).
  2487. * Warning: it considers the longest extension (for example: .tar.gz)
  2488. */
  2489. kwsys_stl::string SystemTools::GetFilenameWithoutExtension(const kwsys_stl::string& filename)
  2490. {
  2491. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  2492. kwsys_stl::string::size_type dot_pos = name.find(".");
  2493. if(dot_pos != kwsys_stl::string::npos)
  2494. {
  2495. return name.substr(0, dot_pos);
  2496. }
  2497. else
  2498. {
  2499. return name;
  2500. }
  2501. }
  2502. /**
  2503. * Return file name without extension of a full filename (i.e. without path).
  2504. * Warning: it considers the last extension (for example: removes .gz
  2505. * from .tar.gz)
  2506. */
  2507. kwsys_stl::string
  2508. SystemTools::GetFilenameWithoutLastExtension(const kwsys_stl::string& filename)
  2509. {
  2510. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  2511. kwsys_stl::string::size_type dot_pos = name.rfind(".");
  2512. if(dot_pos != kwsys_stl::string::npos)
  2513. {
  2514. return name.substr(0, dot_pos);
  2515. }
  2516. else
  2517. {
  2518. return name;
  2519. }
  2520. }
  2521. bool SystemTools::FileHasSignature(const char *filename,
  2522. const char *signature,
  2523. long offset)
  2524. {
  2525. if (!filename || !signature)
  2526. {
  2527. return false;
  2528. }
  2529. FILE *fp;
  2530. fp = fopen(filename, "rb");
  2531. if (!fp)
  2532. {
  2533. return false;
  2534. }
  2535. fseek(fp, offset, SEEK_SET);
  2536. bool res = false;
  2537. size_t signature_len = strlen(signature);
  2538. char *buffer = new char [signature_len];
  2539. if (fread(buffer, 1, signature_len, fp) == signature_len)
  2540. {
  2541. res = (!strncmp(buffer, signature, signature_len) ? true : false);
  2542. }
  2543. delete [] buffer;
  2544. fclose(fp);
  2545. return res;
  2546. }
  2547. SystemTools::FileTypeEnum
  2548. SystemTools::DetectFileType(const char *filename,
  2549. unsigned long length,
  2550. double percent_bin)
  2551. {
  2552. if (!filename || percent_bin < 0)
  2553. {
  2554. return SystemTools::FileTypeUnknown;
  2555. }
  2556. FILE *fp;
  2557. fp = fopen(filename, "rb");
  2558. if (!fp)
  2559. {
  2560. return SystemTools::FileTypeUnknown;
  2561. }
  2562. // Allocate buffer and read bytes
  2563. unsigned char *buffer = new unsigned char [length];
  2564. size_t read_length = fread(buffer, 1, length, fp);
  2565. fclose(fp);
  2566. if (read_length == 0)
  2567. {
  2568. return SystemTools::FileTypeUnknown;
  2569. }
  2570. // Loop over contents and count
  2571. size_t text_count = 0;
  2572. const unsigned char *ptr = buffer;
  2573. const unsigned char *buffer_end = buffer + read_length;
  2574. while (ptr != buffer_end)
  2575. {
  2576. if ((*ptr >= 0x20 && *ptr <= 0x7F) ||
  2577. *ptr == '\n' ||
  2578. *ptr == '\r' ||
  2579. *ptr == '\t')
  2580. {
  2581. text_count++;
  2582. }
  2583. ptr++;
  2584. }
  2585. delete [] buffer;
  2586. double current_percent_bin =
  2587. ((double)(read_length - text_count) / (double)read_length);
  2588. if (current_percent_bin >= percent_bin)
  2589. {
  2590. return SystemTools::FileTypeBinary;
  2591. }
  2592. return SystemTools::FileTypeText;
  2593. }
  2594. bool SystemTools::LocateFileInDir(const char *filename,
  2595. const char *dir,
  2596. kwsys_stl::string& filename_found,
  2597. int try_filename_dirs)
  2598. {
  2599. if (!filename || !dir)
  2600. {
  2601. return false;
  2602. }
  2603. // Get the basename of 'filename'
  2604. kwsys_stl::string filename_base = SystemTools::GetFilenameName(filename);
  2605. // Check if 'dir' is really a directory
  2606. // If win32 and matches something like C:, accept it as a dir
  2607. kwsys_stl::string real_dir;
  2608. if (!SystemTools::FileIsDirectory(dir))
  2609. {
  2610. #if _WIN32
  2611. size_t dir_len = strlen(dir);
  2612. if (dir_len < 2 || dir[dir_len - 1] != ':')
  2613. {
  2614. #endif
  2615. real_dir = SystemTools::GetFilenamePath(dir);
  2616. dir = real_dir.c_str();
  2617. #if _WIN32
  2618. }
  2619. #endif
  2620. }
  2621. // Try to find the file in 'dir'
  2622. bool res = false;
  2623. if (filename_base.size() && dir)
  2624. {
  2625. size_t dir_len = strlen(dir);
  2626. int need_slash =
  2627. (dir_len && dir[dir_len - 1] != '/' && dir[dir_len - 1] != '\\');
  2628. kwsys_stl::string temp = dir;
  2629. if (need_slash)
  2630. {
  2631. temp += "/";
  2632. }
  2633. temp += filename_base;
  2634. if (SystemTools::FileExists(filename_found.c_str()))
  2635. {
  2636. res = true;
  2637. filename_found = temp;
  2638. }
  2639. // If not found, we can try harder by appending part of the file to
  2640. // to the directory to look inside.
  2641. // Example: if we were looking for /foo/bar/yo.txt in /d1/d2, then
  2642. // try to find yo.txt in /d1/d2/bar, then /d1/d2/foo/bar, etc.
  2643. else if (try_filename_dirs)
  2644. {
  2645. kwsys_stl::string filename_dir(filename);
  2646. kwsys_stl::string filename_dir_base;
  2647. kwsys_stl::string filename_dir_bases;
  2648. do
  2649. {
  2650. filename_dir = SystemTools::GetFilenamePath(filename_dir);
  2651. filename_dir_base = SystemTools::GetFilenameName(filename_dir);
  2652. #if _WIN32
  2653. if (!filename_dir_base.size() ||
  2654. filename_dir_base[filename_dir_base.size() - 1] == ':')
  2655. #else
  2656. if (!filename_dir_base.size())
  2657. #endif
  2658. {
  2659. break;
  2660. }
  2661. filename_dir_bases = filename_dir_base + "/" + filename_dir_bases;
  2662. temp = dir;
  2663. if (need_slash)
  2664. {
  2665. temp += "/";
  2666. }
  2667. temp += filename_dir_bases;
  2668. res = SystemTools::LocateFileInDir(
  2669. filename_base.c_str(), temp.c_str(), filename_found, 0);
  2670. } while (!res && filename_dir_base.size());
  2671. }
  2672. }
  2673. return res;
  2674. }
  2675. bool SystemTools::FileIsFullPath(const char* in_name)
  2676. {
  2677. kwsys_stl::string name = in_name;
  2678. #if defined(_WIN32) || defined(__CYGWIN__)
  2679. // On Windows, the name must be at least two characters long.
  2680. if(name.length() < 2)
  2681. {
  2682. return false;
  2683. }
  2684. if(name[1] == ':')
  2685. {
  2686. return true;
  2687. }
  2688. if(name[0] == '\\')
  2689. {
  2690. return true;
  2691. }
  2692. #else
  2693. // On UNIX, the name must be at least one character long.
  2694. if(name.length() < 1)
  2695. {
  2696. return false;
  2697. }
  2698. #endif
  2699. // On UNIX, the name must begin in a '/'.
  2700. // On Windows, if the name begins in a '/', then it is a full
  2701. // network path.
  2702. if(name[0] == '/')
  2703. {
  2704. return true;
  2705. }
  2706. return false;
  2707. }
  2708. bool SystemTools::GetShortPath(const char* path, kwsys_stl::string& shortPath)
  2709. {
  2710. #if defined(WIN32) && !defined(__CYGWIN__)
  2711. const int size = int(strlen(path)) +1; // size of return
  2712. char *buffer = new char[size]; // create a buffer
  2713. char *tempPath = new char[size]; // create a buffer
  2714. int ret;
  2715. // if the path passed in has quotes around it, first remove the quotes
  2716. if (path[0] == '"' && path[strlen(path)-1] == '"')
  2717. {
  2718. strcpy(tempPath,path+1);
  2719. tempPath[strlen(tempPath)-1] = '\0';
  2720. }
  2721. else
  2722. {
  2723. strcpy(tempPath,path);
  2724. }
  2725. buffer[0] = 0;
  2726. ret = GetShortPathName(tempPath, buffer, size);
  2727. if(buffer[0] == 0 || ret > size)
  2728. {
  2729. delete [] buffer;
  2730. delete [] tempPath;
  2731. return false;
  2732. }
  2733. else
  2734. {
  2735. shortPath = buffer;
  2736. delete [] buffer;
  2737. delete [] tempPath;
  2738. return true;
  2739. }
  2740. #else
  2741. shortPath = path;
  2742. return true;
  2743. #endif
  2744. }
  2745. void SystemTools::SplitProgramFromArgs(const char* path,
  2746. kwsys_stl::string& program, kwsys_stl::string& args)
  2747. {
  2748. // see if this is a full path to a program
  2749. // if so then set program to path and args to nothing
  2750. if(SystemTools::FileExists(path))
  2751. {
  2752. program = path;
  2753. args = "";
  2754. return;
  2755. }
  2756. // Try to find the program in the path, note the program
  2757. // may have spaces in its name so we have to look for it
  2758. kwsys_stl::vector<kwsys_stl::string> e;
  2759. kwsys_stl::string findProg = SystemTools::FindProgram(path, e);
  2760. if(findProg.size())
  2761. {
  2762. program = findProg;
  2763. args = "";
  2764. return;
  2765. }
  2766. // Now try and peel off space separated chunks from the end of the string
  2767. // so the largest path possible is found allowing for spaces in the path
  2768. kwsys_stl::string dir = path;
  2769. kwsys_stl::string::size_type spacePos = dir.rfind(' ');
  2770. while(spacePos != kwsys_stl::string::npos)
  2771. {
  2772. kwsys_stl::string tryProg = dir.substr(0, spacePos);
  2773. // See if the file exists
  2774. if(SystemTools::FileExists(tryProg.c_str()))
  2775. {
  2776. program = tryProg;
  2777. // remove trailing spaces from program
  2778. kwsys_stl::string::size_type pos = program.size()-1;
  2779. while(program[pos] == ' ')
  2780. {
  2781. program.erase(pos);
  2782. pos--;
  2783. }
  2784. args = dir.substr(spacePos, dir.size()-spacePos);
  2785. return;
  2786. }
  2787. // Now try and find the the program in the path
  2788. findProg = SystemTools::FindProgram(tryProg.c_str(), e);
  2789. if(findProg.size())
  2790. {
  2791. program = findProg;
  2792. // remove trailing spaces from program
  2793. kwsys_stl::string::size_type pos = program.size()-1;
  2794. while(program[pos] == ' ')
  2795. {
  2796. program.erase(pos);
  2797. pos--;
  2798. }
  2799. args = dir.substr(spacePos, dir.size()-spacePos);
  2800. return;
  2801. }
  2802. // move past the space for the next search
  2803. spacePos--;
  2804. spacePos = dir.rfind(' ', spacePos);
  2805. }
  2806. program = "";
  2807. args = "";
  2808. }
  2809. kwsys_stl::string SystemTools::GetCurrentDateTime(const char* format)
  2810. {
  2811. char buf[1024];
  2812. time_t t;
  2813. time(&t);
  2814. strftime(buf, sizeof(buf), format, localtime(&t));
  2815. return buf;
  2816. }
  2817. kwsys_stl::string SystemTools::MakeCindentifier(const char* s)
  2818. {
  2819. kwsys_stl::string str(s);
  2820. if (str.find_first_of("0123456789") == 0)
  2821. {
  2822. str = "_" + str;
  2823. }
  2824. kwsys_stl::string permited_chars("_"
  2825. "abcdefghijklmnopqrstuvwxyz"
  2826. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  2827. "0123456789");
  2828. kwsys_stl::string::size_type pos = 0;
  2829. while ((pos = str.find_first_not_of(permited_chars, pos)) != kwsys_stl::string::npos)
  2830. {
  2831. str[pos] = '_';
  2832. }
  2833. return str;
  2834. }
  2835. // Due to a buggy stream library on the HP and another on Mac OSX, we
  2836. // need this very carefully written version of getline. Returns true
  2837. // if any data were read before the end-of-file was reached.
  2838. bool SystemTools::GetLineFromStream(kwsys_ios::istream& is, kwsys_stl::string& line,
  2839. bool *has_newline /* = 0 */)
  2840. {
  2841. const int bufferSize = 1024;
  2842. char buffer[bufferSize];
  2843. line = "";
  2844. bool haveData = false;
  2845. if ( has_newline )
  2846. {
  2847. *has_newline = false;
  2848. }
  2849. // If no characters are read from the stream, the end of file has
  2850. // been reached.
  2851. while((is.getline(buffer, bufferSize), is.gcount() > 0))
  2852. {
  2853. haveData = true;
  2854. line.append(buffer);
  2855. // If newline character was read, the gcount includes the
  2856. // character, but the buffer does not. The end of line has been
  2857. // reached.
  2858. if(strlen(buffer) < static_cast<size_t>(is.gcount()))
  2859. {
  2860. if ( has_newline )
  2861. {
  2862. *has_newline = true;
  2863. }
  2864. break;
  2865. }
  2866. // The fail bit may be set. Clear it.
  2867. is.clear(is.rdstate() & ~kwsys_ios::ios::failbit);
  2868. }
  2869. return haveData;
  2870. }
  2871. int SystemTools::GetTerminalWidth()
  2872. {
  2873. int width = -1;
  2874. #ifndef _WIN32
  2875. struct winsize ws;
  2876. char *columns; /* Unix98 environment variable */
  2877. if(ioctl(1, TIOCGWINSZ, &ws) != -1 && ws.ws_col>0 && ws.ws_row>0)
  2878. {
  2879. width = ws.ws_col;
  2880. }
  2881. if(!isatty(STDOUT_FILENO))
  2882. {
  2883. width = -1;
  2884. }
  2885. columns = getenv("COLUMNS");
  2886. if(columns && *columns)
  2887. {
  2888. long t;
  2889. char *endptr;
  2890. t = strtol(columns, &endptr, 0);
  2891. if(endptr && !*endptr && (t>0) && (t<1000))
  2892. {
  2893. width = (int)t;
  2894. }
  2895. }
  2896. if ( width < 9 )
  2897. {
  2898. width = -1;
  2899. }
  2900. #endif
  2901. return width;
  2902. }
  2903. bool SystemTools::GetPermissions(const char* file, mode_t& mode)
  2904. {
  2905. if ( !file )
  2906. {
  2907. return false;
  2908. }
  2909. struct stat st;
  2910. if ( stat(file, &st) < 0 )
  2911. {
  2912. return false;
  2913. }
  2914. mode = st.st_mode;
  2915. return true;
  2916. }
  2917. bool SystemTools::SetPermissions(const char* file, mode_t mode)
  2918. {
  2919. if ( !file )
  2920. {
  2921. return false;
  2922. }
  2923. if ( !SystemTools::FileExists(file) )
  2924. {
  2925. return false;
  2926. }
  2927. if ( chmod(file, mode) < 0 )
  2928. {
  2929. return false;
  2930. }
  2931. return true;
  2932. }
  2933. kwsys_stl::string SystemTools::GetParentDirectory(const char* fileOrDir)
  2934. {
  2935. if ( !fileOrDir || !*fileOrDir )
  2936. {
  2937. return "";
  2938. }
  2939. kwsys_stl::string res = fileOrDir;
  2940. SystemTools::ConvertToUnixSlashes(res);
  2941. kwsys_stl::string::size_type cc = res.size()-1;
  2942. if ( res[cc] == '/' )
  2943. {
  2944. cc --;
  2945. }
  2946. for ( ; cc > 0; cc -- )
  2947. {
  2948. if ( res[cc] == '/' )
  2949. {
  2950. break;
  2951. }
  2952. }
  2953. return res.substr(0, cc);
  2954. }
  2955. bool SystemTools::IsSubDirectory(const char* cSubdir, const char* cDir)
  2956. {
  2957. kwsys_stl::string subdir = cSubdir;
  2958. kwsys_stl::string dir = cDir;
  2959. SystemTools::ConvertToUnixSlashes(dir);
  2960. kwsys_stl::string path = subdir;
  2961. do
  2962. {
  2963. path = SystemTools::GetParentDirectory(path.c_str());
  2964. if ( dir == path )
  2965. {
  2966. return true;
  2967. }
  2968. }
  2969. while ( path.size() > dir.size() );
  2970. return false;
  2971. }
  2972. kwsys_stl::string SystemTools::FileExistsInParentDirectories(const char* fname,
  2973. const char* directory, const char* toplevel)
  2974. {
  2975. kwsys_stl::string file = fname;
  2976. SystemTools::ConvertToUnixSlashes(file);
  2977. kwsys_stl::string dir = directory;
  2978. SystemTools::ConvertToUnixSlashes(dir);
  2979. while ( !dir.empty() )
  2980. {
  2981. kwsys_stl::string path = dir + "/" + file;
  2982. if ( SystemTools::FileExists(path.c_str()) )
  2983. {
  2984. return path;
  2985. }
  2986. if ( dir.size() < strlen(toplevel) )
  2987. {
  2988. break;
  2989. }
  2990. dir = SystemTools::GetParentDirectory(dir.c_str());
  2991. }
  2992. return "";
  2993. }
  2994. void SystemTools::Delay(unsigned int msec)
  2995. {
  2996. #ifdef _WIN32
  2997. Sleep(msec);
  2998. #else
  2999. usleep(msec * 1000);
  3000. #endif
  3001. }
  3002. void SystemTools::ConvertWindowsCommandLineToUnixArguments(
  3003. const char *cmd_line, int *argc, char ***argv)
  3004. {
  3005. if (!cmd_line || !argc || !argv)
  3006. {
  3007. return;
  3008. }
  3009. // A space delimites an argument except when it is inside a quote
  3010. (*argc) = 1;
  3011. size_t cmd_line_len = strlen(cmd_line);
  3012. size_t i;
  3013. for (i = 0; i < cmd_line_len; i++)
  3014. {
  3015. while (isspace(cmd_line[i]) && i < cmd_line_len)
  3016. {
  3017. i++;
  3018. }
  3019. if (i < cmd_line_len)
  3020. {
  3021. if (cmd_line[i] == '\"')
  3022. {
  3023. i++;
  3024. while (cmd_line[i] != '\"' && i < cmd_line_len)
  3025. {
  3026. i++;
  3027. }
  3028. (*argc)++;
  3029. }
  3030. else
  3031. {
  3032. while (!isspace(cmd_line[i]) && i < cmd_line_len)
  3033. {
  3034. i++;
  3035. }
  3036. (*argc)++;
  3037. }
  3038. }
  3039. }
  3040. (*argv) = new char* [(*argc) + 1];
  3041. (*argv)[(*argc)] = NULL;
  3042. // Set the first arg to be the exec name
  3043. (*argv)[0] = new char [1024];
  3044. #ifdef _WIN32
  3045. ::GetModuleFileName(0, (*argv)[0], 1024);
  3046. #else
  3047. (*argv)[0][0] = '\0';
  3048. #endif
  3049. // Allocate the others
  3050. int j;
  3051. for (j = 1; j < (*argc); j++)
  3052. {
  3053. (*argv)[j] = new char [cmd_line_len + 10];
  3054. }
  3055. // Grab the args
  3056. size_t pos;
  3057. int argc_idx = 1;
  3058. for (i = 0; i < cmd_line_len; i++)
  3059. {
  3060. while (isspace(cmd_line[i]) && i < cmd_line_len)
  3061. {
  3062. i++;
  3063. }
  3064. if (i < cmd_line_len)
  3065. {
  3066. if (cmd_line[i] == '\"')
  3067. {
  3068. i++;
  3069. pos = i;
  3070. while (cmd_line[i] != '\"' && i < cmd_line_len)
  3071. {
  3072. i++;
  3073. }
  3074. memcpy((*argv)[argc_idx], &cmd_line[pos], i - pos);
  3075. (*argv)[argc_idx][i - pos] = '\0';
  3076. argc_idx++;
  3077. }
  3078. else
  3079. {
  3080. pos = i;
  3081. while (!isspace(cmd_line[i]) && i < cmd_line_len)
  3082. {
  3083. i++;
  3084. }
  3085. memcpy((*argv)[argc_idx], &cmd_line[pos], i - pos);
  3086. (*argv)[argc_idx][i - pos] = '\0';
  3087. argc_idx++;
  3088. }
  3089. }
  3090. }
  3091. }
  3092. kwsys_stl::string SystemTools::GetOperatingSystemNameAndVersion()
  3093. {
  3094. kwsys_stl::string res;
  3095. #ifdef _WIN32
  3096. char buffer[256];
  3097. OSVERSIONINFOEX osvi;
  3098. BOOL bOsVersionInfoEx;
  3099. // Try calling GetVersionEx using the OSVERSIONINFOEX structure.
  3100. // If that fails, try using the OSVERSIONINFO structure.
  3101. ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
  3102. osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
  3103. bOsVersionInfoEx = GetVersionEx((OSVERSIONINFO *)&osvi);
  3104. if (!bOsVersionInfoEx)
  3105. {
  3106. osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
  3107. if (!GetVersionEx((OSVERSIONINFO *)&osvi))
  3108. {
  3109. return 0;
  3110. }
  3111. }
  3112. switch (osvi.dwPlatformId)
  3113. {
  3114. // Test for the Windows NT product family.
  3115. case VER_PLATFORM_WIN32_NT:
  3116. // Test for the specific product family.
  3117. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2)
  3118. {
  3119. res += "Microsoft Windows Server 2003 family";
  3120. }
  3121. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
  3122. {
  3123. res += "Microsoft Windows XP";
  3124. }
  3125. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0)
  3126. {
  3127. res += "Microsoft Windows 2000";
  3128. }
  3129. if (osvi.dwMajorVersion <= 4)
  3130. {
  3131. res += "Microsoft Windows NT";
  3132. }
  3133. // Test for specific product on Windows NT 4.0 SP6 and later.
  3134. if (bOsVersionInfoEx)
  3135. {
  3136. // Test for the workstation type.
  3137. #if (_MSC_VER >= 1300)
  3138. if (osvi.wProductType == VER_NT_WORKSTATION)
  3139. {
  3140. if (osvi.dwMajorVersion == 4)
  3141. {
  3142. res += " Workstation 4.0";
  3143. }
  3144. else if (osvi.wSuiteMask & VER_SUITE_PERSONAL)
  3145. {
  3146. res += " Home Edition";
  3147. }
  3148. else
  3149. {
  3150. res += " Professional";
  3151. }
  3152. }
  3153. // Test for the server type.
  3154. else if (osvi.wProductType == VER_NT_SERVER)
  3155. {
  3156. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2)
  3157. {
  3158. if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
  3159. {
  3160. res += " Datacenter Edition";
  3161. }
  3162. else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
  3163. {
  3164. res += " Enterprise Edition";
  3165. }
  3166. else if (osvi.wSuiteMask == VER_SUITE_BLADE)
  3167. {
  3168. res += " Web Edition";
  3169. }
  3170. else
  3171. {
  3172. res += " Standard Edition";
  3173. }
  3174. }
  3175. else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0)
  3176. {
  3177. if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
  3178. {
  3179. res += " Datacenter Server";
  3180. }
  3181. else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
  3182. {
  3183. res += " Advanced Server";
  3184. }
  3185. else
  3186. {
  3187. res += " Server";
  3188. }
  3189. }
  3190. else // Windows NT 4.0
  3191. {
  3192. if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
  3193. {
  3194. res += " Server 4.0, Enterprise Edition";
  3195. }
  3196. else
  3197. {
  3198. res += " Server 4.0";
  3199. }
  3200. }
  3201. }
  3202. #endif // Visual Studio 7 and up
  3203. }
  3204. // Test for specific product on Windows NT 4.0 SP5 and earlier
  3205. else
  3206. {
  3207. HKEY hKey;
  3208. #define BUFSIZE 80
  3209. char szProductType[BUFSIZE];
  3210. DWORD dwBufLen=BUFSIZE;
  3211. LONG lRet;
  3212. lRet = RegOpenKeyEx(
  3213. HKEY_LOCAL_MACHINE,
  3214. "SYSTEM\\CurrentControlSet\\Control\\ProductOptions",
  3215. 0, KEY_QUERY_VALUE, &hKey);
  3216. if (lRet != ERROR_SUCCESS)
  3217. {
  3218. return 0;
  3219. }
  3220. lRet = RegQueryValueEx(hKey, "ProductType", NULL, NULL,
  3221. (LPBYTE) szProductType, &dwBufLen);
  3222. if ((lRet != ERROR_SUCCESS) || (dwBufLen > BUFSIZE))
  3223. {
  3224. return 0;
  3225. }
  3226. RegCloseKey(hKey);
  3227. if (lstrcmpi("WINNT", szProductType) == 0)
  3228. {
  3229. res += " Workstation";
  3230. }
  3231. if (lstrcmpi("LANMANNT", szProductType) == 0)
  3232. {
  3233. res += " Server";
  3234. }
  3235. if (lstrcmpi("SERVERNT", szProductType) == 0)
  3236. {
  3237. res += " Advanced Server";
  3238. }
  3239. res += " ";
  3240. sprintf(buffer, "%d", osvi.dwMajorVersion);
  3241. res += buffer;
  3242. res += ".";
  3243. sprintf(buffer, "%d", osvi.dwMinorVersion);
  3244. res += buffer;
  3245. }
  3246. // Display service pack (if any) and build number.
  3247. if (osvi.dwMajorVersion == 4 &&
  3248. lstrcmpi(osvi.szCSDVersion, "Service Pack 6") == 0)
  3249. {
  3250. HKEY hKey;
  3251. LONG lRet;
  3252. // Test for SP6 versus SP6a.
  3253. lRet = RegOpenKeyEx(
  3254. HKEY_LOCAL_MACHINE,
  3255. "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Hotfix\\Q246009",
  3256. 0, KEY_QUERY_VALUE, &hKey);
  3257. if (lRet == ERROR_SUCCESS)
  3258. {
  3259. res += " Service Pack 6a (Build ";
  3260. sprintf(buffer, "%d", osvi.dwBuildNumber & 0xFFFF);
  3261. res += buffer;
  3262. res += ")";
  3263. }
  3264. else // Windows NT 4.0 prior to SP6a
  3265. {
  3266. res += " ";
  3267. res += osvi.szCSDVersion;
  3268. res += " (Build ";
  3269. sprintf(buffer, "%d", osvi.dwBuildNumber & 0xFFFF);
  3270. res += buffer;
  3271. res += ")";
  3272. }
  3273. RegCloseKey(hKey);
  3274. }
  3275. else // Windows NT 3.51 and earlier or Windows 2000 and later
  3276. {
  3277. res += " ";
  3278. res += osvi.szCSDVersion;
  3279. res += " (Build ";
  3280. sprintf(buffer, "%d", osvi.dwBuildNumber & 0xFFFF);
  3281. res += buffer;
  3282. res += ")";
  3283. }
  3284. break;
  3285. // Test for the Windows 95 product family.
  3286. case VER_PLATFORM_WIN32_WINDOWS:
  3287. if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0)
  3288. {
  3289. res += "Microsoft Windows 95";
  3290. if (osvi.szCSDVersion[1] == 'C' || osvi.szCSDVersion[1] == 'B')
  3291. {
  3292. res += " OSR2";
  3293. }
  3294. }
  3295. if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10)
  3296. {
  3297. res += "Microsoft Windows 98";
  3298. if (osvi.szCSDVersion[1] == 'A')
  3299. {
  3300. res += " SE";
  3301. }
  3302. }
  3303. if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90)
  3304. {
  3305. res += "Microsoft Windows Millennium Edition";
  3306. }
  3307. break;
  3308. case VER_PLATFORM_WIN32s:
  3309. res += "Microsoft Win32s";
  3310. break;
  3311. }
  3312. #endif
  3313. return res;
  3314. }
  3315. // These must NOT be initialized. Default initialization to zero is
  3316. // necessary.
  3317. unsigned int SystemToolsManagerCount;
  3318. SystemToolsTranslationMap *SystemTools::TranslationMap;
  3319. // SystemToolsManager manages the SystemTools singleton.
  3320. // SystemToolsManager should be included in any translation unit
  3321. // that will use SystemTools or that implements the singleton
  3322. // pattern. It makes sure that the SystemTools singleton is created
  3323. // before and destroyed after all other singletons in CMake.
  3324. SystemToolsManager::SystemToolsManager()
  3325. {
  3326. if(++SystemToolsManagerCount == 1)
  3327. {
  3328. SystemTools::ClassInitialize();
  3329. }
  3330. }
  3331. SystemToolsManager::~SystemToolsManager()
  3332. {
  3333. if(--SystemToolsManagerCount == 0)
  3334. {
  3335. SystemTools::ClassFinalize();
  3336. }
  3337. }
  3338. void SystemTools::ClassInitialize()
  3339. {
  3340. // Allocate the translation map first.
  3341. SystemTools::TranslationMap = new SystemToolsTranslationMap;
  3342. // Add some special translation paths for unix. These are not added
  3343. // for windows because drive letters need to be maintained. Also,
  3344. // there are not sym-links and mount points on windows anyway.
  3345. #if !defined(_WIN32) || defined(__CYGWIN__)
  3346. // Work-around an SGI problem by always adding this mapping:
  3347. SystemTools::AddTranslationPath("/tmp_mnt/", "/");
  3348. // The tmp path is frequently a logical path so always keep it:
  3349. SystemTools::AddKeepPath("/tmp/");
  3350. // If the current working directory is a logical path then keep the
  3351. // logical name.
  3352. if(const char* pwd = getenv("PWD"))
  3353. {
  3354. char buf[2048];
  3355. if(const char* cwd = Getcwd(buf, 2048))
  3356. {
  3357. // The current working directory may be a logical path. Find
  3358. // the shortest logical path that still produces the correct
  3359. // physical path.
  3360. kwsys_stl::string cwd_changed;
  3361. kwsys_stl::string pwd_changed;
  3362. // Test progressively shorter logical-to-physical mappings.
  3363. kwsys_stl::string pwd_str = pwd;
  3364. kwsys_stl::string cwd_str = cwd;
  3365. kwsys_stl::string pwd_path;
  3366. Realpath(pwd, pwd_path);
  3367. while(cwd_str == pwd_path && cwd_str != pwd_str)
  3368. {
  3369. // The current pair of paths is a working logical mapping.
  3370. cwd_changed = cwd_str;
  3371. pwd_changed = pwd_str;
  3372. // Strip off one directory level and see if the logical
  3373. // mapping still works.
  3374. pwd_str = SystemTools::GetFilenamePath(pwd_str.c_str());
  3375. cwd_str = SystemTools::GetFilenamePath(cwd_str.c_str());
  3376. Realpath(pwd_str.c_str(), pwd_path);
  3377. }
  3378. // Add the translation to keep the logical path name.
  3379. if(!cwd_changed.empty() && !pwd_changed.empty())
  3380. {
  3381. SystemTools::AddTranslationPath(cwd_changed.c_str(),
  3382. pwd_changed.c_str());
  3383. }
  3384. }
  3385. }
  3386. #endif
  3387. }
  3388. void SystemTools::ClassFinalize()
  3389. {
  3390. delete SystemTools::TranslationMap;
  3391. }
  3392. } // namespace KWSYS_NAMESPACE
  3393. #if defined(_MSC_VER) && defined(_DEBUG)
  3394. # include <crtdbg.h>
  3395. # include <stdio.h>
  3396. # include <stdlib.h>
  3397. namespace KWSYS_NAMESPACE
  3398. {
  3399. static int SystemToolsDebugReport(int, char* message, int*)
  3400. {
  3401. fprintf(stderr, message);
  3402. exit(1);
  3403. }
  3404. void SystemTools::EnableMSVCDebugHook()
  3405. {
  3406. if(getenv("DART_TEST_FROM_DART"))
  3407. {
  3408. _CrtSetReportHook(SystemToolsDebugReport);
  3409. }
  3410. }
  3411. } // namespace KWSYS_NAMESPACE
  3412. #else
  3413. namespace KWSYS_NAMESPACE
  3414. {
  3415. void SystemTools::EnableMSVCDebugHook() {}
  3416. } // namespace KWSYS_NAMESPACE
  3417. #endif