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. # include "cmCryptoHash.h"
  23. #endif
  24. #if defined(CMAKE_USE_ELF_PARSER)
  25. # include "cmELF.h"
  26. #endif
  27. #if defined(CMAKE_USE_MACH_PARSER)
  28. # include "cmMachO.h"
  29. #endif
  30. #include <algorithm>
  31. #include <cassert>
  32. #include <cctype>
  33. #include <cerrno>
  34. #include <cstdio>
  35. #include <cstdlib>
  36. #include <cstring>
  37. #include <ctime>
  38. #include <iostream>
  39. #include <sstream>
  40. #include <utility>
  41. #include <vector>
  42. #include <fcntl.h>
  43. #include "cmsys/Directory.hxx"
  44. #include "cmsys/Encoding.hxx"
  45. #include "cmsys/FStream.hxx"
  46. #include "cmsys/RegularExpression.hxx"
  47. #include "cmsys/System.h"
  48. #include "cmsys/Terminal.h"
  49. #if defined(_WIN32)
  50. # include <windows.h>
  51. // include wincrypt.h after windows.h
  52. # include <wincrypt.h>
  53. #else
  54. # include <unistd.h>
  55. # include <sys/time.h>
  56. #endif
  57. #if defined(_WIN32) && \
  58. (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__MINGW32__))
  59. # include <io.h>
  60. #endif
  61. #if defined(__APPLE__)
  62. # include <mach-o/dyld.h>
  63. #endif
  64. #ifdef __QNX__
  65. # include <malloc.h> /* for malloc/free on QNX */
  66. #endif
  67. namespace {
  68. cmSystemTools::InterruptCallback s_InterruptCallback;
  69. cmSystemTools::MessageCallback s_MessageCallback;
  70. cmSystemTools::OutputCallback s_StderrCallback;
  71. cmSystemTools::OutputCallback s_StdoutCallback;
  72. } // namespace
  73. #if !defined(HAVE_ENVIRON_NOT_REQUIRE_PROTOTYPE)
  74. // For GetEnvironmentVariables
  75. # if defined(_WIN32)
  76. extern __declspec(dllimport) char** environ;
  77. # else
  78. extern char** environ;
  79. # endif
  80. #endif
  81. #if !defined(CMAKE_BOOTSTRAP)
  82. static std::string cm_archive_entry_pathname(struct archive_entry* entry)
  83. {
  84. # if cmsys_STL_HAS_WSTRING
  85. return cmsys::Encoding::ToNarrow(archive_entry_pathname_w(entry));
  86. # else
  87. return archive_entry_pathname(entry);
  88. # endif
  89. }
  90. static int cm_archive_read_open_file(struct archive* a, const char* file,
  91. int block_size)
  92. {
  93. # if cmsys_STL_HAS_WSTRING
  94. std::wstring wfile = cmsys::Encoding::ToWide(file);
  95. return archive_read_open_filename_w(a, wfile.c_str(), block_size);
  96. # else
  97. return archive_read_open_filename(a, file, block_size);
  98. # endif
  99. }
  100. #endif
  101. #ifdef _WIN32
  102. #elif defined(__APPLE__)
  103. # include <crt_externs.h>
  104. # define environ (*_NSGetEnviron())
  105. #endif
  106. bool cmSystemTools::s_RunCommandHideConsole = false;
  107. bool cmSystemTools::s_DisableRunCommandOutput = false;
  108. bool cmSystemTools::s_ErrorOccured = false;
  109. bool cmSystemTools::s_FatalErrorOccured = false;
  110. bool cmSystemTools::s_ForceUnixPaths = false;
  111. // replace replace with with as many times as it shows up in source.
  112. // write the result into source.
  113. #if defined(_WIN32) && !defined(__CYGWIN__)
  114. void cmSystemTools::ExpandRegistryValues(std::string& source, KeyWOW64 view)
  115. {
  116. // Regular expression to match anything inside [...] that begins in HKEY.
  117. // Note that there is a special rule for regular expressions to match a
  118. // close square-bracket inside a list delimited by square brackets.
  119. // The "[^]]" part of this expression will match any character except
  120. // a close square-bracket. The ']' character must be the first in the
  121. // list of characters inside the [^...] block of the expression.
  122. cmsys::RegularExpression regEntry("\\[(HKEY[^]]*)\\]");
  123. // check for black line or comment
  124. while (regEntry.find(source)) {
  125. // the arguments are the second match
  126. std::string key = regEntry.match(1);
  127. std::string val;
  128. if (ReadRegistryValue(key.c_str(), val, view)) {
  129. std::string reg = cmStrCat('[', key, ']');
  130. cmSystemTools::ReplaceString(source, reg.c_str(), val.c_str());
  131. } else {
  132. std::string reg = cmStrCat('[', key, ']');
  133. cmSystemTools::ReplaceString(source, reg.c_str(), "/registry");
  134. }
  135. }
  136. }
  137. #else
  138. void cmSystemTools::ExpandRegistryValues(std::string& source,
  139. KeyWOW64 /*unused*/)
  140. {
  141. cmsys::RegularExpression regEntry("\\[(HKEY[^]]*)\\]");
  142. while (regEntry.find(source)) {
  143. // the arguments are the second match
  144. std::string key = regEntry.match(1);
  145. std::string reg = cmStrCat('[', key, ']');
  146. cmSystemTools::ReplaceString(source, reg.c_str(), "/registry");
  147. }
  148. }
  149. #endif
  150. std::string cmSystemTools::HelpFileName(cm::string_view str)
  151. {
  152. std::string name(str);
  153. cmSystemTools::ReplaceString(name, "<", "");
  154. cmSystemTools::ReplaceString(name, ">", "");
  155. return name;
  156. }
  157. void cmSystemTools::Error(const std::string& m)
  158. {
  159. std::string message = "CMake Error: " + m;
  160. cmSystemTools::s_ErrorOccured = true;
  161. cmSystemTools::Message(message, "Error");
  162. }
  163. void cmSystemTools::SetInterruptCallback(InterruptCallback f)
  164. {
  165. s_InterruptCallback = std::move(f);
  166. }
  167. bool cmSystemTools::GetInterruptFlag()
  168. {
  169. if (s_InterruptCallback) {
  170. return s_InterruptCallback();
  171. }
  172. return false;
  173. }
  174. void cmSystemTools::SetMessageCallback(MessageCallback f)
  175. {
  176. s_MessageCallback = std::move(f);
  177. }
  178. void cmSystemTools::SetStdoutCallback(OutputCallback f)
  179. {
  180. s_StdoutCallback = std::move(f);
  181. }
  182. void cmSystemTools::SetStderrCallback(OutputCallback f)
  183. {
  184. s_StderrCallback = std::move(f);
  185. }
  186. void cmSystemTools::Stderr(const std::string& s)
  187. {
  188. if (s_StderrCallback) {
  189. s_StderrCallback(s);
  190. } else {
  191. std::cerr << s << std::flush;
  192. }
  193. }
  194. void cmSystemTools::Stdout(const std::string& s)
  195. {
  196. if (s_StdoutCallback) {
  197. s_StdoutCallback(s);
  198. } else {
  199. std::cout << s << std::flush;
  200. }
  201. }
  202. void cmSystemTools::Message(const std::string& m, const char* title)
  203. {
  204. if (s_MessageCallback) {
  205. s_MessageCallback(m, title);
  206. } else {
  207. std::cerr << m << std::endl;
  208. }
  209. }
  210. void cmSystemTools::ReportLastSystemError(const char* msg)
  211. {
  212. std::string m =
  213. cmStrCat(msg, ": System Error: ", Superclass::GetLastSystemError());
  214. cmSystemTools::Error(m);
  215. }
  216. void cmSystemTools::ParseWindowsCommandLine(const char* command,
  217. std::vector<std::string>& args)
  218. {
  219. // See the MSDN document "Parsing C Command-Line Arguments" at
  220. // http://msdn2.microsoft.com/en-us/library/a1y7w461.aspx for rules
  221. // of parsing the windows command line.
  222. bool in_argument = false;
  223. bool in_quotes = false;
  224. int backslashes = 0;
  225. std::string arg;
  226. for (const char* c = command; *c; ++c) {
  227. if (*c == '\\') {
  228. ++backslashes;
  229. in_argument = true;
  230. } else if (*c == '"') {
  231. int backslash_pairs = backslashes >> 1;
  232. int backslash_escaped = backslashes & 1;
  233. arg.append(backslash_pairs, '\\');
  234. backslashes = 0;
  235. if (backslash_escaped) {
  236. /* An odd number of backslashes precede this quote.
  237. It is escaped. */
  238. arg.append(1, '"');
  239. } else {
  240. /* An even number of backslashes precede this quote.
  241. It is not escaped. */
  242. in_quotes = !in_quotes;
  243. }
  244. in_argument = true;
  245. } else {
  246. arg.append(backslashes, '\\');
  247. backslashes = 0;
  248. if (cmIsSpace(*c)) {
  249. if (in_quotes) {
  250. arg.append(1, *c);
  251. } else if (in_argument) {
  252. args.push_back(arg);
  253. arg.clear();
  254. in_argument = false;
  255. }
  256. } else {
  257. in_argument = true;
  258. arg.append(1, *c);
  259. }
  260. }
  261. }
  262. arg.append(backslashes, '\\');
  263. if (in_argument) {
  264. args.push_back(arg);
  265. }
  266. }
  267. class cmSystemToolsArgV
  268. {
  269. char** ArgV;
  270. public:
  271. cmSystemToolsArgV(char** argv)
  272. : ArgV(argv)
  273. {
  274. }
  275. ~cmSystemToolsArgV()
  276. {
  277. for (char** arg = this->ArgV; arg && *arg; ++arg) {
  278. free(*arg);
  279. }
  280. free(this->ArgV);
  281. }
  282. cmSystemToolsArgV(const cmSystemToolsArgV&) = delete;
  283. cmSystemToolsArgV& operator=(const cmSystemToolsArgV&) = delete;
  284. void Store(std::vector<std::string>& args) const
  285. {
  286. for (char** arg = this->ArgV; arg && *arg; ++arg) {
  287. args.emplace_back(*arg);
  288. }
  289. }
  290. };
  291. void cmSystemTools::ParseUnixCommandLine(const char* command,
  292. std::vector<std::string>& args)
  293. {
  294. // Invoke the underlying parser.
  295. cmSystemToolsArgV argv(cmsysSystem_Parse_CommandForUnix(command, 0));
  296. argv.Store(args);
  297. }
  298. std::vector<std::string> cmSystemTools::HandleResponseFile(
  299. std::vector<std::string>::const_iterator argBeg,
  300. std::vector<std::string>::const_iterator argEnd)
  301. {
  302. std::vector<std::string> arg_full;
  303. for (std::string const& arg : cmMakeRange(argBeg, argEnd)) {
  304. if (cmHasLiteralPrefix(arg, "@")) {
  305. cmsys::ifstream responseFile(arg.substr(1).c_str(), std::ios::in);
  306. if (!responseFile) {
  307. std::string error = cmStrCat("failed to open for reading (",
  308. cmSystemTools::GetLastSystemError(),
  309. "):\n ", cm::string_view(arg).substr(1));
  310. cmSystemTools::Error(error);
  311. } else {
  312. std::string line;
  313. cmSystemTools::GetLineFromStream(responseFile, line);
  314. std::vector<std::string> args2;
  315. #ifdef _WIN32
  316. cmSystemTools::ParseWindowsCommandLine(line.c_str(), args2);
  317. #else
  318. cmSystemTools::ParseUnixCommandLine(line.c_str(), args2);
  319. #endif
  320. cm::append(arg_full, args2);
  321. }
  322. } else {
  323. arg_full.push_back(arg);
  324. }
  325. }
  326. return arg_full;
  327. }
  328. std::vector<std::string> cmSystemTools::ParseArguments(const std::string& cmd)
  329. {
  330. std::vector<std::string> args;
  331. std::string arg;
  332. bool win_path = false;
  333. const char* command = cmd.c_str();
  334. if (command[0] && command[1] &&
  335. ((command[0] != '/' && command[1] == ':' && command[2] == '\\') ||
  336. (command[0] == '\"' && command[1] != '/' && command[2] == ':' &&
  337. command[3] == '\\') ||
  338. (command[0] == '\'' && command[1] != '/' && command[2] == ':' &&
  339. command[3] == '\\') ||
  340. (command[0] == '\\' && command[1] == '\\'))) {
  341. win_path = true;
  342. }
  343. // Split the command into an argv array.
  344. for (const char* c = command; *c;) {
  345. // Skip over whitespace.
  346. while (*c == ' ' || *c == '\t') {
  347. ++c;
  348. }
  349. arg.clear();
  350. if (*c == '"') {
  351. // Parse a quoted argument.
  352. ++c;
  353. while (*c && *c != '"') {
  354. arg.append(1, *c);
  355. ++c;
  356. }
  357. if (*c) {
  358. ++c;
  359. }
  360. args.push_back(arg);
  361. } else if (*c == '\'') {
  362. // Parse a quoted argument.
  363. ++c;
  364. while (*c && *c != '\'') {
  365. arg.append(1, *c);
  366. ++c;
  367. }
  368. if (*c) {
  369. ++c;
  370. }
  371. args.push_back(arg);
  372. } else if (*c) {
  373. // Parse an unquoted argument.
  374. while (*c && *c != ' ' && *c != '\t') {
  375. if (*c == '\\' && !win_path) {
  376. ++c;
  377. if (*c) {
  378. arg.append(1, *c);
  379. ++c;
  380. }
  381. } else {
  382. arg.append(1, *c);
  383. ++c;
  384. }
  385. }
  386. args.push_back(arg);
  387. }
  388. }
  389. return args;
  390. }
  391. bool cmSystemTools::SplitProgramFromArgs(std::string const& command,
  392. std::string& program,
  393. std::string& args)
  394. {
  395. const char* c = command.c_str();
  396. // Skip leading whitespace.
  397. while (isspace(static_cast<unsigned char>(*c))) {
  398. ++c;
  399. }
  400. // Parse one command-line element up to an unquoted space.
  401. bool in_escape = false;
  402. bool in_double = false;
  403. bool in_single = false;
  404. for (; *c; ++c) {
  405. if (in_single) {
  406. if (*c == '\'') {
  407. in_single = false;
  408. } else {
  409. program += *c;
  410. }
  411. } else if (in_escape) {
  412. in_escape = false;
  413. program += *c;
  414. } else if (*c == '\\') {
  415. in_escape = true;
  416. } else if (in_double) {
  417. if (*c == '"') {
  418. in_double = false;
  419. } else {
  420. program += *c;
  421. }
  422. } else if (*c == '"') {
  423. in_double = true;
  424. } else if (*c == '\'') {
  425. in_single = true;
  426. } else if (isspace(static_cast<unsigned char>(*c))) {
  427. break;
  428. } else {
  429. program += *c;
  430. }
  431. }
  432. // The remainder of the command line holds unparsed arguments.
  433. args = c;
  434. return !in_single && !in_escape && !in_double;
  435. }
  436. size_t cmSystemTools::CalculateCommandLineLengthLimit()
  437. {
  438. size_t sz =
  439. #ifdef _WIN32
  440. // There's a maximum of 65536 bytes and thus 32768 WCHARs on Windows
  441. // However, cmd.exe itself can only handle 8191 WCHARs and Ninja for
  442. // example uses it to spawn processes.
  443. size_t(8191);
  444. #elif defined(__linux)
  445. // MAX_ARG_STRLEN is the maximum length of a string permissible for
  446. // the execve() syscall on Linux. It's defined as (PAGE_SIZE * 32)
  447. // in Linux's binfmts.h
  448. static_cast<size_t>(sysconf(_SC_PAGESIZE) * 32);
  449. #else
  450. size_t(0);
  451. #endif
  452. #if defined(_SC_ARG_MAX)
  453. // ARG_MAX is the maximum size of the command and environment
  454. // that can be passed to the exec functions on UNIX.
  455. // The value in limits.h does not need to be present and may
  456. // depend upon runtime memory constraints, hence sysconf()
  457. // should be used to query it.
  458. long szArgMax = sysconf(_SC_ARG_MAX);
  459. // A return value of -1 signifies an undetermined limit, but
  460. // it does not imply an infinite limit, and thus is ignored.
  461. if (szArgMax != -1) {
  462. // We estimate the size of the environment block to be 1000.
  463. // This isn't accurate at all, but leaves some headroom.
  464. szArgMax = szArgMax < 1000 ? 0 : szArgMax - 1000;
  465. # if defined(_WIN32) || defined(__linux)
  466. sz = std::min(sz, static_cast<size_t>(szArgMax));
  467. # else
  468. sz = static_cast<size_t>(szArgMax);
  469. # endif
  470. }
  471. #endif
  472. return sz;
  473. }
  474. bool cmSystemTools::RunSingleCommand(std::vector<std::string> const& command,
  475. std::string* captureStdOut,
  476. std::string* captureStdErr, int* retVal,
  477. const char* dir, OutputOption outputflag,
  478. cmDuration timeout, Encoding encoding)
  479. {
  480. std::vector<const char*> argv;
  481. argv.reserve(command.size() + 1);
  482. for (std::string const& cmd : command) {
  483. argv.push_back(cmd.c_str());
  484. }
  485. argv.push_back(nullptr);
  486. cmsysProcess* cp = cmsysProcess_New();
  487. cmsysProcess_SetCommand(cp, argv.data());
  488. cmsysProcess_SetWorkingDirectory(cp, dir);
  489. if (cmSystemTools::GetRunCommandHideConsole()) {
  490. cmsysProcess_SetOption(cp, cmsysProcess_Option_HideWindow, 1);
  491. }
  492. if (outputflag == OUTPUT_PASSTHROUGH) {
  493. cmsysProcess_SetPipeShared(cp, cmsysProcess_Pipe_STDOUT, 1);
  494. cmsysProcess_SetPipeShared(cp, cmsysProcess_Pipe_STDERR, 1);
  495. captureStdOut = nullptr;
  496. captureStdErr = nullptr;
  497. } else if (outputflag == OUTPUT_MERGE ||
  498. (captureStdErr && captureStdErr == captureStdOut)) {
  499. cmsysProcess_SetOption(cp, cmsysProcess_Option_MergeOutput, 1);
  500. captureStdErr = nullptr;
  501. }
  502. assert(!captureStdErr || captureStdErr != captureStdOut);
  503. cmsysProcess_SetTimeout(cp, timeout.count());
  504. cmsysProcess_Execute(cp);
  505. std::vector<char> tempStdOut;
  506. std::vector<char> tempStdErr;
  507. char* data;
  508. int length;
  509. int pipe;
  510. cmProcessOutput processOutput(encoding);
  511. std::string strdata;
  512. if (outputflag != OUTPUT_PASSTHROUGH &&
  513. (captureStdOut || captureStdErr || outputflag != OUTPUT_NONE)) {
  514. while ((pipe = cmsysProcess_WaitForData(cp, &data, &length, nullptr)) >
  515. 0) {
  516. // Translate NULL characters in the output into valid text.
  517. for (int i = 0; i < length; ++i) {
  518. if (data[i] == '\0') {
  519. data[i] = ' ';
  520. }
  521. }
  522. if (pipe == cmsysProcess_Pipe_STDOUT) {
  523. if (outputflag != OUTPUT_NONE) {
  524. processOutput.DecodeText(data, length, strdata, 1);
  525. cmSystemTools::Stdout(strdata);
  526. }
  527. if (captureStdOut) {
  528. cm::append(tempStdOut, data, data + length);
  529. }
  530. } else if (pipe == cmsysProcess_Pipe_STDERR) {
  531. if (outputflag != OUTPUT_NONE) {
  532. processOutput.DecodeText(data, length, strdata, 2);
  533. cmSystemTools::Stderr(strdata);
  534. }
  535. if (captureStdErr) {
  536. cm::append(tempStdErr, data, data + length);
  537. }
  538. }
  539. }
  540. if (outputflag != OUTPUT_NONE) {
  541. processOutput.DecodeText(std::string(), strdata, 1);
  542. if (!strdata.empty()) {
  543. cmSystemTools::Stdout(strdata);
  544. }
  545. processOutput.DecodeText(std::string(), strdata, 2);
  546. if (!strdata.empty()) {
  547. cmSystemTools::Stderr(strdata);
  548. }
  549. }
  550. }
  551. cmsysProcess_WaitForExit(cp, nullptr);
  552. if (captureStdOut) {
  553. captureStdOut->assign(tempStdOut.begin(), tempStdOut.end());
  554. processOutput.DecodeText(*captureStdOut, *captureStdOut);
  555. }
  556. if (captureStdErr) {
  557. captureStdErr->assign(tempStdErr.begin(), tempStdErr.end());
  558. processOutput.DecodeText(*captureStdErr, *captureStdErr);
  559. }
  560. bool result = true;
  561. if (cmsysProcess_GetState(cp) == cmsysProcess_State_Exited) {
  562. if (retVal) {
  563. *retVal = cmsysProcess_GetExitValue(cp);
  564. } else {
  565. if (cmsysProcess_GetExitValue(cp) != 0) {
  566. result = false;
  567. }
  568. }
  569. } else if (cmsysProcess_GetState(cp) == cmsysProcess_State_Exception) {
  570. const char* exception_str = cmsysProcess_GetExceptionString(cp);
  571. if (outputflag != OUTPUT_NONE) {
  572. std::cerr << exception_str << std::endl;
  573. }
  574. if (captureStdErr) {
  575. captureStdErr->append(exception_str, strlen(exception_str));
  576. } else if (captureStdOut) {
  577. captureStdOut->append(exception_str, strlen(exception_str));
  578. }
  579. result = false;
  580. } else if (cmsysProcess_GetState(cp) == cmsysProcess_State_Error) {
  581. const char* error_str = cmsysProcess_GetErrorString(cp);
  582. if (outputflag != OUTPUT_NONE) {
  583. std::cerr << error_str << std::endl;
  584. }
  585. if (captureStdErr) {
  586. captureStdErr->append(error_str, strlen(error_str));
  587. } else if (captureStdOut) {
  588. captureStdOut->append(error_str, strlen(error_str));
  589. }
  590. result = false;
  591. } else if (cmsysProcess_GetState(cp) == cmsysProcess_State_Expired) {
  592. const char* error_str = "Process terminated due to timeout\n";
  593. if (outputflag != OUTPUT_NONE) {
  594. std::cerr << error_str << std::endl;
  595. }
  596. if (captureStdErr) {
  597. captureStdErr->append(error_str, strlen(error_str));
  598. }
  599. result = false;
  600. }
  601. cmsysProcess_Delete(cp);
  602. return result;
  603. }
  604. bool cmSystemTools::RunSingleCommand(const std::string& command,
  605. std::string* captureStdOut,
  606. std::string* captureStdErr, int* retVal,
  607. const char* dir, OutputOption outputflag,
  608. cmDuration timeout)
  609. {
  610. if (s_DisableRunCommandOutput) {
  611. outputflag = OUTPUT_NONE;
  612. }
  613. std::vector<std::string> args = cmSystemTools::ParseArguments(command);
  614. if (args.empty()) {
  615. return false;
  616. }
  617. return cmSystemTools::RunSingleCommand(args, captureStdOut, captureStdErr,
  618. retVal, dir, outputflag, timeout);
  619. }
  620. std::string cmSystemTools::PrintSingleCommand(
  621. std::vector<std::string> const& command)
  622. {
  623. if (command.empty()) {
  624. return std::string();
  625. }
  626. return cmWrap('"', command, '"', " ");
  627. }
  628. bool cmSystemTools::DoesFileExistWithExtensions(
  629. const std::string& name, const std::vector<std::string>& headerExts)
  630. {
  631. std::string hname;
  632. for (std::string const& headerExt : headerExts) {
  633. hname = cmStrCat(name, '.', headerExt);
  634. if (cmSystemTools::FileExists(hname)) {
  635. return true;
  636. }
  637. }
  638. return false;
  639. }
  640. std::string cmSystemTools::FileExistsInParentDirectories(
  641. const std::string& fname, const std::string& directory,
  642. const std::string& toplevel)
  643. {
  644. std::string file = fname;
  645. cmSystemTools::ConvertToUnixSlashes(file);
  646. std::string dir = directory;
  647. cmSystemTools::ConvertToUnixSlashes(dir);
  648. std::string prevDir;
  649. while (dir != prevDir) {
  650. std::string path = cmStrCat(dir, "/", file);
  651. if (cmSystemTools::FileExists(path)) {
  652. return path;
  653. }
  654. if (dir.size() < toplevel.size()) {
  655. break;
  656. }
  657. prevDir = dir;
  658. dir = cmSystemTools::GetParentDirectory(dir);
  659. }
  660. return "";
  661. }
  662. #ifdef _WIN32
  663. cmSystemTools::WindowsFileRetry cmSystemTools::GetWindowsFileRetry()
  664. {
  665. static WindowsFileRetry retry = { 0, 0 };
  666. if (!retry.Count) {
  667. unsigned int data[2] = { 0, 0 };
  668. HKEY const keys[2] = { HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE };
  669. wchar_t const* const values[2] = { L"FilesystemRetryCount",
  670. L"FilesystemRetryDelay" };
  671. for (int k = 0; k < 2; ++k) {
  672. HKEY hKey;
  673. if (RegOpenKeyExW(keys[k], L"Software\\Kitware\\CMake\\Config", 0,
  674. KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS) {
  675. for (int v = 0; v < 2; ++v) {
  676. DWORD dwData, dwType, dwSize = 4;
  677. if (!data[v] &&
  678. RegQueryValueExW(hKey, values[v], 0, &dwType, (BYTE*)&dwData,
  679. &dwSize) == ERROR_SUCCESS &&
  680. dwType == REG_DWORD && dwSize == 4) {
  681. data[v] = static_cast<unsigned int>(dwData);
  682. }
  683. }
  684. RegCloseKey(hKey);
  685. }
  686. }
  687. retry.Count = data[0] ? data[0] : 5;
  688. retry.Delay = data[1] ? data[1] : 500;
  689. }
  690. return retry;
  691. }
  692. #endif
  693. std::string cmSystemTools::GetRealPathResolvingWindowsSubst(
  694. const std::string& path, std::string* errorMessage)
  695. {
  696. #ifdef _WIN32
  697. // uv_fs_realpath uses Windows Vista API so fallback to kwsys if not found
  698. std::string resolved_path;
  699. uv_fs_t req;
  700. int err = uv_fs_realpath(NULL, &req, path.c_str(), NULL);
  701. if (!err) {
  702. resolved_path = std::string((char*)req.ptr);
  703. cmSystemTools::ConvertToUnixSlashes(resolved_path);
  704. // Normalize to upper-case drive letter as GetActualCaseForPath does.
  705. if (resolved_path.size() > 1 && resolved_path[1] == ':') {
  706. resolved_path[0] = toupper(resolved_path[0]);
  707. }
  708. } else if (err == UV_ENOSYS) {
  709. resolved_path = cmsys::SystemTools::GetRealPath(path, errorMessage);
  710. } else if (errorMessage) {
  711. LPSTR message = NULL;
  712. DWORD size = FormatMessageA(
  713. FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
  714. FORMAT_MESSAGE_IGNORE_INSERTS,
  715. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&message, 0,
  716. NULL);
  717. *errorMessage = std::string(message, size);
  718. LocalFree(message);
  719. resolved_path = "";
  720. } else {
  721. resolved_path = path;
  722. }
  723. return resolved_path;
  724. #else
  725. return cmsys::SystemTools::GetRealPath(path, errorMessage);
  726. #endif
  727. }
  728. void cmSystemTools::InitializeLibUV()
  729. {
  730. #if defined(_WIN32)
  731. // Perform libuv one-time initialization now, and then un-do its
  732. // global _fmode setting so that using libuv does not change the
  733. // default file text/binary mode. See libuv issue 840.
  734. uv_loop_close(uv_default_loop());
  735. # ifdef _MSC_VER
  736. _set_fmode(_O_TEXT);
  737. # else
  738. _fmode = _O_TEXT;
  739. # endif
  740. // Replace libuv's report handler with our own to suppress popups.
  741. cmSystemTools::EnableMSVCDebugHook();
  742. #endif
  743. }
  744. bool cmSystemTools::RenameFile(const std::string& oldname,
  745. const std::string& newname)
  746. {
  747. #ifdef _WIN32
  748. # ifndef INVALID_FILE_ATTRIBUTES
  749. # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
  750. # endif
  751. /* Windows MoveFileEx may not replace read-only or in-use files. If it
  752. fails then remove the read-only attribute from any existing destination.
  753. Try multiple times since we may be racing against another process
  754. creating/opening the destination file just before our MoveFileEx. */
  755. WindowsFileRetry retry = cmSystemTools::GetWindowsFileRetry();
  756. while (
  757. !MoveFileExW(SystemTools::ConvertToWindowsExtendedPath(oldname).c_str(),
  758. SystemTools::ConvertToWindowsExtendedPath(newname).c_str(),
  759. MOVEFILE_REPLACE_EXISTING) &&
  760. --retry.Count) {
  761. DWORD last_error = GetLastError();
  762. // Try again only if failure was due to access/sharing permissions.
  763. if (last_error != ERROR_ACCESS_DENIED &&
  764. last_error != ERROR_SHARING_VIOLATION) {
  765. return false;
  766. }
  767. DWORD attrs = GetFileAttributesW(
  768. SystemTools::ConvertToWindowsExtendedPath(newname).c_str());
  769. if ((attrs != INVALID_FILE_ATTRIBUTES) &&
  770. (attrs & FILE_ATTRIBUTE_READONLY)) {
  771. // Remove the read-only attribute from the destination file.
  772. SetFileAttributesW(
  773. SystemTools::ConvertToWindowsExtendedPath(newname).c_str(),
  774. attrs & ~FILE_ATTRIBUTE_READONLY);
  775. } else {
  776. // The file may be temporarily in use so wait a bit.
  777. cmSystemTools::Delay(retry.Delay);
  778. }
  779. }
  780. return retry.Count > 0;
  781. #else
  782. /* On UNIX we have an OS-provided call to do this atomically. */
  783. return rename(oldname.c_str(), newname.c_str()) == 0;
  784. #endif
  785. }
  786. void cmSystemTools::MoveFileIfDifferent(const std::string& source,
  787. const std::string& destination)
  788. {
  789. if (FilesDiffer(source, destination)) {
  790. if (RenameFile(source, destination)) {
  791. return;
  792. }
  793. CopyFileAlways(source, destination);
  794. }
  795. RemoveFile(source);
  796. }
  797. std::string cmSystemTools::ComputeFileHash(const std::string& source,
  798. cmCryptoHash::Algo algo)
  799. {
  800. #if !defined(CMAKE_BOOTSTRAP)
  801. cmCryptoHash hash(algo);
  802. return hash.HashFile(source);
  803. #else
  804. (void)source;
  805. cmSystemTools::Message("hashsum not supported in bootstrapping mode",
  806. "Error");
  807. return std::string();
  808. #endif
  809. }
  810. std::string cmSystemTools::ComputeStringMD5(const std::string& input)
  811. {
  812. #if !defined(CMAKE_BOOTSTRAP)
  813. cmCryptoHash md5(cmCryptoHash::AlgoMD5);
  814. return md5.HashString(input);
  815. #else
  816. (void)input;
  817. cmSystemTools::Message("md5sum not supported in bootstrapping mode",
  818. "Error");
  819. return "";
  820. #endif
  821. }
  822. std::string cmSystemTools::ComputeCertificateThumbprint(
  823. const std::string& source)
  824. {
  825. std::string thumbprint;
  826. #if !defined(CMAKE_BOOTSTRAP) && defined(_WIN32)
  827. BYTE* certData = NULL;
  828. CRYPT_INTEGER_BLOB cryptBlob;
  829. HCERTSTORE certStore = NULL;
  830. PCCERT_CONTEXT certContext = NULL;
  831. HANDLE certFile = CreateFileW(
  832. cmsys::Encoding::ToWide(source.c_str()).c_str(), GENERIC_READ,
  833. FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  834. if (certFile != INVALID_HANDLE_VALUE && certFile != NULL) {
  835. DWORD fileSize = GetFileSize(certFile, NULL);
  836. if (fileSize != INVALID_FILE_SIZE) {
  837. certData = new BYTE[fileSize];
  838. if (certData != NULL) {
  839. DWORD dwRead = 0;
  840. if (ReadFile(certFile, certData, fileSize, &dwRead, NULL)) {
  841. cryptBlob.cbData = fileSize;
  842. cryptBlob.pbData = certData;
  843. // Verify that this is a valid cert
  844. if (PFXIsPFXBlob(&cryptBlob)) {
  845. // Open the certificate as a store
  846. certStore = PFXImportCertStore(&cryptBlob, NULL, CRYPT_EXPORTABLE);
  847. if (certStore != NULL) {
  848. // There should only be 1 cert.
  849. certContext =
  850. CertEnumCertificatesInStore(certStore, certContext);
  851. if (certContext != NULL) {
  852. // The hash is 20 bytes
  853. BYTE hashData[20];
  854. DWORD hashLength = 20;
  855. // Buffer to print the hash. Each byte takes 2 chars +
  856. // terminating character
  857. char hashPrint[41];
  858. char* pHashPrint = hashPrint;
  859. // Get the hash property from the certificate
  860. if (CertGetCertificateContextProperty(
  861. certContext, CERT_HASH_PROP_ID, hashData, &hashLength)) {
  862. for (DWORD i = 0; i < hashLength; i++) {
  863. // Convert each byte to hexadecimal
  864. sprintf(pHashPrint, "%02X", hashData[i]);
  865. pHashPrint += 2;
  866. }
  867. *pHashPrint = '\0';
  868. thumbprint = hashPrint;
  869. }
  870. CertFreeCertificateContext(certContext);
  871. }
  872. CertCloseStore(certStore, 0);
  873. }
  874. }
  875. }
  876. delete[] certData;
  877. }
  878. }
  879. CloseHandle(certFile);
  880. }
  881. #else
  882. (void)source;
  883. cmSystemTools::Message("ComputeCertificateThumbprint is not implemented",
  884. "Error");
  885. #endif
  886. return thumbprint;
  887. }
  888. void cmSystemTools::Glob(const std::string& directory,
  889. const std::string& regexp,
  890. std::vector<std::string>& files)
  891. {
  892. cmsys::Directory d;
  893. cmsys::RegularExpression reg(regexp.c_str());
  894. if (d.Load(directory)) {
  895. size_t numf;
  896. unsigned int i;
  897. numf = d.GetNumberOfFiles();
  898. for (i = 0; i < numf; i++) {
  899. std::string fname = d.GetFile(i);
  900. if (reg.find(fname)) {
  901. files.push_back(std::move(fname));
  902. }
  903. }
  904. }
  905. }
  906. void cmSystemTools::GlobDirs(const std::string& path,
  907. std::vector<std::string>& files)
  908. {
  909. std::string::size_type pos = path.find("/*");
  910. if (pos == std::string::npos) {
  911. files.push_back(path);
  912. return;
  913. }
  914. std::string startPath = path.substr(0, pos);
  915. std::string finishPath = path.substr(pos + 2);
  916. cmsys::Directory d;
  917. if (d.Load(startPath)) {
  918. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i) {
  919. if ((std::string(d.GetFile(i)) != ".") &&
  920. (std::string(d.GetFile(i)) != "..")) {
  921. std::string fname = cmStrCat(startPath, '/', d.GetFile(i));
  922. if (cmSystemTools::FileIsDirectory(fname)) {
  923. fname += finishPath;
  924. cmSystemTools::GlobDirs(fname, files);
  925. }
  926. }
  927. }
  928. }
  929. }
  930. bool cmSystemTools::SimpleGlob(const std::string& glob,
  931. std::vector<std::string>& files,
  932. int type /* = 0 */)
  933. {
  934. files.clear();
  935. if (glob.back() != '*') {
  936. return false;
  937. }
  938. std::string path = cmSystemTools::GetFilenamePath(glob);
  939. std::string ppath = cmSystemTools::GetFilenameName(glob);
  940. ppath = ppath.substr(0, ppath.size() - 1);
  941. if (path.empty()) {
  942. path = "/";
  943. }
  944. bool res = false;
  945. cmsys::Directory d;
  946. if (d.Load(path)) {
  947. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i) {
  948. if ((std::string(d.GetFile(i)) != ".") &&
  949. (std::string(d.GetFile(i)) != "..")) {
  950. std::string fname = path;
  951. if (path.back() != '/') {
  952. fname += "/";
  953. }
  954. fname += d.GetFile(i);
  955. std::string sfname = d.GetFile(i);
  956. if (type > 0 && cmSystemTools::FileIsDirectory(fname)) {
  957. continue;
  958. }
  959. if (type < 0 && !cmSystemTools::FileIsDirectory(fname)) {
  960. continue;
  961. }
  962. if (sfname.size() >= ppath.size() &&
  963. sfname.substr(0, ppath.size()) == 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. }