SystemTools.cxx 132 KB

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