1
0

SystemTools.cxx 129 KB

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