cmSystemTools.cxx 99 KB

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