cmSystemTools.cxx 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971
  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. std::string cmSystemTools::ConvertToRunCommandPath(const std::string& path)
  1136. {
  1137. #if defined(_WIN32) && !defined(__CYGWIN__)
  1138. return cmSystemTools::ConvertToWindowsOutputPath(path);
  1139. #else
  1140. return cmSystemTools::ConvertToUnixOutputPath(path);
  1141. #endif
  1142. }
  1143. // compute the relative path from here to there
  1144. std::string cmSystemTools::RelativePath(std::string const& local,
  1145. std::string const& remote)
  1146. {
  1147. if (!cmSystemTools::FileIsFullPath(local)) {
  1148. cmSystemTools::Error("RelativePath must be passed a full path to local: " +
  1149. local);
  1150. }
  1151. if (!cmSystemTools::FileIsFullPath(remote)) {
  1152. cmSystemTools::Error(
  1153. "RelativePath must be passed a full path to remote: " + remote);
  1154. }
  1155. return cmsys::SystemTools::RelativePath(local, remote);
  1156. }
  1157. std::string cmSystemTools::ForceToRelativePath(std::string const& local_path,
  1158. std::string const& remote_path)
  1159. {
  1160. // The paths should never be quoted.
  1161. assert(local_path.front() != '\"');
  1162. assert(remote_path.front() != '\"');
  1163. // The local path should never have a trailing slash except if it is just the
  1164. // bare root directory
  1165. assert(local_path.empty() || local_path.back() != '/' ||
  1166. local_path.size() == 1 ||
  1167. (local_path.size() == 3 && local_path[1] == ':' &&
  1168. ((local_path[0] >= 'A' && local_path[0] <= 'Z') ||
  1169. (local_path[0] >= 'a' && local_path[0] <= 'z'))));
  1170. // If the path is already relative then just return the path.
  1171. if (!cmSystemTools::FileIsFullPath(remote_path)) {
  1172. return remote_path;
  1173. }
  1174. // Identify the longest shared path component between the remote
  1175. // path and the local path.
  1176. std::vector<std::string> local;
  1177. cmSystemTools::SplitPath(local_path, local);
  1178. std::vector<std::string> remote;
  1179. cmSystemTools::SplitPath(remote_path, remote);
  1180. unsigned int common = 0;
  1181. while (common < remote.size() && common < local.size() &&
  1182. cmSystemTools::ComparePath(remote[common], local[common])) {
  1183. ++common;
  1184. }
  1185. // If no part of the path is in common then return the full path.
  1186. if (common == 0) {
  1187. return remote_path;
  1188. }
  1189. // If the entire path is in common then just return a ".".
  1190. if (common == remote.size() && common == local.size()) {
  1191. return ".";
  1192. }
  1193. // If the entire path is in common except for a trailing slash then
  1194. // just return a "./".
  1195. if (common + 1 == remote.size() && remote[common].empty() &&
  1196. common == local.size()) {
  1197. return "./";
  1198. }
  1199. // Construct the relative path.
  1200. std::string relative;
  1201. // First add enough ../ to get up to the level of the shared portion
  1202. // of the path. Leave off the trailing slash. Note that the last
  1203. // component of local will never be empty because local should never
  1204. // have a trailing slash.
  1205. for (unsigned int i = common; i < local.size(); ++i) {
  1206. relative += "..";
  1207. if (i < local.size() - 1) {
  1208. relative += "/";
  1209. }
  1210. }
  1211. // Now add the portion of the destination path that is not included
  1212. // in the shared portion of the path. Add a slash the first time
  1213. // only if there was already something in the path. If there was a
  1214. // trailing slash in the input then the last iteration of the loop
  1215. // will add a slash followed by an empty string which will preserve
  1216. // the trailing slash in the output.
  1217. if (!relative.empty() && !remote.empty()) {
  1218. relative += "/";
  1219. }
  1220. relative += cmJoin(cmMakeRange(remote).advance(common), "/");
  1221. // Finally return the path.
  1222. return relative;
  1223. }
  1224. #ifndef CMAKE_BOOTSTRAP
  1225. bool cmSystemTools::UnsetEnv(const char* value)
  1226. {
  1227. # if !defined(HAVE_UNSETENV)
  1228. std::string var = cmStrCat(value, '=');
  1229. return cmSystemTools::PutEnv(var);
  1230. # else
  1231. unsetenv(value);
  1232. return true;
  1233. # endif
  1234. }
  1235. std::vector<std::string> cmSystemTools::GetEnvironmentVariables()
  1236. {
  1237. std::vector<std::string> env;
  1238. int cc;
  1239. for (cc = 0; environ[cc]; ++cc) {
  1240. env.emplace_back(environ[cc]);
  1241. }
  1242. return env;
  1243. }
  1244. void cmSystemTools::AppendEnv(std::vector<std::string> const& env)
  1245. {
  1246. for (std::string const& eit : env) {
  1247. cmSystemTools::PutEnv(eit);
  1248. }
  1249. }
  1250. cmSystemTools::SaveRestoreEnvironment::SaveRestoreEnvironment()
  1251. {
  1252. this->Env = cmSystemTools::GetEnvironmentVariables();
  1253. }
  1254. cmSystemTools::SaveRestoreEnvironment::~SaveRestoreEnvironment()
  1255. {
  1256. // First clear everything in the current environment:
  1257. std::vector<std::string> currentEnv = GetEnvironmentVariables();
  1258. for (std::string var : currentEnv) {
  1259. std::string::size_type pos = var.find('=');
  1260. if (pos != std::string::npos) {
  1261. var = var.substr(0, pos);
  1262. }
  1263. cmSystemTools::UnsetEnv(var.c_str());
  1264. }
  1265. // Then put back each entry from the original environment:
  1266. cmSystemTools::AppendEnv(this->Env);
  1267. }
  1268. #endif
  1269. void cmSystemTools::EnableVSConsoleOutput()
  1270. {
  1271. #ifdef _WIN32
  1272. // Visual Studio tools like devenv may not
  1273. // display output to the console unless this environment variable is
  1274. // set. We need it to capture the output of these build tools.
  1275. // Note for future work that one could pass "/out \\.\pipe\NAME" to
  1276. // either of these executables where NAME is created with
  1277. // CreateNamedPipe. This would bypass the internal buffering of the
  1278. // output and allow it to be captured on the fly.
  1279. cmSystemTools::PutEnv("vsconsoleoutput=1");
  1280. # ifndef CMAKE_BOOTSTRAP
  1281. // VS sets an environment variable to tell MS tools like "cl" to report
  1282. // output through a backdoor pipe instead of stdout/stderr. Unset the
  1283. // environment variable to close this backdoor for any path of process
  1284. // invocations that passes through CMake so we can capture the output.
  1285. cmSystemTools::UnsetEnv("VS_UNICODE_OUTPUT");
  1286. # endif
  1287. #endif
  1288. }
  1289. bool cmSystemTools::IsPathToFramework(const std::string& path)
  1290. {
  1291. return (cmSystemTools::FileIsFullPath(path) &&
  1292. cmHasLiteralSuffix(path, ".framework"));
  1293. }
  1294. bool cmSystemTools::CreateTar(const std::string& outFileName,
  1295. const std::vector<std::string>& files,
  1296. cmTarCompression compressType, bool verbose,
  1297. std::string const& mtime,
  1298. std::string const& format, int compressionLevel)
  1299. {
  1300. #if !defined(CMAKE_BOOTSTRAP)
  1301. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1302. cmsys::ofstream fout(outFileName.c_str(), std::ios::out | std::ios::binary);
  1303. if (!fout) {
  1304. std::string e = cmStrCat("Cannot open output file \"", outFileName,
  1305. "\": ", cmSystemTools::GetLastSystemError());
  1306. cmSystemTools::Error(e);
  1307. return false;
  1308. }
  1309. cmArchiveWrite::Compress compress = cmArchiveWrite::CompressNone;
  1310. switch (compressType) {
  1311. case TarCompressGZip:
  1312. compress = cmArchiveWrite::CompressGZip;
  1313. break;
  1314. case TarCompressBZip2:
  1315. compress = cmArchiveWrite::CompressBZip2;
  1316. break;
  1317. case TarCompressXZ:
  1318. compress = cmArchiveWrite::CompressXZ;
  1319. break;
  1320. case TarCompressZstd:
  1321. compress = cmArchiveWrite::CompressZstd;
  1322. break;
  1323. case TarCompressNone:
  1324. compress = cmArchiveWrite::CompressNone;
  1325. break;
  1326. }
  1327. cmArchiveWrite a(fout, compress, format.empty() ? "paxr" : format,
  1328. compressionLevel);
  1329. a.Open();
  1330. a.SetMTime(mtime);
  1331. a.SetVerbose(verbose);
  1332. bool tarCreatedSuccessfully = true;
  1333. for (auto path : files) {
  1334. if (cmSystemTools::FileIsFullPath(path)) {
  1335. // Get the relative path to the file.
  1336. path = cmSystemTools::RelativePath(cwd, path);
  1337. }
  1338. if (!a.Add(path)) {
  1339. cmSystemTools::Error(a.GetError());
  1340. tarCreatedSuccessfully = false;
  1341. }
  1342. }
  1343. return tarCreatedSuccessfully;
  1344. #else
  1345. (void)outFileName;
  1346. (void)files;
  1347. (void)verbose;
  1348. return false;
  1349. #endif
  1350. }
  1351. #if !defined(CMAKE_BOOTSTRAP)
  1352. namespace {
  1353. # define BSDTAR_FILESIZE_PRINTF "%lu"
  1354. # define BSDTAR_FILESIZE_TYPE unsigned long
  1355. void list_item_verbose(FILE* out, struct archive_entry* entry)
  1356. {
  1357. char tmp[100];
  1358. size_t w;
  1359. const char* p;
  1360. const char* fmt;
  1361. time_t tim;
  1362. static time_t now;
  1363. size_t u_width = 6;
  1364. size_t gs_width = 13;
  1365. /*
  1366. * We avoid collecting the entire list in memory at once by
  1367. * listing things as we see them. However, that also means we can't
  1368. * just pre-compute the field widths. Instead, we start with guesses
  1369. * and just widen them as necessary. These numbers are completely
  1370. * arbitrary.
  1371. */
  1372. if (!now) {
  1373. time(&now);
  1374. }
  1375. fprintf(out, "%s %d ", archive_entry_strmode(entry),
  1376. archive_entry_nlink(entry));
  1377. /* Use uname if it's present, else uid. */
  1378. p = archive_entry_uname(entry);
  1379. if ((p == nullptr) || (*p == '\0')) {
  1380. sprintf(tmp, "%lu ", static_cast<unsigned long>(archive_entry_uid(entry)));
  1381. p = tmp;
  1382. }
  1383. w = strlen(p);
  1384. if (w > u_width) {
  1385. u_width = w;
  1386. }
  1387. fprintf(out, "%-*s ", static_cast<int>(u_width), p);
  1388. /* Use gname if it's present, else gid. */
  1389. p = archive_entry_gname(entry);
  1390. if (p != nullptr && p[0] != '\0') {
  1391. fprintf(out, "%s", p);
  1392. w = strlen(p);
  1393. } else {
  1394. sprintf(tmp, "%lu", static_cast<unsigned long>(archive_entry_gid(entry)));
  1395. w = strlen(tmp);
  1396. fprintf(out, "%s", tmp);
  1397. }
  1398. /*
  1399. * Print device number or file size, right-aligned so as to make
  1400. * total width of group and devnum/filesize fields be gs_width.
  1401. * If gs_width is too small, grow it.
  1402. */
  1403. if (archive_entry_filetype(entry) == AE_IFCHR ||
  1404. archive_entry_filetype(entry) == AE_IFBLK) {
  1405. unsigned long rdevmajor = archive_entry_rdevmajor(entry);
  1406. unsigned long rdevminor = archive_entry_rdevminor(entry);
  1407. sprintf(tmp, "%lu,%lu", rdevmajor, rdevminor);
  1408. } else {
  1409. /*
  1410. * Note the use of platform-dependent macros to format
  1411. * the filesize here. We need the format string and the
  1412. * corresponding type for the cast.
  1413. */
  1414. sprintf(tmp, BSDTAR_FILESIZE_PRINTF,
  1415. static_cast<BSDTAR_FILESIZE_TYPE>(archive_entry_size(entry)));
  1416. }
  1417. if (w + strlen(tmp) >= gs_width) {
  1418. gs_width = w + strlen(tmp) + 1;
  1419. }
  1420. fprintf(out, "%*s", static_cast<int>(gs_width - w), tmp);
  1421. /* Format the time using 'ls -l' conventions. */
  1422. tim = archive_entry_mtime(entry);
  1423. # define HALF_YEAR ((time_t)365 * 86400 / 2)
  1424. # if defined(_WIN32) && !defined(__CYGWIN__)
  1425. /* Windows' strftime function does not support %e format. */
  1426. # define DAY_FMT "%d"
  1427. # else
  1428. # define DAY_FMT "%e" /* Day number without leading zeros */
  1429. # endif
  1430. if (tim < now - HALF_YEAR || tim > now + HALF_YEAR) {
  1431. fmt = DAY_FMT " %b %Y";
  1432. } else {
  1433. fmt = DAY_FMT " %b %H:%M";
  1434. }
  1435. strftime(tmp, sizeof(tmp), fmt, localtime(&tim));
  1436. fprintf(out, " %s ", tmp);
  1437. fprintf(out, "%s", cm_archive_entry_pathname(entry).c_str());
  1438. /* Extra information for links. */
  1439. if (archive_entry_hardlink(entry)) /* Hard link */
  1440. {
  1441. fprintf(out, " link to %s", archive_entry_hardlink(entry));
  1442. } else if (archive_entry_symlink(entry)) /* Symbolic link */
  1443. {
  1444. fprintf(out, " -> %s", archive_entry_symlink(entry));
  1445. }
  1446. fflush(out);
  1447. }
  1448. void ArchiveError(const char* m1, struct archive* a)
  1449. {
  1450. std::string message(m1);
  1451. const char* m2 = archive_error_string(a);
  1452. if (m2) {
  1453. message += m2;
  1454. }
  1455. cmSystemTools::Error(message);
  1456. }
  1457. bool la_diagnostic(struct archive* ar, __LA_SSIZE_T r)
  1458. {
  1459. // See archive.h definition of ARCHIVE_OK for return values.
  1460. if (r >= ARCHIVE_OK) {
  1461. return true;
  1462. }
  1463. if (r >= ARCHIVE_WARN) {
  1464. const char* warn = archive_error_string(ar);
  1465. if (!warn) {
  1466. warn = "unknown warning";
  1467. }
  1468. std::cerr << "cmake -E tar: warning: " << warn << '\n';
  1469. return true;
  1470. }
  1471. // Error.
  1472. const char* err = archive_error_string(ar);
  1473. if (!err) {
  1474. err = "unknown error";
  1475. }
  1476. std::cerr << "cmake -E tar: error: " << err << '\n';
  1477. return false;
  1478. }
  1479. // Return 'true' on success
  1480. bool copy_data(struct archive* ar, struct archive* aw)
  1481. {
  1482. long r;
  1483. const void* buff;
  1484. size_t size;
  1485. # if defined(ARCHIVE_VERSION_NUMBER) && ARCHIVE_VERSION_NUMBER >= 3000000
  1486. __LA_INT64_T offset;
  1487. # else
  1488. off_t offset;
  1489. # endif
  1490. for (;;) {
  1491. // See archive.h definition of ARCHIVE_OK for return values.
  1492. r = archive_read_data_block(ar, &buff, &size, &offset);
  1493. if (r == ARCHIVE_EOF) {
  1494. return true;
  1495. }
  1496. if (!la_diagnostic(ar, r)) {
  1497. return false;
  1498. }
  1499. // See archive.h definition of ARCHIVE_OK for return values.
  1500. __LA_SSIZE_T const w = archive_write_data_block(aw, buff, size, offset);
  1501. if (!la_diagnostic(ar, w)) {
  1502. return false;
  1503. }
  1504. }
  1505. # if !defined(__clang__) && !defined(__HP_aCC)
  1506. return false; /* this should not happen but it quiets some compilers */
  1507. # endif
  1508. }
  1509. bool extract_tar(const std::string& outFileName,
  1510. const std::vector<std::string>& files, bool verbose,
  1511. bool extract)
  1512. {
  1513. cmLocaleRAII localeRAII;
  1514. static_cast<void>(localeRAII);
  1515. struct archive* a = archive_read_new();
  1516. struct archive* ext = archive_write_disk_new();
  1517. archive_read_support_filter_all(a);
  1518. archive_read_support_format_all(a);
  1519. struct archive_entry* entry;
  1520. struct archive* matching = archive_match_new();
  1521. if (matching == nullptr) {
  1522. cmSystemTools::Error("Out of memory");
  1523. return false;
  1524. }
  1525. for (const auto& filename : files) {
  1526. if (archive_match_include_pattern(matching, filename.c_str()) !=
  1527. ARCHIVE_OK) {
  1528. cmSystemTools::Error("Failed to add to inclusion list: " + filename);
  1529. return false;
  1530. }
  1531. }
  1532. int r = cm_archive_read_open_file(a, outFileName.c_str(), 10240);
  1533. if (r) {
  1534. ArchiveError("Problem with archive_read_open_file(): ", a);
  1535. archive_write_free(ext);
  1536. archive_read_close(a);
  1537. return false;
  1538. }
  1539. for (;;) {
  1540. r = archive_read_next_header(a, &entry);
  1541. if (r == ARCHIVE_EOF) {
  1542. break;
  1543. }
  1544. if (r != ARCHIVE_OK) {
  1545. ArchiveError("Problem with archive_read_next_header(): ", a);
  1546. break;
  1547. }
  1548. if (archive_match_excluded(matching, entry)) {
  1549. continue;
  1550. }
  1551. if (verbose) {
  1552. if (extract) {
  1553. cmSystemTools::Stdout("x ");
  1554. cmSystemTools::Stdout(cm_archive_entry_pathname(entry));
  1555. } else {
  1556. list_item_verbose(stdout, entry);
  1557. }
  1558. cmSystemTools::Stdout("\n");
  1559. } else if (!extract) {
  1560. cmSystemTools::Stdout(cm_archive_entry_pathname(entry));
  1561. cmSystemTools::Stdout("\n");
  1562. }
  1563. if (extract) {
  1564. r = archive_write_disk_set_options(ext, ARCHIVE_EXTRACT_TIME);
  1565. if (r != ARCHIVE_OK) {
  1566. ArchiveError("Problem with archive_write_disk_set_options(): ", ext);
  1567. break;
  1568. }
  1569. r = archive_write_header(ext, entry);
  1570. if (r == ARCHIVE_OK) {
  1571. if (!copy_data(a, ext)) {
  1572. break;
  1573. }
  1574. r = archive_write_finish_entry(ext);
  1575. if (r != ARCHIVE_OK) {
  1576. ArchiveError("Problem with archive_write_finish_entry(): ", ext);
  1577. break;
  1578. }
  1579. }
  1580. # ifdef _WIN32
  1581. else if (const char* linktext = archive_entry_symlink(entry)) {
  1582. std::cerr << "cmake -E tar: warning: skipping symbolic link \""
  1583. << cm_archive_entry_pathname(entry) << "\" -> \"" << linktext
  1584. << "\"." << std::endl;
  1585. }
  1586. # endif
  1587. else {
  1588. ArchiveError("Problem with archive_write_header(): ", ext);
  1589. cmSystemTools::Error("Current file: " +
  1590. cm_archive_entry_pathname(entry));
  1591. break;
  1592. }
  1593. }
  1594. }
  1595. bool error_occured = false;
  1596. if (matching != nullptr) {
  1597. const char* p;
  1598. int ar;
  1599. while ((ar = archive_match_path_unmatched_inclusions_next(matching, &p)) ==
  1600. ARCHIVE_OK) {
  1601. cmSystemTools::Error("tar: " + std::string(p) +
  1602. ": Not found in archive");
  1603. error_occured = true;
  1604. }
  1605. if (error_occured) {
  1606. return false;
  1607. }
  1608. if (ar == ARCHIVE_FATAL) {
  1609. cmSystemTools::Error("tar: Out of memory");
  1610. return false;
  1611. }
  1612. }
  1613. archive_match_free(matching);
  1614. archive_write_free(ext);
  1615. archive_read_close(a);
  1616. archive_read_free(a);
  1617. return r == ARCHIVE_EOF || r == ARCHIVE_OK;
  1618. }
  1619. }
  1620. #endif
  1621. bool cmSystemTools::ExtractTar(const std::string& outFileName,
  1622. const std::vector<std::string>& files,
  1623. bool verbose)
  1624. {
  1625. #if !defined(CMAKE_BOOTSTRAP)
  1626. return extract_tar(outFileName, files, verbose, true);
  1627. #else
  1628. (void)outFileName;
  1629. (void)files;
  1630. (void)verbose;
  1631. return false;
  1632. #endif
  1633. }
  1634. bool cmSystemTools::ListTar(const std::string& outFileName,
  1635. const std::vector<std::string>& files,
  1636. bool verbose)
  1637. {
  1638. #if !defined(CMAKE_BOOTSTRAP)
  1639. return extract_tar(outFileName, files, verbose, false);
  1640. #else
  1641. (void)outFileName;
  1642. (void)files;
  1643. (void)verbose;
  1644. return false;
  1645. #endif
  1646. }
  1647. int cmSystemTools::WaitForLine(cmsysProcess* process, std::string& line,
  1648. cmDuration timeout, std::vector<char>& out,
  1649. std::vector<char>& err)
  1650. {
  1651. line.clear();
  1652. auto outiter = out.begin();
  1653. auto erriter = err.begin();
  1654. cmProcessOutput processOutput;
  1655. std::string strdata;
  1656. while (true) {
  1657. // Check for a newline in stdout.
  1658. for (; outiter != out.end(); ++outiter) {
  1659. if ((*outiter == '\r') && ((outiter + 1) == out.end())) {
  1660. break;
  1661. }
  1662. if (*outiter == '\n' || *outiter == '\0') {
  1663. std::vector<char>::size_type length = outiter - out.begin();
  1664. if (length > 1 && *(outiter - 1) == '\r') {
  1665. --length;
  1666. }
  1667. if (length > 0) {
  1668. line.append(&out[0], length);
  1669. }
  1670. out.erase(out.begin(), outiter + 1);
  1671. return cmsysProcess_Pipe_STDOUT;
  1672. }
  1673. }
  1674. // Check for a newline in stderr.
  1675. for (; erriter != err.end(); ++erriter) {
  1676. if ((*erriter == '\r') && ((erriter + 1) == err.end())) {
  1677. break;
  1678. }
  1679. if (*erriter == '\n' || *erriter == '\0') {
  1680. std::vector<char>::size_type length = erriter - err.begin();
  1681. if (length > 1 && *(erriter - 1) == '\r') {
  1682. --length;
  1683. }
  1684. if (length > 0) {
  1685. line.append(&err[0], length);
  1686. }
  1687. err.erase(err.begin(), erriter + 1);
  1688. return cmsysProcess_Pipe_STDERR;
  1689. }
  1690. }
  1691. // No newlines found. Wait for more data from the process.
  1692. int length;
  1693. char* data;
  1694. double timeoutAsDbl = timeout.count();
  1695. int pipe =
  1696. cmsysProcess_WaitForData(process, &data, &length, &timeoutAsDbl);
  1697. if (pipe == cmsysProcess_Pipe_Timeout) {
  1698. // Timeout has been exceeded.
  1699. return pipe;
  1700. }
  1701. if (pipe == cmsysProcess_Pipe_STDOUT) {
  1702. processOutput.DecodeText(data, length, strdata, 1);
  1703. // Append to the stdout buffer.
  1704. std::vector<char>::size_type size = out.size();
  1705. cm::append(out, strdata);
  1706. outiter = out.begin() + size;
  1707. } else if (pipe == cmsysProcess_Pipe_STDERR) {
  1708. processOutput.DecodeText(data, length, strdata, 2);
  1709. // Append to the stderr buffer.
  1710. std::vector<char>::size_type size = err.size();
  1711. cm::append(err, strdata);
  1712. erriter = err.begin() + size;
  1713. } else if (pipe == cmsysProcess_Pipe_None) {
  1714. // Both stdout and stderr pipes have broken. Return leftover data.
  1715. processOutput.DecodeText(std::string(), strdata, 1);
  1716. if (!strdata.empty()) {
  1717. std::vector<char>::size_type size = out.size();
  1718. cm::append(out, strdata);
  1719. outiter = out.begin() + size;
  1720. }
  1721. processOutput.DecodeText(std::string(), strdata, 2);
  1722. if (!strdata.empty()) {
  1723. std::vector<char>::size_type size = err.size();
  1724. cm::append(err, strdata);
  1725. erriter = err.begin() + size;
  1726. }
  1727. if (!out.empty()) {
  1728. line.append(&out[0], outiter - out.begin());
  1729. out.erase(out.begin(), out.end());
  1730. return cmsysProcess_Pipe_STDOUT;
  1731. }
  1732. if (!err.empty()) {
  1733. line.append(&err[0], erriter - err.begin());
  1734. err.erase(err.begin(), err.end());
  1735. return cmsysProcess_Pipe_STDERR;
  1736. }
  1737. return cmsysProcess_Pipe_None;
  1738. }
  1739. }
  1740. }
  1741. #ifdef _WIN32
  1742. static void EnsureStdPipe(DWORD fd)
  1743. {
  1744. if (GetStdHandle(fd) != INVALID_HANDLE_VALUE) {
  1745. return;
  1746. }
  1747. SECURITY_ATTRIBUTES sa;
  1748. sa.nLength = sizeof(sa);
  1749. sa.lpSecurityDescriptor = NULL;
  1750. sa.bInheritHandle = TRUE;
  1751. HANDLE h = CreateFileW(
  1752. L"NUL",
  1753. fd == STD_INPUT_HANDLE ? FILE_GENERIC_READ
  1754. : FILE_GENERIC_WRITE | FILE_READ_ATTRIBUTES,
  1755. FILE_SHARE_READ | FILE_SHARE_WRITE, &sa, OPEN_EXISTING, 0, NULL);
  1756. if (h == INVALID_HANDLE_VALUE) {
  1757. LPSTR message = NULL;
  1758. DWORD size = FormatMessageA(
  1759. FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
  1760. FORMAT_MESSAGE_IGNORE_INSERTS,
  1761. NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  1762. (LPSTR)&message, 0, NULL);
  1763. std::string msg = std::string(message, size);
  1764. LocalFree(message);
  1765. std::cerr << "failed to open NUL for missing stdio pipe: " << msg;
  1766. abort();
  1767. }
  1768. SetStdHandle(fd, h);
  1769. }
  1770. void cmSystemTools::EnsureStdPipes()
  1771. {
  1772. EnsureStdPipe(STD_INPUT_HANDLE);
  1773. EnsureStdPipe(STD_OUTPUT_HANDLE);
  1774. EnsureStdPipe(STD_ERROR_HANDLE);
  1775. }
  1776. #else
  1777. static void EnsureStdPipe(int fd)
  1778. {
  1779. if (fcntl(fd, F_GETFD) != -1 || errno != EBADF) {
  1780. return;
  1781. }
  1782. int f = open("/dev/null", fd == STDIN_FILENO ? O_RDONLY : O_WRONLY);
  1783. if (f == -1) {
  1784. perror("failed to open /dev/null for missing stdio pipe");
  1785. abort();
  1786. }
  1787. if (f != fd) {
  1788. dup2(f, fd);
  1789. close(f);
  1790. }
  1791. }
  1792. void cmSystemTools::EnsureStdPipes()
  1793. {
  1794. EnsureStdPipe(STDIN_FILENO);
  1795. EnsureStdPipe(STDOUT_FILENO);
  1796. EnsureStdPipe(STDERR_FILENO);
  1797. }
  1798. #endif
  1799. void cmSystemTools::DoNotInheritStdPipes()
  1800. {
  1801. #ifdef _WIN32
  1802. // Check to see if we are attached to a console
  1803. // if so, then do not stop the inherited pipes
  1804. // or stdout and stderr will not show up in dos
  1805. // shell windows
  1806. CONSOLE_SCREEN_BUFFER_INFO hOutInfo;
  1807. HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
  1808. if (GetConsoleScreenBufferInfo(hOut, &hOutInfo)) {
  1809. return;
  1810. }
  1811. {
  1812. HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
  1813. DuplicateHandle(GetCurrentProcess(), out, GetCurrentProcess(), &out, 0,
  1814. FALSE, DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
  1815. SetStdHandle(STD_OUTPUT_HANDLE, out);
  1816. }
  1817. {
  1818. HANDLE out = GetStdHandle(STD_ERROR_HANDLE);
  1819. DuplicateHandle(GetCurrentProcess(), out, GetCurrentProcess(), &out, 0,
  1820. FALSE, DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
  1821. SetStdHandle(STD_ERROR_HANDLE, out);
  1822. }
  1823. #endif
  1824. }
  1825. #ifdef _WIN32
  1826. # ifndef CRYPT_SILENT
  1827. # define CRYPT_SILENT 0x40 /* Not defined by VS 6 version of header. */
  1828. # endif
  1829. static int WinCryptRandom(void* data, size_t size)
  1830. {
  1831. int result = 0;
  1832. HCRYPTPROV hProvider = 0;
  1833. if (CryptAcquireContextW(&hProvider, 0, 0, PROV_RSA_FULL,
  1834. CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) {
  1835. result = CryptGenRandom(hProvider, (DWORD)size, (BYTE*)data) ? 1 : 0;
  1836. CryptReleaseContext(hProvider, 0);
  1837. }
  1838. return result;
  1839. }
  1840. #endif
  1841. unsigned int cmSystemTools::RandomSeed()
  1842. {
  1843. #if defined(_WIN32) && !defined(__CYGWIN__)
  1844. unsigned int seed = 0;
  1845. // Try using a real random source.
  1846. if (WinCryptRandom(&seed, sizeof(seed))) {
  1847. return seed;
  1848. }
  1849. // Fall back to the time and pid.
  1850. FILETIME ft;
  1851. GetSystemTimeAsFileTime(&ft);
  1852. unsigned int t1 = static_cast<unsigned int>(ft.dwHighDateTime);
  1853. unsigned int t2 = static_cast<unsigned int>(ft.dwLowDateTime);
  1854. unsigned int pid = static_cast<unsigned int>(GetCurrentProcessId());
  1855. return t1 ^ t2 ^ pid;
  1856. #else
  1857. union
  1858. {
  1859. unsigned int integer;
  1860. char bytes[sizeof(unsigned int)];
  1861. } seed;
  1862. // Try using a real random source.
  1863. cmsys::ifstream fin;
  1864. fin.rdbuf()->pubsetbuf(nullptr, 0); // Unbuffered read.
  1865. fin.open("/dev/urandom");
  1866. if (fin.good() && fin.read(seed.bytes, sizeof(seed)) &&
  1867. fin.gcount() == sizeof(seed)) {
  1868. return seed.integer;
  1869. }
  1870. // Fall back to the time and pid.
  1871. struct timeval t;
  1872. gettimeofday(&t, nullptr);
  1873. unsigned int pid = static_cast<unsigned int>(getpid());
  1874. unsigned int tv_sec = static_cast<unsigned int>(t.tv_sec);
  1875. unsigned int tv_usec = static_cast<unsigned int>(t.tv_usec);
  1876. // Since tv_usec never fills more than 11 bits we shift it to fill
  1877. // in the slow-changing high-order bits of tv_sec.
  1878. return tv_sec ^ (tv_usec << 21) ^ pid;
  1879. #endif
  1880. }
  1881. static std::string cmSystemToolsCMakeCommand;
  1882. static std::string cmSystemToolsCTestCommand;
  1883. static std::string cmSystemToolsCPackCommand;
  1884. static std::string cmSystemToolsCMakeCursesCommand;
  1885. static std::string cmSystemToolsCMakeGUICommand;
  1886. static std::string cmSystemToolsCMClDepsCommand;
  1887. static std::string cmSystemToolsCMakeRoot;
  1888. static std::string cmSystemToolsHTMLDoc;
  1889. void cmSystemTools::FindCMakeResources(const char* argv0)
  1890. {
  1891. std::string exe_dir;
  1892. #if defined(_WIN32) && !defined(__CYGWIN__)
  1893. (void)argv0; // ignore this on windows
  1894. wchar_t modulepath[_MAX_PATH];
  1895. ::GetModuleFileNameW(NULL, modulepath, sizeof(modulepath));
  1896. std::string path = cmsys::Encoding::ToNarrow(modulepath);
  1897. std::string realPath =
  1898. cmSystemTools::GetRealPathResolvingWindowsSubst(path, NULL);
  1899. if (realPath.empty()) {
  1900. realPath = path;
  1901. }
  1902. exe_dir = cmSystemTools::GetFilenamePath(realPath);
  1903. #elif defined(__APPLE__)
  1904. (void)argv0; // ignore this on OS X
  1905. # define CM_EXE_PATH_LOCAL_SIZE 16384
  1906. char exe_path_local[CM_EXE_PATH_LOCAL_SIZE];
  1907. # if defined(MAC_OS_X_VERSION_10_3) && !defined(MAC_OS_X_VERSION_10_4)
  1908. unsigned long exe_path_size = CM_EXE_PATH_LOCAL_SIZE;
  1909. # else
  1910. uint32_t exe_path_size = CM_EXE_PATH_LOCAL_SIZE;
  1911. # endif
  1912. # undef CM_EXE_PATH_LOCAL_SIZE
  1913. char* exe_path = exe_path_local;
  1914. if (_NSGetExecutablePath(exe_path, &exe_path_size) < 0) {
  1915. exe_path = static_cast<char*>(malloc(exe_path_size));
  1916. _NSGetExecutablePath(exe_path, &exe_path_size);
  1917. }
  1918. exe_dir =
  1919. cmSystemTools::GetFilenamePath(cmSystemTools::GetRealPath(exe_path));
  1920. if (exe_path != exe_path_local) {
  1921. free(exe_path);
  1922. }
  1923. if (cmSystemTools::GetFilenameName(exe_dir) == "MacOS") {
  1924. // The executable is inside an application bundle.
  1925. // Look for ..<CMAKE_BIN_DIR> (install tree) and then fall back to
  1926. // ../../../bin (build tree).
  1927. exe_dir = cmSystemTools::GetFilenamePath(exe_dir);
  1928. if (cmSystemTools::FileExists(exe_dir + CMAKE_BIN_DIR "/cmake")) {
  1929. exe_dir += CMAKE_BIN_DIR;
  1930. } else {
  1931. exe_dir = cmSystemTools::GetFilenamePath(exe_dir);
  1932. exe_dir = cmSystemTools::GetFilenamePath(exe_dir);
  1933. }
  1934. }
  1935. #else
  1936. std::string errorMsg;
  1937. std::string exe;
  1938. if (cmSystemTools::FindProgramPath(argv0, exe, errorMsg)) {
  1939. // remove symlinks
  1940. exe = cmSystemTools::GetRealPath(exe);
  1941. exe_dir = cmSystemTools::GetFilenamePath(exe);
  1942. } else {
  1943. // ???
  1944. }
  1945. #endif
  1946. exe_dir = cmSystemTools::GetActualCaseForPath(exe_dir);
  1947. cmSystemToolsCMakeCommand =
  1948. cmStrCat(exe_dir, "/cmake", cmSystemTools::GetExecutableExtension());
  1949. #ifdef CMAKE_BOOTSTRAP
  1950. // The bootstrap cmake does not provide the other tools,
  1951. // so use the directory where they are about to be built.
  1952. exe_dir = CMAKE_BOOTSTRAP_BINARY_DIR "/bin";
  1953. #endif
  1954. cmSystemToolsCTestCommand =
  1955. cmStrCat(exe_dir, "/ctest", cmSystemTools::GetExecutableExtension());
  1956. cmSystemToolsCPackCommand =
  1957. cmStrCat(exe_dir, "/cpack", cmSystemTools::GetExecutableExtension());
  1958. cmSystemToolsCMakeGUICommand =
  1959. cmStrCat(exe_dir, "/cmake-gui", cmSystemTools::GetExecutableExtension());
  1960. if (!cmSystemTools::FileExists(cmSystemToolsCMakeGUICommand)) {
  1961. cmSystemToolsCMakeGUICommand.clear();
  1962. }
  1963. cmSystemToolsCMakeCursesCommand =
  1964. cmStrCat(exe_dir, "/ccmake", cmSystemTools::GetExecutableExtension());
  1965. if (!cmSystemTools::FileExists(cmSystemToolsCMakeCursesCommand)) {
  1966. cmSystemToolsCMakeCursesCommand.clear();
  1967. }
  1968. cmSystemToolsCMClDepsCommand =
  1969. cmStrCat(exe_dir, "/cmcldeps", cmSystemTools::GetExecutableExtension());
  1970. if (!cmSystemTools::FileExists(cmSystemToolsCMClDepsCommand)) {
  1971. cmSystemToolsCMClDepsCommand.clear();
  1972. }
  1973. #ifndef CMAKE_BOOTSTRAP
  1974. // Install tree has
  1975. // - "<prefix><CMAKE_BIN_DIR>/cmake"
  1976. // - "<prefix><CMAKE_DATA_DIR>"
  1977. // - "<prefix><CMAKE_DOC_DIR>"
  1978. if (cmHasLiteralSuffix(exe_dir, CMAKE_BIN_DIR)) {
  1979. std::string const prefix =
  1980. exe_dir.substr(0, exe_dir.size() - cmStrLen(CMAKE_BIN_DIR));
  1981. cmSystemToolsCMakeRoot = cmStrCat(prefix, CMAKE_DATA_DIR);
  1982. if (cmSystemTools::FileExists(
  1983. cmStrCat(prefix, CMAKE_DOC_DIR "/html/index.html"))) {
  1984. cmSystemToolsHTMLDoc = cmStrCat(prefix, CMAKE_DOC_DIR "/html");
  1985. }
  1986. }
  1987. if (cmSystemToolsCMakeRoot.empty() ||
  1988. !cmSystemTools::FileExists(
  1989. cmStrCat(cmSystemToolsCMakeRoot, "/Modules/CMake.cmake"))) {
  1990. // Build tree has "<build>/bin[/<config>]/cmake" and
  1991. // "<build>/CMakeFiles/CMakeSourceDir.txt".
  1992. std::string dir = cmSystemTools::GetFilenamePath(exe_dir);
  1993. std::string src_dir_txt = cmStrCat(dir, "/CMakeFiles/CMakeSourceDir.txt");
  1994. cmsys::ifstream fin(src_dir_txt.c_str());
  1995. std::string src_dir;
  1996. if (fin && cmSystemTools::GetLineFromStream(fin, src_dir) &&
  1997. cmSystemTools::FileIsDirectory(src_dir)) {
  1998. cmSystemToolsCMakeRoot = src_dir;
  1999. } else {
  2000. dir = cmSystemTools::GetFilenamePath(dir);
  2001. src_dir_txt = cmStrCat(dir, "/CMakeFiles/CMakeSourceDir.txt");
  2002. cmsys::ifstream fin2(src_dir_txt.c_str());
  2003. if (fin2 && cmSystemTools::GetLineFromStream(fin2, src_dir) &&
  2004. cmSystemTools::FileIsDirectory(src_dir)) {
  2005. cmSystemToolsCMakeRoot = src_dir;
  2006. }
  2007. }
  2008. if (!cmSystemToolsCMakeRoot.empty() && cmSystemToolsHTMLDoc.empty() &&
  2009. cmSystemTools::FileExists(
  2010. cmStrCat(dir, "/Utilities/Sphinx/html/index.html"))) {
  2011. cmSystemToolsHTMLDoc = cmStrCat(dir, "/Utilities/Sphinx/html");
  2012. }
  2013. }
  2014. #else
  2015. // Bootstrap build knows its source.
  2016. cmSystemToolsCMakeRoot = CMAKE_BOOTSTRAP_SOURCE_DIR;
  2017. #endif
  2018. }
  2019. std::string const& cmSystemTools::GetCMakeCommand()
  2020. {
  2021. return cmSystemToolsCMakeCommand;
  2022. }
  2023. std::string const& cmSystemTools::GetCTestCommand()
  2024. {
  2025. return cmSystemToolsCTestCommand;
  2026. }
  2027. std::string const& cmSystemTools::GetCPackCommand()
  2028. {
  2029. return cmSystemToolsCPackCommand;
  2030. }
  2031. std::string const& cmSystemTools::GetCMakeCursesCommand()
  2032. {
  2033. return cmSystemToolsCMakeCursesCommand;
  2034. }
  2035. std::string const& cmSystemTools::GetCMakeGUICommand()
  2036. {
  2037. return cmSystemToolsCMakeGUICommand;
  2038. }
  2039. std::string const& cmSystemTools::GetCMClDepsCommand()
  2040. {
  2041. return cmSystemToolsCMClDepsCommand;
  2042. }
  2043. std::string const& cmSystemTools::GetCMakeRoot()
  2044. {
  2045. return cmSystemToolsCMakeRoot;
  2046. }
  2047. std::string const& cmSystemTools::GetHTMLDoc()
  2048. {
  2049. return cmSystemToolsHTMLDoc;
  2050. }
  2051. std::string cmSystemTools::GetCurrentWorkingDirectory()
  2052. {
  2053. return cmSystemTools::CollapseFullPath(
  2054. cmsys::SystemTools::GetCurrentWorkingDirectory());
  2055. }
  2056. void cmSystemTools::MakefileColorEcho(int color, const char* message,
  2057. bool newline, bool enabled)
  2058. {
  2059. // On some platforms (an MSYS prompt) cmsysTerminal may not be able
  2060. // to determine whether the stream is displayed on a tty. In this
  2061. // case it assumes no unless we tell it otherwise. Since we want
  2062. // color messages to be displayed for users we will assume yes.
  2063. // However, we can test for some situations when the answer is most
  2064. // likely no.
  2065. int assumeTTY = cmsysTerminal_Color_AssumeTTY;
  2066. if (cmSystemTools::HasEnv("DART_TEST_FROM_DART") ||
  2067. cmSystemTools::HasEnv("DASHBOARD_TEST_FROM_CTEST") ||
  2068. cmSystemTools::HasEnv("CTEST_INTERACTIVE_DEBUG_MODE")) {
  2069. // Avoid printing color escapes during dashboard builds.
  2070. assumeTTY = 0;
  2071. }
  2072. if (enabled && color != cmsysTerminal_Color_Normal) {
  2073. // Print with color. Delay the newline until later so that
  2074. // all color restore sequences appear before it.
  2075. cmsysTerminal_cfprintf(color | assumeTTY, stdout, "%s", message);
  2076. } else {
  2077. // Color is disabled. Print without color.
  2078. fprintf(stdout, "%s", message);
  2079. }
  2080. if (newline) {
  2081. fprintf(stdout, "\n");
  2082. }
  2083. }
  2084. bool cmSystemTools::GuessLibrarySOName(std::string const& fullPath,
  2085. std::string& soname)
  2086. {
  2087. // For ELF shared libraries use a real parser to get the correct
  2088. // soname.
  2089. #if defined(CMAKE_USE_ELF_PARSER)
  2090. cmELF elf(fullPath.c_str());
  2091. if (elf) {
  2092. return elf.GetSOName(soname);
  2093. }
  2094. #endif
  2095. // If the file is not a symlink we have no guess for its soname.
  2096. if (!cmSystemTools::FileIsSymlink(fullPath)) {
  2097. return false;
  2098. }
  2099. if (!cmSystemTools::ReadSymlink(fullPath, soname)) {
  2100. return false;
  2101. }
  2102. // If the symlink has a path component we have no guess for the soname.
  2103. if (!cmSystemTools::GetFilenamePath(soname).empty()) {
  2104. return false;
  2105. }
  2106. // If the symlink points at an extended version of the same name
  2107. // assume it is the soname.
  2108. std::string name = cmSystemTools::GetFilenameName(fullPath);
  2109. return soname.length() > name.length() &&
  2110. soname.compare(0, name.length(), name) == 0;
  2111. }
  2112. bool cmSystemTools::GuessLibraryInstallName(std::string const& fullPath,
  2113. std::string& soname)
  2114. {
  2115. #if defined(CMAKE_USE_MACH_PARSER)
  2116. cmMachO macho(fullPath.c_str());
  2117. if (macho) {
  2118. return macho.GetInstallName(soname);
  2119. }
  2120. #else
  2121. (void)fullPath;
  2122. (void)soname;
  2123. #endif
  2124. return false;
  2125. }
  2126. #if defined(CMAKE_USE_ELF_PARSER)
  2127. std::string::size_type cmSystemToolsFindRPath(std::string const& have,
  2128. std::string const& want)
  2129. {
  2130. std::string::size_type pos = 0;
  2131. while (pos < have.size()) {
  2132. // Look for an occurrence of the string.
  2133. std::string::size_type const beg = have.find(want, pos);
  2134. if (beg == std::string::npos) {
  2135. return std::string::npos;
  2136. }
  2137. // Make sure it is separated from preceding entries.
  2138. if (beg > 0 && have[beg - 1] != ':') {
  2139. pos = beg + 1;
  2140. continue;
  2141. }
  2142. // Make sure it is separated from following entries.
  2143. std::string::size_type const end = beg + want.size();
  2144. if (end < have.size() && have[end] != ':') {
  2145. pos = beg + 1;
  2146. continue;
  2147. }
  2148. // Return the position of the path portion.
  2149. return beg;
  2150. }
  2151. // The desired rpath was not found.
  2152. return std::string::npos;
  2153. }
  2154. #endif
  2155. #if defined(CMAKE_USE_ELF_PARSER)
  2156. struct cmSystemToolsRPathInfo
  2157. {
  2158. unsigned long Position;
  2159. unsigned long Size;
  2160. std::string Name;
  2161. std::string Value;
  2162. };
  2163. #endif
  2164. #if defined(CMAKE_USE_ELF_PARSER)
  2165. bool cmSystemTools::ChangeRPath(std::string const& file,
  2166. std::string const& oldRPath,
  2167. std::string const& newRPath,
  2168. bool removeEnvironmentRPath, std::string* emsg,
  2169. bool* changed)
  2170. {
  2171. if (changed) {
  2172. *changed = false;
  2173. }
  2174. int rp_count = 0;
  2175. bool remove_rpath = true;
  2176. cmSystemToolsRPathInfo rp[2];
  2177. {
  2178. // Parse the ELF binary.
  2179. cmELF elf(file.c_str());
  2180. // Get the RPATH and RUNPATH entries from it.
  2181. int se_count = 0;
  2182. cmELF::StringEntry const* se[2] = { nullptr, nullptr };
  2183. const char* se_name[2] = { nullptr, nullptr };
  2184. if (cmELF::StringEntry const* se_rpath = elf.GetRPath()) {
  2185. se[se_count] = se_rpath;
  2186. se_name[se_count] = "RPATH";
  2187. ++se_count;
  2188. }
  2189. if (cmELF::StringEntry const* se_runpath = elf.GetRunPath()) {
  2190. se[se_count] = se_runpath;
  2191. se_name[se_count] = "RUNPATH";
  2192. ++se_count;
  2193. }
  2194. if (se_count == 0) {
  2195. if (newRPath.empty()) {
  2196. // The new rpath is empty and there is no rpath anyway so it is
  2197. // okay.
  2198. return true;
  2199. }
  2200. if (emsg) {
  2201. *emsg =
  2202. cmStrCat("No valid ELF RPATH or RUNPATH entry exists in the file; ",
  2203. elf.GetErrorMessage());
  2204. }
  2205. return false;
  2206. }
  2207. for (int i = 0; i < se_count; ++i) {
  2208. // If both RPATH and RUNPATH refer to the same string literal it
  2209. // needs to be changed only once.
  2210. if (rp_count && rp[0].Position == se[i]->Position) {
  2211. continue;
  2212. }
  2213. // Make sure the current rpath contains the old rpath.
  2214. std::string::size_type pos =
  2215. cmSystemToolsFindRPath(se[i]->Value, oldRPath);
  2216. if (pos == std::string::npos) {
  2217. // If it contains the new rpath instead then it is okay.
  2218. if (cmSystemToolsFindRPath(se[i]->Value, newRPath) !=
  2219. std::string::npos) {
  2220. remove_rpath = false;
  2221. continue;
  2222. }
  2223. if (emsg) {
  2224. std::ostringstream e;
  2225. /* clang-format off */
  2226. e << "The current " << se_name[i] << " is:\n"
  2227. << " " << se[i]->Value << "\n"
  2228. << "which does not contain:\n"
  2229. << " " << oldRPath << "\n"
  2230. << "as was expected.";
  2231. /* clang-format on */
  2232. *emsg = e.str();
  2233. }
  2234. return false;
  2235. }
  2236. // Store information about the entry in the file.
  2237. rp[rp_count].Position = se[i]->Position;
  2238. rp[rp_count].Size = se[i]->Size;
  2239. rp[rp_count].Name = se_name[i];
  2240. std::string::size_type prefix_len = pos;
  2241. // If oldRPath was at the end of the file's RPath, and newRPath is empty,
  2242. // we should remove the unnecessary ':' at the end.
  2243. if (newRPath.empty() && pos > 0 && se[i]->Value[pos - 1] == ':' &&
  2244. pos + oldRPath.length() == se[i]->Value.length()) {
  2245. prefix_len--;
  2246. }
  2247. // Construct the new value which preserves the part of the path
  2248. // not being changed.
  2249. if (!removeEnvironmentRPath) {
  2250. rp[rp_count].Value = se[i]->Value.substr(0, prefix_len);
  2251. }
  2252. rp[rp_count].Value += newRPath;
  2253. rp[rp_count].Value += se[i]->Value.substr(pos + oldRPath.length());
  2254. if (!rp[rp_count].Value.empty()) {
  2255. remove_rpath = false;
  2256. }
  2257. // Make sure there is enough room to store the new rpath and at
  2258. // least one null terminator.
  2259. if (rp[rp_count].Size < rp[rp_count].Value.length() + 1) {
  2260. if (emsg) {
  2261. *emsg = cmStrCat("The replacement path is too long for the ",
  2262. se_name[i], " entry.");
  2263. }
  2264. return false;
  2265. }
  2266. // This entry is ready for update.
  2267. ++rp_count;
  2268. }
  2269. }
  2270. // If no runtime path needs to be changed, we are done.
  2271. if (rp_count == 0) {
  2272. return true;
  2273. }
  2274. // If the resulting rpath is empty, just remove the entire entry instead.
  2275. if (remove_rpath) {
  2276. return cmSystemTools::RemoveRPath(file, emsg, changed);
  2277. }
  2278. {
  2279. // Open the file for update.
  2280. cmsys::ofstream f(file.c_str(),
  2281. std::ios::in | std::ios::out | std::ios::binary);
  2282. if (!f) {
  2283. if (emsg) {
  2284. *emsg = "Error opening file for update.";
  2285. }
  2286. return false;
  2287. }
  2288. // Store the new RPATH and RUNPATH strings.
  2289. for (int i = 0; i < rp_count; ++i) {
  2290. // Seek to the RPATH position.
  2291. if (!f.seekp(rp[i].Position)) {
  2292. if (emsg) {
  2293. *emsg = cmStrCat("Error seeking to ", rp[i].Name, " position.");
  2294. }
  2295. return false;
  2296. }
  2297. // Write the new rpath. Follow it with enough null terminators to
  2298. // fill the string table entry.
  2299. f << rp[i].Value;
  2300. for (unsigned long j = rp[i].Value.length(); j < rp[i].Size; ++j) {
  2301. f << '\0';
  2302. }
  2303. // Make sure it wrote correctly.
  2304. if (!f) {
  2305. if (emsg) {
  2306. *emsg = cmStrCat("Error writing the new ", rp[i].Name,
  2307. " string to the file.");
  2308. }
  2309. return false;
  2310. }
  2311. }
  2312. }
  2313. // Everything was updated successfully.
  2314. if (changed) {
  2315. *changed = true;
  2316. }
  2317. return true;
  2318. }
  2319. #else
  2320. bool cmSystemTools::ChangeRPath(std::string const& /*file*/,
  2321. std::string const& /*oldRPath*/,
  2322. std::string const& /*newRPath*/,
  2323. bool /*removeEnvironmentRPath*/,
  2324. std::string* /*emsg*/, bool* /*changed*/)
  2325. {
  2326. return false;
  2327. }
  2328. #endif
  2329. bool cmSystemTools::VersionCompare(cmSystemTools::CompareOp op,
  2330. const char* lhss, const char* rhss)
  2331. {
  2332. const char* endl = lhss;
  2333. const char* endr = rhss;
  2334. unsigned long lhs;
  2335. unsigned long rhs;
  2336. while (((*endl >= '0') && (*endl <= '9')) ||
  2337. ((*endr >= '0') && (*endr <= '9'))) {
  2338. // Do component-wise comparison.
  2339. lhs = strtoul(endl, const_cast<char**>(&endl), 10);
  2340. rhs = strtoul(endr, const_cast<char**>(&endr), 10);
  2341. if (lhs < rhs) {
  2342. // lhs < rhs, so true if operation is LESS
  2343. return (op & cmSystemTools::OP_LESS) != 0;
  2344. }
  2345. if (lhs > rhs) {
  2346. // lhs > rhs, so true if operation is GREATER
  2347. return (op & cmSystemTools::OP_GREATER) != 0;
  2348. }
  2349. if (*endr == '.') {
  2350. endr++;
  2351. }
  2352. if (*endl == '.') {
  2353. endl++;
  2354. }
  2355. }
  2356. // lhs == rhs, so true if operation is EQUAL
  2357. return (op & cmSystemTools::OP_EQUAL) != 0;
  2358. }
  2359. bool cmSystemTools::VersionCompareEqual(std::string const& lhs,
  2360. std::string const& rhs)
  2361. {
  2362. return cmSystemTools::VersionCompare(cmSystemTools::OP_EQUAL, lhs.c_str(),
  2363. rhs.c_str());
  2364. }
  2365. bool cmSystemTools::VersionCompareGreater(std::string const& lhs,
  2366. std::string const& rhs)
  2367. {
  2368. return cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER, lhs.c_str(),
  2369. rhs.c_str());
  2370. }
  2371. bool cmSystemTools::VersionCompareGreaterEq(std::string const& lhs,
  2372. std::string const& rhs)
  2373. {
  2374. return cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER_EQUAL,
  2375. lhs.c_str(), rhs.c_str());
  2376. }
  2377. static size_t cm_strverscmp_find_first_difference_or_end(const char* lhs,
  2378. const char* rhs)
  2379. {
  2380. size_t i = 0;
  2381. /* Step forward until we find a difference or both strings end together.
  2382. The difference may lie on the null-terminator of one string. */
  2383. while (lhs[i] == rhs[i] && lhs[i] != 0) {
  2384. ++i;
  2385. }
  2386. return i;
  2387. }
  2388. static size_t cm_strverscmp_find_digits_begin(const char* s, size_t i)
  2389. {
  2390. /* Step back until we are not preceded by a digit. */
  2391. while (i > 0 && isdigit(s[i - 1])) {
  2392. --i;
  2393. }
  2394. return i;
  2395. }
  2396. static size_t cm_strverscmp_find_digits_end(const char* s, size_t i)
  2397. {
  2398. /* Step forward over digits. */
  2399. while (isdigit(s[i])) {
  2400. ++i;
  2401. }
  2402. return i;
  2403. }
  2404. static size_t cm_strverscmp_count_leading_zeros(const char* s, size_t b)
  2405. {
  2406. size_t i = b;
  2407. /* Step forward over zeros that are followed by another digit. */
  2408. while (s[i] == '0' && isdigit(s[i + 1])) {
  2409. ++i;
  2410. }
  2411. return i - b;
  2412. }
  2413. static int cm_strverscmp(const char* lhs, const char* rhs)
  2414. {
  2415. size_t const i = cm_strverscmp_find_first_difference_or_end(lhs, rhs);
  2416. if (lhs[i] != rhs[i]) {
  2417. /* The strings differ starting at 'i'. Check for a digit sequence. */
  2418. size_t const b = cm_strverscmp_find_digits_begin(lhs, i);
  2419. if (b != i || (isdigit(lhs[i]) && isdigit(rhs[i]))) {
  2420. /* A digit sequence starts at 'b', preceding or at 'i'. */
  2421. /* Look for leading zeros, implying a leading decimal point. */
  2422. size_t const lhs_zeros = cm_strverscmp_count_leading_zeros(lhs, b);
  2423. size_t const rhs_zeros = cm_strverscmp_count_leading_zeros(rhs, b);
  2424. if (lhs_zeros != rhs_zeros) {
  2425. /* The side with more leading zeros orders first. */
  2426. return rhs_zeros > lhs_zeros ? 1 : -1;
  2427. }
  2428. if (lhs_zeros == 0) {
  2429. /* No leading zeros; compare digit sequence lengths. */
  2430. size_t const lhs_end = cm_strverscmp_find_digits_end(lhs, i);
  2431. size_t const rhs_end = cm_strverscmp_find_digits_end(rhs, i);
  2432. if (lhs_end != rhs_end) {
  2433. /* The side with fewer digits orders first. */
  2434. return lhs_end > rhs_end ? 1 : -1;
  2435. }
  2436. }
  2437. }
  2438. }
  2439. /* Ordering was not decided by digit sequence lengths; compare bytes. */
  2440. return lhs[i] - rhs[i];
  2441. }
  2442. int cmSystemTools::strverscmp(std::string const& lhs, std::string const& rhs)
  2443. {
  2444. return cm_strverscmp(lhs.c_str(), rhs.c_str());
  2445. }
  2446. #if defined(CMAKE_USE_ELF_PARSER)
  2447. bool cmSystemTools::RemoveRPath(std::string const& file, std::string* emsg,
  2448. bool* removed)
  2449. {
  2450. if (removed) {
  2451. *removed = false;
  2452. }
  2453. int zeroCount = 0;
  2454. unsigned long zeroPosition[2] = { 0, 0 };
  2455. unsigned long zeroSize[2] = { 0, 0 };
  2456. unsigned long bytesBegin = 0;
  2457. std::vector<char> bytes;
  2458. {
  2459. // Parse the ELF binary.
  2460. cmELF elf(file.c_str());
  2461. // Get the RPATH and RUNPATH entries from it and sort them by index
  2462. // in the dynamic section header.
  2463. int se_count = 0;
  2464. cmELF::StringEntry const* se[2] = { nullptr, nullptr };
  2465. if (cmELF::StringEntry const* se_rpath = elf.GetRPath()) {
  2466. se[se_count++] = se_rpath;
  2467. }
  2468. if (cmELF::StringEntry const* se_runpath = elf.GetRunPath()) {
  2469. se[se_count++] = se_runpath;
  2470. }
  2471. if (se_count == 0) {
  2472. // There is no RPATH or RUNPATH anyway.
  2473. return true;
  2474. }
  2475. if (se_count == 2 && se[1]->IndexInSection < se[0]->IndexInSection) {
  2476. std::swap(se[0], se[1]);
  2477. }
  2478. // Obtain a copy of the dynamic entries
  2479. cmELF::DynamicEntryList dentries = elf.GetDynamicEntries();
  2480. if (dentries.empty()) {
  2481. // This should happen only for invalid ELF files where a DT_NULL
  2482. // appears before the end of the table.
  2483. if (emsg) {
  2484. *emsg = "DYNAMIC section contains a DT_NULL before the end.";
  2485. }
  2486. return false;
  2487. }
  2488. // Save information about the string entries to be zeroed.
  2489. zeroCount = se_count;
  2490. for (int i = 0; i < se_count; ++i) {
  2491. zeroPosition[i] = se[i]->Position;
  2492. zeroSize[i] = se[i]->Size;
  2493. }
  2494. // Get size of one DYNAMIC entry
  2495. unsigned long const sizeof_dentry =
  2496. elf.GetDynamicEntryPosition(1) - elf.GetDynamicEntryPosition(0);
  2497. // Adjust the entry list as necessary to remove the run path
  2498. unsigned long entriesErased = 0;
  2499. for (auto it = dentries.begin(); it != dentries.end();) {
  2500. if (it->first == cmELF::TagRPath || it->first == cmELF::TagRunPath) {
  2501. it = dentries.erase(it);
  2502. entriesErased++;
  2503. continue;
  2504. }
  2505. if (cmELF::TagMipsRldMapRel != 0 &&
  2506. it->first == cmELF::TagMipsRldMapRel) {
  2507. // Background: debuggers need to know the "linker map" which contains
  2508. // the addresses each dynamic object is loaded at. Most arches use
  2509. // the DT_DEBUG tag which the dynamic linker writes to (directly) and
  2510. // contain the location of the linker map, however on MIPS the
  2511. // .dynamic section is always read-only so this is not possible. MIPS
  2512. // objects instead contain a DT_MIPS_RLD_MAP tag which contains the
  2513. // address where the dynamic linker will write to (an indirect
  2514. // version of DT_DEBUG). Since this doesn't work when using PIE, a
  2515. // relative equivalent was created - DT_MIPS_RLD_MAP_REL. Since this
  2516. // version contains a relative offset, moving it changes the
  2517. // calculated address. This may cause the dynamic linker to write
  2518. // into memory it should not be changing.
  2519. //
  2520. // To fix this, we adjust the value of DT_MIPS_RLD_MAP_REL here. If
  2521. // we move it up by n bytes, we add n bytes to the value of this tag.
  2522. it->second += entriesErased * sizeof_dentry;
  2523. }
  2524. it++;
  2525. }
  2526. // Encode new entries list
  2527. bytes = elf.EncodeDynamicEntries(dentries);
  2528. bytesBegin = elf.GetDynamicEntryPosition(0);
  2529. }
  2530. // Open the file for update.
  2531. cmsys::ofstream f(file.c_str(),
  2532. std::ios::in | std::ios::out | std::ios::binary);
  2533. if (!f) {
  2534. if (emsg) {
  2535. *emsg = "Error opening file for update.";
  2536. }
  2537. return false;
  2538. }
  2539. // Write the new DYNAMIC table header.
  2540. if (!f.seekp(bytesBegin)) {
  2541. if (emsg) {
  2542. *emsg = "Error seeking to DYNAMIC table header for RPATH.";
  2543. }
  2544. return false;
  2545. }
  2546. if (!f.write(&bytes[0], bytes.size())) {
  2547. if (emsg) {
  2548. *emsg = "Error replacing DYNAMIC table header.";
  2549. }
  2550. return false;
  2551. }
  2552. // Fill the RPATH and RUNPATH strings with zero bytes.
  2553. for (int i = 0; i < zeroCount; ++i) {
  2554. if (!f.seekp(zeroPosition[i])) {
  2555. if (emsg) {
  2556. *emsg = "Error seeking to RPATH position.";
  2557. }
  2558. return false;
  2559. }
  2560. for (unsigned long j = 0; j < zeroSize[i]; ++j) {
  2561. f << '\0';
  2562. }
  2563. if (!f) {
  2564. if (emsg) {
  2565. *emsg = "Error writing the empty rpath string to the file.";
  2566. }
  2567. return false;
  2568. }
  2569. }
  2570. // Everything was updated successfully.
  2571. if (removed) {
  2572. *removed = true;
  2573. }
  2574. return true;
  2575. }
  2576. #else
  2577. bool cmSystemTools::RemoveRPath(std::string const& /*file*/,
  2578. std::string* /*emsg*/, bool* /*removed*/)
  2579. {
  2580. return false;
  2581. }
  2582. #endif
  2583. bool cmSystemTools::CheckRPath(std::string const& file,
  2584. std::string const& newRPath)
  2585. {
  2586. #if defined(CMAKE_USE_ELF_PARSER)
  2587. // Parse the ELF binary.
  2588. cmELF elf(file.c_str());
  2589. // Get the RPATH or RUNPATH entry from it.
  2590. cmELF::StringEntry const* se = elf.GetRPath();
  2591. if (!se) {
  2592. se = elf.GetRunPath();
  2593. }
  2594. // Make sure the current rpath contains the new rpath.
  2595. if (newRPath.empty()) {
  2596. if (!se) {
  2597. return true;
  2598. }
  2599. } else {
  2600. if (se &&
  2601. cmSystemToolsFindRPath(se->Value, newRPath) != std::string::npos) {
  2602. return true;
  2603. }
  2604. }
  2605. return false;
  2606. #else
  2607. (void)file;
  2608. (void)newRPath;
  2609. return false;
  2610. #endif
  2611. }
  2612. bool cmSystemTools::RepeatedRemoveDirectory(const std::string& dir)
  2613. {
  2614. #ifdef _WIN32
  2615. // Windows sometimes locks files temporarily so try a few times.
  2616. WindowsFileRetry retry = cmSystemTools::GetWindowsFileRetry();
  2617. for (unsigned int i = 0; i < retry.Count; ++i) {
  2618. if (cmSystemTools::RemoveADirectory(dir)) {
  2619. return true;
  2620. }
  2621. cmSystemTools::Delay(retry.Delay);
  2622. }
  2623. return false;
  2624. #else
  2625. return cmSystemTools::RemoveADirectory(dir);
  2626. #endif
  2627. }
  2628. std::string cmSystemTools::EncodeURL(std::string const& in, bool escapeSlashes)
  2629. {
  2630. std::string out;
  2631. for (char c : in) {
  2632. char hexCh[4] = { 0, 0, 0, 0 };
  2633. hexCh[0] = c;
  2634. switch (c) {
  2635. case '+':
  2636. case '?':
  2637. case '\\':
  2638. case '&':
  2639. case ' ':
  2640. case '=':
  2641. case '%':
  2642. sprintf(hexCh, "%%%02X", static_cast<int>(c));
  2643. break;
  2644. case '/':
  2645. if (escapeSlashes) {
  2646. strcpy(hexCh, "%2F");
  2647. }
  2648. break;
  2649. default:
  2650. break;
  2651. }
  2652. out.append(hexCh);
  2653. }
  2654. return out;
  2655. }
  2656. bool cmSystemTools::CreateSymlink(const std::string& origName,
  2657. const std::string& newName,
  2658. std::string* errorMessage)
  2659. {
  2660. uv_fs_t req;
  2661. int flags = 0;
  2662. #if defined(_WIN32)
  2663. if (cmsys::SystemTools::FileIsDirectory(origName)) {
  2664. flags |= UV_FS_SYMLINK_DIR;
  2665. }
  2666. #endif
  2667. int err = uv_fs_symlink(nullptr, &req, origName.c_str(), newName.c_str(),
  2668. flags, nullptr);
  2669. if (err) {
  2670. std::string e =
  2671. "failed to create symbolic link '" + newName + "': " + uv_strerror(err);
  2672. if (errorMessage) {
  2673. *errorMessage = std::move(e);
  2674. } else {
  2675. cmSystemTools::Error(e);
  2676. }
  2677. return false;
  2678. }
  2679. return true;
  2680. }
  2681. bool cmSystemTools::CreateLink(const std::string& origName,
  2682. const std::string& newName,
  2683. std::string* errorMessage)
  2684. {
  2685. uv_fs_t req;
  2686. int err =
  2687. uv_fs_link(nullptr, &req, origName.c_str(), newName.c_str(), nullptr);
  2688. if (err) {
  2689. std::string e =
  2690. "failed to create link '" + newName + "': " + uv_strerror(err);
  2691. if (errorMessage) {
  2692. *errorMessage = std::move(e);
  2693. } else {
  2694. cmSystemTools::Error(e);
  2695. }
  2696. return false;
  2697. }
  2698. return true;
  2699. }