cmSystemTools.cxx 113 KB

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