SystemTools.cxx 130 KB

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