SystemTools.cxx 131 KB

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