SystemTools.cxx 104 KB

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