SystemTools.cxx 127 KB

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