cmSystemTools.cxx 100 KB

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