SystemTools.cxx 123 KB

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