SystemTools.cxx 135 KB

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