cmSystemTools.cxx 109 KB

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