cmSystemTools.cxx 126 KB

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