cmSystemTools.cxx 87 KB

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