SystemTools.cxx 128 KB

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