SystemTools.cxx 123 KB

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