SystemTools.cxx 128 KB

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