cmSystemTools.cxx 81 KB

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