SystemTools.cxx 128 KB

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