SystemTools.cxx 130 KB

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