cmSystemTools.cxx 108 KB

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