SystemTools.cxx 127 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705
  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. struct timespec times[2] = { { 0, UTIME_OMIT }, { 0, UTIME_NOW } };
  1226. if (utimensat(AT_FDCWD, filename.c_str(), times, 0) < 0) {
  1227. return false;
  1228. }
  1229. #else
  1230. struct stat st;
  1231. if (stat(filename.c_str(), &st) < 0) {
  1232. return false;
  1233. }
  1234. struct timeval mtime;
  1235. gettimeofday(&mtime, 0);
  1236. # if KWSYS_CXX_HAS_UTIMES
  1237. struct timeval atime;
  1238. # if KWSYS_CXX_STAT_HAS_ST_MTIM
  1239. atime.tv_sec = st.st_atim.tv_sec;
  1240. atime.tv_usec = st.st_atim.tv_nsec / 1000;
  1241. # elif KWSYS_CXX_STAT_HAS_ST_MTIMESPEC
  1242. atime.tv_sec = st.st_atimespec.tv_sec;
  1243. atime.tv_usec = st.st_atimespec.tv_nsec / 1000;
  1244. # else
  1245. atime.tv_sec = st.st_atime;
  1246. atime.tv_usec = 0;
  1247. # endif
  1248. struct timeval times[2] = { atime, mtime };
  1249. if (utimes(filename.c_str(), times) < 0) {
  1250. return false;
  1251. }
  1252. # else
  1253. struct utimbuf times = { st.st_atime, mtime.tv_sec };
  1254. if (utime(filename.c_str(), &times) < 0) {
  1255. return false;
  1256. }
  1257. # endif
  1258. #endif
  1259. return true;
  1260. }
  1261. bool SystemTools::FileTimeCompare(const std::string& f1, const std::string& f2,
  1262. int* result)
  1263. {
  1264. // Default to same time.
  1265. *result = 0;
  1266. #if !defined(_WIN32) || defined(__CYGWIN__)
  1267. // POSIX version. Use stat function to get file modification time.
  1268. struct stat s1;
  1269. if (stat(f1.c_str(), &s1) != 0) {
  1270. return false;
  1271. }
  1272. struct stat s2;
  1273. if (stat(f2.c_str(), &s2) != 0) {
  1274. return false;
  1275. }
  1276. # if KWSYS_CXX_STAT_HAS_ST_MTIM
  1277. // Compare using nanosecond resolution.
  1278. if (s1.st_mtim.tv_sec < s2.st_mtim.tv_sec) {
  1279. *result = -1;
  1280. } else if (s1.st_mtim.tv_sec > s2.st_mtim.tv_sec) {
  1281. *result = 1;
  1282. } else if (s1.st_mtim.tv_nsec < s2.st_mtim.tv_nsec) {
  1283. *result = -1;
  1284. } else if (s1.st_mtim.tv_nsec > s2.st_mtim.tv_nsec) {
  1285. *result = 1;
  1286. }
  1287. # elif KWSYS_CXX_STAT_HAS_ST_MTIMESPEC
  1288. // Compare using nanosecond resolution.
  1289. if (s1.st_mtimespec.tv_sec < s2.st_mtimespec.tv_sec) {
  1290. *result = -1;
  1291. } else if (s1.st_mtimespec.tv_sec > s2.st_mtimespec.tv_sec) {
  1292. *result = 1;
  1293. } else if (s1.st_mtimespec.tv_nsec < s2.st_mtimespec.tv_nsec) {
  1294. *result = -1;
  1295. } else if (s1.st_mtimespec.tv_nsec > s2.st_mtimespec.tv_nsec) {
  1296. *result = 1;
  1297. }
  1298. # else
  1299. // Compare using 1 second resolution.
  1300. if (s1.st_mtime < s2.st_mtime) {
  1301. *result = -1;
  1302. } else if (s1.st_mtime > s2.st_mtime) {
  1303. *result = 1;
  1304. }
  1305. # endif
  1306. #else
  1307. // Windows version. Get the modification time from extended file attributes.
  1308. WIN32_FILE_ATTRIBUTE_DATA f1d;
  1309. WIN32_FILE_ATTRIBUTE_DATA f2d;
  1310. if (!GetFileAttributesExW(Encoding::ToWindowsExtendedPath(f1).c_str(),
  1311. GetFileExInfoStandard, &f1d)) {
  1312. return false;
  1313. }
  1314. if (!GetFileAttributesExW(Encoding::ToWindowsExtendedPath(f2).c_str(),
  1315. GetFileExInfoStandard, &f2d)) {
  1316. return false;
  1317. }
  1318. // Compare the file times using resolution provided by system call.
  1319. *result = (int)CompareFileTime(&f1d.ftLastWriteTime, &f2d.ftLastWriteTime);
  1320. #endif
  1321. return true;
  1322. }
  1323. // Return a capitalized string (i.e the first letter is uppercased, all other
  1324. // are lowercased)
  1325. std::string SystemTools::Capitalized(const std::string& s)
  1326. {
  1327. std::string n;
  1328. if (s.empty()) {
  1329. return n;
  1330. }
  1331. n.resize(s.size());
  1332. n[0] = static_cast<std::string::value_type>(toupper(s[0]));
  1333. for (size_t i = 1; i < s.size(); i++) {
  1334. n[i] = static_cast<std::string::value_type>(tolower(s[i]));
  1335. }
  1336. return n;
  1337. }
  1338. // Return capitalized words
  1339. std::string SystemTools::CapitalizedWords(const std::string& s)
  1340. {
  1341. std::string n(s);
  1342. for (size_t i = 0; i < s.size(); i++) {
  1343. #if defined(_MSC_VER) && defined(_MT) && defined(_DEBUG)
  1344. // MS has an assert that will fail if s[i] < 0; setting
  1345. // LC_CTYPE using setlocale() does *not* help. Painful.
  1346. if ((int)s[i] >= 0 && isalpha(s[i]) &&
  1347. (i == 0 || ((int)s[i - 1] >= 0 && isspace(s[i - 1]))))
  1348. #else
  1349. if (isalpha(s[i]) && (i == 0 || isspace(s[i - 1])))
  1350. #endif
  1351. {
  1352. n[i] = static_cast<std::string::value_type>(toupper(s[i]));
  1353. }
  1354. }
  1355. return n;
  1356. }
  1357. // Return uncapitalized words
  1358. std::string SystemTools::UnCapitalizedWords(const std::string& s)
  1359. {
  1360. std::string n(s);
  1361. for (size_t i = 0; i < s.size(); i++) {
  1362. #if defined(_MSC_VER) && defined(_MT) && defined(_DEBUG)
  1363. // MS has an assert that will fail if s[i] < 0; setting
  1364. // LC_CTYPE using setlocale() does *not* help. Painful.
  1365. if ((int)s[i] >= 0 && isalpha(s[i]) &&
  1366. (i == 0 || ((int)s[i - 1] >= 0 && isspace(s[i - 1]))))
  1367. #else
  1368. if (isalpha(s[i]) && (i == 0 || isspace(s[i - 1])))
  1369. #endif
  1370. {
  1371. n[i] = static_cast<std::string::value_type>(tolower(s[i]));
  1372. }
  1373. }
  1374. return n;
  1375. }
  1376. // only works for words with at least two letters
  1377. std::string SystemTools::AddSpaceBetweenCapitalizedWords(const std::string& s)
  1378. {
  1379. std::string n;
  1380. if (!s.empty()) {
  1381. n.reserve(s.size());
  1382. n += s[0];
  1383. for (size_t i = 1; i < s.size(); i++) {
  1384. if (isupper(s[i]) && !isspace(s[i - 1]) && !isupper(s[i - 1])) {
  1385. n += ' ';
  1386. }
  1387. n += s[i];
  1388. }
  1389. }
  1390. return n;
  1391. }
  1392. char* SystemTools::AppendStrings(const char* str1, const char* str2)
  1393. {
  1394. if (!str1) {
  1395. return SystemTools::DuplicateString(str2);
  1396. }
  1397. if (!str2) {
  1398. return SystemTools::DuplicateString(str1);
  1399. }
  1400. size_t len1 = strlen(str1);
  1401. char* newstr = new char[len1 + strlen(str2) + 1];
  1402. if (!newstr) {
  1403. return KWSYS_NULLPTR;
  1404. }
  1405. strcpy(newstr, str1);
  1406. strcat(newstr + len1, str2);
  1407. return newstr;
  1408. }
  1409. char* SystemTools::AppendStrings(const char* str1, const char* str2,
  1410. const char* str3)
  1411. {
  1412. if (!str1) {
  1413. return SystemTools::AppendStrings(str2, str3);
  1414. }
  1415. if (!str2) {
  1416. return SystemTools::AppendStrings(str1, str3);
  1417. }
  1418. if (!str3) {
  1419. return SystemTools::AppendStrings(str1, str2);
  1420. }
  1421. size_t len1 = strlen(str1), len2 = strlen(str2);
  1422. char* newstr = new char[len1 + len2 + strlen(str3) + 1];
  1423. if (!newstr) {
  1424. return KWSYS_NULLPTR;
  1425. }
  1426. strcpy(newstr, str1);
  1427. strcat(newstr + len1, str2);
  1428. strcat(newstr + len1 + len2, str3);
  1429. return newstr;
  1430. }
  1431. // Return a lower case string
  1432. std::string SystemTools::LowerCase(const std::string& s)
  1433. {
  1434. std::string n;
  1435. n.resize(s.size());
  1436. for (size_t i = 0; i < s.size(); i++) {
  1437. n[i] = static_cast<std::string::value_type>(tolower(s[i]));
  1438. }
  1439. return n;
  1440. }
  1441. // Return a lower case string
  1442. std::string SystemTools::UpperCase(const std::string& s)
  1443. {
  1444. std::string n;
  1445. n.resize(s.size());
  1446. for (size_t i = 0; i < s.size(); i++) {
  1447. n[i] = static_cast<std::string::value_type>(toupper(s[i]));
  1448. }
  1449. return n;
  1450. }
  1451. // Count char in string
  1452. size_t SystemTools::CountChar(const char* str, char c)
  1453. {
  1454. size_t count = 0;
  1455. if (str) {
  1456. while (*str) {
  1457. if (*str == c) {
  1458. ++count;
  1459. }
  1460. ++str;
  1461. }
  1462. }
  1463. return count;
  1464. }
  1465. // Remove chars in string
  1466. char* SystemTools::RemoveChars(const char* str, const char* toremove)
  1467. {
  1468. if (!str) {
  1469. return KWSYS_NULLPTR;
  1470. }
  1471. char* clean_str = new char[strlen(str) + 1];
  1472. char* ptr = clean_str;
  1473. while (*str) {
  1474. const char* str2 = toremove;
  1475. while (*str2 && *str != *str2) {
  1476. ++str2;
  1477. }
  1478. if (!*str2) {
  1479. *ptr++ = *str;
  1480. }
  1481. ++str;
  1482. }
  1483. *ptr = '\0';
  1484. return clean_str;
  1485. }
  1486. // Remove chars in string
  1487. char* SystemTools::RemoveCharsButUpperHex(const char* str)
  1488. {
  1489. if (!str) {
  1490. return KWSYS_NULLPTR;
  1491. }
  1492. char* clean_str = new char[strlen(str) + 1];
  1493. char* ptr = clean_str;
  1494. while (*str) {
  1495. if ((*str >= '0' && *str <= '9') || (*str >= 'A' && *str <= 'F')) {
  1496. *ptr++ = *str;
  1497. }
  1498. ++str;
  1499. }
  1500. *ptr = '\0';
  1501. return clean_str;
  1502. }
  1503. // Replace chars in string
  1504. char* SystemTools::ReplaceChars(char* str, const char* toreplace,
  1505. char replacement)
  1506. {
  1507. if (str) {
  1508. char* ptr = str;
  1509. while (*ptr) {
  1510. const char* ptr2 = toreplace;
  1511. while (*ptr2) {
  1512. if (*ptr == *ptr2) {
  1513. *ptr = replacement;
  1514. }
  1515. ++ptr2;
  1516. }
  1517. ++ptr;
  1518. }
  1519. }
  1520. return str;
  1521. }
  1522. // Returns if string starts with another string
  1523. bool SystemTools::StringStartsWith(const char* str1, const char* str2)
  1524. {
  1525. if (!str1 || !str2) {
  1526. return false;
  1527. }
  1528. size_t len1 = strlen(str1), len2 = strlen(str2);
  1529. return len1 >= len2 && !strncmp(str1, str2, len2) ? true : false;
  1530. }
  1531. // Returns if string starts with another string
  1532. bool SystemTools::StringStartsWith(const std::string& str1, const char* str2)
  1533. {
  1534. if (!str2) {
  1535. return false;
  1536. }
  1537. size_t len1 = str1.size(), len2 = strlen(str2);
  1538. return len1 >= len2 && !strncmp(str1.c_str(), str2, len2) ? true : false;
  1539. }
  1540. // Returns if string ends with another string
  1541. bool SystemTools::StringEndsWith(const char* str1, const char* str2)
  1542. {
  1543. if (!str1 || !str2) {
  1544. return false;
  1545. }
  1546. size_t len1 = strlen(str1), len2 = strlen(str2);
  1547. return len1 >= len2 && !strncmp(str1 + (len1 - len2), str2, len2) ? true
  1548. : false;
  1549. }
  1550. // Returns if string ends with another string
  1551. bool SystemTools::StringEndsWith(const std::string& str1, const char* str2)
  1552. {
  1553. if (!str2) {
  1554. return false;
  1555. }
  1556. size_t len1 = str1.size(), len2 = strlen(str2);
  1557. return len1 >= len2 && !strncmp(str1.c_str() + (len1 - len2), str2, len2)
  1558. ? true
  1559. : false;
  1560. }
  1561. // Returns a pointer to the last occurrence of str2 in str1
  1562. const char* SystemTools::FindLastString(const char* str1, const char* str2)
  1563. {
  1564. if (!str1 || !str2) {
  1565. return KWSYS_NULLPTR;
  1566. }
  1567. size_t len1 = strlen(str1), len2 = strlen(str2);
  1568. if (len1 >= len2) {
  1569. const char* ptr = str1 + len1 - len2;
  1570. do {
  1571. if (!strncmp(ptr, str2, len2)) {
  1572. return ptr;
  1573. }
  1574. } while (ptr-- != str1);
  1575. }
  1576. return KWSYS_NULLPTR;
  1577. }
  1578. // Duplicate string
  1579. char* SystemTools::DuplicateString(const char* str)
  1580. {
  1581. if (str) {
  1582. char* newstr = new char[strlen(str) + 1];
  1583. return strcpy(newstr, str);
  1584. }
  1585. return KWSYS_NULLPTR;
  1586. }
  1587. // Return a cropped string
  1588. std::string SystemTools::CropString(const std::string& s, size_t max_len)
  1589. {
  1590. if (!s.size() || max_len == 0 || max_len >= s.size()) {
  1591. return s;
  1592. }
  1593. std::string n;
  1594. n.reserve(max_len);
  1595. size_t middle = max_len / 2;
  1596. n += s.substr(0, middle);
  1597. n += s.substr(s.size() - (max_len - middle));
  1598. if (max_len > 2) {
  1599. n[middle] = '.';
  1600. if (max_len > 3) {
  1601. n[middle - 1] = '.';
  1602. if (max_len > 4) {
  1603. n[middle + 1] = '.';
  1604. }
  1605. }
  1606. }
  1607. return n;
  1608. }
  1609. std::vector<std::string> SystemTools::SplitString(const std::string& p,
  1610. char sep, bool isPath)
  1611. {
  1612. std::string path = p;
  1613. std::vector<std::string> paths;
  1614. if (path.empty()) {
  1615. return paths;
  1616. }
  1617. if (isPath && path[0] == '/') {
  1618. path.erase(path.begin());
  1619. paths.push_back("/");
  1620. }
  1621. std::string::size_type pos1 = 0;
  1622. std::string::size_type pos2 = path.find(sep, pos1 + 1);
  1623. while (pos2 != std::string::npos) {
  1624. paths.push_back(path.substr(pos1, pos2 - pos1));
  1625. pos1 = pos2 + 1;
  1626. pos2 = path.find(sep, pos1 + 1);
  1627. }
  1628. paths.push_back(path.substr(pos1, pos2 - pos1));
  1629. return paths;
  1630. }
  1631. int SystemTools::EstimateFormatLength(const char* format, va_list ap)
  1632. {
  1633. if (!format) {
  1634. return 0;
  1635. }
  1636. // Quick-hack attempt at estimating the length of the string.
  1637. // Should never under-estimate.
  1638. // Start with the length of the format string itself.
  1639. size_t length = strlen(format);
  1640. // Increase the length for every argument in the format.
  1641. const char* cur = format;
  1642. while (*cur) {
  1643. if (*cur++ == '%') {
  1644. // Skip "%%" since it doesn't correspond to a va_arg.
  1645. if (*cur != '%') {
  1646. while (!int(isalpha(*cur))) {
  1647. ++cur;
  1648. }
  1649. switch (*cur) {
  1650. case 's': {
  1651. // Check the length of the string.
  1652. char* s = va_arg(ap, char*);
  1653. if (s) {
  1654. length += strlen(s);
  1655. }
  1656. } break;
  1657. case 'e':
  1658. case 'f':
  1659. case 'g': {
  1660. // Assume the argument contributes no more than 64 characters.
  1661. length += 64;
  1662. // Eat the argument.
  1663. static_cast<void>(va_arg(ap, double));
  1664. } break;
  1665. default: {
  1666. // Assume the argument contributes no more than 64 characters.
  1667. length += 64;
  1668. // Eat the argument.
  1669. static_cast<void>(va_arg(ap, int));
  1670. } break;
  1671. }
  1672. }
  1673. // Move past the characters just tested.
  1674. ++cur;
  1675. }
  1676. }
  1677. return static_cast<int>(length);
  1678. }
  1679. std::string SystemTools::EscapeChars(const char* str,
  1680. const char* chars_to_escape,
  1681. char escape_char)
  1682. {
  1683. std::string n;
  1684. if (str) {
  1685. if (!chars_to_escape || !*chars_to_escape) {
  1686. n.append(str);
  1687. } else {
  1688. n.reserve(strlen(str));
  1689. while (*str) {
  1690. const char* ptr = chars_to_escape;
  1691. while (*ptr) {
  1692. if (*str == *ptr) {
  1693. n += escape_char;
  1694. break;
  1695. }
  1696. ++ptr;
  1697. }
  1698. n += *str;
  1699. ++str;
  1700. }
  1701. }
  1702. }
  1703. return n;
  1704. }
  1705. #ifdef __VMS
  1706. static void ConvertVMSToUnix(std::string& path)
  1707. {
  1708. std::string::size_type rootEnd = path.find(":[");
  1709. std::string::size_type pathEnd = path.find("]");
  1710. if (rootEnd != std::string::npos) {
  1711. std::string root = path.substr(0, rootEnd);
  1712. std::string pathPart = path.substr(rootEnd + 2, pathEnd - rootEnd - 2);
  1713. const char* pathCString = pathPart.c_str();
  1714. const char* pos0 = pathCString;
  1715. for (std::string::size_type pos = 0; *pos0; ++pos) {
  1716. if (*pos0 == '.') {
  1717. pathPart[pos] = '/';
  1718. }
  1719. pos0++;
  1720. }
  1721. path = "/" + root + "/" + pathPart;
  1722. }
  1723. }
  1724. #endif
  1725. // convert windows slashes to unix slashes
  1726. void SystemTools::ConvertToUnixSlashes(std::string& path)
  1727. {
  1728. if (path.empty()) {
  1729. return;
  1730. }
  1731. const char* pathCString = path.c_str();
  1732. bool hasDoubleSlash = false;
  1733. #ifdef __VMS
  1734. ConvertVMSToUnix(path);
  1735. #else
  1736. const char* pos0 = pathCString;
  1737. for (std::string::size_type pos = 0; *pos0; ++pos) {
  1738. if (*pos0 == '\\') {
  1739. path[pos] = '/';
  1740. }
  1741. // Also, reuse the loop to check for slash followed by another slash
  1742. if (!hasDoubleSlash && *(pos0 + 1) == '/' && *(pos0 + 2) == '/') {
  1743. # ifdef _WIN32
  1744. // However, on windows if the first characters are both slashes,
  1745. // then keep them that way, so that network paths can be handled.
  1746. if (pos > 0) {
  1747. hasDoubleSlash = true;
  1748. }
  1749. # else
  1750. hasDoubleSlash = true;
  1751. # endif
  1752. }
  1753. pos0++;
  1754. }
  1755. if (hasDoubleSlash) {
  1756. SystemTools::ReplaceString(path, "//", "/");
  1757. }
  1758. #endif
  1759. // remove any trailing slash
  1760. // if there is a tilda ~ then replace it with HOME
  1761. pathCString = path.c_str();
  1762. if (pathCString[0] == '~' &&
  1763. (pathCString[1] == '/' || pathCString[1] == '\0')) {
  1764. std::string homeEnv;
  1765. if (SystemTools::GetEnv("HOME", homeEnv)) {
  1766. path.replace(0, 1, homeEnv);
  1767. }
  1768. }
  1769. #ifdef HAVE_GETPWNAM
  1770. else if (pathCString[0] == '~') {
  1771. std::string::size_type idx = path.find_first_of("/\0");
  1772. std::string user = path.substr(1, idx - 1);
  1773. passwd* pw = getpwnam(user.c_str());
  1774. if (pw) {
  1775. path.replace(0, idx, pw->pw_dir);
  1776. }
  1777. }
  1778. #endif
  1779. // remove trailing slash if the path is more than
  1780. // a single /
  1781. pathCString = path.c_str();
  1782. size_t size = path.size();
  1783. if (size > 1 && *path.rbegin() == '/') {
  1784. // if it is c:/ then do not remove the trailing slash
  1785. if (!((size == 3 && pathCString[1] == ':'))) {
  1786. path.resize(size - 1);
  1787. }
  1788. }
  1789. }
  1790. #ifdef _WIN32
  1791. std::wstring SystemTools::ConvertToWindowsExtendedPath(
  1792. const std::string& source)
  1793. {
  1794. return Encoding::ToWindowsExtendedPath(source);
  1795. }
  1796. #endif
  1797. // change // to /, and escape any spaces in the path
  1798. std::string SystemTools::ConvertToUnixOutputPath(const std::string& path)
  1799. {
  1800. std::string ret = path;
  1801. // remove // except at the beginning might be a cygwin drive
  1802. std::string::size_type pos = 1;
  1803. while ((pos = ret.find("//", pos)) != std::string::npos) {
  1804. ret.erase(pos, 1);
  1805. }
  1806. // escape spaces and () in the path
  1807. if (ret.find_first_of(" ") != std::string::npos) {
  1808. std::string result;
  1809. char lastch = 1;
  1810. for (const char* ch = ret.c_str(); *ch != '\0'; ++ch) {
  1811. // if it is already escaped then don't try to escape it again
  1812. if ((*ch == ' ') && lastch != '\\') {
  1813. result += '\\';
  1814. }
  1815. result += *ch;
  1816. lastch = *ch;
  1817. }
  1818. ret = result;
  1819. }
  1820. return ret;
  1821. }
  1822. std::string SystemTools::ConvertToOutputPath(const std::string& path)
  1823. {
  1824. #if defined(_WIN32) && !defined(__CYGWIN__)
  1825. return SystemTools::ConvertToWindowsOutputPath(path);
  1826. #else
  1827. return SystemTools::ConvertToUnixOutputPath(path);
  1828. #endif
  1829. }
  1830. // remove double slashes not at the start
  1831. std::string SystemTools::ConvertToWindowsOutputPath(const std::string& path)
  1832. {
  1833. std::string ret;
  1834. // make it big enough for all of path and double quotes
  1835. ret.reserve(path.size() + 3);
  1836. // put path into the string
  1837. ret = path;
  1838. std::string::size_type pos = 0;
  1839. // first convert all of the slashes
  1840. while ((pos = ret.find('/', pos)) != std::string::npos) {
  1841. ret[pos] = '\\';
  1842. pos++;
  1843. }
  1844. // check for really small paths
  1845. if (ret.size() < 2) {
  1846. return ret;
  1847. }
  1848. // now clean up a bit and remove double slashes
  1849. // Only if it is not the first position in the path which is a network
  1850. // path on windows
  1851. pos = 1; // start at position 1
  1852. if (ret[0] == '\"') {
  1853. pos = 2; // if the string is already quoted then start at 2
  1854. if (ret.size() < 3) {
  1855. return ret;
  1856. }
  1857. }
  1858. while ((pos = ret.find("\\\\", pos)) != std::string::npos) {
  1859. ret.erase(pos, 1);
  1860. }
  1861. // now double quote the path if it has spaces in it
  1862. // and is not already double quoted
  1863. if (ret.find(' ') != std::string::npos && ret[0] != '\"') {
  1864. ret.insert(static_cast<std::string::size_type>(0),
  1865. static_cast<std::string::size_type>(1), '\"');
  1866. ret.append(1, '\"');
  1867. }
  1868. return ret;
  1869. }
  1870. bool SystemTools::CopyFileIfDifferent(const std::string& source,
  1871. const std::string& destination)
  1872. {
  1873. // special check for a destination that is a directory
  1874. // FilesDiffer does not handle file to directory compare
  1875. if (SystemTools::FileIsDirectory(destination)) {
  1876. std::string new_destination = destination;
  1877. SystemTools::ConvertToUnixSlashes(new_destination);
  1878. new_destination += '/';
  1879. std::string source_name = source;
  1880. new_destination += SystemTools::GetFilenameName(source_name);
  1881. if (SystemTools::FilesDiffer(source, new_destination)) {
  1882. return SystemTools::CopyFileAlways(source, destination);
  1883. } else {
  1884. // the files are the same so the copy is done return
  1885. // true
  1886. return true;
  1887. }
  1888. }
  1889. // source and destination are files so do a copy if they
  1890. // are different
  1891. if (SystemTools::FilesDiffer(source, destination)) {
  1892. return SystemTools::CopyFileAlways(source, destination);
  1893. }
  1894. // at this point the files must be the same so return true
  1895. return true;
  1896. }
  1897. #define KWSYS_ST_BUFFER 4096
  1898. bool SystemTools::FilesDiffer(const std::string& source,
  1899. const std::string& destination)
  1900. {
  1901. #if defined(_WIN32)
  1902. WIN32_FILE_ATTRIBUTE_DATA statSource;
  1903. if (GetFileAttributesExW(Encoding::ToWindowsExtendedPath(source).c_str(),
  1904. GetFileExInfoStandard, &statSource) == 0) {
  1905. return true;
  1906. }
  1907. WIN32_FILE_ATTRIBUTE_DATA statDestination;
  1908. if (GetFileAttributesExW(
  1909. Encoding::ToWindowsExtendedPath(destination).c_str(),
  1910. GetFileExInfoStandard, &statDestination) == 0) {
  1911. return true;
  1912. }
  1913. if (statSource.nFileSizeHigh != statDestination.nFileSizeHigh ||
  1914. statSource.nFileSizeLow != statDestination.nFileSizeLow) {
  1915. return true;
  1916. }
  1917. if (statSource.nFileSizeHigh == 0 && statSource.nFileSizeLow == 0) {
  1918. return false;
  1919. }
  1920. off_t nleft =
  1921. ((__int64)statSource.nFileSizeHigh << 32) + statSource.nFileSizeLow;
  1922. #else
  1923. struct stat statSource;
  1924. if (stat(source.c_str(), &statSource) != 0) {
  1925. return true;
  1926. }
  1927. struct stat statDestination;
  1928. if (stat(destination.c_str(), &statDestination) != 0) {
  1929. return true;
  1930. }
  1931. if (statSource.st_size != statDestination.st_size) {
  1932. return true;
  1933. }
  1934. if (statSource.st_size == 0) {
  1935. return false;
  1936. }
  1937. off_t nleft = statSource.st_size;
  1938. #endif
  1939. #if defined(_WIN32)
  1940. kwsys::ifstream finSource(source.c_str(), (std::ios::binary | std::ios::in));
  1941. kwsys::ifstream finDestination(destination.c_str(),
  1942. (std::ios::binary | std::ios::in));
  1943. #else
  1944. kwsys::ifstream finSource(source.c_str());
  1945. kwsys::ifstream finDestination(destination.c_str());
  1946. #endif
  1947. if (!finSource || !finDestination) {
  1948. return true;
  1949. }
  1950. // Compare the files a block at a time.
  1951. char source_buf[KWSYS_ST_BUFFER];
  1952. char dest_buf[KWSYS_ST_BUFFER];
  1953. while (nleft > 0) {
  1954. // Read a block from each file.
  1955. std::streamsize nnext = (nleft > KWSYS_ST_BUFFER)
  1956. ? KWSYS_ST_BUFFER
  1957. : static_cast<std::streamsize>(nleft);
  1958. finSource.read(source_buf, nnext);
  1959. finDestination.read(dest_buf, nnext);
  1960. // If either failed to read assume they are different.
  1961. if (static_cast<std::streamsize>(finSource.gcount()) != nnext ||
  1962. static_cast<std::streamsize>(finDestination.gcount()) != nnext) {
  1963. return true;
  1964. }
  1965. // If this block differs the file differs.
  1966. if (memcmp(static_cast<const void*>(source_buf),
  1967. static_cast<const void*>(dest_buf),
  1968. static_cast<size_t>(nnext)) != 0) {
  1969. return true;
  1970. }
  1971. // Update the byte count remaining.
  1972. nleft -= nnext;
  1973. }
  1974. // No differences found.
  1975. return false;
  1976. }
  1977. /**
  1978. * Copy a file named by "source" to the file named by "destination".
  1979. */
  1980. bool SystemTools::CopyFileAlways(const std::string& source,
  1981. const std::string& destination)
  1982. {
  1983. // If files are the same do not copy
  1984. if (SystemTools::SameFile(source, destination)) {
  1985. return true;
  1986. }
  1987. mode_t perm = 0;
  1988. bool perms = SystemTools::GetPermissions(source, perm);
  1989. std::string real_destination = destination;
  1990. if (SystemTools::FileIsDirectory(source)) {
  1991. SystemTools::MakeDirectory(destination);
  1992. } else {
  1993. const int bufferSize = 4096;
  1994. char buffer[bufferSize];
  1995. // If destination is a directory, try to create a file with the same
  1996. // name as the source in that directory.
  1997. std::string destination_dir;
  1998. if (SystemTools::FileIsDirectory(destination)) {
  1999. destination_dir = real_destination;
  2000. SystemTools::ConvertToUnixSlashes(real_destination);
  2001. real_destination += '/';
  2002. std::string source_name = source;
  2003. real_destination += SystemTools::GetFilenameName(source_name);
  2004. } else {
  2005. destination_dir = SystemTools::GetFilenamePath(destination);
  2006. }
  2007. // Create destination directory
  2008. SystemTools::MakeDirectory(destination_dir);
  2009. // Open files
  2010. #if defined(_WIN32)
  2011. kwsys::ifstream fin(
  2012. Encoding::ToNarrow(Encoding::ToWindowsExtendedPath(source)).c_str(),
  2013. std::ios::in | std::ios::binary);
  2014. #else
  2015. kwsys::ifstream fin(source.c_str(), std::ios::in | std::ios::binary);
  2016. #endif
  2017. if (!fin) {
  2018. return false;
  2019. }
  2020. // try and remove the destination file so that read only destination files
  2021. // can be written to.
  2022. // If the remove fails continue so that files in read only directories
  2023. // that do not allow file removal can be modified.
  2024. SystemTools::RemoveFile(real_destination);
  2025. #if defined(_WIN32)
  2026. kwsys::ofstream fout(
  2027. Encoding::ToNarrow(Encoding::ToWindowsExtendedPath(real_destination))
  2028. .c_str(),
  2029. std::ios::out | std::ios::trunc | std::ios::binary);
  2030. #else
  2031. kwsys::ofstream fout(real_destination.c_str(),
  2032. std::ios::out | std::ios::trunc | std::ios::binary);
  2033. #endif
  2034. if (!fout) {
  2035. return false;
  2036. }
  2037. // This copy loop is very sensitive on certain platforms with
  2038. // slightly broken stream libraries (like HPUX). Normally, it is
  2039. // incorrect to not check the error condition on the fin.read()
  2040. // before using the data, but the fin.gcount() will be zero if an
  2041. // error occurred. Therefore, the loop should be safe everywhere.
  2042. while (fin) {
  2043. fin.read(buffer, bufferSize);
  2044. if (fin.gcount()) {
  2045. fout.write(buffer, fin.gcount());
  2046. } else {
  2047. break;
  2048. }
  2049. }
  2050. // Make sure the operating system has finished writing the file
  2051. // before closing it. This will ensure the file is finished before
  2052. // the check below.
  2053. fout.flush();
  2054. fin.close();
  2055. fout.close();
  2056. if (!fout) {
  2057. return false;
  2058. }
  2059. }
  2060. if (perms) {
  2061. if (!SystemTools::SetPermissions(real_destination, perm)) {
  2062. return false;
  2063. }
  2064. }
  2065. return true;
  2066. }
  2067. bool SystemTools::CopyAFile(const std::string& source,
  2068. const std::string& destination, bool always)
  2069. {
  2070. if (always) {
  2071. return SystemTools::CopyFileAlways(source, destination);
  2072. } else {
  2073. return SystemTools::CopyFileIfDifferent(source, destination);
  2074. }
  2075. }
  2076. /**
  2077. * Copy a directory content from "source" directory to the directory named by
  2078. * "destination".
  2079. */
  2080. bool SystemTools::CopyADirectory(const std::string& source,
  2081. const std::string& destination, bool always)
  2082. {
  2083. Directory dir;
  2084. if (dir.Load(source) == 0) {
  2085. return false;
  2086. }
  2087. size_t fileNum;
  2088. if (!SystemTools::MakeDirectory(destination)) {
  2089. return false;
  2090. }
  2091. for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum) {
  2092. if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)), ".") &&
  2093. strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)), "..")) {
  2094. std::string fullPath = source;
  2095. fullPath += "/";
  2096. fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
  2097. if (SystemTools::FileIsDirectory(fullPath)) {
  2098. std::string fullDestPath = destination;
  2099. fullDestPath += "/";
  2100. fullDestPath += dir.GetFile(static_cast<unsigned long>(fileNum));
  2101. if (!SystemTools::CopyADirectory(fullPath, fullDestPath, always)) {
  2102. return false;
  2103. }
  2104. } else {
  2105. if (!SystemTools::CopyAFile(fullPath, destination, always)) {
  2106. return false;
  2107. }
  2108. }
  2109. }
  2110. }
  2111. return true;
  2112. }
  2113. // return size of file; also returns zero if no file exists
  2114. unsigned long SystemTools::FileLength(const std::string& filename)
  2115. {
  2116. unsigned long length = 0;
  2117. #ifdef _WIN32
  2118. WIN32_FILE_ATTRIBUTE_DATA fs;
  2119. if (GetFileAttributesExW(Encoding::ToWindowsExtendedPath(filename).c_str(),
  2120. GetFileExInfoStandard, &fs) != 0) {
  2121. /* To support the full 64-bit file size, use fs.nFileSizeHigh
  2122. * and fs.nFileSizeLow to construct the 64 bit size
  2123. length = ((__int64)fs.nFileSizeHigh << 32) + fs.nFileSizeLow;
  2124. */
  2125. length = static_cast<unsigned long>(fs.nFileSizeLow);
  2126. }
  2127. #else
  2128. struct stat fs;
  2129. if (stat(filename.c_str(), &fs) == 0) {
  2130. length = static_cast<unsigned long>(fs.st_size);
  2131. }
  2132. #endif
  2133. return length;
  2134. }
  2135. int SystemTools::Strucmp(const char* l, const char* r)
  2136. {
  2137. int lc;
  2138. int rc;
  2139. do {
  2140. lc = tolower(*l++);
  2141. rc = tolower(*r++);
  2142. } while (lc == rc && lc);
  2143. return lc - rc;
  2144. }
  2145. // return file's modified time
  2146. long int SystemTools::ModifiedTime(const std::string& filename)
  2147. {
  2148. long int mt = 0;
  2149. #ifdef _WIN32
  2150. WIN32_FILE_ATTRIBUTE_DATA fs;
  2151. if (GetFileAttributesExW(Encoding::ToWindowsExtendedPath(filename).c_str(),
  2152. GetFileExInfoStandard, &fs) != 0) {
  2153. mt = windows_filetime_to_posix_time(fs.ftLastWriteTime);
  2154. }
  2155. #else
  2156. struct stat fs;
  2157. if (stat(filename.c_str(), &fs) == 0) {
  2158. mt = static_cast<long int>(fs.st_mtime);
  2159. }
  2160. #endif
  2161. return mt;
  2162. }
  2163. // return file's creation time
  2164. long int SystemTools::CreationTime(const std::string& filename)
  2165. {
  2166. long int ct = 0;
  2167. #ifdef _WIN32
  2168. WIN32_FILE_ATTRIBUTE_DATA fs;
  2169. if (GetFileAttributesExW(Encoding::ToWindowsExtendedPath(filename).c_str(),
  2170. GetFileExInfoStandard, &fs) != 0) {
  2171. ct = windows_filetime_to_posix_time(fs.ftCreationTime);
  2172. }
  2173. #else
  2174. struct stat fs;
  2175. if (stat(filename.c_str(), &fs) == 0) {
  2176. ct = fs.st_ctime >= 0 ? static_cast<long int>(fs.st_ctime) : 0;
  2177. }
  2178. #endif
  2179. return ct;
  2180. }
  2181. std::string SystemTools::GetLastSystemError()
  2182. {
  2183. int e = errno;
  2184. return strerror(e);
  2185. }
  2186. #ifdef _WIN32
  2187. static bool IsJunction(const std::wstring& source)
  2188. {
  2189. # ifdef FSCTL_GET_REPARSE_POINT
  2190. const DWORD JUNCTION_ATTRS =
  2191. FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT;
  2192. DWORD attrs = GetFileAttributesW(source.c_str());
  2193. if (attrs == INVALID_FILE_ATTRIBUTES) {
  2194. return false;
  2195. }
  2196. if ((attrs & JUNCTION_ATTRS) != JUNCTION_ATTRS) {
  2197. return false;
  2198. }
  2199. // Adjust privileges so that we can succefully open junction points.
  2200. HANDLE token;
  2201. TOKEN_PRIVILEGES privs;
  2202. OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &token);
  2203. LookupPrivilegeValue(NULL, SE_BACKUP_NAME, &privs.Privileges[0].Luid);
  2204. privs.PrivilegeCount = 1;
  2205. privs.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  2206. AdjustTokenPrivileges(token, FALSE, &privs, sizeof(TOKEN_PRIVILEGES), NULL,
  2207. NULL);
  2208. CloseHandle(token);
  2209. HANDLE dir = CreateFileW(
  2210. source.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING,
  2211. FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, NULL);
  2212. if (dir == INVALID_HANDLE_VALUE) {
  2213. return false;
  2214. }
  2215. // Query whether this is a reparse point or not.
  2216. BYTE buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
  2217. REPARSE_GUID_DATA_BUFFER* reparse_buffer = (REPARSE_GUID_DATA_BUFFER*)buffer;
  2218. DWORD sentinel;
  2219. BOOL success =
  2220. DeviceIoControl(dir, FSCTL_GET_REPARSE_POINT, NULL, 0, reparse_buffer,
  2221. MAXIMUM_REPARSE_DATA_BUFFER_SIZE, &sentinel, NULL);
  2222. CloseHandle(dir);
  2223. return (success &&
  2224. (reparse_buffer->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT));
  2225. # else
  2226. return false;
  2227. # endif
  2228. }
  2229. static bool DeleteJunction(const std::wstring& source)
  2230. {
  2231. # ifdef FSCTL_DELETE_REPARSE_POINT
  2232. // Adjust privileges so that we can succefully open junction points as
  2233. // read/write.
  2234. HANDLE token;
  2235. TOKEN_PRIVILEGES privs;
  2236. OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &token);
  2237. LookupPrivilegeValue(NULL, SE_RESTORE_NAME, &privs.Privileges[0].Luid);
  2238. privs.PrivilegeCount = 1;
  2239. privs.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  2240. AdjustTokenPrivileges(token, FALSE, &privs, sizeof(TOKEN_PRIVILEGES), NULL,
  2241. NULL);
  2242. CloseHandle(token);
  2243. HANDLE dir = CreateFileW(
  2244. source.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING,
  2245. FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, NULL);
  2246. if (dir == INVALID_HANDLE_VALUE) {
  2247. return false;
  2248. }
  2249. // Set up the structure so that we can delete the junction.
  2250. std::vector<BYTE> buffer(REPARSE_GUID_DATA_BUFFER_HEADER_SIZE, 0);
  2251. REPARSE_GUID_DATA_BUFFER* reparse_buffer =
  2252. (REPARSE_GUID_DATA_BUFFER*)&buffer[0];
  2253. DWORD sentinel;
  2254. reparse_buffer->ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
  2255. BOOL success = DeviceIoControl(
  2256. dir, FSCTL_DELETE_REPARSE_POINT, reparse_buffer,
  2257. REPARSE_GUID_DATA_BUFFER_HEADER_SIZE, NULL, 0, &sentinel, NULL);
  2258. CloseHandle(dir);
  2259. return !!success;
  2260. # else
  2261. return false;
  2262. # endif
  2263. }
  2264. #endif
  2265. bool SystemTools::RemoveFile(const std::string& source)
  2266. {
  2267. #ifdef _WIN32
  2268. std::wstring const& ws = Encoding::ToWindowsExtendedPath(source);
  2269. if (DeleteFileW(ws.c_str())) {
  2270. return true;
  2271. }
  2272. DWORD err = GetLastError();
  2273. if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND) {
  2274. return true;
  2275. }
  2276. if (err != ERROR_ACCESS_DENIED) {
  2277. return false;
  2278. }
  2279. /* The file may be read-only. Try adding write permission. */
  2280. mode_t mode;
  2281. if (!SystemTools::GetPermissions(source, mode) ||
  2282. !SystemTools::SetPermissions(source, S_IWRITE)) {
  2283. SetLastError(err);
  2284. return false;
  2285. }
  2286. if (IsJunction(ws) && DeleteJunction(ws)) {
  2287. return true;
  2288. }
  2289. const DWORD DIRECTORY_SOFT_LINK_ATTRS =
  2290. FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT;
  2291. DWORD attrs = GetFileAttributesW(ws.c_str());
  2292. if (attrs != INVALID_FILE_ATTRIBUTES &&
  2293. (attrs & DIRECTORY_SOFT_LINK_ATTRS) == DIRECTORY_SOFT_LINK_ATTRS &&
  2294. RemoveDirectoryW(ws.c_str())) {
  2295. return true;
  2296. }
  2297. if (DeleteFileW(ws.c_str()) || GetLastError() == ERROR_FILE_NOT_FOUND ||
  2298. GetLastError() == ERROR_PATH_NOT_FOUND) {
  2299. return true;
  2300. }
  2301. /* Try to restore the original permissions. */
  2302. SystemTools::SetPermissions(source, mode);
  2303. SetLastError(err);
  2304. return false;
  2305. #else
  2306. return unlink(source.c_str()) == 0 || errno == ENOENT;
  2307. #endif
  2308. }
  2309. bool SystemTools::RemoveADirectory(const std::string& source)
  2310. {
  2311. // Add write permission to the directory so we can modify its
  2312. // content to remove files and directories from it.
  2313. mode_t mode;
  2314. if (SystemTools::GetPermissions(source, mode)) {
  2315. #if defined(_WIN32) && !defined(__CYGWIN__)
  2316. mode |= S_IWRITE;
  2317. #else
  2318. mode |= S_IWUSR;
  2319. #endif
  2320. SystemTools::SetPermissions(source, mode);
  2321. }
  2322. Directory dir;
  2323. dir.Load(source);
  2324. size_t fileNum;
  2325. for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum) {
  2326. if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)), ".") &&
  2327. strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)), "..")) {
  2328. std::string fullPath = source;
  2329. fullPath += "/";
  2330. fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
  2331. if (SystemTools::FileIsDirectory(fullPath) &&
  2332. !SystemTools::FileIsSymlink(fullPath)) {
  2333. if (!SystemTools::RemoveADirectory(fullPath)) {
  2334. return false;
  2335. }
  2336. } else {
  2337. if (!SystemTools::RemoveFile(fullPath)) {
  2338. return false;
  2339. }
  2340. }
  2341. }
  2342. }
  2343. return (Rmdir(source) == 0);
  2344. }
  2345. /**
  2346. */
  2347. size_t SystemTools::GetMaximumFilePathLength()
  2348. {
  2349. return KWSYS_SYSTEMTOOLS_MAXPATH;
  2350. }
  2351. /**
  2352. * Find the file the given name. Searches the given path and then
  2353. * the system search path. Returns the full path to the file if it is
  2354. * found. Otherwise, the empty string is returned.
  2355. */
  2356. std::string SystemTools::FindName(const std::string& name,
  2357. const std::vector<std::string>& userPaths,
  2358. bool no_system_path)
  2359. {
  2360. // Add the system search path to our path first
  2361. std::vector<std::string> path;
  2362. if (!no_system_path) {
  2363. SystemTools::GetPath(path, "CMAKE_FILE_PATH");
  2364. SystemTools::GetPath(path);
  2365. }
  2366. // now add the additional paths
  2367. {
  2368. for (std::vector<std::string>::const_iterator i = userPaths.begin();
  2369. i != userPaths.end(); ++i) {
  2370. path.push_back(*i);
  2371. }
  2372. }
  2373. // Add a trailing slash to all paths to aid the search process.
  2374. {
  2375. for (std::vector<std::string>::iterator i = path.begin(); i != path.end();
  2376. ++i) {
  2377. std::string& p = *i;
  2378. if (p.empty() || *p.rbegin() != '/') {
  2379. p += "/";
  2380. }
  2381. }
  2382. }
  2383. // now look for the file
  2384. std::string tryPath;
  2385. for (std::vector<std::string>::const_iterator p = path.begin();
  2386. p != path.end(); ++p) {
  2387. tryPath = *p;
  2388. tryPath += name;
  2389. if (SystemTools::FileExists(tryPath)) {
  2390. return tryPath;
  2391. }
  2392. }
  2393. // Couldn't find the file.
  2394. return "";
  2395. }
  2396. /**
  2397. * Find the file the given name. Searches the given path and then
  2398. * the system search path. Returns the full path to the file if it is
  2399. * found. Otherwise, the empty string is returned.
  2400. */
  2401. std::string SystemTools::FindFile(const std::string& name,
  2402. const std::vector<std::string>& userPaths,
  2403. bool no_system_path)
  2404. {
  2405. std::string tryPath = SystemTools::FindName(name, userPaths, no_system_path);
  2406. if (!tryPath.empty() && !SystemTools::FileIsDirectory(tryPath)) {
  2407. return SystemTools::CollapseFullPath(tryPath);
  2408. }
  2409. // Couldn't find the file.
  2410. return "";
  2411. }
  2412. /**
  2413. * Find the directory the given name. Searches the given path and then
  2414. * the system search path. Returns the full path to the directory if it is
  2415. * found. Otherwise, the empty string is returned.
  2416. */
  2417. std::string SystemTools::FindDirectory(
  2418. const std::string& name, const std::vector<std::string>& userPaths,
  2419. bool no_system_path)
  2420. {
  2421. std::string tryPath = SystemTools::FindName(name, userPaths, no_system_path);
  2422. if (!tryPath.empty() && SystemTools::FileIsDirectory(tryPath)) {
  2423. return SystemTools::CollapseFullPath(tryPath);
  2424. }
  2425. // Couldn't find the file.
  2426. return "";
  2427. }
  2428. /**
  2429. * Find the executable with the given name. Searches the given path and then
  2430. * the system search path. Returns the full path to the executable if it is
  2431. * found. Otherwise, the empty string is returned.
  2432. */
  2433. std::string SystemTools::FindProgram(const char* nameIn,
  2434. const std::vector<std::string>& userPaths,
  2435. bool no_system_path)
  2436. {
  2437. if (!nameIn || !*nameIn) {
  2438. return "";
  2439. }
  2440. return SystemTools::FindProgram(std::string(nameIn), userPaths,
  2441. no_system_path);
  2442. }
  2443. std::string SystemTools::FindProgram(const std::string& name,
  2444. const std::vector<std::string>& userPaths,
  2445. bool no_system_path)
  2446. {
  2447. std::string tryPath;
  2448. #if defined(_WIN32) || defined(__CYGWIN__) || defined(__MINGW32__)
  2449. std::vector<std::string> extensions;
  2450. // check to see if the name already has a .xxx at
  2451. // the end of it
  2452. // on windows try .com then .exe
  2453. if (name.size() <= 3 || name[name.size() - 4] != '.') {
  2454. extensions.push_back(".com");
  2455. extensions.push_back(".exe");
  2456. // first try with extensions if the os supports them
  2457. for (std::vector<std::string>::iterator i = extensions.begin();
  2458. i != extensions.end(); ++i) {
  2459. tryPath = name;
  2460. tryPath += *i;
  2461. if (SystemTools::FileExists(tryPath, true)) {
  2462. return SystemTools::CollapseFullPath(tryPath);
  2463. }
  2464. }
  2465. }
  2466. #endif
  2467. // now try just the name
  2468. if (SystemTools::FileExists(name, true)) {
  2469. return SystemTools::CollapseFullPath(name);
  2470. }
  2471. // now construct the path
  2472. std::vector<std::string> path;
  2473. // Add the system search path to our path.
  2474. if (!no_system_path) {
  2475. SystemTools::GetPath(path);
  2476. }
  2477. // now add the additional paths
  2478. {
  2479. for (std::vector<std::string>::const_iterator i = userPaths.begin();
  2480. i != userPaths.end(); ++i) {
  2481. path.push_back(*i);
  2482. }
  2483. }
  2484. // Add a trailing slash to all paths to aid the search process.
  2485. {
  2486. for (std::vector<std::string>::iterator i = path.begin(); i != path.end();
  2487. ++i) {
  2488. std::string& p = *i;
  2489. if (p.empty() || *p.rbegin() != '/') {
  2490. p += "/";
  2491. }
  2492. }
  2493. }
  2494. // Try each path
  2495. for (std::vector<std::string>::iterator p = path.begin(); p != path.end();
  2496. ++p) {
  2497. #ifdef _WIN32
  2498. // Remove double quotes from the path on windows
  2499. SystemTools::ReplaceString(*p, "\"", "");
  2500. #endif
  2501. #if defined(_WIN32) || defined(__CYGWIN__) || defined(__MINGW32__)
  2502. // first try with extensions
  2503. for (std::vector<std::string>::iterator ext = extensions.begin();
  2504. ext != extensions.end(); ++ext) {
  2505. tryPath = *p;
  2506. tryPath += name;
  2507. tryPath += *ext;
  2508. if (SystemTools::FileExists(tryPath, true)) {
  2509. return SystemTools::CollapseFullPath(tryPath);
  2510. }
  2511. }
  2512. #endif
  2513. // now try it without them
  2514. tryPath = *p;
  2515. tryPath += name;
  2516. if (SystemTools::FileExists(tryPath, true)) {
  2517. return SystemTools::CollapseFullPath(tryPath);
  2518. }
  2519. }
  2520. // Couldn't find the program.
  2521. return "";
  2522. }
  2523. std::string SystemTools::FindProgram(const std::vector<std::string>& names,
  2524. const std::vector<std::string>& path,
  2525. bool noSystemPath)
  2526. {
  2527. for (std::vector<std::string>::const_iterator it = names.begin();
  2528. it != names.end(); ++it) {
  2529. // Try to find the program.
  2530. std::string result = SystemTools::FindProgram(*it, path, noSystemPath);
  2531. if (!result.empty()) {
  2532. return result;
  2533. }
  2534. }
  2535. return "";
  2536. }
  2537. /**
  2538. * Find the library with the given name. Searches the given path and then
  2539. * the system search path. Returns the full path to the library if it is
  2540. * found. Otherwise, the empty string is returned.
  2541. */
  2542. std::string SystemTools::FindLibrary(const std::string& name,
  2543. const std::vector<std::string>& userPaths)
  2544. {
  2545. // See if the executable exists as written.
  2546. if (SystemTools::FileExists(name, true)) {
  2547. return SystemTools::CollapseFullPath(name);
  2548. }
  2549. // Add the system search path to our path.
  2550. std::vector<std::string> path;
  2551. SystemTools::GetPath(path);
  2552. // now add the additional paths
  2553. {
  2554. for (std::vector<std::string>::const_iterator i = userPaths.begin();
  2555. i != userPaths.end(); ++i) {
  2556. path.push_back(*i);
  2557. }
  2558. }
  2559. // Add a trailing slash to all paths to aid the search process.
  2560. {
  2561. for (std::vector<std::string>::iterator i = path.begin(); i != path.end();
  2562. ++i) {
  2563. std::string& p = *i;
  2564. if (p.empty() || *p.rbegin() != '/') {
  2565. p += "/";
  2566. }
  2567. }
  2568. }
  2569. std::string tryPath;
  2570. for (std::vector<std::string>::const_iterator p = path.begin();
  2571. p != path.end(); ++p) {
  2572. #if defined(__APPLE__)
  2573. tryPath = *p;
  2574. tryPath += name;
  2575. tryPath += ".framework";
  2576. if (SystemTools::FileIsDirectory(tryPath)) {
  2577. return SystemTools::CollapseFullPath(tryPath);
  2578. }
  2579. #endif
  2580. #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__MINGW32__)
  2581. tryPath = *p;
  2582. tryPath += name;
  2583. tryPath += ".lib";
  2584. if (SystemTools::FileExists(tryPath, true)) {
  2585. return SystemTools::CollapseFullPath(tryPath);
  2586. }
  2587. #else
  2588. tryPath = *p;
  2589. tryPath += "lib";
  2590. tryPath += name;
  2591. tryPath += ".so";
  2592. if (SystemTools::FileExists(tryPath, true)) {
  2593. return SystemTools::CollapseFullPath(tryPath);
  2594. }
  2595. tryPath = *p;
  2596. tryPath += "lib";
  2597. tryPath += name;
  2598. tryPath += ".a";
  2599. if (SystemTools::FileExists(tryPath, true)) {
  2600. return SystemTools::CollapseFullPath(tryPath);
  2601. }
  2602. tryPath = *p;
  2603. tryPath += "lib";
  2604. tryPath += name;
  2605. tryPath += ".sl";
  2606. if (SystemTools::FileExists(tryPath, true)) {
  2607. return SystemTools::CollapseFullPath(tryPath);
  2608. }
  2609. tryPath = *p;
  2610. tryPath += "lib";
  2611. tryPath += name;
  2612. tryPath += ".dylib";
  2613. if (SystemTools::FileExists(tryPath, true)) {
  2614. return SystemTools::CollapseFullPath(tryPath);
  2615. }
  2616. tryPath = *p;
  2617. tryPath += "lib";
  2618. tryPath += name;
  2619. tryPath += ".dll";
  2620. if (SystemTools::FileExists(tryPath, true)) {
  2621. return SystemTools::CollapseFullPath(tryPath);
  2622. }
  2623. #endif
  2624. }
  2625. // Couldn't find the library.
  2626. return "";
  2627. }
  2628. std::string SystemTools::GetRealPath(const std::string& path,
  2629. std::string* errorMessage)
  2630. {
  2631. std::string ret;
  2632. Realpath(path, ret, errorMessage);
  2633. return ret;
  2634. }
  2635. bool SystemTools::FileIsDirectory(const std::string& inName)
  2636. {
  2637. if (inName.empty()) {
  2638. return false;
  2639. }
  2640. size_t length = inName.size();
  2641. const char* name = inName.c_str();
  2642. // Remove any trailing slash from the name except in a root component.
  2643. char local_buffer[KWSYS_SYSTEMTOOLS_MAXPATH];
  2644. std::string string_buffer;
  2645. size_t last = length - 1;
  2646. if (last > 0 && (name[last] == '/' || name[last] == '\\') &&
  2647. strcmp(name, "/") != 0 && name[last - 1] != ':') {
  2648. if (last < sizeof(local_buffer)) {
  2649. memcpy(local_buffer, name, last);
  2650. local_buffer[last] = '\0';
  2651. name = local_buffer;
  2652. } else {
  2653. string_buffer.append(name, last);
  2654. name = string_buffer.c_str();
  2655. }
  2656. }
  2657. // Now check the file node type.
  2658. #if defined(_WIN32)
  2659. DWORD attr =
  2660. GetFileAttributesW(Encoding::ToWindowsExtendedPath(name).c_str());
  2661. if (attr != INVALID_FILE_ATTRIBUTES) {
  2662. return (attr & FILE_ATTRIBUTE_DIRECTORY) != 0;
  2663. #else
  2664. struct stat fs;
  2665. if (stat(name, &fs) == 0) {
  2666. return S_ISDIR(fs.st_mode);
  2667. #endif
  2668. } else {
  2669. return false;
  2670. }
  2671. }
  2672. bool SystemTools::FileIsSymlink(const std::string& name)
  2673. {
  2674. #if defined(_WIN32)
  2675. DWORD attr =
  2676. GetFileAttributesW(Encoding::ToWindowsExtendedPath(name).c_str());
  2677. if (attr != INVALID_FILE_ATTRIBUTES) {
  2678. return (attr & FILE_ATTRIBUTE_REPARSE_POINT) != 0;
  2679. } else {
  2680. return false;
  2681. }
  2682. #else
  2683. struct stat fs;
  2684. if (lstat(name.c_str(), &fs) == 0) {
  2685. return S_ISLNK(fs.st_mode);
  2686. } else {
  2687. return false;
  2688. }
  2689. #endif
  2690. }
  2691. bool SystemTools::FileIsFIFO(const std::string& name)
  2692. {
  2693. #if defined(_WIN32)
  2694. HANDLE hFile =
  2695. CreateFileW(Encoding::ToWide(name).c_str(), GENERIC_READ, FILE_SHARE_READ,
  2696. NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
  2697. if (hFile == INVALID_HANDLE_VALUE) {
  2698. return false;
  2699. }
  2700. const DWORD type = GetFileType(hFile);
  2701. CloseHandle(hFile);
  2702. return type == FILE_TYPE_PIPE;
  2703. #else
  2704. struct stat fs;
  2705. if (lstat(name.c_str(), &fs) == 0) {
  2706. return S_ISFIFO(fs.st_mode);
  2707. } else {
  2708. return false;
  2709. }
  2710. #endif
  2711. }
  2712. #if defined(_WIN32) && !defined(__CYGWIN__)
  2713. bool SystemTools::CreateSymlink(const std::string&, const std::string&)
  2714. {
  2715. return false;
  2716. }
  2717. #else
  2718. bool SystemTools::CreateSymlink(const std::string& origName,
  2719. const std::string& newName)
  2720. {
  2721. return symlink(origName.c_str(), newName.c_str()) >= 0;
  2722. }
  2723. #endif
  2724. #if defined(_WIN32) && !defined(__CYGWIN__)
  2725. bool SystemTools::ReadSymlink(const std::string&, std::string&)
  2726. {
  2727. return false;
  2728. }
  2729. #else
  2730. bool SystemTools::ReadSymlink(const std::string& newName,
  2731. std::string& origName)
  2732. {
  2733. char buf[KWSYS_SYSTEMTOOLS_MAXPATH + 1];
  2734. int count = static_cast<int>(
  2735. readlink(newName.c_str(), buf, KWSYS_SYSTEMTOOLS_MAXPATH));
  2736. if (count >= 0) {
  2737. // Add null-terminator.
  2738. buf[count] = 0;
  2739. origName = buf;
  2740. return true;
  2741. } else {
  2742. return false;
  2743. }
  2744. }
  2745. #endif
  2746. int SystemTools::ChangeDirectory(const std::string& dir)
  2747. {
  2748. return Chdir(dir);
  2749. }
  2750. std::string SystemTools::GetCurrentWorkingDirectory(bool collapse)
  2751. {
  2752. char buf[2048];
  2753. const char* cwd = Getcwd(buf, 2048);
  2754. std::string path;
  2755. if (cwd) {
  2756. path = cwd;
  2757. }
  2758. if (collapse) {
  2759. return SystemTools::CollapseFullPath(path);
  2760. }
  2761. return path;
  2762. }
  2763. std::string SystemTools::GetProgramPath(const std::string& in_name)
  2764. {
  2765. std::string dir, file;
  2766. SystemTools::SplitProgramPath(in_name, dir, file);
  2767. return dir;
  2768. }
  2769. bool SystemTools::SplitProgramPath(const std::string& in_name,
  2770. std::string& dir, std::string& file, bool)
  2771. {
  2772. dir = in_name;
  2773. file = "";
  2774. SystemTools::ConvertToUnixSlashes(dir);
  2775. if (!SystemTools::FileIsDirectory(dir)) {
  2776. std::string::size_type slashPos = dir.rfind("/");
  2777. if (slashPos != std::string::npos) {
  2778. file = dir.substr(slashPos + 1);
  2779. dir = dir.substr(0, slashPos);
  2780. } else {
  2781. file = dir;
  2782. dir = "";
  2783. }
  2784. }
  2785. if (!(dir.empty()) && !SystemTools::FileIsDirectory(dir)) {
  2786. std::string oldDir = in_name;
  2787. SystemTools::ConvertToUnixSlashes(oldDir);
  2788. dir = in_name;
  2789. return false;
  2790. }
  2791. return true;
  2792. }
  2793. bool SystemTools::FindProgramPath(const char* argv0, std::string& pathOut,
  2794. std::string& errorMsg, const char* exeName,
  2795. const char* buildDir,
  2796. const char* installPrefix)
  2797. {
  2798. std::vector<std::string> failures;
  2799. std::string self = argv0 ? argv0 : "";
  2800. failures.push_back(self);
  2801. SystemTools::ConvertToUnixSlashes(self);
  2802. self = SystemTools::FindProgram(self);
  2803. if (!SystemTools::FileExists(self)) {
  2804. if (buildDir) {
  2805. std::string intdir = ".";
  2806. #ifdef CMAKE_INTDIR
  2807. intdir = CMAKE_INTDIR;
  2808. #endif
  2809. self = buildDir;
  2810. self += "/bin/";
  2811. self += intdir;
  2812. self += "/";
  2813. self += exeName;
  2814. self += SystemTools::GetExecutableExtension();
  2815. }
  2816. }
  2817. if (installPrefix) {
  2818. if (!SystemTools::FileExists(self)) {
  2819. failures.push_back(self);
  2820. self = installPrefix;
  2821. self += "/bin/";
  2822. self += exeName;
  2823. }
  2824. }
  2825. if (!SystemTools::FileExists(self)) {
  2826. failures.push_back(self);
  2827. std::ostringstream msg;
  2828. msg << "Can not find the command line program ";
  2829. if (exeName) {
  2830. msg << exeName;
  2831. }
  2832. msg << "\n";
  2833. if (argv0) {
  2834. msg << " argv[0] = \"" << argv0 << "\"\n";
  2835. }
  2836. msg << " Attempted paths:\n";
  2837. std::vector<std::string>::iterator i;
  2838. for (i = failures.begin(); i != failures.end(); ++i) {
  2839. msg << " \"" << *i << "\"\n";
  2840. }
  2841. errorMsg = msg.str();
  2842. return false;
  2843. }
  2844. pathOut = self;
  2845. return true;
  2846. }
  2847. std::string SystemTools::CollapseFullPath(const std::string& in_relative)
  2848. {
  2849. return SystemTools::CollapseFullPath(in_relative, KWSYS_NULLPTR);
  2850. }
  2851. void SystemTools::AddTranslationPath(const std::string& a,
  2852. const std::string& b)
  2853. {
  2854. std::string path_a = a;
  2855. std::string path_b = b;
  2856. SystemTools::ConvertToUnixSlashes(path_a);
  2857. SystemTools::ConvertToUnixSlashes(path_b);
  2858. // First check this is a directory path, since we don't want the table to
  2859. // grow too fat
  2860. if (SystemTools::FileIsDirectory(path_a)) {
  2861. // Make sure the path is a full path and does not contain no '..'
  2862. // Ken--the following code is incorrect. .. can be in a valid path
  2863. // for example /home/martink/MyHubba...Hubba/Src
  2864. if (SystemTools::FileIsFullPath(path_b) &&
  2865. path_b.find("..") == std::string::npos) {
  2866. // Before inserting make sure path ends with '/'
  2867. if (!path_a.empty() && *path_a.rbegin() != '/') {
  2868. path_a += '/';
  2869. }
  2870. if (!path_b.empty() && *path_b.rbegin() != '/') {
  2871. path_b += '/';
  2872. }
  2873. if (!(path_a == path_b)) {
  2874. SystemTools::TranslationMap->insert(
  2875. SystemToolsTranslationMap::value_type(path_a, path_b));
  2876. }
  2877. }
  2878. }
  2879. }
  2880. void SystemTools::AddKeepPath(const std::string& dir)
  2881. {
  2882. std::string cdir;
  2883. Realpath(SystemTools::CollapseFullPath(dir), cdir);
  2884. SystemTools::AddTranslationPath(cdir, dir);
  2885. }
  2886. void SystemTools::CheckTranslationPath(std::string& path)
  2887. {
  2888. // Do not translate paths that are too short to have meaningful
  2889. // translations.
  2890. if (path.size() < 2) {
  2891. return;
  2892. }
  2893. // Always add a trailing slash before translation. It does not
  2894. // matter if this adds an extra slash, but we do not want to
  2895. // translate part of a directory (like the foo part of foo-dir).
  2896. path += "/";
  2897. // In case a file was specified we still have to go through this:
  2898. // Now convert any path found in the table back to the one desired:
  2899. std::map<std::string, std::string>::const_iterator it;
  2900. for (it = SystemTools::TranslationMap->begin();
  2901. it != SystemTools::TranslationMap->end(); ++it) {
  2902. // We need to check of the path is a substring of the other path
  2903. if (path.find(it->first) == 0) {
  2904. path = path.replace(0, it->first.size(), it->second);
  2905. }
  2906. }
  2907. // Remove the trailing slash we added before.
  2908. path.erase(path.end() - 1, path.end());
  2909. }
  2910. static void SystemToolsAppendComponents(
  2911. std::vector<std::string>& out_components,
  2912. std::vector<std::string>::iterator first,
  2913. std::vector<std::string>::iterator last)
  2914. {
  2915. static const std::string up = "..";
  2916. static const std::string cur = ".";
  2917. for (std::vector<std::string>::const_iterator i = first; i != last; ++i) {
  2918. if (*i == up) {
  2919. if (out_components.size() > 1) {
  2920. out_components.resize(out_components.size() - 1);
  2921. }
  2922. } else if (!i->empty() && *i != cur) {
  2923. #if __cplusplus >= 201103L || (defined(_MSVC_LANG) && _MSVC_LANG >= 201103L)
  2924. out_components.push_back(std::move(*i));
  2925. #else
  2926. out_components.push_back(*i);
  2927. #endif
  2928. }
  2929. }
  2930. }
  2931. std::string SystemTools::CollapseFullPath(const std::string& in_path,
  2932. const char* in_base)
  2933. {
  2934. // Use the current working directory as a base path.
  2935. char buf[2048];
  2936. const char* res_in_base = in_base;
  2937. if (!res_in_base) {
  2938. if (const char* cwd = Getcwd(buf, 2048)) {
  2939. res_in_base = cwd;
  2940. } else {
  2941. res_in_base = "";
  2942. }
  2943. }
  2944. return SystemTools::CollapseFullPath(in_path, std::string(res_in_base));
  2945. }
  2946. std::string SystemTools::CollapseFullPath(const std::string& in_path,
  2947. const std::string& in_base)
  2948. {
  2949. // Collect the output path components.
  2950. std::vector<std::string> out_components;
  2951. // Split the input path components.
  2952. std::vector<std::string> path_components;
  2953. SystemTools::SplitPath(in_path, path_components);
  2954. out_components.reserve(path_components.size());
  2955. // If the input path is relative, start with a base path.
  2956. if (path_components[0].empty()) {
  2957. std::vector<std::string> base_components;
  2958. // Use the given base path.
  2959. SystemTools::SplitPath(in_base, base_components);
  2960. // Append base path components to the output path.
  2961. out_components.push_back(base_components[0]);
  2962. SystemToolsAppendComponents(out_components, base_components.begin() + 1,
  2963. base_components.end());
  2964. }
  2965. // Append input path components to the output path.
  2966. SystemToolsAppendComponents(out_components, path_components.begin(),
  2967. path_components.end());
  2968. // Transform the path back to a string.
  2969. std::string newPath = SystemTools::JoinPath(out_components);
  2970. // Update the translation table with this potentially new path. I am not
  2971. // sure why this line is here, it seems really questionable, but yet I
  2972. // would put good money that if I remove it something will break, basically
  2973. // from what I can see it created a mapping from the collapsed path, to be
  2974. // replaced by the input path, which almost completely does the opposite of
  2975. // this function, the only thing preventing this from happening a lot is
  2976. // that if the in_path has a .. in it, then it is not added to the
  2977. // translation table. So for most calls this either does nothing due to the
  2978. // .. or it adds a translation between identical paths as nothing was
  2979. // collapsed, so I am going to try to comment it out, and see what hits the
  2980. // fan, hopefully quickly.
  2981. // Commented out line below:
  2982. // SystemTools::AddTranslationPath(newPath, in_path);
  2983. SystemTools::CheckTranslationPath(newPath);
  2984. #ifdef _WIN32
  2985. newPath = SystemTools::GetActualCaseForPathCached(newPath);
  2986. SystemTools::ConvertToUnixSlashes(newPath);
  2987. #endif
  2988. // Return the reconstructed path.
  2989. return newPath;
  2990. }
  2991. // compute the relative path from here to there
  2992. std::string SystemTools::RelativePath(const std::string& local,
  2993. const std::string& remote)
  2994. {
  2995. if (!SystemTools::FileIsFullPath(local)) {
  2996. return "";
  2997. }
  2998. if (!SystemTools::FileIsFullPath(remote)) {
  2999. return "";
  3000. }
  3001. std::string l = SystemTools::CollapseFullPath(local);
  3002. std::string r = SystemTools::CollapseFullPath(remote);
  3003. // split up both paths into arrays of strings using / as a separator
  3004. std::vector<std::string> localSplit = SystemTools::SplitString(l, '/', true);
  3005. std::vector<std::string> remoteSplit =
  3006. SystemTools::SplitString(r, '/', true);
  3007. std::vector<std::string>
  3008. commonPath; // store shared parts of path in this array
  3009. std::vector<std::string> finalPath; // store the final relative path here
  3010. // count up how many matching directory names there are from the start
  3011. unsigned int sameCount = 0;
  3012. while (((sameCount <= (localSplit.size() - 1)) &&
  3013. (sameCount <= (remoteSplit.size() - 1))) &&
  3014. // for Windows and Apple do a case insensitive string compare
  3015. #if defined(_WIN32) || defined(__APPLE__)
  3016. SystemTools::Strucmp(localSplit[sameCount].c_str(),
  3017. remoteSplit[sameCount].c_str()) == 0
  3018. #else
  3019. localSplit[sameCount] == remoteSplit[sameCount]
  3020. #endif
  3021. ) {
  3022. // put the common parts of the path into the commonPath array
  3023. commonPath.push_back(localSplit[sameCount]);
  3024. // erase the common parts of the path from the original path arrays
  3025. localSplit[sameCount] = "";
  3026. remoteSplit[sameCount] = "";
  3027. sameCount++;
  3028. }
  3029. // If there is nothing in common at all then just return the full
  3030. // path. This is the case only on windows when the paths have
  3031. // different drive letters. On unix two full paths always at least
  3032. // have the root "/" in common so we will return a relative path
  3033. // that passes through the root directory.
  3034. if (sameCount == 0) {
  3035. return remote;
  3036. }
  3037. // for each entry that is not common in the local path
  3038. // add a ../ to the finalpath array, this gets us out of the local
  3039. // path into the remote dir
  3040. for (unsigned int i = 0; i < localSplit.size(); ++i) {
  3041. if (!localSplit[i].empty()) {
  3042. finalPath.push_back("../");
  3043. }
  3044. }
  3045. // for each entry that is not common in the remote path add it
  3046. // to the final path.
  3047. for (std::vector<std::string>::iterator vit = remoteSplit.begin();
  3048. vit != remoteSplit.end(); ++vit) {
  3049. if (!vit->empty()) {
  3050. finalPath.push_back(*vit);
  3051. }
  3052. }
  3053. std::string relativePath; // result string
  3054. // now turn the array of directories into a unix path by puttint /
  3055. // between each entry that does not already have one
  3056. for (std::vector<std::string>::iterator vit1 = finalPath.begin();
  3057. vit1 != finalPath.end(); ++vit1) {
  3058. if (!relativePath.empty() && *relativePath.rbegin() != '/') {
  3059. relativePath += "/";
  3060. }
  3061. relativePath += *vit1;
  3062. }
  3063. return relativePath;
  3064. }
  3065. #ifdef _WIN32
  3066. static std::string GetCasePathName(std::string const& pathIn)
  3067. {
  3068. std::string casePath;
  3069. // First check if the file is relative. We don't fix relative paths since the
  3070. // real case depends on the root directory and the given path fragment may
  3071. // have meaning elsewhere in the project.
  3072. if (!SystemTools::FileIsFullPath(pathIn)) {
  3073. // This looks unnecessary, but it allows for the return value optimization
  3074. // since all return paths return the same local variable.
  3075. casePath = pathIn;
  3076. return casePath;
  3077. }
  3078. std::vector<std::string> path_components;
  3079. SystemTools::SplitPath(pathIn, path_components);
  3080. // Start with root component.
  3081. std::vector<std::string>::size_type idx = 0;
  3082. casePath = path_components[idx++];
  3083. // make sure drive letter is always upper case
  3084. if (casePath.size() > 1 && casePath[1] == ':') {
  3085. casePath[0] = toupper(casePath[0]);
  3086. }
  3087. const char* sep = "";
  3088. // If network path, fill casePath with server/share so FindFirstFile
  3089. // will work after that. Maybe someday call other APIs to get
  3090. // actual case of servers and shares.
  3091. if (path_components.size() > 2 && path_components[0] == "//") {
  3092. casePath += path_components[idx++];
  3093. casePath += "/";
  3094. casePath += path_components[idx++];
  3095. sep = "/";
  3096. }
  3097. // Convert case of all components that exist.
  3098. bool converting = true;
  3099. for (; idx < path_components.size(); idx++) {
  3100. casePath += sep;
  3101. sep = "/";
  3102. if (converting) {
  3103. // If path component contains wildcards, we skip matching
  3104. // because these filenames are not allowed on windows,
  3105. // and we do not want to match a different file.
  3106. if (path_components[idx].find('*') != std::string::npos ||
  3107. path_components[idx].find('?') != std::string::npos) {
  3108. converting = false;
  3109. } else {
  3110. std::string test_str = casePath;
  3111. test_str += path_components[idx];
  3112. WIN32_FIND_DATAW findData;
  3113. HANDLE hFind =
  3114. ::FindFirstFileW(Encoding::ToWide(test_str).c_str(), &findData);
  3115. if (INVALID_HANDLE_VALUE != hFind) {
  3116. path_components[idx] = Encoding::ToNarrow(findData.cFileName);
  3117. ::FindClose(hFind);
  3118. } else {
  3119. converting = false;
  3120. }
  3121. }
  3122. }
  3123. casePath += path_components[idx];
  3124. }
  3125. return casePath;
  3126. }
  3127. #endif
  3128. std::string SystemTools::GetActualCaseForPath(const std::string& p)
  3129. {
  3130. #ifndef _WIN32
  3131. return p;
  3132. #else
  3133. return GetCasePathName(p);
  3134. #endif
  3135. }
  3136. #ifdef _WIN32
  3137. std::string SystemTools::GetActualCaseForPathCached(std::string const& p)
  3138. {
  3139. // Check to see if actual case has already been called
  3140. // for this path, and the result is stored in the PathCaseMap
  3141. SystemToolsPathCaseMap::iterator i = SystemTools::PathCaseMap->find(p);
  3142. if (i != SystemTools::PathCaseMap->end()) {
  3143. return i->second;
  3144. }
  3145. std::string casePath = GetCasePathName(p);
  3146. if (casePath.size() > MAX_PATH) {
  3147. return casePath;
  3148. }
  3149. (*SystemTools::PathCaseMap)[p] = casePath;
  3150. return casePath;
  3151. }
  3152. #endif
  3153. const char* SystemTools::SplitPathRootComponent(const std::string& p,
  3154. std::string* root)
  3155. {
  3156. // Identify the root component.
  3157. const char* c = p.c_str();
  3158. if ((c[0] == '/' && c[1] == '/') || (c[0] == '\\' && c[1] == '\\')) {
  3159. // Network path.
  3160. if (root) {
  3161. *root = "//";
  3162. }
  3163. c += 2;
  3164. } else if (c[0] == '/' || c[0] == '\\') {
  3165. // Unix path (or Windows path w/out drive letter).
  3166. if (root) {
  3167. *root = "/";
  3168. }
  3169. c += 1;
  3170. } else if (c[0] && c[1] == ':' && (c[2] == '/' || c[2] == '\\')) {
  3171. // Windows path.
  3172. if (root) {
  3173. (*root) = "_:/";
  3174. (*root)[0] = c[0];
  3175. }
  3176. c += 3;
  3177. } else if (c[0] && c[1] == ':') {
  3178. // Path relative to a windows drive working directory.
  3179. if (root) {
  3180. (*root) = "_:";
  3181. (*root)[0] = c[0];
  3182. }
  3183. c += 2;
  3184. } else if (c[0] == '~') {
  3185. // Home directory. The returned root should always have a
  3186. // trailing slash so that appending components as
  3187. // c[0]c[1]/c[2]/... works. The remaining path returned should
  3188. // skip the first slash if it exists:
  3189. //
  3190. // "~" : root = "~/" , return ""
  3191. // "~/ : root = "~/" , return ""
  3192. // "~/x : root = "~/" , return "x"
  3193. // "~u" : root = "~u/", return ""
  3194. // "~u/" : root = "~u/", return ""
  3195. // "~u/x" : root = "~u/", return "x"
  3196. size_t n = 1;
  3197. while (c[n] && c[n] != '/') {
  3198. ++n;
  3199. }
  3200. if (root) {
  3201. root->assign(c, n);
  3202. *root += '/';
  3203. }
  3204. if (c[n] == '/') {
  3205. ++n;
  3206. }
  3207. c += n;
  3208. } else {
  3209. // Relative path.
  3210. if (root) {
  3211. *root = "";
  3212. }
  3213. }
  3214. // Return the remaining path.
  3215. return c;
  3216. }
  3217. void SystemTools::SplitPath(const std::string& p,
  3218. std::vector<std::string>& components,
  3219. bool expand_home_dir)
  3220. {
  3221. const char* c;
  3222. components.clear();
  3223. // Identify the root component.
  3224. {
  3225. std::string root;
  3226. c = SystemTools::SplitPathRootComponent(p, &root);
  3227. // Expand home directory references if requested.
  3228. if (expand_home_dir && !root.empty() && root[0] == '~') {
  3229. std::string homedir;
  3230. root = root.substr(0, root.size() - 1);
  3231. if (root.size() == 1) {
  3232. #if defined(_WIN32) && !defined(__CYGWIN__)
  3233. if (!SystemTools::GetEnv("USERPROFILE", homedir))
  3234. #endif
  3235. SystemTools::GetEnv("HOME", homedir);
  3236. }
  3237. #ifdef HAVE_GETPWNAM
  3238. else if (passwd* pw = getpwnam(root.c_str() + 1)) {
  3239. if (pw->pw_dir) {
  3240. homedir = pw->pw_dir;
  3241. }
  3242. }
  3243. #endif
  3244. if (!homedir.empty() &&
  3245. (*homedir.rbegin() == '/' || *homedir.rbegin() == '\\')) {
  3246. homedir.resize(homedir.size() - 1);
  3247. }
  3248. SystemTools::SplitPath(homedir, components);
  3249. } else {
  3250. components.push_back(root);
  3251. }
  3252. }
  3253. // Parse the remaining components.
  3254. const char* first = c;
  3255. const char* last = first;
  3256. for (; *last; ++last) {
  3257. if (*last == '/' || *last == '\\') {
  3258. // End of a component. Save it.
  3259. components.push_back(std::string(first, last));
  3260. first = last + 1;
  3261. }
  3262. }
  3263. // Save the last component unless there were no components.
  3264. if (last != c) {
  3265. components.push_back(std::string(first, last));
  3266. }
  3267. }
  3268. std::string SystemTools::JoinPath(const std::vector<std::string>& components)
  3269. {
  3270. return SystemTools::JoinPath(components.begin(), components.end());
  3271. }
  3272. std::string SystemTools::JoinPath(
  3273. std::vector<std::string>::const_iterator first,
  3274. std::vector<std::string>::const_iterator last)
  3275. {
  3276. // Construct result in a single string.
  3277. std::string result;
  3278. size_t len = 0;
  3279. std::vector<std::string>::const_iterator i;
  3280. for (i = first; i != last; ++i) {
  3281. len += 1 + i->size();
  3282. }
  3283. result.reserve(len);
  3284. // The first two components do not add a slash.
  3285. if (first != last) {
  3286. result.append(*first++);
  3287. }
  3288. if (first != last) {
  3289. result.append(*first++);
  3290. }
  3291. // All remaining components are always separated with a slash.
  3292. while (first != last) {
  3293. result.push_back('/');
  3294. result.append((*first++));
  3295. }
  3296. // Return the concatenated result.
  3297. return result;
  3298. }
  3299. bool SystemTools::ComparePath(const std::string& c1, const std::string& c2)
  3300. {
  3301. #if defined(_WIN32) || defined(__APPLE__)
  3302. # ifdef _MSC_VER
  3303. return _stricmp(c1.c_str(), c2.c_str()) == 0;
  3304. # elif defined(__APPLE__) || defined(__GNUC__)
  3305. return strcasecmp(c1.c_str(), c2.c_str()) == 0;
  3306. # else
  3307. return SystemTools::Strucmp(c1.c_str(), c2.c_str()) == 0;
  3308. # endif
  3309. #else
  3310. return c1 == c2;
  3311. #endif
  3312. }
  3313. bool SystemTools::Split(const std::string& str,
  3314. std::vector<std::string>& lines, char separator)
  3315. {
  3316. std::string data(str);
  3317. std::string::size_type lpos = 0;
  3318. while (lpos < data.length()) {
  3319. std::string::size_type rpos = data.find_first_of(separator, lpos);
  3320. if (rpos == std::string::npos) {
  3321. // Line ends at end of string without a newline.
  3322. lines.push_back(data.substr(lpos));
  3323. return false;
  3324. } else {
  3325. // Line ends in a "\n", remove the character.
  3326. lines.push_back(data.substr(lpos, rpos - lpos));
  3327. }
  3328. lpos = rpos + 1;
  3329. }
  3330. return true;
  3331. }
  3332. bool SystemTools::Split(const std::string& str,
  3333. std::vector<std::string>& lines)
  3334. {
  3335. std::string data(str);
  3336. std::string::size_type lpos = 0;
  3337. while (lpos < data.length()) {
  3338. std::string::size_type rpos = data.find_first_of("\n", lpos);
  3339. if (rpos == std::string::npos) {
  3340. // Line ends at end of string without a newline.
  3341. lines.push_back(data.substr(lpos));
  3342. return false;
  3343. }
  3344. if ((rpos > lpos) && (data[rpos - 1] == '\r')) {
  3345. // Line ends in a "\r\n" pair, remove both characters.
  3346. lines.push_back(data.substr(lpos, (rpos - 1) - lpos));
  3347. } else {
  3348. // Line ends in a "\n", remove the character.
  3349. lines.push_back(data.substr(lpos, rpos - lpos));
  3350. }
  3351. lpos = rpos + 1;
  3352. }
  3353. return true;
  3354. }
  3355. /**
  3356. * Return path of a full filename (no trailing slashes).
  3357. * Warning: returned path is converted to Unix slashes format.
  3358. */
  3359. std::string SystemTools::GetFilenamePath(const std::string& filename)
  3360. {
  3361. std::string fn = filename;
  3362. SystemTools::ConvertToUnixSlashes(fn);
  3363. std::string::size_type slash_pos = fn.rfind("/");
  3364. if (slash_pos != std::string::npos) {
  3365. std::string ret = fn.substr(0, slash_pos);
  3366. if (ret.size() == 2 && ret[1] == ':') {
  3367. return ret + '/';
  3368. }
  3369. if (ret.empty()) {
  3370. return "/";
  3371. }
  3372. return ret;
  3373. } else {
  3374. return "";
  3375. }
  3376. }
  3377. /**
  3378. * Return file name of a full filename (i.e. file name without path).
  3379. */
  3380. std::string SystemTools::GetFilenameName(const std::string& filename)
  3381. {
  3382. #if defined(_WIN32) || defined(KWSYS_SYSTEMTOOLS_SUPPORT_WINDOWS_SLASHES)
  3383. const char* separators = "/\\";
  3384. #else
  3385. char separators = '/';
  3386. #endif
  3387. std::string::size_type slash_pos = filename.find_last_of(separators);
  3388. if (slash_pos != std::string::npos) {
  3389. return filename.substr(slash_pos + 1);
  3390. } else {
  3391. return filename;
  3392. }
  3393. }
  3394. /**
  3395. * Return file extension of a full filename (dot included).
  3396. * Warning: this is the longest extension (for example: .tar.gz)
  3397. */
  3398. std::string SystemTools::GetFilenameExtension(const std::string& filename)
  3399. {
  3400. std::string name = SystemTools::GetFilenameName(filename);
  3401. std::string::size_type dot_pos = name.find('.');
  3402. if (dot_pos != std::string::npos) {
  3403. return name.substr(dot_pos);
  3404. } else {
  3405. return "";
  3406. }
  3407. }
  3408. /**
  3409. * Return file extension of a full filename (dot included).
  3410. * Warning: this is the shortest extension (for example: .gz of .tar.gz)
  3411. */
  3412. std::string SystemTools::GetFilenameLastExtension(const std::string& filename)
  3413. {
  3414. std::string name = SystemTools::GetFilenameName(filename);
  3415. std::string::size_type dot_pos = name.rfind('.');
  3416. if (dot_pos != std::string::npos) {
  3417. return name.substr(dot_pos);
  3418. } else {
  3419. return "";
  3420. }
  3421. }
  3422. /**
  3423. * Return file name without extension of a full filename (i.e. without path).
  3424. * Warning: it considers the longest extension (for example: .tar.gz)
  3425. */
  3426. std::string SystemTools::GetFilenameWithoutExtension(
  3427. const std::string& filename)
  3428. {
  3429. std::string name = SystemTools::GetFilenameName(filename);
  3430. std::string::size_type dot_pos = name.find('.');
  3431. if (dot_pos != std::string::npos) {
  3432. return name.substr(0, dot_pos);
  3433. } else {
  3434. return name;
  3435. }
  3436. }
  3437. /**
  3438. * Return file name without extension of a full filename (i.e. without path).
  3439. * Warning: it considers the last extension (for example: removes .gz
  3440. * from .tar.gz)
  3441. */
  3442. std::string SystemTools::GetFilenameWithoutLastExtension(
  3443. const std::string& filename)
  3444. {
  3445. std::string name = SystemTools::GetFilenameName(filename);
  3446. std::string::size_type dot_pos = name.rfind('.');
  3447. if (dot_pos != std::string::npos) {
  3448. return name.substr(0, dot_pos);
  3449. } else {
  3450. return name;
  3451. }
  3452. }
  3453. bool SystemTools::FileHasSignature(const char* filename, const char* signature,
  3454. long offset)
  3455. {
  3456. if (!filename || !signature) {
  3457. return false;
  3458. }
  3459. FILE* fp = Fopen(filename, "rb");
  3460. if (!fp) {
  3461. return false;
  3462. }
  3463. fseek(fp, offset, SEEK_SET);
  3464. bool res = false;
  3465. size_t signature_len = strlen(signature);
  3466. char* buffer = new char[signature_len];
  3467. if (fread(buffer, 1, signature_len, fp) == signature_len) {
  3468. res = (!strncmp(buffer, signature, signature_len) ? true : false);
  3469. }
  3470. delete[] buffer;
  3471. fclose(fp);
  3472. return res;
  3473. }
  3474. SystemTools::FileTypeEnum SystemTools::DetectFileType(const char* filename,
  3475. unsigned long length,
  3476. double percent_bin)
  3477. {
  3478. if (!filename || percent_bin < 0) {
  3479. return SystemTools::FileTypeUnknown;
  3480. }
  3481. if (SystemTools::FileIsDirectory(filename)) {
  3482. return SystemTools::FileTypeUnknown;
  3483. }
  3484. FILE* fp = Fopen(filename, "rb");
  3485. if (!fp) {
  3486. return SystemTools::FileTypeUnknown;
  3487. }
  3488. // Allocate buffer and read bytes
  3489. unsigned char* buffer = new unsigned char[length];
  3490. size_t read_length = fread(buffer, 1, length, fp);
  3491. fclose(fp);
  3492. if (read_length == 0) {
  3493. delete[] buffer;
  3494. return SystemTools::FileTypeUnknown;
  3495. }
  3496. // Loop over contents and count
  3497. size_t text_count = 0;
  3498. const unsigned char* ptr = buffer;
  3499. const unsigned char* buffer_end = buffer + read_length;
  3500. while (ptr != buffer_end) {
  3501. if ((*ptr >= 0x20 && *ptr <= 0x7F) || *ptr == '\n' || *ptr == '\r' ||
  3502. *ptr == '\t') {
  3503. text_count++;
  3504. }
  3505. ptr++;
  3506. }
  3507. delete[] buffer;
  3508. double current_percent_bin = (static_cast<double>(read_length - text_count) /
  3509. static_cast<double>(read_length));
  3510. if (current_percent_bin >= percent_bin) {
  3511. return SystemTools::FileTypeBinary;
  3512. }
  3513. return SystemTools::FileTypeText;
  3514. }
  3515. bool SystemTools::LocateFileInDir(const char* filename, const char* dir,
  3516. std::string& filename_found,
  3517. int try_filename_dirs)
  3518. {
  3519. if (!filename || !dir) {
  3520. return false;
  3521. }
  3522. // Get the basename of 'filename'
  3523. std::string filename_base = SystemTools::GetFilenameName(filename);
  3524. // Check if 'dir' is really a directory
  3525. // If win32 and matches something like C:, accept it as a dir
  3526. std::string real_dir;
  3527. if (!SystemTools::FileIsDirectory(dir)) {
  3528. #if defined(_WIN32)
  3529. size_t dir_len = strlen(dir);
  3530. if (dir_len < 2 || dir[dir_len - 1] != ':') {
  3531. #endif
  3532. real_dir = SystemTools::GetFilenamePath(dir);
  3533. dir = real_dir.c_str();
  3534. #if defined(_WIN32)
  3535. }
  3536. #endif
  3537. }
  3538. // Try to find the file in 'dir'
  3539. bool res = false;
  3540. if (!filename_base.empty() && dir) {
  3541. size_t dir_len = strlen(dir);
  3542. int need_slash =
  3543. (dir_len && dir[dir_len - 1] != '/' && dir[dir_len - 1] != '\\');
  3544. std::string temp = dir;
  3545. if (need_slash) {
  3546. temp += "/";
  3547. }
  3548. temp += filename_base;
  3549. if (SystemTools::FileExists(temp)) {
  3550. res = true;
  3551. filename_found = temp;
  3552. }
  3553. // If not found, we can try harder by appending part of the file to
  3554. // to the directory to look inside.
  3555. // Example: if we were looking for /foo/bar/yo.txt in /d1/d2, then
  3556. // try to find yo.txt in /d1/d2/bar, then /d1/d2/foo/bar, etc.
  3557. else if (try_filename_dirs) {
  3558. std::string filename_dir(filename);
  3559. std::string filename_dir_base;
  3560. std::string filename_dir_bases;
  3561. do {
  3562. filename_dir = SystemTools::GetFilenamePath(filename_dir);
  3563. filename_dir_base = SystemTools::GetFilenameName(filename_dir);
  3564. #if defined(_WIN32)
  3565. if (filename_dir_base.empty() || *filename_dir_base.rbegin() == ':')
  3566. #else
  3567. if (filename_dir_base.empty())
  3568. #endif
  3569. {
  3570. break;
  3571. }
  3572. filename_dir_bases = filename_dir_base + "/" + filename_dir_bases;
  3573. temp = dir;
  3574. if (need_slash) {
  3575. temp += "/";
  3576. }
  3577. temp += filename_dir_bases;
  3578. res = SystemTools::LocateFileInDir(filename_base.c_str(), temp.c_str(),
  3579. filename_found, 0);
  3580. } while (!res && !filename_dir_base.empty());
  3581. }
  3582. }
  3583. return res;
  3584. }
  3585. bool SystemTools::FileIsFullPath(const std::string& in_name)
  3586. {
  3587. return SystemTools::FileIsFullPath(in_name.c_str(), in_name.size());
  3588. }
  3589. bool SystemTools::FileIsFullPath(const char* in_name)
  3590. {
  3591. return SystemTools::FileIsFullPath(in_name,
  3592. in_name[0] ? (in_name[1] ? 2 : 1) : 0);
  3593. }
  3594. bool SystemTools::FileIsFullPath(const char* in_name, size_t len)
  3595. {
  3596. #if defined(_WIN32) || defined(__CYGWIN__)
  3597. // On Windows, the name must be at least two characters long.
  3598. if (len < 2) {
  3599. return false;
  3600. }
  3601. if (in_name[1] == ':') {
  3602. return true;
  3603. }
  3604. if (in_name[0] == '\\') {
  3605. return true;
  3606. }
  3607. #else
  3608. // On UNIX, the name must be at least one character long.
  3609. if (len < 1) {
  3610. return false;
  3611. }
  3612. #endif
  3613. #if !defined(_WIN32)
  3614. if (in_name[0] == '~') {
  3615. return true;
  3616. }
  3617. #endif
  3618. // On UNIX, the name must begin in a '/'.
  3619. // On Windows, if the name begins in a '/', then it is a full
  3620. // network path.
  3621. if (in_name[0] == '/') {
  3622. return true;
  3623. }
  3624. return false;
  3625. }
  3626. bool SystemTools::GetShortPath(const std::string& path, std::string& shortPath)
  3627. {
  3628. #if defined(_WIN32) && !defined(__CYGWIN__)
  3629. std::string tempPath = path; // create a buffer
  3630. // if the path passed in has quotes around it, first remove the quotes
  3631. if (!path.empty() && path[0] == '"' && *path.rbegin() == '"') {
  3632. tempPath = path.substr(1, path.length() - 2);
  3633. }
  3634. std::wstring wtempPath = Encoding::ToWide(tempPath);
  3635. DWORD ret = GetShortPathNameW(wtempPath.c_str(), NULL, 0);
  3636. std::vector<wchar_t> buffer(ret);
  3637. if (ret != 0) {
  3638. ret = GetShortPathNameW(wtempPath.c_str(), &buffer[0],
  3639. static_cast<DWORD>(buffer.size()));
  3640. }
  3641. if (ret == 0) {
  3642. return false;
  3643. } else {
  3644. shortPath = Encoding::ToNarrow(&buffer[0]);
  3645. return true;
  3646. }
  3647. #else
  3648. shortPath = path;
  3649. return true;
  3650. #endif
  3651. }
  3652. std::string SystemTools::GetCurrentDateTime(const char* format)
  3653. {
  3654. char buf[1024];
  3655. time_t t;
  3656. time(&t);
  3657. strftime(buf, sizeof(buf), format, localtime(&t));
  3658. return std::string(buf);
  3659. }
  3660. std::string SystemTools::MakeCidentifier(const std::string& s)
  3661. {
  3662. std::string str(s);
  3663. if (str.find_first_of("0123456789") == 0) {
  3664. str = "_" + str;
  3665. }
  3666. std::string permited_chars("_"
  3667. "abcdefghijklmnopqrstuvwxyz"
  3668. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  3669. "0123456789");
  3670. std::string::size_type pos = 0;
  3671. while ((pos = str.find_first_not_of(permited_chars, pos)) !=
  3672. std::string::npos) {
  3673. str[pos] = '_';
  3674. }
  3675. return str;
  3676. }
  3677. // Convenience function around std::getline which removes a trailing carriage
  3678. // return and can truncate the buffer as needed. Returns true
  3679. // if any data were read before the end-of-file was reached.
  3680. bool SystemTools::GetLineFromStream(std::istream& is, std::string& line,
  3681. bool* has_newline /* = 0 */,
  3682. long sizeLimit /* = -1 */)
  3683. {
  3684. // Start with an empty line.
  3685. line = "";
  3686. // Early short circuit return if stream is no good. Just return
  3687. // false and the empty line. (Probably means caller tried to
  3688. // create a file stream with a non-existent file name...)
  3689. //
  3690. if (!is) {
  3691. if (has_newline) {
  3692. *has_newline = false;
  3693. }
  3694. return false;
  3695. }
  3696. std::getline(is, line);
  3697. bool haveData = !line.empty() || !is.eof();
  3698. if (!line.empty()) {
  3699. // Avoid storing a carriage return character.
  3700. if (*line.rbegin() == '\r') {
  3701. line.resize(line.size() - 1);
  3702. }
  3703. // if we read too much then truncate the buffer
  3704. if (sizeLimit >= 0 && line.size() >= static_cast<size_t>(sizeLimit)) {
  3705. line.resize(sizeLimit);
  3706. }
  3707. }
  3708. // Return the results.
  3709. if (has_newline) {
  3710. *has_newline = !is.eof();
  3711. }
  3712. return haveData;
  3713. }
  3714. int SystemTools::GetTerminalWidth()
  3715. {
  3716. int width = -1;
  3717. #ifdef HAVE_TTY_INFO
  3718. struct winsize ws;
  3719. std::string columns; /* Unix98 environment variable */
  3720. if (ioctl(1, TIOCGWINSZ, &ws) != -1 && ws.ws_col > 0 && ws.ws_row > 0) {
  3721. width = ws.ws_col;
  3722. }
  3723. if (!isatty(STDOUT_FILENO)) {
  3724. width = -1;
  3725. }
  3726. if (SystemTools::GetEnv("COLUMNS", columns) && !columns.empty()) {
  3727. long t;
  3728. char* endptr;
  3729. t = strtol(columns.c_str(), &endptr, 0);
  3730. if (endptr && !*endptr && (t > 0) && (t < 1000)) {
  3731. width = static_cast<int>(t);
  3732. }
  3733. }
  3734. if (width < 9) {
  3735. width = -1;
  3736. }
  3737. #endif
  3738. return width;
  3739. }
  3740. bool SystemTools::GetPermissions(const char* file, mode_t& mode)
  3741. {
  3742. if (!file) {
  3743. return false;
  3744. }
  3745. return SystemTools::GetPermissions(std::string(file), mode);
  3746. }
  3747. bool SystemTools::GetPermissions(const std::string& file, mode_t& mode)
  3748. {
  3749. #if defined(_WIN32)
  3750. DWORD attr =
  3751. GetFileAttributesW(Encoding::ToWindowsExtendedPath(file).c_str());
  3752. if (attr == INVALID_FILE_ATTRIBUTES) {
  3753. return false;
  3754. }
  3755. if ((attr & FILE_ATTRIBUTE_READONLY) != 0) {
  3756. mode = (_S_IREAD | (_S_IREAD >> 3) | (_S_IREAD >> 6));
  3757. } else {
  3758. mode = (_S_IWRITE | (_S_IWRITE >> 3) | (_S_IWRITE >> 6)) |
  3759. (_S_IREAD | (_S_IREAD >> 3) | (_S_IREAD >> 6));
  3760. }
  3761. if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
  3762. mode |= S_IFDIR | (_S_IEXEC | (_S_IEXEC >> 3) | (_S_IEXEC >> 6));
  3763. } else {
  3764. mode |= S_IFREG;
  3765. }
  3766. size_t dotPos = file.rfind('.');
  3767. const char* ext = dotPos == std::string::npos ? 0 : (file.c_str() + dotPos);
  3768. if (ext &&
  3769. (Strucmp(ext, ".exe") == 0 || Strucmp(ext, ".com") == 0 ||
  3770. Strucmp(ext, ".cmd") == 0 || Strucmp(ext, ".bat") == 0)) {
  3771. mode |= (_S_IEXEC | (_S_IEXEC >> 3) | (_S_IEXEC >> 6));
  3772. }
  3773. #else
  3774. struct stat st;
  3775. if (stat(file.c_str(), &st) < 0) {
  3776. return false;
  3777. }
  3778. mode = st.st_mode;
  3779. #endif
  3780. return true;
  3781. }
  3782. bool SystemTools::SetPermissions(const char* file, mode_t mode,
  3783. bool honor_umask)
  3784. {
  3785. if (!file) {
  3786. return false;
  3787. }
  3788. return SystemTools::SetPermissions(std::string(file), mode, honor_umask);
  3789. }
  3790. bool SystemTools::SetPermissions(const std::string& file, mode_t mode,
  3791. bool honor_umask)
  3792. {
  3793. if (!SystemTools::PathExists(file)) {
  3794. return false;
  3795. }
  3796. if (honor_umask) {
  3797. mode_t currentMask = umask(0);
  3798. umask(currentMask);
  3799. mode &= ~currentMask;
  3800. }
  3801. #ifdef _WIN32
  3802. if (_wchmod(Encoding::ToWindowsExtendedPath(file).c_str(), mode) < 0)
  3803. #else
  3804. if (chmod(file.c_str(), mode) < 0)
  3805. #endif
  3806. {
  3807. return false;
  3808. }
  3809. return true;
  3810. }
  3811. std::string SystemTools::GetParentDirectory(const std::string& fileOrDir)
  3812. {
  3813. return SystemTools::GetFilenamePath(fileOrDir);
  3814. }
  3815. bool SystemTools::IsSubDirectory(const std::string& cSubdir,
  3816. const std::string& cDir)
  3817. {
  3818. if (cDir.empty()) {
  3819. return false;
  3820. }
  3821. std::string subdir = cSubdir;
  3822. std::string dir = cDir;
  3823. SystemTools::ConvertToUnixSlashes(subdir);
  3824. SystemTools::ConvertToUnixSlashes(dir);
  3825. if (subdir.size() <= dir.size() || dir.empty()) {
  3826. return false;
  3827. }
  3828. bool isRootPath = *dir.rbegin() == '/'; // like "/" or "C:/"
  3829. size_t expectedSlashPosition = isRootPath ? dir.size() - 1u : dir.size();
  3830. if (subdir[expectedSlashPosition] != '/') {
  3831. return false;
  3832. }
  3833. std::string s = subdir.substr(0, dir.size());
  3834. return SystemTools::ComparePath(s, dir);
  3835. }
  3836. void SystemTools::Delay(unsigned int msec)
  3837. {
  3838. #ifdef _WIN32
  3839. Sleep(msec);
  3840. #else
  3841. // The sleep function gives 1 second resolution and the usleep
  3842. // function gives 1e-6 second resolution but on some platforms has a
  3843. // maximum sleep time of 1 second. This could be re-implemented to
  3844. // use select with masked signals or pselect to mask signals
  3845. // atomically. If select is given empty sets and zero as the max
  3846. // file descriptor but a non-zero timeout it can be used to block
  3847. // for a precise amount of time.
  3848. if (msec >= 1000) {
  3849. sleep(msec / 1000);
  3850. usleep((msec % 1000) * 1000);
  3851. } else {
  3852. usleep(msec * 1000);
  3853. }
  3854. #endif
  3855. }
  3856. std::string SystemTools::GetOperatingSystemNameAndVersion()
  3857. {
  3858. std::string res;
  3859. #ifdef _WIN32
  3860. char buffer[256];
  3861. OSVERSIONINFOEXA osvi;
  3862. BOOL bOsVersionInfoEx;
  3863. ZeroMemory(&osvi, sizeof(osvi));
  3864. osvi.dwOSVersionInfoSize = sizeof(osvi);
  3865. # ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx
  3866. # pragma warning(push)
  3867. # ifdef __INTEL_COMPILER
  3868. # pragma warning(disable : 1478)
  3869. # else
  3870. # pragma warning(disable : 4996)
  3871. # endif
  3872. # endif
  3873. bOsVersionInfoEx = GetVersionExA((OSVERSIONINFOA*)&osvi);
  3874. if (!bOsVersionInfoEx) {
  3875. return 0;
  3876. }
  3877. # ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx
  3878. # pragma warning(pop)
  3879. # endif
  3880. switch (osvi.dwPlatformId) {
  3881. // Test for the Windows NT product family.
  3882. case VER_PLATFORM_WIN32_NT:
  3883. // Test for the specific product family.
  3884. if (osvi.dwMajorVersion == 10 && osvi.dwMinorVersion == 0) {
  3885. if (osvi.wProductType == VER_NT_WORKSTATION) {
  3886. res += "Microsoft Windows 10";
  3887. } else {
  3888. res += "Microsoft Windows Server 2016 family";
  3889. }
  3890. }
  3891. if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 3) {
  3892. if (osvi.wProductType == VER_NT_WORKSTATION) {
  3893. res += "Microsoft Windows 8.1";
  3894. } else {
  3895. res += "Microsoft Windows Server 2012 R2 family";
  3896. }
  3897. }
  3898. if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 2) {
  3899. if (osvi.wProductType == VER_NT_WORKSTATION) {
  3900. res += "Microsoft Windows 8";
  3901. } else {
  3902. res += "Microsoft Windows Server 2012 family";
  3903. }
  3904. }
  3905. if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 1) {
  3906. if (osvi.wProductType == VER_NT_WORKSTATION) {
  3907. res += "Microsoft Windows 7";
  3908. } else {
  3909. res += "Microsoft Windows Server 2008 R2 family";
  3910. }
  3911. }
  3912. if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 0) {
  3913. if (osvi.wProductType == VER_NT_WORKSTATION) {
  3914. res += "Microsoft Windows Vista";
  3915. } else {
  3916. res += "Microsoft Windows Server 2008 family";
  3917. }
  3918. }
  3919. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2) {
  3920. res += "Microsoft Windows Server 2003 family";
  3921. }
  3922. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1) {
  3923. res += "Microsoft Windows XP";
  3924. }
  3925. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0) {
  3926. res += "Microsoft Windows 2000";
  3927. }
  3928. if (osvi.dwMajorVersion <= 4) {
  3929. res += "Microsoft Windows NT";
  3930. }
  3931. // Test for specific product on Windows NT 4.0 SP6 and later.
  3932. if (bOsVersionInfoEx) {
  3933. // Test for the workstation type.
  3934. if (osvi.wProductType == VER_NT_WORKSTATION) {
  3935. if (osvi.dwMajorVersion == 4) {
  3936. res += " Workstation 4.0";
  3937. } else if (osvi.dwMajorVersion == 5) {
  3938. if (osvi.wSuiteMask & VER_SUITE_PERSONAL) {
  3939. res += " Home Edition";
  3940. } else {
  3941. res += " Professional";
  3942. }
  3943. }
  3944. }
  3945. // Test for the server type.
  3946. else if (osvi.wProductType == VER_NT_SERVER) {
  3947. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2) {
  3948. if (osvi.wSuiteMask & VER_SUITE_DATACENTER) {
  3949. res += " Datacenter Edition";
  3950. } else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) {
  3951. res += " Enterprise Edition";
  3952. } else if (osvi.wSuiteMask == VER_SUITE_BLADE) {
  3953. res += " Web Edition";
  3954. } else {
  3955. res += " Standard Edition";
  3956. }
  3957. }
  3958. else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0) {
  3959. if (osvi.wSuiteMask & VER_SUITE_DATACENTER) {
  3960. res += " Datacenter Server";
  3961. } else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) {
  3962. res += " Advanced Server";
  3963. } else {
  3964. res += " Server";
  3965. }
  3966. }
  3967. else if (osvi.dwMajorVersion <= 4) // Windows NT 4.0
  3968. {
  3969. if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) {
  3970. res += " Server 4.0, Enterprise Edition";
  3971. } else {
  3972. res += " Server 4.0";
  3973. }
  3974. }
  3975. }
  3976. }
  3977. // Test for specific product on Windows NT 4.0 SP5 and earlier
  3978. else {
  3979. HKEY hKey;
  3980. # define BUFSIZE 80
  3981. wchar_t szProductType[BUFSIZE];
  3982. DWORD dwBufLen = BUFSIZE;
  3983. LONG lRet;
  3984. lRet =
  3985. RegOpenKeyExW(HKEY_LOCAL_MACHINE,
  3986. L"SYSTEM\\CurrentControlSet\\Control\\ProductOptions",
  3987. 0, KEY_QUERY_VALUE, &hKey);
  3988. if (lRet != ERROR_SUCCESS) {
  3989. return 0;
  3990. }
  3991. lRet = RegQueryValueExW(hKey, L"ProductType", NULL, NULL,
  3992. (LPBYTE)szProductType, &dwBufLen);
  3993. if ((lRet != ERROR_SUCCESS) || (dwBufLen > BUFSIZE)) {
  3994. return 0;
  3995. }
  3996. RegCloseKey(hKey);
  3997. if (lstrcmpiW(L"WINNT", szProductType) == 0) {
  3998. res += " Workstation";
  3999. }
  4000. if (lstrcmpiW(L"LANMANNT", szProductType) == 0) {
  4001. res += " Server";
  4002. }
  4003. if (lstrcmpiW(L"SERVERNT", szProductType) == 0) {
  4004. res += " Advanced Server";
  4005. }
  4006. res += " ";
  4007. sprintf(buffer, "%ld", osvi.dwMajorVersion);
  4008. res += buffer;
  4009. res += ".";
  4010. sprintf(buffer, "%ld", osvi.dwMinorVersion);
  4011. res += buffer;
  4012. }
  4013. // Display service pack (if any) and build number.
  4014. if (osvi.dwMajorVersion == 4 &&
  4015. lstrcmpiA(osvi.szCSDVersion, "Service Pack 6") == 0) {
  4016. HKEY hKey;
  4017. LONG lRet;
  4018. // Test for SP6 versus SP6a.
  4019. lRet = RegOpenKeyExW(
  4020. HKEY_LOCAL_MACHINE,
  4021. L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Hotfix\\Q246009",
  4022. 0, KEY_QUERY_VALUE, &hKey);
  4023. if (lRet == ERROR_SUCCESS) {
  4024. res += " Service Pack 6a (Build ";
  4025. sprintf(buffer, "%ld", osvi.dwBuildNumber & 0xFFFF);
  4026. res += buffer;
  4027. res += ")";
  4028. } else // Windows NT 4.0 prior to SP6a
  4029. {
  4030. res += " ";
  4031. res += osvi.szCSDVersion;
  4032. res += " (Build ";
  4033. sprintf(buffer, "%ld", osvi.dwBuildNumber & 0xFFFF);
  4034. res += buffer;
  4035. res += ")";
  4036. }
  4037. RegCloseKey(hKey);
  4038. } else // Windows NT 3.51 and earlier or Windows 2000 and later
  4039. {
  4040. res += " ";
  4041. res += osvi.szCSDVersion;
  4042. res += " (Build ";
  4043. sprintf(buffer, "%ld", osvi.dwBuildNumber & 0xFFFF);
  4044. res += buffer;
  4045. res += ")";
  4046. }
  4047. break;
  4048. // Test for the Windows 95 product family.
  4049. case VER_PLATFORM_WIN32_WINDOWS:
  4050. if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0) {
  4051. res += "Microsoft Windows 95";
  4052. if (osvi.szCSDVersion[1] == 'C' || osvi.szCSDVersion[1] == 'B') {
  4053. res += " OSR2";
  4054. }
  4055. }
  4056. if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10) {
  4057. res += "Microsoft Windows 98";
  4058. if (osvi.szCSDVersion[1] == 'A') {
  4059. res += " SE";
  4060. }
  4061. }
  4062. if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90) {
  4063. res += "Microsoft Windows Millennium Edition";
  4064. }
  4065. break;
  4066. case VER_PLATFORM_WIN32s:
  4067. res += "Microsoft Win32s";
  4068. break;
  4069. }
  4070. #endif
  4071. return res;
  4072. }
  4073. bool SystemTools::ParseURLProtocol(const std::string& URL,
  4074. std::string& protocol,
  4075. std::string& dataglom)
  4076. {
  4077. // match 0 entire url
  4078. // match 1 protocol
  4079. // match 2 dataglom following protocol://
  4080. kwsys::RegularExpression urlRe(VTK_URL_PROTOCOL_REGEX);
  4081. if (!urlRe.find(URL))
  4082. return false;
  4083. protocol = urlRe.match(1);
  4084. dataglom = urlRe.match(2);
  4085. return true;
  4086. }
  4087. bool SystemTools::ParseURL(const std::string& URL, std::string& protocol,
  4088. std::string& username, std::string& password,
  4089. std::string& hostname, std::string& dataport,
  4090. std::string& database)
  4091. {
  4092. kwsys::RegularExpression urlRe(VTK_URL_REGEX);
  4093. if (!urlRe.find(URL))
  4094. return false;
  4095. // match 0 URL
  4096. // match 1 protocol
  4097. // match 2 mangled user
  4098. // match 3 username
  4099. // match 4 mangled password
  4100. // match 5 password
  4101. // match 6 hostname
  4102. // match 7 mangled port
  4103. // match 8 dataport
  4104. // match 9 database name
  4105. protocol = urlRe.match(1);
  4106. username = urlRe.match(3);
  4107. password = urlRe.match(5);
  4108. hostname = urlRe.match(6);
  4109. dataport = urlRe.match(8);
  4110. database = urlRe.match(9);
  4111. return true;
  4112. }
  4113. // These must NOT be initialized. Default initialization to zero is
  4114. // necessary.
  4115. static unsigned int SystemToolsManagerCount;
  4116. SystemToolsTranslationMap* SystemTools::TranslationMap;
  4117. #ifdef _WIN32
  4118. SystemToolsPathCaseMap* SystemTools::PathCaseMap;
  4119. SystemToolsEnvMap* SystemTools::EnvMap;
  4120. #endif
  4121. #ifdef __CYGWIN__
  4122. SystemToolsTranslationMap* SystemTools::Cyg2Win32Map;
  4123. #endif
  4124. // SystemToolsManager manages the SystemTools singleton.
  4125. // SystemToolsManager should be included in any translation unit
  4126. // that will use SystemTools or that implements the singleton
  4127. // pattern. It makes sure that the SystemTools singleton is created
  4128. // before and destroyed after all other singletons in CMake.
  4129. SystemToolsManager::SystemToolsManager()
  4130. {
  4131. if (++SystemToolsManagerCount == 1) {
  4132. SystemTools::ClassInitialize();
  4133. }
  4134. }
  4135. SystemToolsManager::~SystemToolsManager()
  4136. {
  4137. if (--SystemToolsManagerCount == 0) {
  4138. SystemTools::ClassFinalize();
  4139. }
  4140. }
  4141. #if defined(__VMS)
  4142. // On VMS we configure the run time C library to be more UNIX like.
  4143. // http://h71000.www7.hp.com/doc/732final/5763/5763pro_004.html
  4144. extern "C" int decc$feature_get_index(char* name);
  4145. extern "C" int decc$feature_set_value(int index, int mode, int value);
  4146. static int SetVMSFeature(char* name, int value)
  4147. {
  4148. int i;
  4149. errno = 0;
  4150. i = decc$feature_get_index(name);
  4151. return i >= 0 && (decc$feature_set_value(i, 1, value) >= 0 || errno == 0);
  4152. }
  4153. #endif
  4154. void SystemTools::ClassInitialize()
  4155. {
  4156. #ifdef __VMS
  4157. SetVMSFeature("DECC$FILENAME_UNIX_ONLY", 1);
  4158. #endif
  4159. // Allocate the translation map first.
  4160. SystemTools::TranslationMap = new SystemToolsTranslationMap;
  4161. #ifdef _WIN32
  4162. SystemTools::PathCaseMap = new SystemToolsPathCaseMap;
  4163. SystemTools::EnvMap = new SystemToolsEnvMap;
  4164. #endif
  4165. #ifdef __CYGWIN__
  4166. SystemTools::Cyg2Win32Map = new SystemToolsTranslationMap;
  4167. #endif
  4168. // Add some special translation paths for unix. These are not added
  4169. // for windows because drive letters need to be maintained. Also,
  4170. // there are not sym-links and mount points on windows anyway.
  4171. #if !defined(_WIN32) || defined(__CYGWIN__)
  4172. // The tmp path is frequently a logical path so always keep it:
  4173. SystemTools::AddKeepPath("/tmp/");
  4174. // If the current working directory is a logical path then keep the
  4175. // logical name.
  4176. std::string pwd_str;
  4177. if (SystemTools::GetEnv("PWD", pwd_str)) {
  4178. char buf[2048];
  4179. if (const char* cwd = Getcwd(buf, 2048)) {
  4180. // The current working directory may be a logical path. Find
  4181. // the shortest logical path that still produces the correct
  4182. // physical path.
  4183. std::string cwd_changed;
  4184. std::string pwd_changed;
  4185. // Test progressively shorter logical-to-physical mappings.
  4186. std::string cwd_str = cwd;
  4187. std::string pwd_path;
  4188. Realpath(pwd_str.c_str(), pwd_path);
  4189. while (cwd_str == pwd_path && cwd_str != pwd_str) {
  4190. // The current pair of paths is a working logical mapping.
  4191. cwd_changed = cwd_str;
  4192. pwd_changed = pwd_str;
  4193. // Strip off one directory level and see if the logical
  4194. // mapping still works.
  4195. pwd_str = SystemTools::GetFilenamePath(pwd_str);
  4196. cwd_str = SystemTools::GetFilenamePath(cwd_str);
  4197. Realpath(pwd_str.c_str(), pwd_path);
  4198. }
  4199. // Add the translation to keep the logical path name.
  4200. if (!cwd_changed.empty() && !pwd_changed.empty()) {
  4201. SystemTools::AddTranslationPath(cwd_changed, pwd_changed);
  4202. }
  4203. }
  4204. }
  4205. #endif
  4206. }
  4207. void SystemTools::ClassFinalize()
  4208. {
  4209. delete SystemTools::TranslationMap;
  4210. #ifdef _WIN32
  4211. delete SystemTools::PathCaseMap;
  4212. delete SystemTools::EnvMap;
  4213. #endif
  4214. #ifdef __CYGWIN__
  4215. delete SystemTools::Cyg2Win32Map;
  4216. #endif
  4217. }
  4218. } // namespace KWSYS_NAMESPACE
  4219. #if defined(_MSC_VER) && defined(_DEBUG)
  4220. # include <crtdbg.h>
  4221. # include <stdio.h>
  4222. # include <stdlib.h>
  4223. namespace KWSYS_NAMESPACE {
  4224. static int SystemToolsDebugReport(int, char* message, int*)
  4225. {
  4226. fprintf(stderr, "%s", message);
  4227. fflush(stderr);
  4228. return 1; // no further reporting required
  4229. }
  4230. void SystemTools::EnableMSVCDebugHook()
  4231. {
  4232. if (SystemTools::HasEnv("DART_TEST_FROM_DART") ||
  4233. SystemTools::HasEnv("DASHBOARD_TEST_FROM_CTEST")) {
  4234. _CrtSetReportHook(SystemToolsDebugReport);
  4235. }
  4236. }
  4237. } // namespace KWSYS_NAMESPACE
  4238. #else
  4239. namespace KWSYS_NAMESPACE {
  4240. void SystemTools::EnableMSVCDebugHook()
  4241. {
  4242. }
  4243. } // namespace KWSYS_NAMESPACE
  4244. #endif