SystemTools.cxx 119 KB

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