SystemTools.cxx 134 KB

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