cmSystemTools.cxx 92 KB

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