SystemTools.cxx 129 KB

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