cmSystemTools.cxx 81 KB

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