cmSystemTools.cxx 84 KB

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