cmSystemTools.cxx 98 KB

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