cmSystemTools.cxx 99 KB

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