cmSystemTools.cxx 81 KB

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