cmSystemTools.cxx 90 KB

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