SystemTools.cxx 118 KB

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