cmSystemTools.cxx 108 KB

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