cmSystemTools.cxx 107 KB

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