cmSystemTools.cxx 120 KB

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