SystemTools.cxx 106 KB

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