cmSystemTools.cxx 108 KB

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