SystemTools.cxx 128 KB

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