SystemTools.cxx 130 KB

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