SystemTools.cxx 128 KB

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