SystemTools.cxx 137 KB

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