SystemTools.cxx 126 KB

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