cmSystemTools.cxx 125 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file LICENSE.rst or https://cmake.org/licensing for details. */
  3. #if !defined(_WIN32) && !defined(__sun) && !defined(__OpenBSD__)
  4. // POSIX APIs are needed
  5. // NOLINTNEXTLINE(bugprone-reserved-identifier)
  6. # define _POSIX_C_SOURCE 200809L
  7. #endif
  8. #if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__NetBSD__) || \
  9. defined(__QNX__)
  10. // For isascii
  11. // NOLINTNEXTLINE(bugprone-reserved-identifier)
  12. # define _XOPEN_SOURCE 700
  13. #endif
  14. #if defined(__APPLE__)
  15. // Restore Darwin APIs removed by _POSIX_C_SOURCE.
  16. // NOLINTNEXTLINE(bugprone-reserved-identifier)
  17. # define _DARWIN_C_SOURCE
  18. #endif
  19. #ifndef __has_feature
  20. # define __has_feature(x) 0
  21. #endif
  22. #if !defined(__clang__) || __has_feature(cxx_thread_local)
  23. # define CM_HAVE_THREAD_LOCAL
  24. #endif
  25. #include "cmSystemTools.h"
  26. #include <iterator>
  27. #if defined(_WIN32) || defined(__APPLE__)
  28. # include <unordered_map>
  29. #endif
  30. #include <cm/optional>
  31. #include <cmext/algorithm>
  32. #include <cmext/string_view>
  33. #include <cm3p/uv.h>
  34. #include "cmDuration.h"
  35. #include "cmELF.h"
  36. #include "cmMessageMetadata.h"
  37. #include "cmPathResolver.h"
  38. #include "cmProcessOutput.h"
  39. #include "cmRange.h"
  40. #include "cmStringAlgorithms.h"
  41. #include "cmUVHandlePtr.h"
  42. #include "cmUVProcessChain.h"
  43. #include "cmUVStream.h"
  44. #include "cmValue.h"
  45. #include "cmWorkingDirectory.h"
  46. #if !defined(CMAKE_BOOTSTRAP)
  47. # include <cm3p/archive.h>
  48. # include <cm3p/archive_entry.h>
  49. # include "cmArchiveWrite.h"
  50. # include "cmLocale.h"
  51. # ifndef __LA_INT64_T
  52. # define __LA_INT64_T la_int64_t
  53. # endif
  54. # ifndef __LA_SSIZE_T
  55. # define __LA_SSIZE_T la_ssize_t
  56. # endif
  57. #endif
  58. #if defined(CMake_USE_MACH_PARSER)
  59. # include "cmMachO.h"
  60. #endif
  61. #if defined(CMake_USE_XCOFF_PARSER)
  62. # include "cmXCOFF.h"
  63. #endif
  64. #include <algorithm>
  65. #include <cassert>
  66. #include <cctype>
  67. #include <cerrno>
  68. #include <cstdint>
  69. #include <cstdio>
  70. #include <cstdlib>
  71. #include <cstring>
  72. #include <ctime>
  73. #include <functional>
  74. #include <iostream>
  75. #include <memory>
  76. #include <random>
  77. #include <sstream>
  78. #include <utility>
  79. #include <vector>
  80. #ifndef CM_HAVE_THREAD_LOCAL
  81. # include <mutex>
  82. #endif
  83. #include <fcntl.h>
  84. #include "cmsys/Directory.hxx"
  85. #include "cmsys/Encoding.hxx"
  86. #include "cmsys/FStream.hxx"
  87. #include "cmsys/RegularExpression.hxx"
  88. #include "cmsys/System.h"
  89. #if defined(_WIN32)
  90. # include <windows.h>
  91. # include <knownfolders.h>
  92. # include <shlobj.h>
  93. // include wincrypt.h after windows.h
  94. # include <wincrypt.h>
  95. #else
  96. # include <unistd.h>
  97. # include <sys/time.h>
  98. #endif
  99. #if defined(_WIN32) && \
  100. (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__MINGW32__))
  101. # include <io.h>
  102. #endif
  103. #if defined(__APPLE__)
  104. # include <mach-o/dyld.h>
  105. #endif
  106. #ifdef __QNX__
  107. # include <malloc.h> /* for malloc/free on QNX */
  108. #endif
  109. #ifdef __linux__
  110. # include <linux/fs.h>
  111. # include <sys/ioctl.h>
  112. #endif
  113. #if !defined(_WIN32) && !defined(__ANDROID__)
  114. # include <sys/utsname.h>
  115. #endif
  116. #if defined(CMAKE_BOOTSTRAP) && defined(__sun) && defined(__i386)
  117. # define CMAKE_NO_MKDTEMP
  118. #endif
  119. #ifdef CMAKE_NO_MKDTEMP
  120. # include <dlfcn.h>
  121. #endif
  122. #ifndef CMAKE_NO_GETPWNAM
  123. # if defined(_WIN32)
  124. # define CMAKE_NO_GETPWNAM
  125. # endif
  126. #endif
  127. #ifndef CMAKE_NO_GETPWNAM
  128. # include <pwd.h>
  129. #endif
  130. #if defined(_MSC_VER) && _MSC_VER >= 1800
  131. # define CM_WINDOWS_DEPRECATED_GetVersionEx
  132. #endif
  133. namespace {
  134. cmSystemTools::InterruptCallback s_InterruptCallback;
  135. cmSystemTools::MessageCallback s_MessageCallback;
  136. cmSystemTools::OutputCallback s_StderrCallback;
  137. cmSystemTools::OutputCallback s_StdoutCallback;
  138. std::string ResolveTildePath(std::string p)
  139. {
  140. if (!p.empty() && p[0] == '~') {
  141. cm::optional<std::string> home;
  142. std::string::size_type last = p.find_first_of("/\\");
  143. if (last == std::string::npos) {
  144. last = p.size();
  145. }
  146. if (last == 1) {
  147. #if defined(_WIN32) && !defined(__CYGWIN__)
  148. home = cmSystemTools::GetEnvVar("USERPROFILE");
  149. if (!home)
  150. #endif
  151. home = cmSystemTools::GetEnvVar("HOME");
  152. #ifndef CMAKE_NO_GETPWNAM
  153. } else if (last > 1) {
  154. std::string user = p.substr(1, last - 1);
  155. if (passwd* pw = getpwnam(user.c_str())) {
  156. home = std::string(pw->pw_dir);
  157. }
  158. #endif
  159. }
  160. if (home) {
  161. p.replace(0, last, *home);
  162. }
  163. }
  164. return p;
  165. }
  166. #ifdef _WIN32
  167. std::string GetDosDriveWorkingDirectory(char letter)
  168. {
  169. // The Windows command processor tracks a per-drive working
  170. // directory for compatibility with MS-DOS by using special
  171. // environment variables named "=C:".
  172. // https://web.archive.org/web/20100522040616/
  173. // https://blogs.msdn.com/oldnewthing/archive/2010/05/06/10008132.aspx
  174. return cmSystemTools::GetEnvVar(cmStrCat('=', letter, ':'))
  175. .value_or(std::string());
  176. }
  177. cmsys::Status ReadNameOnDisk(std::string const& path, std::string& name)
  178. {
  179. std::wstring wp = cmsys::Encoding::ToWide(path);
  180. HANDLE h = CreateFileW(
  181. wp.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
  182. FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, nullptr);
  183. if (h == INVALID_HANDLE_VALUE) {
  184. return cmsys::Status::Windows_GetLastError();
  185. }
  186. WCHAR local_fni[((sizeof(FILE_NAME_INFO) - 1) / sizeof(WCHAR)) + 1024];
  187. size_t fni_size = sizeof(local_fni);
  188. auto* fni = reinterpret_cast<FILE_NAME_INFO*>(local_fni);
  189. if (!GetFileInformationByHandleEx(h, FileNameInfo, fni, fni_size)) {
  190. DWORD e = GetLastError();
  191. if (e != ERROR_MORE_DATA) {
  192. CloseHandle(h);
  193. return cmsys::Status::Windows(e);
  194. }
  195. fni_size = fni->FileNameLength;
  196. fni = static_cast<FILE_NAME_INFO*>(malloc(fni_size));
  197. if (!fni) {
  198. e = ERROR_NOT_ENOUGH_MEMORY;
  199. CloseHandle(h);
  200. return cmsys::Status::Windows(e);
  201. }
  202. if (!GetFileInformationByHandleEx(h, FileNameInfo, fni, fni_size)) {
  203. e = GetLastError();
  204. free(fni);
  205. CloseHandle(h);
  206. return cmsys::Status::Windows(e);
  207. }
  208. }
  209. std::wstring wn{ fni->FileName, fni->FileNameLength / sizeof(WCHAR) };
  210. std::string nn = cmsys::Encoding::ToNarrow(wn);
  211. std::string::size_type last_slash = nn.find_last_of("/\\");
  212. if (last_slash != std::string::npos) {
  213. name = nn.substr(last_slash + 1);
  214. }
  215. if (fni != reinterpret_cast<FILE_NAME_INFO*>(local_fni)) {
  216. free(fni);
  217. }
  218. CloseHandle(h);
  219. return cmsys::Status::Success();
  220. }
  221. #elif defined(__APPLE__)
  222. cmsys::Status ReadNameOnDiskIterateDir(std::string const& path,
  223. std::string& name)
  224. {
  225. // Read contents of the parent directory to find the
  226. // entry matching the given path.
  227. std::string const bn = cmSystemTools::GetFilenameName(path);
  228. std::string const dn = cmSystemTools::GetFilenamePath(path);
  229. DIR* d = opendir(dn.c_str());
  230. while (struct dirent* dr = readdir(d)) {
  231. if (strcasecmp(dr->d_name, bn.c_str()) == 0) {
  232. name = dr->d_name;
  233. closedir(d);
  234. return cmsys::Status::Success();
  235. }
  236. }
  237. closedir(d);
  238. return cmsys::Status::POSIX(ENOENT);
  239. }
  240. cmsys::Status ReadNameOnDiskFcntlGetPath(std::string const& path,
  241. std::string& name)
  242. {
  243. // macOS (and *BSD) offer a syscall to get an on-disk path to
  244. // a descriptor's file.
  245. int fd = open(path.c_str(), O_SYMLINK | O_RDONLY);
  246. if (fd == -1) {
  247. return cmsys::Status::POSIX(errno);
  248. }
  249. char out[MAXPATHLEN + 1];
  250. if (fcntl(fd, F_GETPATH, out) == -1) {
  251. int e = errno;
  252. close(fd);
  253. return cmsys::Status::POSIX(e);
  254. }
  255. close(fd);
  256. name = cmSystemTools::GetFilenameName(out);
  257. return cmsys::Status::Success();
  258. }
  259. cmsys::Status ReadNameOnDisk(std::string const& path, std::string& name)
  260. {
  261. struct stat stat_path;
  262. if (lstat(path.c_str(), &stat_path) != 0) {
  263. return cmsys::Status::POSIX(errno);
  264. }
  265. // macOS (and *BSD) use namei(9) to cache file paths. Use it unless
  266. // the inode has multiple hardlinks: if it is opened through multiple
  267. // paths, the results may be unpredictable.
  268. if (S_ISDIR(stat_path.st_mode) || stat_path.st_nlink < 2) {
  269. return ReadNameOnDiskFcntlGetPath(path, name);
  270. }
  271. // Fall back to reading the parent directory.
  272. return ReadNameOnDiskIterateDir(path, name);
  273. }
  274. #endif
  275. class RealSystem : public cm::PathResolver::System
  276. {
  277. public:
  278. ~RealSystem() override = default;
  279. cmsys::Status ReadSymlink(std::string const& path,
  280. std::string& link) override
  281. {
  282. return cmSystemTools::ReadSymlink(path, link);
  283. }
  284. bool PathExists(std::string const& path) override
  285. {
  286. return cmSystemTools::PathExists(path);
  287. }
  288. std::string GetWorkingDirectory() override
  289. {
  290. return cmSystemTools::GetLogicalWorkingDirectory();
  291. }
  292. #ifdef _WIN32
  293. std::string GetWorkingDirectoryOnDrive(char letter) override
  294. {
  295. return GetDosDriveWorkingDirectory(letter);
  296. }
  297. #endif
  298. #if defined(_WIN32) || defined(__APPLE__)
  299. struct NameOnDisk
  300. {
  301. cmsys::Status Status;
  302. std::string Name;
  303. };
  304. using NameOnDiskMap = std::unordered_map<std::string, NameOnDisk>;
  305. NameOnDiskMap CachedNameOnDisk;
  306. cmsys::Status ReadName(std::string const& path, std::string& name) override
  307. {
  308. // Cache results to avoid repeated filesystem access.
  309. // We assume any files created by our own process keep their case.
  310. // Index the cache by lower-case paths to make it case-insensitive.
  311. std::string path_lower = cmSystemTools::LowerCase(path);
  312. auto i = this->CachedNameOnDisk.find(path_lower);
  313. if (i == this->CachedNameOnDisk.end()) {
  314. i = this->CachedNameOnDisk.emplace(path_lower, NameOnDisk()).first;
  315. i->second.Status = ReadNameOnDisk(path, i->second.Name);
  316. }
  317. name = i->second.Name;
  318. return i->second.Status;
  319. }
  320. #endif
  321. };
  322. RealSystem RealOS;
  323. } // namespace
  324. #if !defined(HAVE_ENVIRON_NOT_REQUIRE_PROTOTYPE)
  325. // For GetEnvironmentVariables
  326. # if defined(_WIN32)
  327. extern __declspec(dllimport) char** environ;
  328. # else
  329. extern char** environ; // NOLINT(readability-redundant-declaration)
  330. # endif
  331. #endif
  332. #if !defined(CMAKE_BOOTSTRAP)
  333. static std::string cm_archive_entry_pathname(struct archive_entry* entry)
  334. {
  335. return cmsys::Encoding::ToNarrow(archive_entry_pathname_w(entry));
  336. }
  337. static int cm_archive_read_open_file(struct archive* a, char const* file,
  338. int block_size)
  339. {
  340. std::wstring wfile = cmsys::Encoding::ToWide(file);
  341. return archive_read_open_filename_w(a, wfile.c_str(), block_size);
  342. }
  343. #endif
  344. #ifdef _WIN32
  345. #elif defined(__APPLE__)
  346. # include <crt_externs.h>
  347. # define environ (*_NSGetEnviron())
  348. #endif
  349. bool cmSystemTools::s_RunCommandHideConsole = false;
  350. bool cmSystemTools::s_DisableRunCommandOutput = false;
  351. bool cmSystemTools::s_ErrorOccurred = false;
  352. bool cmSystemTools::s_FatalErrorOccurred = false;
  353. bool cmSystemTools::s_ForceUnixPaths = false;
  354. // replace replace with with as many times as it shows up in source.
  355. // write the result into source.
  356. #if defined(_WIN32) && !defined(__CYGWIN__)
  357. void cmSystemTools::ExpandRegistryValues(std::string& source, KeyWOW64 view)
  358. {
  359. // Regular expression to match anything inside [...] that begins in HKEY.
  360. // Note that there is a special rule for regular expressions to match a
  361. // close square-bracket inside a list delimited by square brackets.
  362. // The "[^]]" part of this expression will match any character except
  363. // a close square-bracket. The ']' character must be the first in the
  364. // list of characters inside the [^...] block of the expression.
  365. cmsys::RegularExpression regEntry("\\[(HKEY[^]]*)\\]");
  366. // check for black line or comment
  367. while (regEntry.find(source)) {
  368. // the arguments are the second match
  369. std::string key = regEntry.match(1);
  370. std::string val;
  371. if (ReadRegistryValue(key.c_str(), val, view)) {
  372. std::string reg = cmStrCat('[', key, ']');
  373. cmSystemTools::ReplaceString(source, reg.c_str(), val.c_str());
  374. } else {
  375. std::string reg = cmStrCat('[', key, ']');
  376. cmSystemTools::ReplaceString(source, reg.c_str(), "/registry");
  377. }
  378. }
  379. }
  380. #else
  381. void cmSystemTools::ExpandRegistryValues(std::string& source,
  382. KeyWOW64 /*unused*/)
  383. {
  384. cmsys::RegularExpression regEntry("\\[(HKEY[^]]*)\\]");
  385. while (regEntry.find(source)) {
  386. // the arguments are the second match
  387. std::string key = regEntry.match(1);
  388. std::string reg = cmStrCat('[', key, ']');
  389. cmSystemTools::ReplaceString(source, reg.c_str(), "/registry");
  390. }
  391. }
  392. #endif
  393. // Return a lower case string
  394. std::string cmSystemTools::LowerCase(cm::string_view s)
  395. {
  396. std::string n;
  397. n.resize(s.size());
  398. for (size_t i = 0; i < s.size(); i++) {
  399. n[i] = static_cast<std::string::value_type>(tolower(s[i]));
  400. }
  401. return n;
  402. }
  403. // Return an upper case string
  404. std::string cmSystemTools::UpperCase(cm::string_view s)
  405. {
  406. std::string n;
  407. n.resize(s.size());
  408. for (size_t i = 0; i < s.size(); i++) {
  409. n[i] = static_cast<std::string::value_type>(toupper(s[i]));
  410. }
  411. return n;
  412. }
  413. std::string cmSystemTools::HelpFileName(cm::string_view str)
  414. {
  415. std::string name(str);
  416. cmSystemTools::ReplaceString(name, "<", "");
  417. cmSystemTools::ReplaceString(name, ">", "");
  418. return name;
  419. }
  420. void cmSystemTools::Error(std::string const& m)
  421. {
  422. std::string message = "CMake Error: " + m;
  423. cmSystemTools::s_ErrorOccurred = true;
  424. cmSystemTools::Message(message, "Error");
  425. }
  426. void cmSystemTools::SetInterruptCallback(InterruptCallback f)
  427. {
  428. s_InterruptCallback = std::move(f);
  429. }
  430. bool cmSystemTools::GetInterruptFlag()
  431. {
  432. if (s_InterruptCallback) {
  433. return s_InterruptCallback();
  434. }
  435. return false;
  436. }
  437. void cmSystemTools::SetMessageCallback(MessageCallback f)
  438. {
  439. s_MessageCallback = std::move(f);
  440. }
  441. void cmSystemTools::SetStdoutCallback(OutputCallback f)
  442. {
  443. s_StdoutCallback = std::move(f);
  444. }
  445. void cmSystemTools::SetStderrCallback(OutputCallback f)
  446. {
  447. s_StderrCallback = std::move(f);
  448. }
  449. void cmSystemTools::Stderr(std::string const& s)
  450. {
  451. if (s_StderrCallback) {
  452. s_StderrCallback(s);
  453. } else {
  454. std::cerr << s << std::flush;
  455. }
  456. }
  457. void cmSystemTools::Stdout(std::string const& s)
  458. {
  459. if (s_StdoutCallback) {
  460. s_StdoutCallback(s);
  461. } else {
  462. std::cout << s << std::flush;
  463. }
  464. }
  465. void cmSystemTools::Message(std::string const& m, char const* title)
  466. {
  467. cmMessageMetadata md;
  468. md.title = title;
  469. Message(m, md);
  470. }
  471. void cmSystemTools::Message(std::string const& m, cmMessageMetadata const& md)
  472. {
  473. if (s_MessageCallback) {
  474. s_MessageCallback(m, md);
  475. } else {
  476. std::cerr << m << std::endl;
  477. }
  478. }
  479. void cmSystemTools::ReportLastSystemError(char const* msg)
  480. {
  481. std::string m =
  482. cmStrCat(msg, ": System Error: ", Superclass::GetLastSystemError());
  483. cmSystemTools::Error(m);
  484. }
  485. void cmSystemTools::ParseWindowsCommandLine(char const* command,
  486. std::vector<std::string>& args)
  487. {
  488. // See the MSDN document "Parsing C Command-Line Arguments" at
  489. // http://msdn2.microsoft.com/en-us/library/a1y7w461.aspx for rules
  490. // of parsing the windows command line.
  491. bool in_argument = false;
  492. bool in_quotes = false;
  493. int backslashes = 0;
  494. std::string arg;
  495. for (char const* c = command; *c; ++c) {
  496. if (*c == '\\') {
  497. ++backslashes;
  498. in_argument = true;
  499. } else if (*c == '"') {
  500. int backslash_pairs = backslashes >> 1;
  501. int backslash_escaped = backslashes & 1;
  502. arg.append(backslash_pairs, '\\');
  503. backslashes = 0;
  504. if (backslash_escaped) {
  505. /* An odd number of backslashes precede this quote.
  506. It is escaped. */
  507. arg.append(1, '"');
  508. } else {
  509. /* An even number of backslashes precede this quote.
  510. It is not escaped. */
  511. in_quotes = !in_quotes;
  512. }
  513. in_argument = true;
  514. } else {
  515. arg.append(backslashes, '\\');
  516. backslashes = 0;
  517. if (cmIsSpace(*c)) {
  518. if (in_quotes) {
  519. arg.append(1, *c);
  520. } else if (in_argument) {
  521. args.push_back(arg);
  522. arg.clear();
  523. in_argument = false;
  524. }
  525. } else {
  526. in_argument = true;
  527. arg.append(1, *c);
  528. }
  529. }
  530. }
  531. arg.append(backslashes, '\\');
  532. if (in_argument) {
  533. args.push_back(arg);
  534. }
  535. }
  536. class cmSystemToolsArgV
  537. {
  538. char** ArgV;
  539. public:
  540. cmSystemToolsArgV(char** argv)
  541. : ArgV(argv)
  542. {
  543. }
  544. ~cmSystemToolsArgV()
  545. {
  546. for (char** arg = this->ArgV; arg && *arg; ++arg) {
  547. free(*arg);
  548. }
  549. free(this->ArgV);
  550. }
  551. cmSystemToolsArgV(cmSystemToolsArgV const&) = delete;
  552. cmSystemToolsArgV& operator=(cmSystemToolsArgV const&) = delete;
  553. void Store(std::vector<std::string>& args) const
  554. {
  555. for (char** arg = this->ArgV; arg && *arg; ++arg) {
  556. args.emplace_back(*arg);
  557. }
  558. }
  559. };
  560. void cmSystemTools::ParseUnixCommandLine(char const* command,
  561. std::vector<std::string>& args)
  562. {
  563. // Invoke the underlying parser.
  564. cmSystemToolsArgV argv(cmsysSystem_Parse_CommandForUnix(command, 0));
  565. argv.Store(args);
  566. }
  567. std::vector<std::string> cmSystemTools::HandleResponseFile(
  568. std::vector<std::string>::const_iterator argBeg,
  569. std::vector<std::string>::const_iterator argEnd)
  570. {
  571. std::vector<std::string> arg_full;
  572. for (std::string const& arg : cmMakeRange(argBeg, argEnd)) {
  573. if (cmHasPrefix(arg, '@')) {
  574. cmsys::ifstream responseFile(arg.substr(1).c_str(), std::ios::in);
  575. if (!responseFile) {
  576. std::string error = cmStrCat("failed to open for reading (",
  577. cmSystemTools::GetLastSystemError(),
  578. "):\n ", cm::string_view(arg).substr(1));
  579. cmSystemTools::Error(error);
  580. } else {
  581. std::string line;
  582. cmSystemTools::GetLineFromStream(responseFile, line);
  583. std::vector<std::string> args2;
  584. #ifdef _WIN32
  585. cmSystemTools::ParseWindowsCommandLine(line.c_str(), args2);
  586. #else
  587. cmSystemTools::ParseUnixCommandLine(line.c_str(), args2);
  588. #endif
  589. cm::append(arg_full, args2);
  590. }
  591. } else {
  592. arg_full.push_back(arg);
  593. }
  594. }
  595. return arg_full;
  596. }
  597. std::vector<std::string> cmSystemTools::ParseArguments(std::string const& cmd)
  598. {
  599. std::vector<std::string> args;
  600. std::string arg;
  601. bool win_path = false;
  602. char const* command = cmd.c_str();
  603. if (command[0] && command[1] &&
  604. ((command[0] != '/' && command[1] == ':' && command[2] == '\\') ||
  605. (command[0] == '\"' && command[1] != '/' && command[2] == ':' &&
  606. command[3] == '\\') ||
  607. (command[0] == '\'' && command[1] != '/' && command[2] == ':' &&
  608. command[3] == '\\') ||
  609. (command[0] == '\\' && command[1] == '\\'))) {
  610. win_path = true;
  611. }
  612. // Split the command into an argv array.
  613. for (char const* c = command; *c;) {
  614. // Skip over whitespace.
  615. while (*c == ' ' || *c == '\t') {
  616. ++c;
  617. }
  618. arg.clear();
  619. if (*c == '"') {
  620. // Parse a quoted argument.
  621. ++c;
  622. while (*c && *c != '"') {
  623. arg.append(1, *c);
  624. ++c;
  625. }
  626. if (*c) {
  627. ++c;
  628. }
  629. args.push_back(arg);
  630. } else if (*c == '\'') {
  631. // Parse a quoted argument.
  632. ++c;
  633. while (*c && *c != '\'') {
  634. arg.append(1, *c);
  635. ++c;
  636. }
  637. if (*c) {
  638. ++c;
  639. }
  640. args.push_back(arg);
  641. } else if (*c) {
  642. // Parse an unquoted argument.
  643. while (*c && *c != ' ' && *c != '\t') {
  644. if (*c == '\\' && !win_path) {
  645. ++c;
  646. if (*c) {
  647. arg.append(1, *c);
  648. ++c;
  649. }
  650. } else {
  651. arg.append(1, *c);
  652. ++c;
  653. }
  654. }
  655. args.push_back(arg);
  656. }
  657. }
  658. return args;
  659. }
  660. bool cmSystemTools::SplitProgramFromArgs(std::string const& command,
  661. std::string& program,
  662. std::string& args)
  663. {
  664. char const* c = command.c_str();
  665. // Skip leading whitespace.
  666. while (cmIsSpace(*c)) {
  667. ++c;
  668. }
  669. // Parse one command-line element up to an unquoted space.
  670. bool in_escape = false;
  671. bool in_double = false;
  672. bool in_single = false;
  673. for (; *c; ++c) {
  674. if (in_single) {
  675. if (*c == '\'') {
  676. in_single = false;
  677. } else {
  678. program += *c;
  679. }
  680. } else if (in_escape) {
  681. in_escape = false;
  682. program += *c;
  683. } else if (*c == '\\') {
  684. in_escape = true;
  685. } else if (in_double) {
  686. if (*c == '"') {
  687. in_double = false;
  688. } else {
  689. program += *c;
  690. }
  691. } else if (*c == '"') {
  692. in_double = true;
  693. } else if (*c == '\'') {
  694. in_single = true;
  695. } else if (cmIsSpace(*c)) {
  696. break;
  697. } else {
  698. program += *c;
  699. }
  700. }
  701. // The remainder of the command line holds unparsed arguments.
  702. args = c;
  703. return !in_single && !in_escape && !in_double;
  704. }
  705. std::size_t cmSystemTools::CalculateCommandLineLengthLimit()
  706. {
  707. size_t sz =
  708. #ifdef _WIN32
  709. // There's a maximum of 65536 bytes and thus 32768 WCHARs on Windows
  710. // However, cmd.exe itself can only handle 8191 WCHARs and Ninja for
  711. // example uses it to spawn processes.
  712. size_t(8191);
  713. #elif defined(__linux)
  714. // MAX_ARG_STRLEN is the maximum length of a string permissible for
  715. // the execve() syscall on Linux. It's defined as (PAGE_SIZE * 32)
  716. // in Linux's binfmts.h
  717. static_cast<size_t>(sysconf(_SC_PAGESIZE) * 32);
  718. #else
  719. size_t(0);
  720. #endif
  721. #if defined(_SC_ARG_MAX)
  722. // ARG_MAX is the maximum size of the command and environment
  723. // that can be passed to the exec functions on UNIX.
  724. // The value in climits does not need to be present and may
  725. // depend upon runtime memory constraints, hence sysconf()
  726. // should be used to query it.
  727. long szArgMax = sysconf(_SC_ARG_MAX);
  728. // A return value of -1 signifies an undetermined limit, but
  729. // it does not imply an infinite limit, and thus is ignored.
  730. if (szArgMax != -1) {
  731. // We estimate the size of the environment block to be 1000.
  732. // This isn't accurate at all, but leaves some headroom.
  733. szArgMax = szArgMax < 1000 ? 0 : szArgMax - 1000;
  734. # if defined(_WIN32) || defined(__linux)
  735. sz = std::min(sz, static_cast<size_t>(szArgMax));
  736. # else
  737. sz = static_cast<size_t>(szArgMax);
  738. # endif
  739. }
  740. #endif
  741. return sz;
  742. }
  743. void cmSystemTools::MaybePrependCmdExe(std::vector<std::string>& cmdLine)
  744. {
  745. #if defined(_WIN32) && !defined(__CYGWIN__)
  746. if (!cmdLine.empty()) {
  747. std::string& applicationName = cmdLine.at(0);
  748. static cmsys::RegularExpression const winCmdRegex(
  749. "\\.([Bb][Aa][Tt]|[Cc][Mm][Dd])$");
  750. cmsys::RegularExpressionMatch winCmdMatch;
  751. if (winCmdRegex.find(applicationName.c_str(), winCmdMatch)) {
  752. // Wrap `.bat` and `.cmd` commands with `cmd /c call`.
  753. std::vector<std::string> output;
  754. output.reserve(cmdLine.size() + 3);
  755. output.emplace_back(cmSystemTools::GetComspec());
  756. output.emplace_back("/c");
  757. output.emplace_back("call");
  758. // Convert the batch file path to use backslashes for cmd.exe to parse.
  759. std::replace(applicationName.begin(), applicationName.end(), '/', '\\');
  760. output.emplace_back(applicationName);
  761. std::move(cmdLine.begin() + 1, cmdLine.end(),
  762. std::back_inserter(output));
  763. cmdLine = std::move(output);
  764. }
  765. }
  766. #else
  767. static_cast<void>(cmdLine);
  768. #endif
  769. }
  770. bool cmSystemTools::RunSingleCommand(std::vector<std::string> const& command,
  771. std::string* captureStdOut,
  772. std::string* captureStdErr, int* retVal,
  773. char const* dir, OutputOption outputflag,
  774. cmDuration timeout, Encoding encoding)
  775. {
  776. cmUVProcessChainBuilder builder;
  777. builder.SetExternalStream(cmUVProcessChainBuilder::Stream_INPUT, stdin)
  778. .AddCommand(command);
  779. if (dir) {
  780. builder.SetWorkingDirectory(dir);
  781. }
  782. if (outputflag == OUTPUT_PASSTHROUGH) {
  783. captureStdOut = nullptr;
  784. captureStdErr = nullptr;
  785. builder.SetExternalStream(cmUVProcessChainBuilder::Stream_OUTPUT, stdout)
  786. .SetExternalStream(cmUVProcessChainBuilder::Stream_ERROR, stderr);
  787. } else if (outputflag == OUTPUT_MERGE ||
  788. (captureStdErr && captureStdErr == captureStdOut)) {
  789. builder.SetMergedBuiltinStreams();
  790. captureStdErr = nullptr;
  791. } else {
  792. builder.SetBuiltinStream(cmUVProcessChainBuilder::Stream_OUTPUT)
  793. .SetBuiltinStream(cmUVProcessChainBuilder::Stream_ERROR);
  794. }
  795. assert(!captureStdErr || captureStdErr != captureStdOut);
  796. auto chain = builder.Start();
  797. bool timedOut = false;
  798. cm::uv_timer_ptr timer;
  799. if (timeout.count()) {
  800. timer.init(chain.GetLoop(), &timedOut);
  801. timer.start(
  802. [](uv_timer_t* t) {
  803. auto* timedOutPtr = static_cast<bool*>(t->data);
  804. *timedOutPtr = true;
  805. },
  806. static_cast<uint64_t>(timeout.count() * 1000.0), 0,
  807. cm::uv_update_time::yes);
  808. }
  809. std::vector<char> tempStdOut;
  810. std::vector<char> tempStdErr;
  811. cm::uv_pipe_ptr outStream;
  812. bool outFinished = true;
  813. cm::uv_pipe_ptr errStream;
  814. bool errFinished = true;
  815. cmProcessOutput processOutput(encoding);
  816. std::unique_ptr<cmUVStreamReadHandle> outputHandle;
  817. std::unique_ptr<cmUVStreamReadHandle> errorHandle;
  818. if (outputflag != OUTPUT_PASSTHROUGH &&
  819. (captureStdOut || captureStdErr || outputflag != OUTPUT_NONE)) {
  820. auto startRead =
  821. [&outputflag, &processOutput,
  822. &chain](cm::uv_pipe_ptr& pipe, int stream, std::string* captureStd,
  823. std::vector<char>& tempStd, int id,
  824. void (*outputFunc)(std::string const&),
  825. bool& finished) -> std::unique_ptr<cmUVStreamReadHandle> {
  826. if (stream < 0) {
  827. return nullptr;
  828. }
  829. pipe.init(chain.GetLoop(), 0);
  830. uv_pipe_open(pipe, stream);
  831. finished = false;
  832. return cmUVStreamRead(
  833. pipe,
  834. [outputflag, &processOutput, captureStd, &tempStd, id,
  835. outputFunc](std::vector<char> data) {
  836. // Translate NULL characters in the output into valid text.
  837. for (auto& c : data) {
  838. if (c == '\0') {
  839. c = ' ';
  840. }
  841. }
  842. if (outputflag != OUTPUT_NONE) {
  843. std::string strdata;
  844. processOutput.DecodeText(data.data(), data.size(), strdata, id);
  845. outputFunc(strdata);
  846. }
  847. if (captureStd) {
  848. cm::append(tempStd, data.data(), data.data() + data.size());
  849. }
  850. },
  851. [&finished, outputflag, &processOutput, id, outputFunc]() {
  852. finished = true;
  853. if (outputflag != OUTPUT_NONE) {
  854. std::string strdata;
  855. processOutput.DecodeText(std::string(), strdata, id);
  856. if (!strdata.empty()) {
  857. outputFunc(strdata);
  858. }
  859. }
  860. });
  861. };
  862. outputHandle =
  863. startRead(outStream, chain.OutputStream(), captureStdOut, tempStdOut, 1,
  864. cmSystemTools::Stdout, outFinished);
  865. if (chain.OutputStream() != chain.ErrorStream()) {
  866. errorHandle =
  867. startRead(errStream, chain.ErrorStream(), captureStdErr, tempStdErr, 2,
  868. cmSystemTools::Stderr, errFinished);
  869. }
  870. }
  871. while (!timedOut && !(chain.Finished() && outFinished && errFinished)) {
  872. uv_run(&chain.GetLoop(), UV_RUN_ONCE);
  873. }
  874. if (captureStdOut) {
  875. captureStdOut->assign(tempStdOut.begin(), tempStdOut.end());
  876. processOutput.DecodeText(*captureStdOut, *captureStdOut);
  877. }
  878. if (captureStdErr) {
  879. captureStdErr->assign(tempStdErr.begin(), tempStdErr.end());
  880. processOutput.DecodeText(*captureStdErr, *captureStdErr);
  881. }
  882. bool result = true;
  883. if (timedOut) {
  884. chain.Terminate();
  885. char const* error_str = "Process terminated due to timeout\n";
  886. if (outputflag != OUTPUT_NONE) {
  887. std::cerr << error_str << std::endl;
  888. }
  889. if (captureStdErr) {
  890. captureStdErr->append(error_str, strlen(error_str));
  891. }
  892. result = false;
  893. } else {
  894. auto const& status = chain.GetStatus(0);
  895. auto exception = status.GetException();
  896. switch (exception.first) {
  897. case cmUVProcessChain::ExceptionCode::None:
  898. if (retVal) {
  899. *retVal = static_cast<int>(status.ExitStatus);
  900. } else {
  901. if (status.ExitStatus != 0) {
  902. result = false;
  903. }
  904. }
  905. break;
  906. default: {
  907. if (outputflag != OUTPUT_NONE) {
  908. std::cerr << exception.second << std::endl;
  909. }
  910. if (captureStdErr) {
  911. captureStdErr->append(exception.second);
  912. } else if (captureStdOut) {
  913. captureStdOut->append(exception.second);
  914. }
  915. result = false;
  916. } break;
  917. }
  918. }
  919. return result;
  920. }
  921. bool cmSystemTools::RunSingleCommand(std::string const& command,
  922. std::string* captureStdOut,
  923. std::string* captureStdErr, int* retVal,
  924. char const* dir, OutputOption outputflag,
  925. cmDuration timeout)
  926. {
  927. if (s_DisableRunCommandOutput) {
  928. outputflag = OUTPUT_NONE;
  929. }
  930. std::vector<std::string> args = cmSystemTools::ParseArguments(command);
  931. if (args.empty()) {
  932. return false;
  933. }
  934. return cmSystemTools::RunSingleCommand(args, captureStdOut, captureStdErr,
  935. retVal, dir, outputflag, timeout);
  936. }
  937. std::string cmSystemTools::PrintSingleCommand(
  938. std::vector<std::string> const& command)
  939. {
  940. if (command.empty()) {
  941. return std::string();
  942. }
  943. return cmWrap('"', command, '"', " ");
  944. }
  945. bool cmSystemTools::DoesFileExistWithExtensions(
  946. std::string const& name, std::vector<std::string> const& headerExts)
  947. {
  948. std::string hname;
  949. for (std::string const& headerExt : headerExts) {
  950. hname = cmStrCat(name, '.', headerExt);
  951. if (cmSystemTools::FileExists(hname)) {
  952. return true;
  953. }
  954. }
  955. return false;
  956. }
  957. std::string cmSystemTools::FileExistsInParentDirectories(
  958. std::string const& fname, std::string const& directory,
  959. std::string const& toplevel)
  960. {
  961. std::string file = fname;
  962. cmSystemTools::ConvertToUnixSlashes(file);
  963. std::string dir = directory;
  964. cmSystemTools::ConvertToUnixSlashes(dir);
  965. std::string prevDir;
  966. while (dir != prevDir) {
  967. std::string path = cmStrCat(dir, '/', file);
  968. if (cmSystemTools::FileExists(path)) {
  969. return path;
  970. }
  971. if (dir.size() < toplevel.size()) {
  972. break;
  973. }
  974. prevDir = dir;
  975. dir = cmSystemTools::GetParentDirectory(dir);
  976. }
  977. return "";
  978. }
  979. #ifdef _WIN32
  980. namespace {
  981. /* Helper class to save and restore the specified file (or directory)
  982. attribute bits. Instantiate this class as an automatic variable on the
  983. stack. Its constructor saves a copy of the file attributes, and then its
  984. destructor restores the original attribute settings. */
  985. class SaveRestoreFileAttributes
  986. {
  987. public:
  988. SaveRestoreFileAttributes(std::wstring const& path,
  989. uint32_t file_attrs_to_set);
  990. ~SaveRestoreFileAttributes();
  991. SaveRestoreFileAttributes(SaveRestoreFileAttributes const&) = delete;
  992. SaveRestoreFileAttributes& operator=(SaveRestoreFileAttributes const&) =
  993. delete;
  994. void SetPath(std::wstring const& path) { path_ = path; }
  995. private:
  996. std::wstring path_;
  997. uint32_t original_attr_bits_;
  998. };
  999. SaveRestoreFileAttributes::SaveRestoreFileAttributes(
  1000. std::wstring const& path, uint32_t file_attrs_to_set)
  1001. : path_(path)
  1002. , original_attr_bits_(0)
  1003. {
  1004. // Set the specified attributes for the source file/directory.
  1005. original_attr_bits_ = GetFileAttributesW(path_.c_str());
  1006. if ((INVALID_FILE_ATTRIBUTES != original_attr_bits_) &&
  1007. ((file_attrs_to_set & original_attr_bits_) != file_attrs_to_set)) {
  1008. SetFileAttributesW(path_.c_str(), original_attr_bits_ | file_attrs_to_set);
  1009. }
  1010. }
  1011. // We set attribute bits. Now we need to restore their original state.
  1012. SaveRestoreFileAttributes::~SaveRestoreFileAttributes()
  1013. {
  1014. DWORD last_error = GetLastError();
  1015. // Verify or restore the original attributes.
  1016. const DWORD source_attr_bits = GetFileAttributesW(path_.c_str());
  1017. if (INVALID_FILE_ATTRIBUTES != source_attr_bits) {
  1018. if (original_attr_bits_ != source_attr_bits) {
  1019. // The file still exists, and its attributes aren't our saved values.
  1020. // Time to restore them.
  1021. SetFileAttributesW(path_.c_str(), original_attr_bits_);
  1022. }
  1023. }
  1024. SetLastError(last_error);
  1025. }
  1026. struct WindowsFileRetryInit
  1027. {
  1028. cmSystemTools::WindowsFileRetry Retry;
  1029. bool Explicit;
  1030. };
  1031. WindowsFileRetryInit InitWindowsFileRetry(wchar_t const* const values[2],
  1032. unsigned int const defaults[2])
  1033. {
  1034. unsigned int data[2] = { 0, 0 };
  1035. HKEY const keys[2] = { HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE };
  1036. for (int k = 0; k < 2; ++k) {
  1037. HKEY hKey;
  1038. if (RegOpenKeyExW(keys[k], L"Software\\Kitware\\CMake\\Config", 0,
  1039. KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS) {
  1040. for (int v = 0; v < 2; ++v) {
  1041. DWORD dwData, dwType, dwSize = 4;
  1042. if (!data[v] &&
  1043. RegQueryValueExW(hKey, values[v], 0, &dwType, (BYTE*)&dwData,
  1044. &dwSize) == ERROR_SUCCESS &&
  1045. dwType == REG_DWORD && dwSize == 4) {
  1046. data[v] = static_cast<unsigned int>(dwData);
  1047. }
  1048. }
  1049. RegCloseKey(hKey);
  1050. }
  1051. }
  1052. WindowsFileRetryInit init;
  1053. init.Explicit = data[0] || data[1];
  1054. init.Retry.Count = data[0] ? data[0] : defaults[0];
  1055. init.Retry.Delay = data[1] ? data[1] : defaults[1];
  1056. return init;
  1057. }
  1058. WindowsFileRetryInit InitWindowsFileRetry()
  1059. {
  1060. static wchar_t const* const values[2] = { L"FilesystemRetryCount",
  1061. L"FilesystemRetryDelay" };
  1062. static unsigned int const defaults[2] = { 5, 500 };
  1063. return InitWindowsFileRetry(values, defaults);
  1064. }
  1065. WindowsFileRetryInit InitWindowsDirectoryRetry()
  1066. {
  1067. static wchar_t const* const values[2] = { L"FilesystemDirectoryRetryCount",
  1068. L"FilesystemDirectoryRetryDelay" };
  1069. static unsigned int const defaults[2] = { 120, 500 };
  1070. WindowsFileRetryInit dirInit = InitWindowsFileRetry(values, defaults);
  1071. if (dirInit.Explicit) {
  1072. return dirInit;
  1073. }
  1074. WindowsFileRetryInit fileInit = InitWindowsFileRetry();
  1075. if (fileInit.Explicit) {
  1076. return fileInit;
  1077. }
  1078. return dirInit;
  1079. }
  1080. cmSystemTools::WindowsFileRetry GetWindowsRetry(std::wstring const& path)
  1081. {
  1082. // If we are performing a directory operation, then try and get the
  1083. // appropriate timing info.
  1084. DWORD const attrs = GetFileAttributesW(path.c_str());
  1085. if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY)) {
  1086. return cmSystemTools::GetWindowsDirectoryRetry();
  1087. }
  1088. return cmSystemTools::GetWindowsFileRetry();
  1089. }
  1090. } // end of anonymous namespace
  1091. cmSystemTools::WindowsFileRetry cmSystemTools::GetWindowsFileRetry()
  1092. {
  1093. static WindowsFileRetry retry = InitWindowsFileRetry().Retry;
  1094. return retry;
  1095. }
  1096. cmSystemTools::WindowsFileRetry cmSystemTools::GetWindowsDirectoryRetry()
  1097. {
  1098. static cmSystemTools::WindowsFileRetry retry =
  1099. InitWindowsDirectoryRetry().Retry;
  1100. return retry;
  1101. }
  1102. cmSystemTools::WindowsVersion cmSystemTools::GetWindowsVersion()
  1103. {
  1104. /* Windows version number data. */
  1105. OSVERSIONINFOEXW osviex;
  1106. ZeroMemory(&osviex, sizeof(osviex));
  1107. osviex.dwOSVersionInfoSize = sizeof(osviex);
  1108. # ifdef CM_WINDOWS_DEPRECATED_GetVersionEx
  1109. # pragma warning(push)
  1110. # ifdef __INTEL_COMPILER
  1111. # pragma warning(disable : 1478)
  1112. # elif defined __clang__
  1113. # pragma clang diagnostic push
  1114. # pragma clang diagnostic ignored "-Wdeprecated-declarations"
  1115. # else
  1116. # pragma warning(disable : 4996)
  1117. # endif
  1118. # endif
  1119. GetVersionExW((OSVERSIONINFOW*)&osviex);
  1120. # ifdef CM_WINDOWS_DEPRECATED_GetVersionEx
  1121. # ifdef __clang__
  1122. # pragma clang diagnostic pop
  1123. # else
  1124. # pragma warning(pop)
  1125. # endif
  1126. # endif
  1127. WindowsVersion result;
  1128. result.dwMajorVersion = osviex.dwMajorVersion;
  1129. result.dwMinorVersion = osviex.dwMinorVersion;
  1130. result.dwBuildNumber = osviex.dwBuildNumber;
  1131. return result;
  1132. }
  1133. std::string cmSystemTools::GetComspec()
  1134. {
  1135. std::string comspec;
  1136. if (!cmSystemTools::GetEnv("COMSPEC", comspec) ||
  1137. !cmSystemTools::FileIsFullPath(comspec)) {
  1138. comspec = "cmd.exe";
  1139. }
  1140. return comspec;
  1141. }
  1142. #endif
  1143. // File changes involve removing SETUID/SETGID bits when a file is modified.
  1144. // This behavior is consistent across most Unix-like operating systems.
  1145. class FileModeGuard
  1146. {
  1147. public:
  1148. FileModeGuard(std::string const& file_path, std::string* emsg);
  1149. bool Restore(std::string* emsg);
  1150. bool HasErrors() const;
  1151. private:
  1152. #ifndef _WIN32
  1153. mode_t mode_;
  1154. #endif
  1155. std::string filepath_;
  1156. };
  1157. FileModeGuard::FileModeGuard(std::string const& file_path, std::string* emsg)
  1158. {
  1159. #ifndef _WIN32
  1160. struct stat file_stat;
  1161. if (stat(file_path.c_str(), &file_stat) != 0) {
  1162. if (emsg) {
  1163. *emsg = cmStrCat("Cannot get file stat: ", strerror(errno));
  1164. }
  1165. return;
  1166. }
  1167. mode_ = file_stat.st_mode;
  1168. #else
  1169. static_cast<void>(emsg);
  1170. #endif
  1171. filepath_ = file_path;
  1172. }
  1173. bool FileModeGuard::Restore(std::string* emsg)
  1174. {
  1175. assert(filepath_.empty() == false);
  1176. #ifndef _WIN32
  1177. struct stat file_stat;
  1178. if (stat(filepath_.c_str(), &file_stat) != 0) {
  1179. if (emsg) {
  1180. *emsg = cmStrCat("Cannot get file stat: ", strerror(errno));
  1181. }
  1182. return false;
  1183. }
  1184. // Nothing changed; everything is in the expected state
  1185. if (file_stat.st_mode == mode_) {
  1186. return true;
  1187. }
  1188. if (chmod(filepath_.c_str(), mode_) != 0) {
  1189. if (emsg) {
  1190. *emsg = cmStrCat("Cannot restore the file mode: ", strerror(errno));
  1191. }
  1192. return false;
  1193. }
  1194. #else
  1195. static_cast<void>(emsg);
  1196. #endif
  1197. return true;
  1198. }
  1199. bool FileModeGuard::HasErrors() const
  1200. {
  1201. return filepath_.empty();
  1202. }
  1203. std::string cmSystemTools::GetRealPathResolvingWindowsSubst(
  1204. std::string const& path, std::string* errorMessage)
  1205. {
  1206. #ifdef _WIN32
  1207. // uv_fs_realpath uses Windows Vista API so fallback to kwsys if not found
  1208. std::string resolved_path;
  1209. uv_fs_t req;
  1210. int err = uv_fs_realpath(nullptr, &req, path.c_str(), nullptr);
  1211. if (!err) {
  1212. resolved_path = std::string((char*)req.ptr);
  1213. cmSystemTools::ConvertToUnixSlashes(resolved_path);
  1214. } else if (err == UV_ENOSYS) {
  1215. resolved_path = cmsys::SystemTools::GetRealPath(path, errorMessage);
  1216. } else if (errorMessage) {
  1217. cmsys::Status status =
  1218. cmsys::Status::Windows(uv_fs_get_system_error(&req));
  1219. *errorMessage = status.GetString();
  1220. resolved_path.clear();
  1221. } else {
  1222. resolved_path = path;
  1223. }
  1224. // Normalize to upper-case drive letter as cm::PathResolver does.
  1225. if (resolved_path.size() > 1 && resolved_path[1] == ':') {
  1226. resolved_path[0] = toupper(resolved_path[0]);
  1227. }
  1228. return resolved_path;
  1229. #else
  1230. return cmsys::SystemTools::GetRealPath(path, errorMessage);
  1231. #endif
  1232. }
  1233. std::string cmSystemTools::GetRealPath(std::string const& path,
  1234. std::string* errorMessage)
  1235. {
  1236. #ifdef _WIN32
  1237. std::string resolved_path =
  1238. cmSystemTools::GetRealPathResolvingWindowsSubst(path, errorMessage);
  1239. // If the original path used a subst drive and the real path starts
  1240. // with the substitution, restore the subst drive prefix. This may
  1241. // incorrectly restore a subst drive if the underlying drive was
  1242. // encountered via an absolute symlink, but this is an acceptable
  1243. // limitation to otherwise preserve susbt drives.
  1244. if (resolved_path.size() >= 2 && resolved_path[1] == ':' &&
  1245. path.size() >= 2 && path[1] == ':' &&
  1246. toupper(resolved_path[0]) != toupper(path[0])) {
  1247. // FIXME: Add thread_local or mutex if we use threads.
  1248. static std::map<char, std::string> substMap;
  1249. char const drive = static_cast<char>(toupper(path[0]));
  1250. std::string maybe_subst = cmStrCat(drive, ":/");
  1251. auto smi = substMap.find(drive);
  1252. if (smi == substMap.end()) {
  1253. smi = substMap
  1254. .emplace(
  1255. drive,
  1256. cmSystemTools::GetRealPathResolvingWindowsSubst(maybe_subst))
  1257. .first;
  1258. }
  1259. std::string const& resolved_subst = smi->second;
  1260. std::string::size_type const ns = resolved_subst.size();
  1261. if (ns > 0) {
  1262. std::string::size_type const np = resolved_path.size();
  1263. if (ns == np && resolved_path == resolved_subst) {
  1264. resolved_path = maybe_subst;
  1265. } else if (ns > 0 && ns < np && resolved_path[ns] == '/' &&
  1266. resolved_path.compare(0, ns, resolved_subst) == 0) {
  1267. resolved_path.replace(0, ns + 1, maybe_subst);
  1268. }
  1269. }
  1270. }
  1271. return resolved_path;
  1272. #else
  1273. return cmsys::SystemTools::GetRealPath(path, errorMessage);
  1274. #endif
  1275. }
  1276. void cmSystemTools::InitializeLibUV()
  1277. {
  1278. #if defined(_WIN32)
  1279. // Perform libuv one-time initialization now, and then un-do its
  1280. // global _fmode setting so that using libuv does not change the
  1281. // default file text/binary mode. See libuv issue 840.
  1282. if (uv_loop_t* loop = uv_default_loop()) {
  1283. uv_loop_close(loop);
  1284. }
  1285. # ifdef _MSC_VER
  1286. _set_fmode(_O_TEXT);
  1287. # else
  1288. _fmode = _O_TEXT;
  1289. # endif
  1290. // Replace libuv's report handler with our own to suppress popups.
  1291. cmSystemTools::EnableMSVCDebugHook();
  1292. #endif
  1293. }
  1294. #if defined(_WIN32)
  1295. # include <random>
  1296. # include <wctype.h>
  1297. # ifdef _MSC_VER
  1298. using mode_t = cmSystemTools::SystemTools::mode_t;
  1299. # endif
  1300. #else
  1301. # include <sys/stat.h>
  1302. #endif
  1303. inline int Mkdir(char const* dir, mode_t const* mode)
  1304. {
  1305. #if defined(_WIN32)
  1306. int ret = _wmkdir(cmSystemTools::ConvertToWindowsExtendedPath(dir).c_str());
  1307. if (ret == 0 && mode)
  1308. cmSystemTools::SystemTools::SetPermissions(dir, *mode);
  1309. return ret;
  1310. #else
  1311. return mkdir(dir, mode ? *mode : 0777);
  1312. #endif
  1313. }
  1314. #ifdef CMAKE_NO_MKDTEMP
  1315. namespace {
  1316. char* cm_mkdtemp_fallback(char* template_)
  1317. {
  1318. if (mktemp(template_) == nullptr || mkdir(template_, 0700) != 0) {
  1319. return nullptr;
  1320. }
  1321. return template_;
  1322. }
  1323. using cm_mkdtemp_t = char* (*)(char*);
  1324. cm_mkdtemp_t const cm_mkdtemp = []() -> cm_mkdtemp_t {
  1325. cm_mkdtemp_t f = (cm_mkdtemp_t)dlsym(RTLD_DEFAULT, "mkdtemp");
  1326. dlerror(); // Ignore/cleanup dlsym errors.
  1327. if (!f) {
  1328. f = cm_mkdtemp_fallback;
  1329. }
  1330. return f;
  1331. }();
  1332. }
  1333. #else
  1334. # define cm_mkdtemp mkdtemp
  1335. #endif
  1336. cmsys::Status cmSystemTools::MakeTempDirectory(std::string& path,
  1337. mode_t const* mode)
  1338. {
  1339. if (path.empty()) {
  1340. return cmsys::Status::POSIX(EINVAL);
  1341. }
  1342. return cmSystemTools::MakeTempDirectory(&path.front(), mode);
  1343. }
  1344. cmsys::Status cmSystemTools::MakeTempDirectory(char* path, mode_t const* mode)
  1345. {
  1346. if (!path) {
  1347. return cmsys::Status::POSIX(EINVAL);
  1348. }
  1349. // verify that path ends with "XXXXXX"
  1350. auto const l = std::strlen(path);
  1351. if (!cmHasLiteralSuffix(cm::string_view{ path, l }, "XXXXXX")) {
  1352. return cmsys::Status::POSIX(EINVAL);
  1353. }
  1354. // create parent directories
  1355. auto* sep = path;
  1356. while ((sep = strchr(sep, '/'))) {
  1357. // all underlying functions use C strings,
  1358. // so temporarily end the string here
  1359. *sep = '\0';
  1360. Mkdir(path, mode);
  1361. *sep = '/';
  1362. ++sep;
  1363. }
  1364. #ifdef _WIN32
  1365. int const nchars = 36;
  1366. char const chars[nchars + 1] = "abcdefghijklmnopqrstuvwxyz0123456789";
  1367. std::random_device rd;
  1368. std::mt19937 rg{ rd() };
  1369. std::uniform_int_distribution<int> dist{ 0, nchars - 1 };
  1370. for (auto tries = 100; tries; --tries) {
  1371. for (auto n = l - 6; n < l; ++n) {
  1372. path[n] = chars[dist(rg)];
  1373. }
  1374. if (Mkdir(path, mode) == 0) {
  1375. return cmsys::Status::Success();
  1376. } else if (errno != EEXIST) {
  1377. return cmsys::Status::POSIX_errno();
  1378. }
  1379. }
  1380. return cmsys::Status::POSIX(EAGAIN);
  1381. #else
  1382. if (cm_mkdtemp(path)) {
  1383. if (mode) {
  1384. chmod(path, *mode);
  1385. }
  1386. } else {
  1387. return cmsys::Status::POSIX_errno();
  1388. }
  1389. return cmsys::Status::Success();
  1390. #endif
  1391. }
  1392. #ifdef _WIN32
  1393. namespace {
  1394. bool cmMoveFile(std::wstring const& oldname, std::wstring const& newname,
  1395. cmSystemTools::Replace replace)
  1396. {
  1397. // Not only ignore any previous error, but clear any memory of it.
  1398. SetLastError(0);
  1399. DWORD flags = 0;
  1400. if (replace == cmSystemTools::Replace::Yes) {
  1401. // Use MOVEFILE_REPLACE_EXISTING to replace an existing destination file.
  1402. flags = flags | MOVEFILE_REPLACE_EXISTING;
  1403. }
  1404. return MoveFileExW(oldname.c_str(), newname.c_str(), flags);
  1405. }
  1406. }
  1407. #endif
  1408. cmSystemTools::CopyResult cmSystemTools::CopySingleFile(
  1409. std::string const& oldname, std::string const& newname, CopyWhen when,
  1410. CopyInputRecent inputRecent, std::string* err)
  1411. {
  1412. switch (when) {
  1413. case CopyWhen::Always:
  1414. break;
  1415. case CopyWhen::OnlyIfDifferent:
  1416. if (!FilesDiffer(oldname, newname)) {
  1417. return CopyResult::Success;
  1418. }
  1419. break;
  1420. case CopyWhen::OnlyIfNewer: {
  1421. if (!SystemTools::FileExists(newname)) {
  1422. break;
  1423. }
  1424. int timeResult = 0;
  1425. cmsys::Status timeStatus =
  1426. cmsys::SystemTools::FileTimeCompare(oldname, newname, &timeResult);
  1427. if (timeStatus.IsSuccess() && timeResult <= 0) {
  1428. return CopyResult::Success;
  1429. }
  1430. break;
  1431. }
  1432. }
  1433. mode_t perm = 0;
  1434. cmsys::Status perms = SystemTools::GetPermissions(oldname, perm);
  1435. // If files are the same do not copy
  1436. if (SystemTools::SameFile(oldname, newname)) {
  1437. return CopyResult::Success;
  1438. }
  1439. cmsys::SystemTools::CopyStatus status;
  1440. status = cmsys::SystemTools::CloneFileContent(oldname, newname);
  1441. if (!status) {
  1442. // if cloning did not succeed, fall back to blockwise copy
  1443. #ifdef _WIN32
  1444. if (inputRecent == CopyInputRecent::Yes) {
  1445. // Windows sometimes locks a file immediately after creation.
  1446. // Retry a few times.
  1447. WindowsFileRetry retry = cmSystemTools::GetWindowsFileRetry();
  1448. while ((status =
  1449. cmsys::SystemTools::CopyFileContentBlockwise(oldname, newname),
  1450. status.Path == cmsys::SystemTools::CopyStatus::SourcePath &&
  1451. status.GetPOSIX() == EACCES && --retry.Count)) {
  1452. cmSystemTools::Delay(retry.Delay);
  1453. }
  1454. } else {
  1455. status = cmsys::SystemTools::CopyFileContentBlockwise(oldname, newname);
  1456. }
  1457. #else
  1458. static_cast<void>(inputRecent);
  1459. status = cmsys::SystemTools::CopyFileContentBlockwise(oldname, newname);
  1460. #endif
  1461. }
  1462. if (!status) {
  1463. if (err) {
  1464. *err = status.GetString();
  1465. switch (status.Path) {
  1466. case cmsys::SystemTools::CopyStatus::SourcePath:
  1467. *err = cmStrCat(*err, " (input)");
  1468. break;
  1469. case cmsys::SystemTools::CopyStatus::DestPath:
  1470. *err = cmStrCat(*err, " (output)");
  1471. break;
  1472. default:
  1473. break;
  1474. }
  1475. }
  1476. return CopyResult::Failure;
  1477. }
  1478. if (perms) {
  1479. perms = SystemTools::SetPermissions(newname, perm);
  1480. if (!perms) {
  1481. if (err) {
  1482. *err = cmStrCat(perms.GetString(), " (output)");
  1483. }
  1484. return CopyResult::Failure;
  1485. }
  1486. }
  1487. return CopyResult::Success;
  1488. }
  1489. bool cmSystemTools::RenameFile(std::string const& oldname,
  1490. std::string const& newname)
  1491. {
  1492. return cmSystemTools::RenameFile(oldname, newname, Replace::Yes) ==
  1493. RenameResult::Success;
  1494. }
  1495. cmSystemTools::RenameResult cmSystemTools::RenameFile(
  1496. std::string const& oldname, std::string const& newname, Replace replace,
  1497. std::string* err)
  1498. {
  1499. #ifdef _WIN32
  1500. # ifndef INVALID_FILE_ATTRIBUTES
  1501. # define INVALID_FILE_ATTRIBUTES ((DWORD) - 1)
  1502. # endif
  1503. std::wstring const oldname_wstr =
  1504. SystemTools::ConvertToWindowsExtendedPath(oldname);
  1505. std::wstring const newname_wstr =
  1506. SystemTools::ConvertToWindowsExtendedPath(newname);
  1507. /* Windows MoveFileEx may not replace read-only or in-use files. If it
  1508. fails then remove the read-only attribute from any existing destination.
  1509. Try multiple times since we may be racing against another process
  1510. creating/opening the destination file just before our MoveFileEx. */
  1511. WindowsFileRetry retry = GetWindowsRetry(oldname_wstr);
  1512. // Use RAII to set the attribute bit blocking Microsoft Search Indexing,
  1513. // and restore the previous value upon return.
  1514. SaveRestoreFileAttributes save_restore_file_attributes(
  1515. oldname_wstr, FILE_ATTRIBUTE_NOT_CONTENT_INDEXED);
  1516. DWORD move_last_error = 0;
  1517. while (!cmMoveFile(oldname_wstr, newname_wstr, replace) && --retry.Count) {
  1518. move_last_error = GetLastError();
  1519. // There was no error ==> the operation is not yet complete.
  1520. if (move_last_error == NO_ERROR) {
  1521. break;
  1522. }
  1523. // Try again only if failure was due to access/sharing permissions.
  1524. // Most often ERROR_ACCESS_DENIED (a.k.a. I/O error) for a directory, and
  1525. // ERROR_SHARING_VIOLATION for a file, are caused by one of the following:
  1526. // 1) Anti-Virus Software
  1527. // 2) Windows Search Indexer
  1528. // 3) Windows Explorer has an associated directory already opened.
  1529. if (move_last_error != ERROR_ACCESS_DENIED &&
  1530. move_last_error != ERROR_SHARING_VIOLATION) {
  1531. if (replace == Replace::No && move_last_error == ERROR_ALREADY_EXISTS) {
  1532. return RenameResult::NoReplace;
  1533. }
  1534. if (err) {
  1535. *err = cmsys::Status::Windows(move_last_error).GetString();
  1536. }
  1537. return RenameResult::Failure;
  1538. }
  1539. DWORD const attrs = GetFileAttributesW(newname_wstr.c_str());
  1540. if ((attrs != INVALID_FILE_ATTRIBUTES) &&
  1541. (attrs & FILE_ATTRIBUTE_READONLY) &&
  1542. // FILE_ATTRIBUTE_READONLY is not honored on directories.
  1543. !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {
  1544. // Remove the read-only attribute from the destination file.
  1545. SetFileAttributesW(newname_wstr.c_str(),
  1546. attrs & ~FILE_ATTRIBUTE_READONLY);
  1547. } else {
  1548. // The file may be temporarily in use so wait a bit.
  1549. cmSystemTools::Delay(retry.Delay);
  1550. }
  1551. }
  1552. // If we were successful, then there was no error.
  1553. if (retry.Count > 0) {
  1554. move_last_error = 0;
  1555. // Restore the attributes on the new name.
  1556. save_restore_file_attributes.SetPath(newname_wstr);
  1557. }
  1558. SetLastError(move_last_error);
  1559. if (retry.Count > 0) {
  1560. return RenameResult::Success;
  1561. }
  1562. if (replace == Replace::No && GetLastError() == ERROR_ALREADY_EXISTS) {
  1563. return RenameResult::NoReplace;
  1564. }
  1565. if (err) {
  1566. *err = cmsys::Status::Windows_GetLastError().GetString();
  1567. }
  1568. return RenameResult::Failure;
  1569. #else
  1570. // On UNIX we have OS-provided calls to create 'newname' atomically.
  1571. if (replace == Replace::No) {
  1572. if (link(oldname.c_str(), newname.c_str()) == 0) {
  1573. return RenameResult::Success;
  1574. }
  1575. if (errno == EEXIST) {
  1576. return RenameResult::NoReplace;
  1577. }
  1578. if (err) {
  1579. *err = cmsys::Status::POSIX_errno().GetString();
  1580. }
  1581. return RenameResult::Failure;
  1582. }
  1583. if (rename(oldname.c_str(), newname.c_str()) == 0) {
  1584. return RenameResult::Success;
  1585. }
  1586. if (err) {
  1587. *err = cmsys::Status::POSIX_errno().GetString();
  1588. }
  1589. return RenameResult::Failure;
  1590. #endif
  1591. }
  1592. cmsys::Status cmSystemTools::MoveFileIfDifferent(
  1593. std::string const& source, std::string const& destination)
  1594. {
  1595. cmsys::Status res = {};
  1596. if (FilesDiffer(source, destination)) {
  1597. if (RenameFile(source, destination)) {
  1598. return res;
  1599. }
  1600. res = CopyFileAlways(source, destination);
  1601. }
  1602. RemoveFile(source);
  1603. return res;
  1604. }
  1605. void cmSystemTools::Glob(std::string const& directory,
  1606. std::string const& regexp,
  1607. std::vector<std::string>& files)
  1608. {
  1609. cmsys::Directory d;
  1610. cmsys::RegularExpression reg(regexp.c_str());
  1611. if (d.Load(directory)) {
  1612. size_t numf;
  1613. unsigned int i;
  1614. numf = d.GetNumberOfFiles();
  1615. for (i = 0; i < numf; i++) {
  1616. std::string fname = d.GetFile(i);
  1617. if (reg.find(fname)) {
  1618. files.push_back(std::move(fname));
  1619. }
  1620. }
  1621. }
  1622. }
  1623. void cmSystemTools::GlobDirs(std::string const& path,
  1624. std::vector<std::string>& files)
  1625. {
  1626. std::string::size_type pos = path.find("/*");
  1627. if (pos == std::string::npos) {
  1628. files.push_back(path);
  1629. return;
  1630. }
  1631. std::string startPath = path.substr(0, pos);
  1632. std::string finishPath = path.substr(pos + 2);
  1633. cmsys::Directory d;
  1634. if (d.Load(startPath)) {
  1635. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i) {
  1636. if ((std::string(d.GetFile(i)) != ".") &&
  1637. (std::string(d.GetFile(i)) != "..")) {
  1638. std::string fname = cmStrCat(startPath, '/', d.GetFile(i));
  1639. if (cmSystemTools::FileIsDirectory(fname)) {
  1640. fname += finishPath;
  1641. cmSystemTools::GlobDirs(fname, files);
  1642. }
  1643. }
  1644. }
  1645. }
  1646. }
  1647. bool cmSystemTools::SimpleGlob(std::string const& glob,
  1648. std::vector<std::string>& files,
  1649. int type /* = 0 */)
  1650. {
  1651. files.clear();
  1652. if (glob.back() != '*') {
  1653. return false;
  1654. }
  1655. std::string path = cmSystemTools::GetFilenamePath(glob);
  1656. std::string ppath = cmSystemTools::GetFilenameName(glob);
  1657. ppath = ppath.substr(0, ppath.size() - 1);
  1658. if (path.empty()) {
  1659. path = "/";
  1660. }
  1661. bool res = false;
  1662. cmsys::Directory d;
  1663. if (d.Load(path)) {
  1664. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i) {
  1665. if ((std::string(d.GetFile(i)) != ".") &&
  1666. (std::string(d.GetFile(i)) != "..")) {
  1667. std::string fname = path;
  1668. if (path.back() != '/') {
  1669. fname += "/";
  1670. }
  1671. fname += d.GetFile(i);
  1672. std::string sfname = d.GetFile(i);
  1673. if (type > 0 && cmSystemTools::FileIsDirectory(fname)) {
  1674. continue;
  1675. }
  1676. if (type < 0 && !cmSystemTools::FileIsDirectory(fname)) {
  1677. continue;
  1678. }
  1679. if (cmHasPrefix(sfname, ppath)) {
  1680. files.push_back(fname);
  1681. res = true;
  1682. }
  1683. }
  1684. }
  1685. }
  1686. return res;
  1687. }
  1688. std::string cmSystemTools::ConvertToOutputPath(std::string const& path)
  1689. {
  1690. #if defined(_WIN32) && !defined(__CYGWIN__)
  1691. if (s_ForceUnixPaths) {
  1692. return cmSystemTools::ConvertToUnixOutputPath(path);
  1693. }
  1694. return cmSystemTools::ConvertToWindowsOutputPath(path);
  1695. #else
  1696. return cmSystemTools::ConvertToUnixOutputPath(path);
  1697. #endif
  1698. }
  1699. void cmSystemTools::ConvertToOutputSlashes(std::string& path)
  1700. {
  1701. #if defined(_WIN32) && !defined(__CYGWIN__)
  1702. if (!s_ForceUnixPaths) {
  1703. // Convert to windows slashes.
  1704. std::string::size_type pos = 0;
  1705. while ((pos = path.find('/', pos)) != std::string::npos) {
  1706. path[pos++] = '\\';
  1707. }
  1708. }
  1709. #else
  1710. static_cast<void>(path);
  1711. #endif
  1712. }
  1713. void cmSystemTools::ConvertToLongPath(std::string& path)
  1714. {
  1715. #if defined(_WIN32) && !defined(__CYGWIN__)
  1716. // Try to convert path to a long path only if the path contains character '~'
  1717. if (path.find('~') == std::string::npos) {
  1718. return;
  1719. }
  1720. std::wstring wPath = cmsys::Encoding::ToWide(path);
  1721. DWORD ret = GetLongPathNameW(wPath.c_str(), nullptr, 0);
  1722. std::vector<wchar_t> buffer(ret);
  1723. if (ret != 0) {
  1724. ret = GetLongPathNameW(wPath.c_str(), buffer.data(),
  1725. static_cast<DWORD>(buffer.size()));
  1726. }
  1727. if (ret != 0) {
  1728. path = cmsys::Encoding::ToNarrow(buffer.data());
  1729. }
  1730. #else
  1731. static_cast<void>(path);
  1732. #endif
  1733. }
  1734. std::string cmSystemTools::ConvertToRunCommandPath(std::string const& path)
  1735. {
  1736. #if defined(_WIN32) && !defined(__CYGWIN__)
  1737. return cmSystemTools::ConvertToWindowsOutputPath(path);
  1738. #else
  1739. return cmSystemTools::ConvertToUnixOutputPath(path);
  1740. #endif
  1741. }
  1742. // compute the relative path from here to there
  1743. std::string cmSystemTools::RelativePath(std::string const& local,
  1744. std::string const& remote)
  1745. {
  1746. if (!cmSystemTools::FileIsFullPath(local)) {
  1747. cmSystemTools::Error("RelativePath must be passed a full path to local: " +
  1748. local);
  1749. }
  1750. if (!cmSystemTools::FileIsFullPath(remote)) {
  1751. cmSystemTools::Error(
  1752. "RelativePath must be passed a full path to remote: " + remote);
  1753. }
  1754. return cmsys::SystemTools::RelativePath(local, remote);
  1755. }
  1756. std::string cmSystemTools::ForceToRelativePath(std::string const& local_path,
  1757. std::string const& remote_path)
  1758. {
  1759. // The paths should never be quoted.
  1760. assert(local_path.front() != '\"');
  1761. assert(remote_path.front() != '\"');
  1762. // The local path should never have a trailing slash except if it is just the
  1763. // bare root directory
  1764. assert(local_path.empty() || local_path.back() != '/' ||
  1765. local_path.size() == 1 ||
  1766. (local_path.size() == 3 && local_path[1] == ':' &&
  1767. ((local_path[0] >= 'A' && local_path[0] <= 'Z') ||
  1768. (local_path[0] >= 'a' && local_path[0] <= 'z'))));
  1769. // If the path is already relative then just return the path.
  1770. if (!cmSystemTools::FileIsFullPath(remote_path)) {
  1771. return remote_path;
  1772. }
  1773. // Identify the longest shared path component between the remote
  1774. // path and the local path.
  1775. std::vector<std::string> local;
  1776. cmSystemTools::SplitPath(local_path, local);
  1777. std::vector<std::string> remote;
  1778. cmSystemTools::SplitPath(remote_path, remote);
  1779. unsigned int common = 0;
  1780. while (common < remote.size() && common < local.size() &&
  1781. cmSystemTools::ComparePath(remote[common], local[common])) {
  1782. ++common;
  1783. }
  1784. // If no part of the path is in common then return the full path.
  1785. if (common == 0) {
  1786. return remote_path;
  1787. }
  1788. // If the entire path is in common then just return a ".".
  1789. if (common == remote.size() && common == local.size()) {
  1790. return ".";
  1791. }
  1792. // If the entire path is in common except for a trailing slash then
  1793. // just return a "./".
  1794. if (common + 1 == remote.size() && remote[common].empty() &&
  1795. common == local.size()) {
  1796. return "./";
  1797. }
  1798. // Construct the relative path.
  1799. std::string relative;
  1800. // First add enough ../ to get up to the level of the shared portion
  1801. // of the path. Leave off the trailing slash. Note that the last
  1802. // component of local will never be empty because local should never
  1803. // have a trailing slash.
  1804. for (unsigned int i = common; i < local.size(); ++i) {
  1805. relative += "..";
  1806. if (i < local.size() - 1) {
  1807. relative += "/";
  1808. }
  1809. }
  1810. // Now add the portion of the destination path that is not included
  1811. // in the shared portion of the path. Add a slash the first time
  1812. // only if there was already something in the path. If there was a
  1813. // trailing slash in the input then the last iteration of the loop
  1814. // will add a slash followed by an empty string which will preserve
  1815. // the trailing slash in the output.
  1816. if (!relative.empty() && !remote.empty()) {
  1817. relative += "/";
  1818. }
  1819. relative += cmJoin(cmMakeRange(remote).advance(common), "/");
  1820. // Finally return the path.
  1821. return relative;
  1822. }
  1823. std::string cmSystemTools::RelativeIfUnder(std::string const& top,
  1824. std::string const& in)
  1825. {
  1826. std::string out;
  1827. if (in == top) {
  1828. out = ".";
  1829. } else if (cmSystemTools::IsSubDirectory(in, top)) {
  1830. out = in.substr(top.size() + (top.back() == '/' ? 0 : 1));
  1831. } else {
  1832. out = in;
  1833. }
  1834. return out;
  1835. }
  1836. cm::optional<std::string> cmSystemTools::GetEnvVar(std::string const& var)
  1837. {
  1838. cm::optional<std::string> result;
  1839. {
  1840. std::string value;
  1841. if (cmSystemTools::GetEnv(var, value)) {
  1842. result = std::move(value);
  1843. }
  1844. }
  1845. return result;
  1846. }
  1847. std::vector<std::string> cmSystemTools::GetEnvPathNormalized(
  1848. std::string const& var)
  1849. {
  1850. std::vector<std::string> result;
  1851. if (cm::optional<std::string> env = cmSystemTools::GetEnvVar(var)) {
  1852. std::vector<std::string> p = cmSystemTools::SplitEnvPathNormalized(*env);
  1853. std::move(p.begin(), p.end(), std::back_inserter(result));
  1854. }
  1855. return result;
  1856. }
  1857. std::vector<std::string> cmSystemTools::SplitEnvPath(cm::string_view in)
  1858. {
  1859. #if defined(_WIN32) && !defined(__CYGWIN__)
  1860. static cm::string_view sep = ";"_s;
  1861. #else
  1862. static cm::string_view sep = ":"_s;
  1863. #endif
  1864. std::vector<std::string> paths;
  1865. cm::string_view::size_type e = 0;
  1866. for (;;) {
  1867. cm::string_view::size_type b = in.find_first_not_of(sep, e);
  1868. if (b == cm::string_view::npos) {
  1869. break;
  1870. }
  1871. e = in.find_first_of(sep, b);
  1872. if (e == cm::string_view::npos) {
  1873. paths.emplace_back(in.substr(b));
  1874. break;
  1875. }
  1876. paths.emplace_back(in.substr(b, e - b));
  1877. }
  1878. return paths;
  1879. }
  1880. std::vector<std::string> cmSystemTools::SplitEnvPathNormalized(
  1881. cm::string_view in)
  1882. {
  1883. std::vector<std::string> paths = cmSystemTools::SplitEnvPath(in);
  1884. std::transform(paths.begin(), paths.end(), paths.begin(),
  1885. cmSystemTools::ToNormalizedPathOnDisk);
  1886. return paths;
  1887. }
  1888. std::string cmSystemTools::ToNormalizedPathOnDisk(std::string p)
  1889. {
  1890. p = ResolveTildePath(p);
  1891. using namespace cm::PathResolver;
  1892. #ifdef _WIN32
  1893. // IWYU pragma: no_forward_declare cm::PathResolver::Policies::CasePath
  1894. static Resolver<Policies::CasePath> const resolver(RealOS);
  1895. #else
  1896. // IWYU pragma: no_forward_declare cm::PathResolver::Policies::LogicalPath
  1897. static Resolver<Policies::LogicalPath> const resolver(RealOS);
  1898. #endif
  1899. resolver.Resolve(std::move(p), p);
  1900. return p;
  1901. }
  1902. #ifndef CMAKE_BOOTSTRAP
  1903. bool cmSystemTools::UnsetEnv(char const* value)
  1904. {
  1905. # if !defined(HAVE_UNSETENV)
  1906. return cmSystemTools::UnPutEnv(value);
  1907. # else
  1908. unsetenv(value);
  1909. return true;
  1910. # endif
  1911. }
  1912. std::vector<std::string> cmSystemTools::GetEnvironmentVariables()
  1913. {
  1914. std::vector<std::string> env;
  1915. int cc;
  1916. # ifdef _WIN32
  1917. // if program starts with main, _wenviron is initially NULL, call to
  1918. // _wgetenv and create wide-character string environment
  1919. _wgetenv(L"");
  1920. for (cc = 0; _wenviron[cc]; ++cc) {
  1921. env.emplace_back(cmsys::Encoding::ToNarrow(_wenviron[cc]));
  1922. }
  1923. # else
  1924. for (cc = 0; environ[cc]; ++cc) {
  1925. env.emplace_back(environ[cc]);
  1926. }
  1927. # endif
  1928. return env;
  1929. }
  1930. void cmSystemTools::AppendEnv(std::vector<std::string> const& env)
  1931. {
  1932. for (std::string const& var : env) {
  1933. cmSystemTools::PutEnv(var);
  1934. }
  1935. }
  1936. void cmSystemTools::EnvDiff::AppendEnv(std::vector<std::string> const& env)
  1937. {
  1938. for (std::string const& var : env) {
  1939. this->PutEnv(var);
  1940. }
  1941. }
  1942. void cmSystemTools::EnvDiff::PutEnv(std::string const& env)
  1943. {
  1944. auto const eq_loc = env.find('=');
  1945. if (eq_loc != std::string::npos) {
  1946. std::string name = env.substr(0, eq_loc);
  1947. diff[name] = env.substr(eq_loc + 1);
  1948. } else {
  1949. this->UnPutEnv(env);
  1950. }
  1951. }
  1952. void cmSystemTools::EnvDiff::UnPutEnv(std::string const& env)
  1953. {
  1954. diff[env] = cm::nullopt;
  1955. }
  1956. bool cmSystemTools::EnvDiff::ParseOperation(std::string const& envmod)
  1957. {
  1958. char path_sep = GetSystemPathlistSeparator();
  1959. auto apply_diff = [this](std::string const& name,
  1960. std::function<void(std::string&)> const& apply) {
  1961. cm::optional<std::string> old_value = diff[name];
  1962. std::string output;
  1963. if (old_value) {
  1964. output = *old_value;
  1965. } else {
  1966. char const* curval = cmSystemTools::GetEnv(name);
  1967. if (curval) {
  1968. output = curval;
  1969. }
  1970. }
  1971. apply(output);
  1972. diff[name] = output;
  1973. };
  1974. // Split on `=`
  1975. auto const eq_loc = envmod.find_first_of('=');
  1976. if (eq_loc == std::string::npos) {
  1977. cmSystemTools::Error(cmStrCat(
  1978. "Error: Missing `=` after the variable name in: ", envmod, '\n'));
  1979. return false;
  1980. }
  1981. auto const name = envmod.substr(0, eq_loc);
  1982. // Split value on `:`
  1983. auto const op_value_start = eq_loc + 1;
  1984. auto const colon_loc = envmod.find_first_of(':', op_value_start);
  1985. if (colon_loc == std::string::npos) {
  1986. cmSystemTools::Error(
  1987. cmStrCat("Error: Missing `:` after the operation in: ", envmod, '\n'));
  1988. return false;
  1989. }
  1990. auto const op = envmod.substr(op_value_start, colon_loc - op_value_start);
  1991. auto const value_start = colon_loc + 1;
  1992. auto const value = envmod.substr(value_start);
  1993. // Determine what to do with the operation.
  1994. if (op == "reset"_s) {
  1995. auto entry = diff.find(name);
  1996. if (entry != diff.end()) {
  1997. diff.erase(entry);
  1998. }
  1999. } else if (op == "set"_s) {
  2000. diff[name] = value;
  2001. } else if (op == "unset"_s) {
  2002. diff[name] = cm::nullopt;
  2003. } else if (op == "string_append"_s) {
  2004. apply_diff(name, [&value](std::string& output) { output += value; });
  2005. } else if (op == "string_prepend"_s) {
  2006. apply_diff(name,
  2007. [&value](std::string& output) { output.insert(0, value); });
  2008. } else if (op == "path_list_append"_s) {
  2009. apply_diff(name, [&value, path_sep](std::string& output) {
  2010. if (!output.empty()) {
  2011. output += path_sep;
  2012. }
  2013. output += value;
  2014. });
  2015. } else if (op == "path_list_prepend"_s) {
  2016. apply_diff(name, [&value, path_sep](std::string& output) {
  2017. if (!output.empty()) {
  2018. output.insert(output.begin(), path_sep);
  2019. }
  2020. output.insert(0, value);
  2021. });
  2022. } else if (op == "cmake_list_append"_s) {
  2023. apply_diff(name, [&value](std::string& output) {
  2024. if (!output.empty()) {
  2025. output += ';';
  2026. }
  2027. output += value;
  2028. });
  2029. } else if (op == "cmake_list_prepend"_s) {
  2030. apply_diff(name, [&value](std::string& output) {
  2031. if (!output.empty()) {
  2032. output.insert(output.begin(), ';');
  2033. }
  2034. output.insert(0, value);
  2035. });
  2036. } else {
  2037. cmSystemTools::Error(cmStrCat(
  2038. "Error: Unrecognized environment manipulation argument: ", op, '\n'));
  2039. return false;
  2040. }
  2041. return true;
  2042. }
  2043. void cmSystemTools::EnvDiff::ApplyToCurrentEnv(std::ostringstream* measurement)
  2044. {
  2045. for (auto const& env_apply : diff) {
  2046. if (env_apply.second) {
  2047. auto const env_update =
  2048. cmStrCat(env_apply.first, '=', *env_apply.second);
  2049. cmSystemTools::PutEnv(env_update);
  2050. if (measurement) {
  2051. *measurement << env_update << std::endl;
  2052. }
  2053. } else {
  2054. cmSystemTools::UnsetEnv(env_apply.first.c_str());
  2055. if (measurement) {
  2056. // Signify that this variable is being actively unset
  2057. *measurement << '#' << env_apply.first << "=\n";
  2058. }
  2059. }
  2060. }
  2061. }
  2062. cmSystemTools::SaveRestoreEnvironment::SaveRestoreEnvironment()
  2063. {
  2064. this->Env = cmSystemTools::GetEnvironmentVariables();
  2065. }
  2066. cmSystemTools::SaveRestoreEnvironment::~SaveRestoreEnvironment()
  2067. {
  2068. // First clear everything in the current environment:
  2069. std::vector<std::string> currentEnv = GetEnvironmentVariables();
  2070. for (std::string var : currentEnv) {
  2071. std::string::size_type pos = var.find('=');
  2072. if (pos != std::string::npos) {
  2073. var = var.substr(0, pos);
  2074. }
  2075. cmSystemTools::UnsetEnv(var.c_str());
  2076. }
  2077. // Then put back each entry from the original environment:
  2078. cmSystemTools::AppendEnv(this->Env);
  2079. }
  2080. #endif
  2081. cmSystemTools::ScopedEnv::ScopedEnv(cm::string_view var)
  2082. {
  2083. std::string::size_type pos = var.find('=');
  2084. if (pos != std::string::npos) {
  2085. this->Key = std::string{ var.substr(0, pos) };
  2086. this->Original = cmSystemTools::GetEnvVar(this->Key);
  2087. cm::string_view value = var.substr(pos + 1);
  2088. if (!this->Original && value.empty()) {
  2089. // nothing to do if the environment variable wasn't already set and the
  2090. // new value is also empty. clear the Key member so the destructor also
  2091. // does nothing.
  2092. this->Key.clear();
  2093. } else {
  2094. if (value.empty()) {
  2095. cmSystemTools::UnPutEnv(this->Key);
  2096. } else {
  2097. cmSystemTools::PutEnv(cmStrCat(this->Key, '=', value));
  2098. }
  2099. }
  2100. }
  2101. }
  2102. cmSystemTools::ScopedEnv::~ScopedEnv()
  2103. {
  2104. if (!this->Key.empty()) {
  2105. if (this->Original) {
  2106. cmSystemTools::PutEnv(cmStrCat(this->Key, '=', *this->Original));
  2107. } else {
  2108. cmSystemTools::UnPutEnv(Key);
  2109. }
  2110. }
  2111. }
  2112. void cmSystemTools::EnableVSConsoleOutput()
  2113. {
  2114. #ifdef _WIN32
  2115. // Visual Studio tools like devenv may not
  2116. // display output to the console unless this environment variable is
  2117. // set. We need it to capture the output of these build tools.
  2118. // Note for future work that one could pass "/out \\.\pipe\NAME" to
  2119. // either of these executables where NAME is created with
  2120. // CreateNamedPipe. This would bypass the internal buffering of the
  2121. // output and allow it to be captured on the fly.
  2122. cmSystemTools::PutEnv("vsconsoleoutput=1");
  2123. # ifndef CMAKE_BOOTSTRAP
  2124. // VS sets an environment variable to tell MS tools like "cl" to report
  2125. // output through a backdoor pipe instead of stdout/stderr. Unset the
  2126. // environment variable to close this backdoor for any path of process
  2127. // invocations that passes through CMake so we can capture the output.
  2128. cmSystemTools::UnsetEnv("VS_UNICODE_OUTPUT");
  2129. # endif
  2130. #endif
  2131. }
  2132. bool cmSystemTools::IsPathToFramework(std::string const& path)
  2133. {
  2134. return (cmSystemTools::FileIsFullPath(path) &&
  2135. cmHasLiteralSuffix(path, ".framework"));
  2136. }
  2137. bool cmSystemTools::IsPathToXcFramework(std::string const& path)
  2138. {
  2139. return (cmSystemTools::FileIsFullPath(path) &&
  2140. cmHasLiteralSuffix(path, ".xcframework"));
  2141. }
  2142. bool cmSystemTools::IsPathToMacOSSharedLibrary(std::string const& path)
  2143. {
  2144. return (cmSystemTools::FileIsFullPath(path) &&
  2145. cmHasLiteralSuffix(path, ".dylib"));
  2146. }
  2147. bool cmSystemTools::CreateTar(std::string const& outFileName,
  2148. std::vector<std::string> const& files,
  2149. std::string const& workingDirectory,
  2150. cmTarCompression compressType, bool verbose,
  2151. std::string const& mtime,
  2152. std::string const& format, int compressionLevel)
  2153. {
  2154. #if !defined(CMAKE_BOOTSTRAP)
  2155. cmWorkingDirectory workdir(cmSystemTools::GetLogicalWorkingDirectory());
  2156. if (!workingDirectory.empty()) {
  2157. workdir.SetDirectory(workingDirectory);
  2158. }
  2159. std::string const cwd = cmSystemTools::GetLogicalWorkingDirectory();
  2160. cmsys::ofstream fout(outFileName.c_str(), std::ios::out | std::ios::binary);
  2161. if (!fout) {
  2162. std::string e = cmStrCat("Cannot open output file \"", outFileName,
  2163. "\": ", cmSystemTools::GetLastSystemError());
  2164. cmSystemTools::Error(e);
  2165. return false;
  2166. }
  2167. cmArchiveWrite::Compress compress = cmArchiveWrite::CompressNone;
  2168. switch (compressType) {
  2169. case TarCompressGZip:
  2170. compress = cmArchiveWrite::CompressGZip;
  2171. break;
  2172. case TarCompressBZip2:
  2173. compress = cmArchiveWrite::CompressBZip2;
  2174. break;
  2175. case TarCompressXZ:
  2176. compress = cmArchiveWrite::CompressXZ;
  2177. break;
  2178. case TarCompressZstd:
  2179. compress = cmArchiveWrite::CompressZstd;
  2180. break;
  2181. case TarCompressNone:
  2182. compress = cmArchiveWrite::CompressNone;
  2183. break;
  2184. }
  2185. cmArchiveWrite a(fout, compress, format.empty() ? "paxr" : format,
  2186. compressionLevel);
  2187. if (!a.Open()) {
  2188. cmSystemTools::Error(a.GetError());
  2189. return false;
  2190. }
  2191. a.SetMTime(mtime);
  2192. a.SetVerbose(verbose);
  2193. bool tarCreatedSuccessfully = true;
  2194. for (auto path : files) {
  2195. if (cmSystemTools::FileIsFullPath(path)) {
  2196. // Get the relative path to the file.
  2197. path = cmSystemTools::RelativePath(cwd, path);
  2198. }
  2199. if (!a.Add(path)) {
  2200. cmSystemTools::Error(a.GetError());
  2201. tarCreatedSuccessfully = false;
  2202. }
  2203. }
  2204. return tarCreatedSuccessfully;
  2205. #else
  2206. (void)outFileName;
  2207. (void)files;
  2208. (void)verbose;
  2209. return false;
  2210. #endif
  2211. }
  2212. #if !defined(CMAKE_BOOTSTRAP)
  2213. namespace {
  2214. # define BSDTAR_FILESIZE_PRINTF "%lu"
  2215. # define BSDTAR_FILESIZE_TYPE unsigned long
  2216. void list_item_verbose(FILE* out, struct archive_entry* entry)
  2217. {
  2218. char tmp[100];
  2219. size_t w;
  2220. char const* p;
  2221. char const* fmt;
  2222. time_t tim;
  2223. static time_t now;
  2224. size_t u_width = 6;
  2225. size_t gs_width = 13;
  2226. /*
  2227. * We avoid collecting the entire list in memory at once by
  2228. * listing things as we see them. However, that also means we can't
  2229. * just pre-compute the field widths. Instead, we start with guesses
  2230. * and just widen them as necessary. These numbers are completely
  2231. * arbitrary.
  2232. */
  2233. if (!now) {
  2234. time(&now);
  2235. }
  2236. fprintf(out, "%s %u ", archive_entry_strmode(entry),
  2237. archive_entry_nlink(entry));
  2238. /* Use uname if it's present, else uid. */
  2239. p = archive_entry_uname(entry);
  2240. if (!p || (*p == '\0')) {
  2241. snprintf(tmp, sizeof(tmp), "%lu ",
  2242. static_cast<unsigned long>(archive_entry_uid(entry)));
  2243. p = tmp;
  2244. }
  2245. w = strlen(p);
  2246. if (w > u_width) {
  2247. u_width = w;
  2248. }
  2249. fprintf(out, "%-*s ", static_cast<int>(u_width), p);
  2250. /* Use gname if it's present, else gid. */
  2251. p = archive_entry_gname(entry);
  2252. if (p && p[0] != '\0') {
  2253. fprintf(out, "%s", p);
  2254. w = strlen(p);
  2255. } else {
  2256. snprintf(tmp, sizeof(tmp), "%lu",
  2257. static_cast<unsigned long>(archive_entry_gid(entry)));
  2258. w = strlen(tmp);
  2259. fprintf(out, "%s", tmp);
  2260. }
  2261. /*
  2262. * Print device number or file size, right-aligned so as to make
  2263. * total width of group and devnum/filesize fields be gs_width.
  2264. * If gs_width is too small, grow it.
  2265. */
  2266. if (archive_entry_filetype(entry) == AE_IFCHR ||
  2267. archive_entry_filetype(entry) == AE_IFBLK) {
  2268. unsigned long rdevmajor = archive_entry_rdevmajor(entry);
  2269. unsigned long rdevminor = archive_entry_rdevminor(entry);
  2270. snprintf(tmp, sizeof(tmp), "%lu,%lu", rdevmajor, rdevminor);
  2271. } else {
  2272. /*
  2273. * Note the use of platform-dependent macros to format
  2274. * the filesize here. We need the format string and the
  2275. * corresponding type for the cast.
  2276. */
  2277. snprintf(tmp, sizeof(tmp), BSDTAR_FILESIZE_PRINTF,
  2278. static_cast<BSDTAR_FILESIZE_TYPE>(archive_entry_size(entry)));
  2279. }
  2280. if (w + strlen(tmp) >= gs_width) {
  2281. gs_width = w + strlen(tmp) + 1;
  2282. }
  2283. fprintf(out, "%*s", static_cast<int>(gs_width - w), tmp);
  2284. /* Format the time using 'ls -l' conventions. */
  2285. tim = archive_entry_mtime(entry);
  2286. # define HALF_YEAR ((time_t)365 * 86400 / 2)
  2287. # if defined(_WIN32) && !defined(__CYGWIN__)
  2288. /* Windows' strftime function does not support %e format. */
  2289. # define DAY_FMT "%d"
  2290. # else
  2291. # define DAY_FMT "%e" /* Day number without leading zeros */
  2292. # endif
  2293. if (tim < now - HALF_YEAR || tim > now + HALF_YEAR) {
  2294. fmt = DAY_FMT " %b %Y";
  2295. } else {
  2296. fmt = DAY_FMT " %b %H:%M";
  2297. }
  2298. strftime(tmp, sizeof(tmp), fmt, localtime(&tim));
  2299. fprintf(out, " %s ", tmp);
  2300. fprintf(out, "%s", cm_archive_entry_pathname(entry).c_str());
  2301. /* Extra information for links. */
  2302. if (archive_entry_hardlink(entry)) /* Hard link */
  2303. {
  2304. fprintf(out, " link to %s", archive_entry_hardlink(entry));
  2305. } else if (archive_entry_symlink(entry)) /* Symbolic link */
  2306. {
  2307. fprintf(out, " -> %s", archive_entry_symlink(entry));
  2308. }
  2309. fflush(out);
  2310. }
  2311. void ArchiveError(char const* m1, struct archive* a)
  2312. {
  2313. std::string message(m1);
  2314. char const* m2 = archive_error_string(a);
  2315. if (m2) {
  2316. message += m2;
  2317. }
  2318. cmSystemTools::Error(message);
  2319. }
  2320. bool la_diagnostic(struct archive* ar, __LA_SSIZE_T r)
  2321. {
  2322. // See archive.h definition of ARCHIVE_OK for return values.
  2323. if (r >= ARCHIVE_OK) {
  2324. return true;
  2325. }
  2326. if (r >= ARCHIVE_WARN) {
  2327. char const* warn = archive_error_string(ar);
  2328. if (!warn) {
  2329. warn = "unknown warning";
  2330. }
  2331. std::cerr << "cmake -E tar: warning: " << warn << '\n';
  2332. return true;
  2333. }
  2334. // Error.
  2335. char const* err = archive_error_string(ar);
  2336. if (!err) {
  2337. err = "unknown error";
  2338. }
  2339. std::cerr << "cmake -E tar: error: " << err << '\n';
  2340. return false;
  2341. }
  2342. // Return 'true' on success
  2343. bool copy_data(struct archive* ar, struct archive* aw)
  2344. {
  2345. long r;
  2346. void const* buff;
  2347. size_t size;
  2348. # if defined(ARCHIVE_VERSION_NUMBER) && ARCHIVE_VERSION_NUMBER >= 3000000
  2349. __LA_INT64_T offset;
  2350. # else
  2351. off_t offset;
  2352. # endif
  2353. for (;;) {
  2354. // See archive.h definition of ARCHIVE_OK for return values.
  2355. r = archive_read_data_block(ar, &buff, &size, &offset);
  2356. if (r == ARCHIVE_EOF) {
  2357. return true;
  2358. }
  2359. if (!la_diagnostic(ar, r)) {
  2360. return false;
  2361. }
  2362. // See archive.h definition of ARCHIVE_OK for return values.
  2363. __LA_SSIZE_T const w = archive_write_data_block(aw, buff, size, offset);
  2364. if (!la_diagnostic(ar, w)) {
  2365. return false;
  2366. }
  2367. }
  2368. # if !defined(__clang__) && !defined(__NVCOMPILER) && !defined(__HP_aCC)
  2369. return false; /* this should not happen but it quiets some compilers */
  2370. # endif
  2371. }
  2372. bool extract_tar(std::string const& outFileName,
  2373. std::vector<std::string> const& files, bool verbose,
  2374. cmSystemTools::cmTarExtractTimestamps extractTimestamps,
  2375. bool extract)
  2376. {
  2377. cmLocaleRAII localeRAII;
  2378. static_cast<void>(localeRAII);
  2379. struct archive* a = archive_read_new();
  2380. struct archive* ext = archive_write_disk_new();
  2381. archive_read_support_filter_all(a);
  2382. archive_read_support_format_all(a);
  2383. struct archive_entry* entry;
  2384. struct archive* matching = archive_match_new();
  2385. if (!matching) {
  2386. cmSystemTools::Error("Out of memory");
  2387. return false;
  2388. }
  2389. for (auto const& filename : files) {
  2390. if (archive_match_include_pattern(matching, filename.c_str()) !=
  2391. ARCHIVE_OK) {
  2392. cmSystemTools::Error("Failed to add to inclusion list: " + filename);
  2393. return false;
  2394. }
  2395. }
  2396. int r = cm_archive_read_open_file(a, outFileName.c_str(), 10240);
  2397. if (r) {
  2398. ArchiveError("Problem with archive_read_open_file(): ", a);
  2399. archive_write_free(ext);
  2400. archive_read_close(a);
  2401. return false;
  2402. }
  2403. for (;;) {
  2404. r = archive_read_next_header(a, &entry);
  2405. if (r == ARCHIVE_EOF) {
  2406. break;
  2407. }
  2408. if (r != ARCHIVE_OK) {
  2409. ArchiveError("Problem with archive_read_next_header(): ", a);
  2410. break;
  2411. }
  2412. if (archive_match_excluded(matching, entry)) {
  2413. continue;
  2414. }
  2415. if (verbose) {
  2416. if (extract) {
  2417. cmSystemTools::Stdout(
  2418. cmStrCat("x ", cm_archive_entry_pathname(entry)));
  2419. } else {
  2420. list_item_verbose(stdout, entry);
  2421. }
  2422. cmSystemTools::Stdout("\n");
  2423. } else if (!extract) {
  2424. cmSystemTools::Stdout(cmStrCat(cm_archive_entry_pathname(entry), '\n'));
  2425. }
  2426. if (extract) {
  2427. if (extractTimestamps == cmSystemTools::cmTarExtractTimestamps::Yes) {
  2428. r = archive_write_disk_set_options(ext, ARCHIVE_EXTRACT_TIME);
  2429. if (r != ARCHIVE_OK) {
  2430. ArchiveError("Problem with archive_write_disk_set_options(): ", ext);
  2431. break;
  2432. }
  2433. }
  2434. r = archive_write_header(ext, entry);
  2435. if (r == ARCHIVE_OK) {
  2436. if (!copy_data(a, ext)) {
  2437. break;
  2438. }
  2439. r = archive_write_finish_entry(ext);
  2440. if (r != ARCHIVE_OK) {
  2441. ArchiveError("Problem with archive_write_finish_entry(): ", ext);
  2442. break;
  2443. }
  2444. }
  2445. # ifdef _WIN32
  2446. else if (char const* linktext = archive_entry_symlink(entry)) {
  2447. std::cerr << "cmake -E tar: warning: skipping symbolic link \""
  2448. << cm_archive_entry_pathname(entry) << "\" -> \"" << linktext
  2449. << "\"." << std::endl;
  2450. }
  2451. # endif
  2452. else {
  2453. ArchiveError("Problem with archive_write_header(): ", ext);
  2454. cmSystemTools::Error("Current file: " +
  2455. cm_archive_entry_pathname(entry));
  2456. break;
  2457. }
  2458. }
  2459. }
  2460. bool error_occurred = false;
  2461. if (matching) {
  2462. char const* p;
  2463. int ar;
  2464. while ((ar = archive_match_path_unmatched_inclusions_next(matching, &p)) ==
  2465. ARCHIVE_OK) {
  2466. cmSystemTools::Error("tar: " + std::string(p) +
  2467. ": Not found in archive");
  2468. error_occurred = true;
  2469. }
  2470. if (error_occurred) {
  2471. return false;
  2472. }
  2473. if (ar == ARCHIVE_FATAL) {
  2474. cmSystemTools::Error("tar: Out of memory");
  2475. return false;
  2476. }
  2477. }
  2478. archive_match_free(matching);
  2479. archive_write_free(ext);
  2480. archive_read_close(a);
  2481. archive_read_free(a);
  2482. return r == ARCHIVE_EOF || r == ARCHIVE_OK;
  2483. }
  2484. }
  2485. #endif
  2486. bool cmSystemTools::ExtractTar(std::string const& outFileName,
  2487. std::vector<std::string> const& files,
  2488. cmTarExtractTimestamps extractTimestamps,
  2489. bool verbose)
  2490. {
  2491. #if !defined(CMAKE_BOOTSTRAP)
  2492. return extract_tar(outFileName, files, verbose, extractTimestamps, true);
  2493. #else
  2494. (void)outFileName;
  2495. (void)files;
  2496. (void)extractTimestamps;
  2497. (void)verbose;
  2498. return false;
  2499. #endif
  2500. }
  2501. bool cmSystemTools::ListTar(std::string const& outFileName,
  2502. std::vector<std::string> const& files,
  2503. bool verbose)
  2504. {
  2505. #if !defined(CMAKE_BOOTSTRAP)
  2506. return extract_tar(outFileName, files, verbose, cmTarExtractTimestamps::Yes,
  2507. false);
  2508. #else
  2509. (void)outFileName;
  2510. (void)files;
  2511. (void)verbose;
  2512. return false;
  2513. #endif
  2514. }
  2515. cmSystemTools::WaitForLineResult cmSystemTools::WaitForLine(
  2516. uv_loop_t* loop, uv_stream_t* outPipe, uv_stream_t* errPipe,
  2517. std::string& line, cmDuration timeout, std::vector<char>& out,
  2518. std::vector<char>& err)
  2519. {
  2520. line.clear();
  2521. auto outiter = out.begin();
  2522. auto erriter = err.begin();
  2523. cmProcessOutput processOutput;
  2524. std::string strdata;
  2525. while (true) {
  2526. // Check for a newline in stdout.
  2527. for (; outiter != out.end(); ++outiter) {
  2528. if ((*outiter == '\r') && ((outiter + 1) == out.end())) {
  2529. break;
  2530. }
  2531. if (*outiter == '\n' || *outiter == '\0') {
  2532. std::vector<char>::size_type length = outiter - out.begin();
  2533. if (length > 1 && *(outiter - 1) == '\r') {
  2534. --length;
  2535. }
  2536. if (length > 0) {
  2537. line.append(out.data(), length);
  2538. }
  2539. out.erase(out.begin(), outiter + 1);
  2540. return WaitForLineResult::STDOUT;
  2541. }
  2542. }
  2543. // Check for a newline in stderr.
  2544. for (; erriter != err.end(); ++erriter) {
  2545. if ((*erriter == '\r') && ((erriter + 1) == err.end())) {
  2546. break;
  2547. }
  2548. if (*erriter == '\n' || *erriter == '\0') {
  2549. std::vector<char>::size_type length = erriter - err.begin();
  2550. if (length > 1 && *(erriter - 1) == '\r') {
  2551. --length;
  2552. }
  2553. if (length > 0) {
  2554. line.append(err.data(), length);
  2555. }
  2556. err.erase(err.begin(), erriter + 1);
  2557. return WaitForLineResult::STDERR;
  2558. }
  2559. }
  2560. // No newlines found. Wait for more data from the process.
  2561. struct ReadData
  2562. {
  2563. uv_stream_t* Stream;
  2564. std::vector<char> Buffer;
  2565. bool Read = false;
  2566. bool Finished = false;
  2567. };
  2568. auto startRead =
  2569. [](uv_stream_t* stream,
  2570. ReadData& data) -> std::unique_ptr<cmUVStreamReadHandle> {
  2571. data.Stream = stream;
  2572. return cmUVStreamRead(
  2573. stream,
  2574. [&data](std::vector<char> buf) {
  2575. data.Buffer = std::move(buf);
  2576. data.Read = true;
  2577. uv_read_stop(data.Stream);
  2578. },
  2579. [&data]() { data.Finished = true; });
  2580. };
  2581. ReadData outData;
  2582. auto outHandle = startRead(outPipe, outData);
  2583. ReadData errData;
  2584. auto errHandle = startRead(errPipe, errData);
  2585. cm::uv_timer_ptr timer;
  2586. bool timedOut = false;
  2587. timer.init(*loop, &timedOut);
  2588. timer.start(
  2589. [](uv_timer_t* handle) {
  2590. auto* timedOutPtr = static_cast<bool*>(handle->data);
  2591. *timedOutPtr = true;
  2592. },
  2593. static_cast<uint64_t>(timeout.count() * 1000.0), 0,
  2594. cm::uv_update_time::no);
  2595. uv_run(loop, UV_RUN_ONCE);
  2596. if (timedOut) {
  2597. // Timeout has been exceeded.
  2598. return WaitForLineResult::Timeout;
  2599. }
  2600. if (outData.Read) {
  2601. processOutput.DecodeText(outData.Buffer.data(), outData.Buffer.size(),
  2602. strdata, 1);
  2603. // Append to the stdout buffer.
  2604. std::vector<char>::size_type size = out.size();
  2605. cm::append(out, strdata);
  2606. outiter = out.begin() + size;
  2607. } else if (errData.Read) {
  2608. processOutput.DecodeText(errData.Buffer.data(), errData.Buffer.size(),
  2609. strdata, 2);
  2610. // Append to the stderr buffer.
  2611. std::vector<char>::size_type size = err.size();
  2612. cm::append(err, strdata);
  2613. erriter = err.begin() + size;
  2614. } else if (outData.Finished && errData.Finished) {
  2615. // Both stdout and stderr pipes have broken. Return leftover data.
  2616. processOutput.DecodeText(std::string(), strdata, 1);
  2617. if (!strdata.empty()) {
  2618. std::vector<char>::size_type size = out.size();
  2619. cm::append(out, strdata);
  2620. outiter = out.begin() + size;
  2621. }
  2622. processOutput.DecodeText(std::string(), strdata, 2);
  2623. if (!strdata.empty()) {
  2624. std::vector<char>::size_type size = err.size();
  2625. cm::append(err, strdata);
  2626. erriter = err.begin() + size;
  2627. }
  2628. if (!out.empty()) {
  2629. line.append(out.data(), outiter - out.begin());
  2630. out.erase(out.begin(), out.end());
  2631. return WaitForLineResult::STDOUT;
  2632. }
  2633. if (!err.empty()) {
  2634. line.append(err.data(), erriter - err.begin());
  2635. err.erase(err.begin(), err.end());
  2636. return WaitForLineResult::STDERR;
  2637. }
  2638. return WaitForLineResult::None;
  2639. }
  2640. if (!outData.Finished) {
  2641. uv_read_stop(outPipe);
  2642. }
  2643. if (!errData.Finished) {
  2644. uv_read_stop(errPipe);
  2645. }
  2646. }
  2647. }
  2648. #ifdef _WIN32
  2649. # ifndef CRYPT_SILENT
  2650. # define CRYPT_SILENT 0x40 /* Not defined by VS 6 version of header. */
  2651. # endif
  2652. static int WinCryptRandom(void* data, size_t size)
  2653. {
  2654. int result = 0;
  2655. HCRYPTPROV hProvider = 0;
  2656. if (CryptAcquireContextW(&hProvider, 0, 0, PROV_RSA_FULL,
  2657. CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) {
  2658. result = CryptGenRandom(hProvider, (DWORD)size, (BYTE*)data) ? 1 : 0;
  2659. CryptReleaseContext(hProvider, 0);
  2660. }
  2661. return result;
  2662. }
  2663. #endif
  2664. unsigned int cmSystemTools::RandomSeed()
  2665. {
  2666. #if defined(_WIN32) && !defined(__CYGWIN__)
  2667. unsigned int seed = 0;
  2668. // Try using a real random source.
  2669. if (WinCryptRandom(&seed, sizeof(seed))) {
  2670. return seed;
  2671. }
  2672. // Fall back to the time and pid.
  2673. FILETIME ft;
  2674. GetSystemTimeAsFileTime(&ft);
  2675. unsigned int t1 = static_cast<unsigned int>(ft.dwHighDateTime);
  2676. unsigned int t2 = static_cast<unsigned int>(ft.dwLowDateTime);
  2677. unsigned int pid = static_cast<unsigned int>(GetCurrentProcessId());
  2678. return t1 ^ t2 ^ pid;
  2679. #else
  2680. union
  2681. {
  2682. unsigned int integer;
  2683. char bytes[sizeof(unsigned int)];
  2684. } seed;
  2685. // Try using a real random source.
  2686. cmsys::ifstream fin;
  2687. fin.rdbuf()->pubsetbuf(nullptr, 0); // Unbuffered read.
  2688. fin.open("/dev/urandom");
  2689. if (fin.good() && fin.read(seed.bytes, sizeof(seed)) &&
  2690. fin.gcount() == sizeof(seed)) {
  2691. return seed.integer;
  2692. }
  2693. // Fall back to the time and pid.
  2694. struct timeval t;
  2695. gettimeofday(&t, nullptr);
  2696. unsigned int pid = static_cast<unsigned int>(getpid());
  2697. unsigned int tv_sec = static_cast<unsigned int>(t.tv_sec);
  2698. unsigned int tv_usec = static_cast<unsigned int>(t.tv_usec);
  2699. // Since tv_usec never fills more than 11 bits we shift it to fill
  2700. // in the slow-changing high-order bits of tv_sec.
  2701. return tv_sec ^ (tv_usec << 21) ^ pid;
  2702. #endif
  2703. }
  2704. unsigned int cmSystemTools::RandomNumber()
  2705. {
  2706. #ifndef CM_HAVE_THREAD_LOCAL
  2707. static std::mutex gen_mutex;
  2708. std::lock_guard<std::mutex> gen_mutex_lock(gen_mutex);
  2709. #else
  2710. thread_local
  2711. #endif
  2712. static std::mt19937 gen{ cmSystemTools::RandomSeed() };
  2713. return static_cast<unsigned int>(gen());
  2714. }
  2715. std::string cmSystemTools::FindProgram(std::string const& name,
  2716. std::vector<std::string> const& path)
  2717. {
  2718. std::string exe = cmsys::SystemTools::FindProgram(name, path);
  2719. if (!exe.empty()) {
  2720. exe = cmSystemTools::ToNormalizedPathOnDisk(std::move(exe));
  2721. }
  2722. return exe;
  2723. }
  2724. namespace {
  2725. std::string InitLogicalWorkingDirectory()
  2726. {
  2727. std::string cwd = cmsys::SystemTools::GetCurrentWorkingDirectory();
  2728. std::string pwd;
  2729. if (cmSystemTools::GetEnv("PWD", pwd) &&
  2730. cmSystemTools::FileIsFullPath(pwd)) {
  2731. std::string const pwd_real = cmSystemTools::GetRealPath(pwd);
  2732. if (pwd_real == cwd) {
  2733. cwd = cmSystemTools::ToNormalizedPathOnDisk(std::move(pwd));
  2734. }
  2735. }
  2736. return cwd;
  2737. }
  2738. std::string cmSystemToolsLogicalWorkingDirectory =
  2739. InitLogicalWorkingDirectory();
  2740. std::string cmSystemToolsCMakeCommand;
  2741. std::string cmSystemToolsCTestCommand;
  2742. std::string cmSystemToolsCPackCommand;
  2743. std::string cmSystemToolsCMakeCursesCommand;
  2744. std::string cmSystemToolsCMakeGUICommand;
  2745. std::string cmSystemToolsCMClDepsCommand;
  2746. std::string cmSystemToolsCMakeRoot;
  2747. std::string cmSystemToolsHTMLDoc;
  2748. #if defined(__APPLE__)
  2749. bool IsCMakeAppBundleExe(std::string const& exe)
  2750. {
  2751. return cmHasLiteralSuffix(cmSystemTools::LowerCase(exe), "/macos/cmake");
  2752. }
  2753. #endif
  2754. std::string FindOwnExecutable(char const* argv0)
  2755. {
  2756. #if defined(_WIN32) && !defined(__CYGWIN__)
  2757. static_cast<void>(argv0);
  2758. wchar_t modulepath[_MAX_PATH];
  2759. ::GetModuleFileNameW(nullptr, modulepath, sizeof(modulepath));
  2760. std::string exe = cmsys::Encoding::ToNarrow(modulepath);
  2761. #elif defined(__APPLE__)
  2762. static_cast<void>(argv0);
  2763. # define CM_EXE_PATH_LOCAL_SIZE 16384
  2764. char exe_path_local[CM_EXE_PATH_LOCAL_SIZE];
  2765. # if defined(MAC_OS_X_VERSION_10_3) && !defined(MAC_OS_X_VERSION_10_4)
  2766. unsigned long exe_path_size = CM_EXE_PATH_LOCAL_SIZE;
  2767. # else
  2768. uint32_t exe_path_size = CM_EXE_PATH_LOCAL_SIZE;
  2769. # endif
  2770. # undef CM_EXE_PATH_LOCAL_SIZE
  2771. char* exe_path = exe_path_local;
  2772. if (_NSGetExecutablePath(exe_path, &exe_path_size) < 0) {
  2773. exe_path = static_cast<char*>(malloc(exe_path_size));
  2774. _NSGetExecutablePath(exe_path, &exe_path_size);
  2775. }
  2776. std::string exe = exe_path;
  2777. if (exe_path != exe_path_local) {
  2778. free(exe_path);
  2779. }
  2780. if (IsCMakeAppBundleExe(exe)) {
  2781. // The executable is inside an application bundle.
  2782. // The install tree has "..<CMAKE_BIN_DIR>/cmake-gui".
  2783. // The build tree has '../../../cmake-gui".
  2784. std::string dir = cmSystemTools::GetFilenamePath(exe);
  2785. dir = cmSystemTools::GetFilenamePath(dir);
  2786. exe = cmStrCat(dir, CMAKE_BIN_DIR "/cmake-gui");
  2787. if (!cmSystemTools::PathExists(exe)) {
  2788. dir = cmSystemTools::GetFilenamePath(dir);
  2789. dir = cmSystemTools::GetFilenamePath(dir);
  2790. exe = cmStrCat(dir, "/cmake-gui");
  2791. }
  2792. }
  2793. #else
  2794. std::string exe = cmsys::SystemTools::FindProgram(argv0);
  2795. #endif
  2796. exe = cmSystemTools::ToNormalizedPathOnDisk(std::move(exe));
  2797. return exe;
  2798. }
  2799. #ifndef CMAKE_BOOTSTRAP
  2800. bool ResolveSymlinkToOwnExecutable(std::string& exe, std::string& exe_dir)
  2801. {
  2802. std::string linked_exe;
  2803. if (!cmSystemTools::ReadSymlink(exe, linked_exe)) {
  2804. return false;
  2805. }
  2806. # if defined(__APPLE__)
  2807. // Ignore "cmake-gui -> ../MacOS/CMake".
  2808. if (IsCMakeAppBundleExe(linked_exe)) {
  2809. return false;
  2810. }
  2811. # endif
  2812. if (cmSystemTools::FileIsFullPath(linked_exe)) {
  2813. exe = std::move(linked_exe);
  2814. } else {
  2815. exe = cmStrCat(exe_dir, '/', std::move(linked_exe));
  2816. }
  2817. exe = cmSystemTools::ToNormalizedPathOnDisk(std::move(exe));
  2818. exe_dir = cmSystemTools::GetFilenamePath(exe);
  2819. return true;
  2820. }
  2821. bool FindCMakeResourcesInInstallTree(std::string const& exe_dir)
  2822. {
  2823. // Install tree has
  2824. // - "<prefix><CMAKE_BIN_DIR>/cmake"
  2825. // - "<prefix><CMAKE_DATA_DIR>"
  2826. // - "<prefix><CMAKE_DOC_DIR>"
  2827. if (cmHasLiteralSuffix(exe_dir, CMAKE_BIN_DIR)) {
  2828. std::string const prefix =
  2829. exe_dir.substr(0, exe_dir.size() - cmStrLen(CMAKE_BIN_DIR));
  2830. // Set cmSystemToolsCMakeRoot set to the location expected in an
  2831. // install tree, even if it does not exist, so that
  2832. // cmake::AddCMakePaths can print the location in its error message.
  2833. cmSystemToolsCMakeRoot = cmStrCat(prefix, CMAKE_DATA_DIR);
  2834. if (cmSystemTools::FileExists(
  2835. cmStrCat(cmSystemToolsCMakeRoot, "/Modules/CMake.cmake"))) {
  2836. if (cmSystemTools::FileExists(
  2837. cmStrCat(prefix, CMAKE_DOC_DIR "/html/index.html"))) {
  2838. cmSystemToolsHTMLDoc = cmStrCat(prefix, CMAKE_DOC_DIR "/html");
  2839. }
  2840. return true;
  2841. }
  2842. }
  2843. return false;
  2844. }
  2845. void FindCMakeResourcesInBuildTree(std::string const& exe_dir)
  2846. {
  2847. // Build tree has "<build>/bin[/<config>]/cmake" and
  2848. // "<build>/CMakeFiles/CMakeSourceDir.txt".
  2849. std::string dir = cmSystemTools::GetFilenamePath(exe_dir);
  2850. std::string src_dir_txt = cmStrCat(dir, "/CMakeFiles/CMakeSourceDir.txt");
  2851. cmsys::ifstream fin(src_dir_txt.c_str());
  2852. std::string src_dir;
  2853. if (fin && cmSystemTools::GetLineFromStream(fin, src_dir) &&
  2854. cmSystemTools::FileIsDirectory(src_dir)) {
  2855. cmSystemToolsCMakeRoot = src_dir;
  2856. } else {
  2857. dir = cmSystemTools::GetFilenamePath(dir);
  2858. src_dir_txt = cmStrCat(dir, "/CMakeFiles/CMakeSourceDir.txt");
  2859. cmsys::ifstream fin2(src_dir_txt.c_str());
  2860. if (fin2 && cmSystemTools::GetLineFromStream(fin2, src_dir) &&
  2861. cmSystemTools::FileIsDirectory(src_dir)) {
  2862. cmSystemToolsCMakeRoot = src_dir;
  2863. }
  2864. }
  2865. if (!cmSystemToolsCMakeRoot.empty() && cmSystemToolsHTMLDoc.empty() &&
  2866. cmSystemTools::FileExists(
  2867. cmStrCat(dir, "/Utilities/Sphinx/html/index.html"))) {
  2868. cmSystemToolsHTMLDoc = cmStrCat(dir, "/Utilities/Sphinx/html");
  2869. }
  2870. }
  2871. #endif
  2872. }
  2873. void cmSystemTools::FindCMakeResources(char const* argv0)
  2874. {
  2875. std::string exe = FindOwnExecutable(argv0);
  2876. #ifdef CMAKE_BOOTSTRAP
  2877. // The bootstrap cmake knows its resource locations.
  2878. cmSystemToolsCMakeRoot = CMAKE_BOOTSTRAP_SOURCE_DIR;
  2879. cmSystemToolsCMakeCommand = exe;
  2880. // The bootstrap cmake does not provide the other tools,
  2881. // so use the directory where they are about to be built.
  2882. std::string exe_dir = CMAKE_BOOTSTRAP_BINARY_DIR "/bin";
  2883. #else
  2884. // Find resources relative to our own executable.
  2885. std::string exe_dir = cmSystemTools::GetFilenamePath(exe);
  2886. bool found = false;
  2887. // When running through a symlink to our own executable,
  2888. // preserve symlinks in directory components if possible.
  2889. do {
  2890. found = FindCMakeResourcesInInstallTree(exe_dir);
  2891. } while (!found && ResolveSymlinkToOwnExecutable(exe, exe_dir));
  2892. // If we have not yet found the resources, the above loop will
  2893. // have left 'exe' referring to a real file, not a symlink, so
  2894. // all our binaries should exist under 'exe_dir'. However, the
  2895. // resources may be discoverable only in the real path.
  2896. if (!found) {
  2897. found =
  2898. FindCMakeResourcesInInstallTree(cmSystemTools::GetRealPath(exe_dir));
  2899. }
  2900. if (!found) {
  2901. FindCMakeResourcesInBuildTree(exe_dir);
  2902. }
  2903. cmSystemToolsCMakeCommand =
  2904. cmStrCat(exe_dir, "/cmake", cmSystemTools::GetExecutableExtension());
  2905. #endif
  2906. cmSystemToolsCTestCommand =
  2907. cmStrCat(exe_dir, "/ctest", cmSystemTools::GetExecutableExtension());
  2908. cmSystemToolsCPackCommand =
  2909. cmStrCat(exe_dir, "/cpack", cmSystemTools::GetExecutableExtension());
  2910. cmSystemToolsCMakeGUICommand =
  2911. cmStrCat(exe_dir, "/cmake-gui", cmSystemTools::GetExecutableExtension());
  2912. if (!cmSystemTools::FileExists(cmSystemToolsCMakeGUICommand)) {
  2913. cmSystemToolsCMakeGUICommand.clear();
  2914. }
  2915. cmSystemToolsCMakeCursesCommand =
  2916. cmStrCat(exe_dir, "/ccmake", cmSystemTools::GetExecutableExtension());
  2917. if (!cmSystemTools::FileExists(cmSystemToolsCMakeCursesCommand)) {
  2918. cmSystemToolsCMakeCursesCommand.clear();
  2919. }
  2920. cmSystemToolsCMClDepsCommand =
  2921. cmStrCat(exe_dir, "/cmcldeps", cmSystemTools::GetExecutableExtension());
  2922. if (!cmSystemTools::FileExists(cmSystemToolsCMClDepsCommand)) {
  2923. cmSystemToolsCMClDepsCommand.clear();
  2924. }
  2925. }
  2926. std::string const& cmSystemTools::GetCMakeCommand()
  2927. {
  2928. return cmSystemToolsCMakeCommand;
  2929. }
  2930. std::string const& cmSystemTools::GetCTestCommand()
  2931. {
  2932. return cmSystemToolsCTestCommand;
  2933. }
  2934. std::string const& cmSystemTools::GetCPackCommand()
  2935. {
  2936. return cmSystemToolsCPackCommand;
  2937. }
  2938. std::string const& cmSystemTools::GetCMakeCursesCommand()
  2939. {
  2940. return cmSystemToolsCMakeCursesCommand;
  2941. }
  2942. std::string const& cmSystemTools::GetCMakeGUICommand()
  2943. {
  2944. return cmSystemToolsCMakeGUICommand;
  2945. }
  2946. std::string const& cmSystemTools::GetCMClDepsCommand()
  2947. {
  2948. return cmSystemToolsCMClDepsCommand;
  2949. }
  2950. std::string const& cmSystemTools::GetCMakeRoot()
  2951. {
  2952. return cmSystemToolsCMakeRoot;
  2953. }
  2954. std::string const& cmSystemTools::GetHTMLDoc()
  2955. {
  2956. return cmSystemToolsHTMLDoc;
  2957. }
  2958. cm::optional<std::string> cmSystemTools::GetSystemConfigDirectory()
  2959. {
  2960. #if defined(_WIN32)
  2961. LPWSTR lpwstr;
  2962. if (FAILED(SHGetKnownFolderPath(FOLDERID_LocalAppData, 0, NULL, &lpwstr))) {
  2963. return cm::nullopt;
  2964. }
  2965. std::wstring wstr = std::wstring(lpwstr);
  2966. CoTaskMemFree(lpwstr);
  2967. std::string config = cmsys::Encoding::ToNarrow(wstr);
  2968. cmSystemTools::ConvertToUnixSlashes(config);
  2969. return config;
  2970. #else
  2971. auto config = cmSystemTools::GetEnvVar("XDG_CONFIG_HOME");
  2972. if (!config.has_value()) {
  2973. config = cmSystemTools::GetEnvVar("HOME");
  2974. if (config.has_value()) {
  2975. # if defined(__APPLE__)
  2976. config = cmStrCat(config.value(), "/Library/Application Support");
  2977. # else
  2978. config = cmStrCat(config.value(), "/.config");
  2979. # endif
  2980. }
  2981. }
  2982. return config;
  2983. #endif
  2984. }
  2985. cm::optional<std::string> cmSystemTools::GetCMakeConfigDirectory()
  2986. {
  2987. auto config = cmSystemTools::GetEnvVar("CMAKE_CONFIG_DIR");
  2988. if (!config.has_value()) {
  2989. config = cmSystemTools::GetSystemConfigDirectory();
  2990. if (config.has_value()) {
  2991. #if defined(_WIN32) || defined(__APPLE__)
  2992. config = cmStrCat(config.value(), "/CMake");
  2993. #else
  2994. config = cmStrCat(config.value(), "/cmake");
  2995. #endif
  2996. }
  2997. }
  2998. return config;
  2999. }
  3000. std::string const& cmSystemTools::GetLogicalWorkingDirectory()
  3001. {
  3002. return cmSystemToolsLogicalWorkingDirectory;
  3003. }
  3004. cmsys::Status cmSystemTools::SetLogicalWorkingDirectory(std::string const& lwd)
  3005. {
  3006. cmsys::Status status = cmSystemTools::ChangeDirectory(lwd);
  3007. if (status) {
  3008. cmSystemToolsLogicalWorkingDirectory = lwd;
  3009. }
  3010. return status;
  3011. }
  3012. bool cmSystemTools::GuessLibrarySOName(std::string const& fullPath,
  3013. std::string& soname)
  3014. {
  3015. // For ELF shared libraries use a real parser to get the correct
  3016. // soname.
  3017. cmELF elf(fullPath.c_str());
  3018. if (elf) {
  3019. return elf.GetSOName(soname);
  3020. }
  3021. // If the file is not a symlink we have no guess for its soname.
  3022. if (!cmSystemTools::FileIsSymlink(fullPath)) {
  3023. return false;
  3024. }
  3025. if (!cmSystemTools::ReadSymlink(fullPath, soname)) {
  3026. return false;
  3027. }
  3028. // If the symlink has a path component we have no guess for the soname.
  3029. if (!cmSystemTools::GetFilenamePath(soname).empty()) {
  3030. return false;
  3031. }
  3032. // If the symlink points at an extended version of the same name
  3033. // assume it is the soname.
  3034. std::string name = cmSystemTools::GetFilenameName(fullPath);
  3035. return soname.length() > name.length() &&
  3036. soname.compare(0, name.length(), name) == 0;
  3037. }
  3038. bool cmSystemTools::GuessLibraryInstallName(std::string const& fullPath,
  3039. std::string& soname)
  3040. {
  3041. #if defined(CMake_USE_MACH_PARSER)
  3042. cmMachO macho(fullPath.c_str());
  3043. if (macho) {
  3044. return macho.GetInstallName(soname);
  3045. }
  3046. #else
  3047. (void)fullPath;
  3048. (void)soname;
  3049. #endif
  3050. return false;
  3051. }
  3052. static std::string::size_type cmSystemToolsFindRPath(cm::string_view have,
  3053. cm::string_view want)
  3054. {
  3055. std::string::size_type pos = 0;
  3056. while (pos < have.size()) {
  3057. // Look for an occurrence of the string.
  3058. std::string::size_type const beg = have.find(want, pos);
  3059. if (beg == std::string::npos) {
  3060. return std::string::npos;
  3061. }
  3062. // Make sure it is separated from preceding entries.
  3063. if (beg > 0 && have[beg - 1] != ':') {
  3064. pos = beg + 1;
  3065. continue;
  3066. }
  3067. // Make sure it is separated from following entries.
  3068. std::string::size_type const end = beg + want.size();
  3069. if (end < have.size() && have[end] != ':') {
  3070. pos = beg + 1;
  3071. continue;
  3072. }
  3073. // Return the position of the path portion.
  3074. return beg;
  3075. }
  3076. // The desired rpath was not found.
  3077. return std::string::npos;
  3078. }
  3079. namespace {
  3080. struct cmSystemToolsRPathInfo
  3081. {
  3082. unsigned long Position;
  3083. unsigned long Size;
  3084. std::string Name;
  3085. std::string Value;
  3086. };
  3087. using EmptyCallback = std::function<bool(std::string*, cmELF const&)>;
  3088. using AdjustCallback = std::function<bool(
  3089. cm::optional<std::string>&, std::string const&, char const*, std::string*)>;
  3090. cm::optional<bool> AdjustRPathELF(std::string const& file,
  3091. EmptyCallback const& emptyCallback,
  3092. AdjustCallback const& adjustCallback,
  3093. std::string* emsg, bool* changed)
  3094. {
  3095. if (changed) {
  3096. *changed = false;
  3097. }
  3098. int rp_count = 0;
  3099. bool remove_rpath = true;
  3100. cmSystemToolsRPathInfo rp[2];
  3101. {
  3102. // Parse the ELF binary.
  3103. cmELF elf(file.c_str());
  3104. if (!elf) {
  3105. return cm::nullopt; // Not a valid ELF file.
  3106. }
  3107. if (!elf.HasDynamicSection()) {
  3108. return true; // No dynamic section to update.
  3109. }
  3110. // Get the RPATH and RUNPATH entries from it.
  3111. int se_count = 0;
  3112. cmELF::StringEntry const* se[2] = { nullptr, nullptr };
  3113. char const* se_name[2] = { nullptr, nullptr };
  3114. if (cmELF::StringEntry const* se_rpath = elf.GetRPath()) {
  3115. se[se_count] = se_rpath;
  3116. se_name[se_count] = "RPATH";
  3117. ++se_count;
  3118. }
  3119. if (cmELF::StringEntry const* se_runpath = elf.GetRunPath()) {
  3120. se[se_count] = se_runpath;
  3121. se_name[se_count] = "RUNPATH";
  3122. ++se_count;
  3123. }
  3124. if (se_count == 0) {
  3125. return emptyCallback(emsg, elf);
  3126. }
  3127. for (int i = 0; i < se_count; ++i) {
  3128. // If both RPATH and RUNPATH refer to the same string literal it
  3129. // needs to be changed only once.
  3130. if (rp_count && rp[0].Position == se[i]->Position) {
  3131. continue;
  3132. }
  3133. // Store information about the entry in the file.
  3134. rp[rp_count].Position = se[i]->Position;
  3135. rp[rp_count].Size = se[i]->Size;
  3136. rp[rp_count].Name = se_name[i];
  3137. // Adjust the rpath.
  3138. cm::optional<std::string> outRPath;
  3139. if (!adjustCallback(outRPath, se[i]->Value, se_name[i], emsg)) {
  3140. return false;
  3141. }
  3142. if (outRPath) {
  3143. if (!outRPath->empty()) {
  3144. remove_rpath = false;
  3145. }
  3146. // Make sure there is enough room to store the new rpath and at
  3147. // least one null terminator.
  3148. if (rp[rp_count].Size < outRPath->length() + 1) {
  3149. if (emsg) {
  3150. *emsg = cmStrCat("The replacement path is too long for the ",
  3151. se_name[i], " entry.");
  3152. }
  3153. return false;
  3154. }
  3155. // This entry is ready for update.
  3156. rp[rp_count].Value = std::move(*outRPath);
  3157. ++rp_count;
  3158. } else {
  3159. remove_rpath = false;
  3160. }
  3161. }
  3162. }
  3163. // If no runtime path needs to be changed, we are done.
  3164. if (rp_count == 0) {
  3165. return true;
  3166. }
  3167. // If the resulting rpath is empty, just remove the entire entry instead.
  3168. if (remove_rpath) {
  3169. return cmSystemTools::RemoveRPath(file, emsg, changed);
  3170. }
  3171. FileModeGuard file_mode_guard(file, emsg);
  3172. if (file_mode_guard.HasErrors()) {
  3173. return false;
  3174. }
  3175. {
  3176. // Open the file for update.
  3177. cmsys::ofstream f(file.c_str(),
  3178. std::ios::in | std::ios::out | std::ios::binary);
  3179. if (!f) {
  3180. if (emsg) {
  3181. *emsg = "Error opening file for update.";
  3182. }
  3183. return false;
  3184. }
  3185. // Store the new RPATH and RUNPATH strings.
  3186. for (int i = 0; i < rp_count; ++i) {
  3187. // Seek to the RPATH position.
  3188. if (!f.seekp(rp[i].Position)) {
  3189. if (emsg) {
  3190. *emsg = cmStrCat("Error seeking to ", rp[i].Name, " position.");
  3191. }
  3192. return false;
  3193. }
  3194. // Write the new rpath. Follow it with enough null terminators to
  3195. // fill the string table entry.
  3196. f << rp[i].Value;
  3197. for (unsigned long j = rp[i].Value.length(); j < rp[i].Size; ++j) {
  3198. f << '\0';
  3199. }
  3200. // Make sure it wrote correctly.
  3201. if (!f) {
  3202. if (emsg) {
  3203. *emsg = cmStrCat("Error writing the new ", rp[i].Name,
  3204. " string to the file.");
  3205. }
  3206. return false;
  3207. }
  3208. }
  3209. }
  3210. if (!file_mode_guard.Restore(emsg)) {
  3211. return false;
  3212. }
  3213. // Everything was updated successfully.
  3214. if (changed) {
  3215. *changed = true;
  3216. }
  3217. return true;
  3218. }
  3219. std::function<bool(std::string*, cmELF const&)> MakeEmptyCallback(
  3220. std::string const& newRPath)
  3221. {
  3222. return [newRPath](std::string* emsg, cmELF const& elf) -> bool {
  3223. if (newRPath.empty()) {
  3224. // The new rpath is empty and there is no rpath anyway so it is
  3225. // okay.
  3226. return true;
  3227. }
  3228. if (emsg) {
  3229. *emsg =
  3230. cmStrCat("No valid ELF RPATH or RUNPATH entry exists in the file; ",
  3231. elf.GetErrorMessage());
  3232. }
  3233. return false;
  3234. };
  3235. }
  3236. }
  3237. static cm::optional<bool> ChangeRPathELF(std::string const& file,
  3238. std::string const& oldRPath,
  3239. std::string const& newRPath,
  3240. bool removeEnvironmentRPath,
  3241. std::string* emsg, bool* changed)
  3242. {
  3243. auto adjustCallback = [oldRPath, newRPath, removeEnvironmentRPath](
  3244. cm::optional<std::string>& outRPath,
  3245. std::string const& inRPath, char const* se_name,
  3246. std::string* emsg2) -> bool {
  3247. // Make sure the current rpath contains the old rpath.
  3248. std::string::size_type pos = cmSystemToolsFindRPath(inRPath, oldRPath);
  3249. if (pos == std::string::npos) {
  3250. // If it contains the new rpath instead then it is okay.
  3251. if (cmSystemToolsFindRPath(inRPath, newRPath) != std::string::npos) {
  3252. return true;
  3253. }
  3254. if (emsg2) {
  3255. std::ostringstream e;
  3256. /* clang-format off */
  3257. e << "The current " << se_name << " is:\n"
  3258. " " << inRPath << "\n"
  3259. "which does not contain:\n"
  3260. " " << oldRPath << "\n"
  3261. "as was expected.";
  3262. /* clang-format on */
  3263. *emsg2 = e.str();
  3264. }
  3265. return false;
  3266. }
  3267. std::string::size_type prefix_len = pos;
  3268. // If oldRPath was at the end of the file's RPath, and newRPath is empty,
  3269. // we should remove the unnecessary ':' at the end.
  3270. if (newRPath.empty() && pos > 0 && inRPath[pos - 1] == ':' &&
  3271. pos + oldRPath.length() == inRPath.length()) {
  3272. prefix_len--;
  3273. }
  3274. // Construct the new value which preserves the part of the path
  3275. // not being changed.
  3276. outRPath.emplace();
  3277. if (!removeEnvironmentRPath) {
  3278. *outRPath += inRPath.substr(0, prefix_len);
  3279. }
  3280. *outRPath += newRPath;
  3281. *outRPath += inRPath.substr(pos + oldRPath.length());
  3282. return true;
  3283. };
  3284. return AdjustRPathELF(file, MakeEmptyCallback(newRPath), adjustCallback,
  3285. emsg, changed);
  3286. }
  3287. static cm::optional<bool> SetRPathELF(std::string const& file,
  3288. std::string const& newRPath,
  3289. std::string* emsg, bool* changed)
  3290. {
  3291. auto adjustCallback = [newRPath](cm::optional<std::string>& outRPath,
  3292. std::string const& inRPath,
  3293. char const* /*se_name*/, std::string*
  3294. /*emsg*/) -> bool {
  3295. if (inRPath != newRPath) {
  3296. outRPath = newRPath;
  3297. }
  3298. return true;
  3299. };
  3300. return AdjustRPathELF(file, MakeEmptyCallback(newRPath), adjustCallback,
  3301. emsg, changed);
  3302. }
  3303. static cm::optional<bool> ChangeRPathXCOFF(std::string const& file,
  3304. std::string const& oldRPath,
  3305. std::string const& newRPath,
  3306. bool removeEnvironmentRPath,
  3307. std::string* emsg, bool* changed)
  3308. {
  3309. if (changed) {
  3310. *changed = false;
  3311. }
  3312. #if !defined(CMake_USE_XCOFF_PARSER)
  3313. (void)file;
  3314. (void)oldRPath;
  3315. (void)newRPath;
  3316. (void)removeEnvironmentRPath;
  3317. (void)emsg;
  3318. return cm::nullopt;
  3319. #else
  3320. bool chg = false;
  3321. cmXCOFF xcoff(file.c_str(), cmXCOFF::Mode::ReadWrite);
  3322. if (!xcoff) {
  3323. return cm::nullopt; // Not a valid XCOFF file
  3324. }
  3325. if (cm::optional<cm::string_view> maybeLibPath = xcoff.GetLibPath()) {
  3326. cm::string_view libPath = *maybeLibPath;
  3327. // Make sure the current rpath contains the old rpath.
  3328. std::string::size_type pos = cmSystemToolsFindRPath(libPath, oldRPath);
  3329. if (pos == std::string::npos) {
  3330. // If it contains the new rpath instead then it is okay.
  3331. if (cmSystemToolsFindRPath(libPath, newRPath) != std::string::npos) {
  3332. return true;
  3333. }
  3334. if (emsg) {
  3335. std::ostringstream e;
  3336. /* clang-format off */
  3337. e << "The current RPATH is:\n"
  3338. " " << libPath << "\n"
  3339. "which does not contain:\n"
  3340. " " << oldRPath << "\n"
  3341. "as was expected.";
  3342. /* clang-format on */
  3343. *emsg = e.str();
  3344. }
  3345. return false;
  3346. }
  3347. // The prefix is either empty or ends in a ':'.
  3348. cm::string_view prefix = libPath.substr(0, pos);
  3349. if (newRPath.empty() && !prefix.empty()) {
  3350. prefix.remove_suffix(1);
  3351. }
  3352. // The suffix is either empty or starts in a ':'.
  3353. cm::string_view suffix = libPath.substr(pos + oldRPath.length());
  3354. // Construct the new value which preserves the part of the path
  3355. // not being changed.
  3356. std::string newLibPath;
  3357. if (!removeEnvironmentRPath) {
  3358. newLibPath = std::string(prefix);
  3359. }
  3360. newLibPath += newRPath;
  3361. newLibPath += suffix;
  3362. chg = xcoff.SetLibPath(newLibPath);
  3363. }
  3364. if (!xcoff) {
  3365. if (emsg) {
  3366. *emsg = xcoff.GetErrorMessage();
  3367. }
  3368. return false;
  3369. }
  3370. // Everything was updated successfully.
  3371. if (changed) {
  3372. *changed = chg;
  3373. }
  3374. return true;
  3375. #endif
  3376. }
  3377. static cm::optional<bool> SetRPathXCOFF(std::string const& /*file*/,
  3378. std::string const& /*newRPath*/,
  3379. std::string* /*emsg*/,
  3380. bool* /*changed*/)
  3381. {
  3382. return cm::nullopt; // Not implemented.
  3383. }
  3384. bool cmSystemTools::ChangeRPath(std::string const& file,
  3385. std::string const& oldRPath,
  3386. std::string const& newRPath,
  3387. bool removeEnvironmentRPath, std::string* emsg,
  3388. bool* changed)
  3389. {
  3390. if (cm::optional<bool> result = ChangeRPathELF(
  3391. file, oldRPath, newRPath, removeEnvironmentRPath, emsg, changed)) {
  3392. return result.value();
  3393. }
  3394. if (cm::optional<bool> result = ChangeRPathXCOFF(
  3395. file, oldRPath, newRPath, removeEnvironmentRPath, emsg, changed)) {
  3396. return result.value();
  3397. }
  3398. // The file format is not recognized. Assume it has no RPATH.
  3399. if (newRPath.empty()) {
  3400. // The caller wanted no RPATH anyway.
  3401. return true;
  3402. }
  3403. if (emsg) {
  3404. *emsg = "The file format is not recognized.";
  3405. }
  3406. return false;
  3407. }
  3408. bool cmSystemTools::SetRPath(std::string const& file,
  3409. std::string const& newRPath, std::string* emsg,
  3410. bool* changed)
  3411. {
  3412. if (cm::optional<bool> result = SetRPathELF(file, newRPath, emsg, changed)) {
  3413. return result.value();
  3414. }
  3415. if (cm::optional<bool> result =
  3416. SetRPathXCOFF(file, newRPath, emsg, changed)) {
  3417. return result.value();
  3418. }
  3419. // The file format is not recognized. Assume it has no RPATH.
  3420. if (newRPath.empty()) {
  3421. // The caller wanted no RPATH anyway.
  3422. return true;
  3423. }
  3424. if (emsg) {
  3425. *emsg = "The file format is not recognized.";
  3426. }
  3427. return false;
  3428. }
  3429. namespace {
  3430. bool VersionCompare(cmSystemTools::CompareOp op, char const* lhss,
  3431. char const* rhss)
  3432. {
  3433. char const* endl = lhss;
  3434. char const* endr = rhss;
  3435. while (((*endl >= '0') && (*endl <= '9')) ||
  3436. ((*endr >= '0') && (*endr <= '9'))) {
  3437. // Do component-wise comparison, ignoring leading zeros
  3438. // (components are treated as integers, not as mantissas)
  3439. while (*endl == '0') {
  3440. endl++;
  3441. }
  3442. while (*endr == '0') {
  3443. endr++;
  3444. }
  3445. char const* beginl = endl;
  3446. char const* beginr = endr;
  3447. // count significant digits
  3448. while ((*endl >= '0') && (*endl <= '9')) {
  3449. endl++;
  3450. }
  3451. while ((*endr >= '0') && (*endr <= '9')) {
  3452. endr++;
  3453. }
  3454. // compare number of digits first
  3455. ptrdiff_t r = ((endl - beginl) - (endr - beginr));
  3456. if (r == 0) {
  3457. // compare the digits if number of digits is equal
  3458. r = strncmp(beginl, beginr, endl - beginl);
  3459. }
  3460. if (r < 0) {
  3461. // lhs < rhs, so true if operation is LESS
  3462. return (op & cmSystemTools::OP_LESS) != 0;
  3463. }
  3464. if (r > 0) {
  3465. // lhs > rhs, so true if operation is GREATER
  3466. return (op & cmSystemTools::OP_GREATER) != 0;
  3467. }
  3468. if (*endr == '.') {
  3469. endr++;
  3470. }
  3471. if (*endl == '.') {
  3472. endl++;
  3473. }
  3474. }
  3475. // lhs == rhs, so true if operation is EQUAL
  3476. return (op & cmSystemTools::OP_EQUAL) != 0;
  3477. }
  3478. }
  3479. bool cmSystemTools::VersionCompare(cmSystemTools::CompareOp op,
  3480. std::string const& lhs,
  3481. std::string const& rhs)
  3482. {
  3483. return ::VersionCompare(op, lhs.c_str(), rhs.c_str());
  3484. }
  3485. bool cmSystemTools::VersionCompare(cmSystemTools::CompareOp op,
  3486. std::string const& lhs, char const rhs[])
  3487. {
  3488. return ::VersionCompare(op, lhs.c_str(), rhs);
  3489. }
  3490. bool cmSystemTools::VersionCompareEqual(std::string const& lhs,
  3491. std::string const& rhs)
  3492. {
  3493. return cmSystemTools::VersionCompare(cmSystemTools::OP_EQUAL, lhs, rhs);
  3494. }
  3495. bool cmSystemTools::VersionCompareGreater(std::string const& lhs,
  3496. std::string const& rhs)
  3497. {
  3498. return cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER, lhs, rhs);
  3499. }
  3500. bool cmSystemTools::VersionCompareGreaterEq(std::string const& lhs,
  3501. std::string const& rhs)
  3502. {
  3503. return cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER_EQUAL, lhs,
  3504. rhs);
  3505. }
  3506. static size_t cm_strverscmp_find_first_difference_or_end(char const* lhs,
  3507. char const* rhs)
  3508. {
  3509. size_t i = 0;
  3510. /* Step forward until we find a difference or both strings end together.
  3511. The difference may lie on the null-terminator of one string. */
  3512. while (lhs[i] == rhs[i] && lhs[i] != 0) {
  3513. ++i;
  3514. }
  3515. return i;
  3516. }
  3517. static size_t cm_strverscmp_find_digits_begin(char const* s, size_t i)
  3518. {
  3519. /* Step back until we are not preceded by a digit. */
  3520. while (i > 0 && isdigit(s[i - 1])) {
  3521. --i;
  3522. }
  3523. return i;
  3524. }
  3525. static size_t cm_strverscmp_find_digits_end(char const* s, size_t i)
  3526. {
  3527. /* Step forward over digits. */
  3528. while (isdigit(s[i])) {
  3529. ++i;
  3530. }
  3531. return i;
  3532. }
  3533. static size_t cm_strverscmp_count_leading_zeros(char const* s, size_t b)
  3534. {
  3535. size_t i = b;
  3536. /* Step forward over zeros that are followed by another digit. */
  3537. while (s[i] == '0' && isdigit(s[i + 1])) {
  3538. ++i;
  3539. }
  3540. return i - b;
  3541. }
  3542. static int cm_strverscmp(char const* lhs, char const* rhs)
  3543. {
  3544. size_t const i = cm_strverscmp_find_first_difference_or_end(lhs, rhs);
  3545. if (lhs[i] != rhs[i]) {
  3546. /* The strings differ starting at 'i'. Check for a digit sequence. */
  3547. size_t const b = cm_strverscmp_find_digits_begin(lhs, i);
  3548. if (b != i || (isdigit(lhs[i]) && isdigit(rhs[i]))) {
  3549. /* A digit sequence starts at 'b', preceding or at 'i'. */
  3550. /* Look for leading zeros, implying a leading decimal point. */
  3551. size_t const lhs_zeros = cm_strverscmp_count_leading_zeros(lhs, b);
  3552. size_t const rhs_zeros = cm_strverscmp_count_leading_zeros(rhs, b);
  3553. if (lhs_zeros != rhs_zeros) {
  3554. /* The side with more leading zeros orders first. */
  3555. return rhs_zeros > lhs_zeros ? 1 : -1;
  3556. }
  3557. if (lhs_zeros == 0) {
  3558. /* No leading zeros; compare digit sequence lengths. */
  3559. size_t const lhs_end = cm_strverscmp_find_digits_end(lhs, i);
  3560. size_t const rhs_end = cm_strverscmp_find_digits_end(rhs, i);
  3561. if (lhs_end != rhs_end) {
  3562. /* The side with fewer digits orders first. */
  3563. return lhs_end > rhs_end ? 1 : -1;
  3564. }
  3565. }
  3566. }
  3567. }
  3568. /* Ordering was not decided by digit sequence lengths; compare bytes. */
  3569. return lhs[i] - rhs[i];
  3570. }
  3571. int cmSystemTools::strverscmp(std::string const& lhs, std::string const& rhs)
  3572. {
  3573. return cm_strverscmp(lhs.c_str(), rhs.c_str());
  3574. }
  3575. static cm::optional<bool> RemoveRPathELF(std::string const& file,
  3576. std::string* emsg, bool* removed)
  3577. {
  3578. if (removed) {
  3579. *removed = false;
  3580. }
  3581. int zeroCount = 0;
  3582. unsigned long zeroPosition[2] = { 0, 0 };
  3583. unsigned long zeroSize[2] = { 0, 0 };
  3584. unsigned long bytesBegin = 0;
  3585. std::vector<char> bytes;
  3586. {
  3587. // Parse the ELF binary.
  3588. cmELF elf(file.c_str());
  3589. if (!elf) {
  3590. return cm::nullopt; // Not a valid ELF file.
  3591. }
  3592. // Get the RPATH and RUNPATH entries from it and sort them by index
  3593. // in the dynamic section header.
  3594. int se_count = 0;
  3595. cmELF::StringEntry const* se[2] = { nullptr, nullptr };
  3596. if (cmELF::StringEntry const* se_rpath = elf.GetRPath()) {
  3597. se[se_count++] = se_rpath;
  3598. }
  3599. if (cmELF::StringEntry const* se_runpath = elf.GetRunPath()) {
  3600. se[se_count++] = se_runpath;
  3601. }
  3602. if (se_count == 0) {
  3603. // There is no RPATH or RUNPATH anyway.
  3604. return true;
  3605. }
  3606. if (se_count == 2 && se[1]->IndexInSection < se[0]->IndexInSection) {
  3607. std::swap(se[0], se[1]);
  3608. }
  3609. // Obtain a copy of the dynamic entries
  3610. cmELF::DynamicEntryList dentries = elf.GetDynamicEntries();
  3611. if (dentries.empty()) {
  3612. // This should happen only for invalid ELF files where a DT_NULL
  3613. // appears before the end of the table.
  3614. if (emsg) {
  3615. *emsg = "DYNAMIC section contains a DT_NULL before the end.";
  3616. }
  3617. return false;
  3618. }
  3619. // Save information about the string entries to be zeroed.
  3620. zeroCount = se_count;
  3621. for (int i = 0; i < se_count; ++i) {
  3622. zeroPosition[i] = se[i]->Position;
  3623. zeroSize[i] = se[i]->Size;
  3624. }
  3625. // Get size of one DYNAMIC entry
  3626. unsigned long const sizeof_dentry =
  3627. elf.GetDynamicEntryPosition(1) - elf.GetDynamicEntryPosition(0);
  3628. // Adjust the entry list as necessary to remove the run path
  3629. unsigned long entriesErased = 0;
  3630. for (auto it = dentries.begin(); it != dentries.end();) {
  3631. if (it->first == cmELF::TagRPath || it->first == cmELF::TagRunPath) {
  3632. it = dentries.erase(it);
  3633. entriesErased++;
  3634. continue;
  3635. }
  3636. if (it->first == cmELF::TagMipsRldMapRel && elf.IsMIPS()) {
  3637. // Background: debuggers need to know the "linker map" which contains
  3638. // the addresses each dynamic object is loaded at. Most arches use
  3639. // the DT_DEBUG tag which the dynamic linker writes to (directly) and
  3640. // contain the location of the linker map, however on MIPS the
  3641. // .dynamic section is always read-only so this is not possible. MIPS
  3642. // objects instead contain a DT_MIPS_RLD_MAP tag which contains the
  3643. // address where the dynamic linker will write to (an indirect
  3644. // version of DT_DEBUG). Since this doesn't work when using PIE, a
  3645. // relative equivalent was created - DT_MIPS_RLD_MAP_REL. Since this
  3646. // version contains a relative offset, moving it changes the
  3647. // calculated address. This may cause the dynamic linker to write
  3648. // into memory it should not be changing.
  3649. //
  3650. // To fix this, we adjust the value of DT_MIPS_RLD_MAP_REL here. If
  3651. // we move it up by n bytes, we add n bytes to the value of this tag.
  3652. it->second += entriesErased * sizeof_dentry;
  3653. }
  3654. it++;
  3655. }
  3656. // Encode new entries list
  3657. bytes = elf.EncodeDynamicEntries(dentries);
  3658. bytesBegin = elf.GetDynamicEntryPosition(0);
  3659. }
  3660. FileModeGuard file_mode_guard(file, emsg);
  3661. if (file_mode_guard.HasErrors()) {
  3662. return false;
  3663. }
  3664. // Open the file for update.
  3665. cmsys::ofstream f(file.c_str(),
  3666. std::ios::in | std::ios::out | std::ios::binary);
  3667. if (!f) {
  3668. if (emsg) {
  3669. *emsg = "Error opening file for update.";
  3670. }
  3671. return false;
  3672. }
  3673. // Write the new DYNAMIC table header.
  3674. if (!f.seekp(bytesBegin)) {
  3675. if (emsg) {
  3676. *emsg = "Error seeking to DYNAMIC table header for RPATH.";
  3677. }
  3678. return false;
  3679. }
  3680. if (!f.write(bytes.data(), bytes.size())) {
  3681. if (emsg) {
  3682. *emsg = "Error replacing DYNAMIC table header.";
  3683. }
  3684. return false;
  3685. }
  3686. // Fill the RPATH and RUNPATH strings with zero bytes.
  3687. for (int i = 0; i < zeroCount; ++i) {
  3688. if (!f.seekp(zeroPosition[i])) {
  3689. if (emsg) {
  3690. *emsg = "Error seeking to RPATH position.";
  3691. }
  3692. return false;
  3693. }
  3694. for (unsigned long j = 0; j < zeroSize[i]; ++j) {
  3695. f << '\0';
  3696. }
  3697. if (!f) {
  3698. if (emsg) {
  3699. *emsg = "Error writing the empty rpath string to the file.";
  3700. }
  3701. return false;
  3702. }
  3703. }
  3704. // Close the handle to allow further operations on the file
  3705. f.close();
  3706. if (!file_mode_guard.Restore(emsg)) {
  3707. return false;
  3708. }
  3709. // Everything was updated successfully.
  3710. if (removed) {
  3711. *removed = true;
  3712. }
  3713. return true;
  3714. }
  3715. static cm::optional<bool> RemoveRPathXCOFF(std::string const& file,
  3716. std::string* emsg, bool* removed)
  3717. {
  3718. if (removed) {
  3719. *removed = false;
  3720. }
  3721. #if !defined(CMake_USE_XCOFF_PARSER)
  3722. (void)file;
  3723. (void)emsg;
  3724. return cm::nullopt; // Cannot handle XCOFF files.
  3725. #else
  3726. bool rm = false;
  3727. FileModeGuard file_mode_guard(file, emsg);
  3728. if (file_mode_guard.HasErrors()) {
  3729. return false;
  3730. }
  3731. {
  3732. cmXCOFF xcoff(file.c_str(), cmXCOFF::Mode::ReadWrite);
  3733. if (!xcoff) {
  3734. return cm::nullopt; // Not a valid XCOFF file.
  3735. }
  3736. rm = xcoff.RemoveLibPath();
  3737. if (!xcoff) {
  3738. if (emsg) {
  3739. *emsg = xcoff.GetErrorMessage();
  3740. }
  3741. return false;
  3742. }
  3743. }
  3744. if (!file_mode_guard.Restore(emsg)) {
  3745. return false;
  3746. }
  3747. if (removed) {
  3748. *removed = rm;
  3749. }
  3750. return true;
  3751. #endif
  3752. }
  3753. bool cmSystemTools::RemoveRPath(std::string const& file, std::string* emsg,
  3754. bool* removed)
  3755. {
  3756. if (cm::optional<bool> result = RemoveRPathELF(file, emsg, removed)) {
  3757. return result.value();
  3758. }
  3759. if (cm::optional<bool> result = RemoveRPathXCOFF(file, emsg, removed)) {
  3760. return result.value();
  3761. }
  3762. // The file format is not recognized. Assume it has no RPATH.
  3763. return true;
  3764. }
  3765. bool cmSystemTools::CheckRPath(std::string const& file,
  3766. std::string const& newRPath)
  3767. {
  3768. // Parse the ELF binary.
  3769. cmELF elf(file.c_str());
  3770. if (elf) {
  3771. // Get the RPATH or RUNPATH entry from it.
  3772. cmELF::StringEntry const* se = elf.GetRPath();
  3773. if (!se) {
  3774. se = elf.GetRunPath();
  3775. }
  3776. // Make sure the current rpath contains the new rpath.
  3777. if (newRPath.empty()) {
  3778. if (!se) {
  3779. return true;
  3780. }
  3781. } else {
  3782. if (se &&
  3783. cmSystemToolsFindRPath(se->Value, newRPath) != std::string::npos) {
  3784. return true;
  3785. }
  3786. }
  3787. return false;
  3788. }
  3789. #if defined(CMake_USE_XCOFF_PARSER)
  3790. // Parse the XCOFF binary.
  3791. cmXCOFF xcoff(file.c_str());
  3792. if (xcoff) {
  3793. if (cm::optional<cm::string_view> libPath = xcoff.GetLibPath()) {
  3794. if (cmSystemToolsFindRPath(*libPath, newRPath) != std::string::npos) {
  3795. return true;
  3796. }
  3797. }
  3798. return false;
  3799. }
  3800. #endif
  3801. // The file format is not recognized. Assume it has no RPATH.
  3802. // Therefore we succeed if the new rpath is empty anyway.
  3803. return newRPath.empty();
  3804. }
  3805. cmsys::Status cmSystemTools::RepeatedRemoveDirectory(std::string const& dir)
  3806. {
  3807. #ifdef _WIN32
  3808. // Windows sometimes locks files temporarily so try a few times.
  3809. WindowsFileRetry retry = cmSystemTools::GetWindowsFileRetry();
  3810. cmsys::Status status;
  3811. unsigned int tries = 0;
  3812. while (!(status = cmSystemTools::RemoveADirectory(dir)) &&
  3813. ++tries < retry.Count) {
  3814. cmSystemTools::Delay(retry.Delay);
  3815. }
  3816. return status;
  3817. #else
  3818. return cmSystemTools::RemoveADirectory(dir);
  3819. #endif
  3820. }
  3821. std::string cmSystemTools::EncodeURL(std::string const& in, bool escapeSlashes)
  3822. {
  3823. std::string out;
  3824. for (char c : in) {
  3825. char hexCh[4] = { 0, 0, 0, 0 };
  3826. hexCh[0] = c;
  3827. switch (c) {
  3828. case '+':
  3829. case '?':
  3830. case '\\':
  3831. case '&':
  3832. case ' ':
  3833. case '=':
  3834. case '%':
  3835. snprintf(hexCh, sizeof(hexCh), "%%%02X", static_cast<unsigned int>(c));
  3836. break;
  3837. case '/':
  3838. if (escapeSlashes) {
  3839. strcpy(hexCh, "%2F");
  3840. }
  3841. break;
  3842. default:
  3843. break;
  3844. }
  3845. out.append(hexCh);
  3846. }
  3847. return out;
  3848. }
  3849. cm::optional<cmSystemTools::DirCase> cmSystemTools::GetDirCase(
  3850. std::string const& dir)
  3851. {
  3852. if (!cmSystemTools::FileIsDirectory(dir)) {
  3853. return cm::nullopt;
  3854. }
  3855. #if defined(_WIN32) || defined(__APPLE__)
  3856. return DirCase::Insensitive;
  3857. #elif defined(__linux__)
  3858. int fd = open(dir.c_str(), O_RDONLY);
  3859. if (fd == -1) {
  3860. // cannot open dir but it exists, assume dir is case sensitive.
  3861. return DirCase::Sensitive;
  3862. }
  3863. int attr = 0;
  3864. int ioctl_res = ioctl(fd, FS_IOC_GETFLAGS, &attr);
  3865. close(fd);
  3866. if (ioctl_res == -1) {
  3867. return DirCase::Sensitive;
  3868. }
  3869. // FS_CASEFOLD_FD from linux/fs.h, in Linux libc-dev 5.4+
  3870. // For compat with old libc-dev, define it here.
  3871. int const CMAKE_FS_CASEFOLD_FL = 0x40000000;
  3872. return (attr & CMAKE_FS_CASEFOLD_FL) != 0 ? DirCase::Insensitive
  3873. : DirCase::Sensitive;
  3874. #else
  3875. return DirCase::Sensitive;
  3876. #endif
  3877. }
  3878. cmsys::Status cmSystemTools::CreateSymlink(std::string const& origName,
  3879. std::string const& newName)
  3880. {
  3881. cmsys::Status status =
  3882. cmSystemTools::CreateSymlinkQuietly(origName, newName);
  3883. if (!status) {
  3884. cmSystemTools::Error(cmStrCat("failed to create symbolic link '", newName,
  3885. "': ", status.GetString()));
  3886. }
  3887. return status;
  3888. }
  3889. cmsys::Status cmSystemTools::CreateSymlinkQuietly(std::string const& origName,
  3890. std::string const& newName)
  3891. {
  3892. uv_fs_t req;
  3893. int flags = 0;
  3894. #if defined(_WIN32)
  3895. if (cmsys::SystemTools::FileIsDirectory(origName)) {
  3896. flags |= UV_FS_SYMLINK_DIR;
  3897. }
  3898. #endif
  3899. int err = uv_fs_symlink(nullptr, &req, origName.c_str(), newName.c_str(),
  3900. flags, nullptr);
  3901. cmsys::Status status;
  3902. if (err) {
  3903. #if defined(_WIN32)
  3904. status = cmsys::Status::Windows(uv_fs_get_system_error(&req));
  3905. #elif UV_VERSION_MAJOR > 1 || (UV_VERSION_MAJOR == 1 && UV_VERSION_MINOR >= 38)
  3906. status = cmsys::Status::POSIX(uv_fs_get_system_error(&req));
  3907. #else
  3908. status = cmsys::Status::POSIX(-err);
  3909. #endif
  3910. }
  3911. return status;
  3912. }
  3913. cmsys::Status cmSystemTools::CreateLink(std::string const& origName,
  3914. std::string const& newName)
  3915. {
  3916. cmsys::Status status = cmSystemTools::CreateLinkQuietly(origName, newName);
  3917. if (!status) {
  3918. cmSystemTools::Error(
  3919. cmStrCat("failed to create link '", newName, "': ", status.GetString()));
  3920. }
  3921. return status;
  3922. }
  3923. cmsys::Status cmSystemTools::CreateLinkQuietly(std::string const& origName,
  3924. std::string const& newName)
  3925. {
  3926. uv_fs_t req;
  3927. int err =
  3928. uv_fs_link(nullptr, &req, origName.c_str(), newName.c_str(), nullptr);
  3929. cmsys::Status status;
  3930. if (err) {
  3931. #if defined(_WIN32)
  3932. status = cmsys::Status::Windows(uv_fs_get_system_error(&req));
  3933. #elif UV_VERSION_MAJOR > 1 || (UV_VERSION_MAJOR == 1 && UV_VERSION_MINOR >= 38)
  3934. status = cmsys::Status::POSIX(uv_fs_get_system_error(&req));
  3935. #else
  3936. status = cmsys::Status::POSIX(-err);
  3937. #endif
  3938. }
  3939. return status;
  3940. }
  3941. cm::string_view cmSystemTools::GetSystemName()
  3942. {
  3943. #if defined(_WIN32)
  3944. return "Windows";
  3945. #elif defined(__MSYS__)
  3946. return "MSYS";
  3947. #elif defined(__CYGWIN__)
  3948. return "CYGWIN";
  3949. #elif defined(__ANDROID__)
  3950. return "Android";
  3951. #else
  3952. static struct utsname uts_name;
  3953. static bool initialized = false;
  3954. static cm::string_view systemName;
  3955. if (initialized) {
  3956. return systemName;
  3957. }
  3958. if (uname(&uts_name) >= 0) {
  3959. initialized = true;
  3960. systemName = uts_name.sysname;
  3961. if (cmIsOff(systemName)) {
  3962. systemName = "UnknownOS";
  3963. }
  3964. // fix for BSD/OS, remove the /
  3965. static cmsys::RegularExpression const bsdOsRegex("BSD.OS");
  3966. cmsys::RegularExpressionMatch match;
  3967. if (bsdOsRegex.find(uts_name.sysname, match)) {
  3968. systemName = "BSDOS";
  3969. }
  3970. return systemName;
  3971. }
  3972. return "";
  3973. #endif
  3974. }
  3975. char cmSystemTools::GetSystemPathlistSeparator()
  3976. {
  3977. #if defined(_WIN32)
  3978. return ';';
  3979. #else
  3980. return ':';
  3981. #endif
  3982. }