SystemTools.cxx 128 KB

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