SystemTools.cxx 135 KB

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