cmSystemTools.cxx 109 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #if !defined(_WIN32) && !defined(__sun) && !defined(__OpenBSD__)
  4. // POSIX APIs are needed
  5. // NOLINTNEXTLINE(bugprone-reserved-identifier)
  6. # define _POSIX_C_SOURCE 200809L
  7. #endif
  8. #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__QNX__)
  9. // For isascii
  10. // NOLINTNEXTLINE(bugprone-reserved-identifier)
  11. # define _XOPEN_SOURCE 700
  12. #endif
  13. #if defined(__APPLE__)
  14. // Restore Darwin APIs removed by _POSIX_C_SOURCE.
  15. // NOLINTNEXTLINE(bugprone-reserved-identifier)
  16. # define _DARWIN_C_SOURCE
  17. #endif
  18. #include "cmSystemTools.h"
  19. #include <cm/optional>
  20. #include <cmext/algorithm>
  21. #include <cmext/string_view>
  22. #include <cm3p/uv.h>
  23. #include "cm_fileno.hxx"
  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 wincrypt.h after windows.h
  77. # include <wincrypt.h>
  78. #else
  79. # include <unistd.h>
  80. # include <sys/time.h>
  81. #endif
  82. #if defined(_WIN32) && \
  83. (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__MINGW32__))
  84. # include <io.h>
  85. #endif
  86. #if defined(__APPLE__)
  87. # include <mach-o/dyld.h>
  88. #endif
  89. #ifdef __QNX__
  90. # include <malloc.h> /* for malloc/free on QNX */
  91. #endif
  92. #if !defined(_WIN32) && !defined(__ANDROID__)
  93. # include <sys/utsname.h>
  94. #endif
  95. #if defined(_MSC_VER) && _MSC_VER >= 1800
  96. # define CM_WINDOWS_DEPRECATED_GetVersionEx
  97. #endif
  98. namespace {
  99. cmSystemTools::InterruptCallback s_InterruptCallback;
  100. cmSystemTools::MessageCallback s_MessageCallback;
  101. cmSystemTools::OutputCallback s_StderrCallback;
  102. cmSystemTools::OutputCallback s_StdoutCallback;
  103. } // namespace
  104. #if !defined(HAVE_ENVIRON_NOT_REQUIRE_PROTOTYPE)
  105. // For GetEnvironmentVariables
  106. # if defined(_WIN32)
  107. extern __declspec(dllimport) char** environ;
  108. # else
  109. extern char** environ;
  110. # endif
  111. #endif
  112. #if !defined(CMAKE_BOOTSTRAP)
  113. static std::string cm_archive_entry_pathname(struct archive_entry* entry)
  114. {
  115. # if cmsys_STL_HAS_WSTRING
  116. return cmsys::Encoding::ToNarrow(archive_entry_pathname_w(entry));
  117. # else
  118. return archive_entry_pathname(entry);
  119. # endif
  120. }
  121. static int cm_archive_read_open_file(struct archive* a, const char* file,
  122. int block_size)
  123. {
  124. # if cmsys_STL_HAS_WSTRING
  125. std::wstring wfile = cmsys::Encoding::ToWide(file);
  126. return archive_read_open_filename_w(a, wfile.c_str(), block_size);
  127. # else
  128. return archive_read_open_filename(a, file, block_size);
  129. # endif
  130. }
  131. #endif
  132. #ifdef _WIN32
  133. #elif defined(__APPLE__)
  134. # include <crt_externs.h>
  135. # define environ (*_NSGetEnviron())
  136. #endif
  137. bool cmSystemTools::s_RunCommandHideConsole = false;
  138. bool cmSystemTools::s_DisableRunCommandOutput = false;
  139. bool cmSystemTools::s_ErrorOccurred = false;
  140. bool cmSystemTools::s_FatalErrorOccurred = false;
  141. bool cmSystemTools::s_ForceUnixPaths = false;
  142. // replace replace with with as many times as it shows up in source.
  143. // write the result into source.
  144. #if defined(_WIN32) && !defined(__CYGWIN__)
  145. void cmSystemTools::ExpandRegistryValues(std::string& source, KeyWOW64 view)
  146. {
  147. // Regular expression to match anything inside [...] that begins in HKEY.
  148. // Note that there is a special rule for regular expressions to match a
  149. // close square-bracket inside a list delimited by square brackets.
  150. // The "[^]]" part of this expression will match any character except
  151. // a close square-bracket. The ']' character must be the first in the
  152. // list of characters inside the [^...] block of the expression.
  153. cmsys::RegularExpression regEntry("\\[(HKEY[^]]*)\\]");
  154. // check for black line or comment
  155. while (regEntry.find(source)) {
  156. // the arguments are the second match
  157. std::string key = regEntry.match(1);
  158. std::string val;
  159. if (ReadRegistryValue(key.c_str(), val, view)) {
  160. std::string reg = cmStrCat('[', key, ']');
  161. cmSystemTools::ReplaceString(source, reg.c_str(), val.c_str());
  162. } else {
  163. std::string reg = cmStrCat('[', key, ']');
  164. cmSystemTools::ReplaceString(source, reg.c_str(), "/registry");
  165. }
  166. }
  167. }
  168. #else
  169. void cmSystemTools::ExpandRegistryValues(std::string& source,
  170. KeyWOW64 /*unused*/)
  171. {
  172. cmsys::RegularExpression regEntry("\\[(HKEY[^]]*)\\]");
  173. while (regEntry.find(source)) {
  174. // the arguments are the second match
  175. std::string key = regEntry.match(1);
  176. std::string reg = cmStrCat('[', key, ']');
  177. cmSystemTools::ReplaceString(source, reg.c_str(), "/registry");
  178. }
  179. }
  180. #endif
  181. std::string cmSystemTools::HelpFileName(cm::string_view str)
  182. {
  183. std::string name(str);
  184. cmSystemTools::ReplaceString(name, "<", "");
  185. cmSystemTools::ReplaceString(name, ">", "");
  186. return name;
  187. }
  188. void cmSystemTools::Error(const std::string& m)
  189. {
  190. std::string message = "CMake Error: " + m;
  191. cmSystemTools::s_ErrorOccurred = true;
  192. cmSystemTools::Message(message, "Error");
  193. }
  194. void cmSystemTools::SetInterruptCallback(InterruptCallback f)
  195. {
  196. s_InterruptCallback = std::move(f);
  197. }
  198. bool cmSystemTools::GetInterruptFlag()
  199. {
  200. if (s_InterruptCallback) {
  201. return s_InterruptCallback();
  202. }
  203. return false;
  204. }
  205. void cmSystemTools::SetMessageCallback(MessageCallback f)
  206. {
  207. s_MessageCallback = std::move(f);
  208. }
  209. void cmSystemTools::SetStdoutCallback(OutputCallback f)
  210. {
  211. s_StdoutCallback = std::move(f);
  212. }
  213. void cmSystemTools::SetStderrCallback(OutputCallback f)
  214. {
  215. s_StderrCallback = std::move(f);
  216. }
  217. void cmSystemTools::Stderr(const std::string& s)
  218. {
  219. if (s_StderrCallback) {
  220. s_StderrCallback(s);
  221. } else {
  222. std::cerr << s << std::flush;
  223. }
  224. }
  225. void cmSystemTools::Stdout(const std::string& s)
  226. {
  227. if (s_StdoutCallback) {
  228. s_StdoutCallback(s);
  229. } else {
  230. std::cout << s << std::flush;
  231. }
  232. }
  233. void cmSystemTools::Message(const std::string& m, const char* title)
  234. {
  235. cmMessageMetadata md;
  236. md.title = title;
  237. Message(m, md);
  238. }
  239. void cmSystemTools::Message(const std::string& m, const cmMessageMetadata& md)
  240. {
  241. if (s_MessageCallback) {
  242. s_MessageCallback(m, md);
  243. } else {
  244. std::cerr << m << std::endl;
  245. }
  246. }
  247. void cmSystemTools::ReportLastSystemError(const char* msg)
  248. {
  249. std::string m =
  250. cmStrCat(msg, ": System Error: ", Superclass::GetLastSystemError());
  251. cmSystemTools::Error(m);
  252. }
  253. void cmSystemTools::ParseWindowsCommandLine(const char* command,
  254. std::vector<std::string>& args)
  255. {
  256. // See the MSDN document "Parsing C Command-Line Arguments" at
  257. // http://msdn2.microsoft.com/en-us/library/a1y7w461.aspx for rules
  258. // of parsing the windows command line.
  259. bool in_argument = false;
  260. bool in_quotes = false;
  261. int backslashes = 0;
  262. std::string arg;
  263. for (const char* c = command; *c; ++c) {
  264. if (*c == '\\') {
  265. ++backslashes;
  266. in_argument = true;
  267. } else if (*c == '"') {
  268. int backslash_pairs = backslashes >> 1;
  269. int backslash_escaped = backslashes & 1;
  270. arg.append(backslash_pairs, '\\');
  271. backslashes = 0;
  272. if (backslash_escaped) {
  273. /* An odd number of backslashes precede this quote.
  274. It is escaped. */
  275. arg.append(1, '"');
  276. } else {
  277. /* An even number of backslashes precede this quote.
  278. It is not escaped. */
  279. in_quotes = !in_quotes;
  280. }
  281. in_argument = true;
  282. } else {
  283. arg.append(backslashes, '\\');
  284. backslashes = 0;
  285. if (cmIsSpace(*c)) {
  286. if (in_quotes) {
  287. arg.append(1, *c);
  288. } else if (in_argument) {
  289. args.push_back(arg);
  290. arg.clear();
  291. in_argument = false;
  292. }
  293. } else {
  294. in_argument = true;
  295. arg.append(1, *c);
  296. }
  297. }
  298. }
  299. arg.append(backslashes, '\\');
  300. if (in_argument) {
  301. args.push_back(arg);
  302. }
  303. }
  304. class cmSystemToolsArgV
  305. {
  306. char** ArgV;
  307. public:
  308. cmSystemToolsArgV(char** argv)
  309. : ArgV(argv)
  310. {
  311. }
  312. ~cmSystemToolsArgV()
  313. {
  314. for (char** arg = this->ArgV; arg && *arg; ++arg) {
  315. free(*arg);
  316. }
  317. free(this->ArgV);
  318. }
  319. cmSystemToolsArgV(const cmSystemToolsArgV&) = delete;
  320. cmSystemToolsArgV& operator=(const cmSystemToolsArgV&) = delete;
  321. void Store(std::vector<std::string>& args) const
  322. {
  323. for (char** arg = this->ArgV; arg && *arg; ++arg) {
  324. args.emplace_back(*arg);
  325. }
  326. }
  327. };
  328. void cmSystemTools::ParseUnixCommandLine(const char* command,
  329. std::vector<std::string>& args)
  330. {
  331. // Invoke the underlying parser.
  332. cmSystemToolsArgV argv(cmsysSystem_Parse_CommandForUnix(command, 0));
  333. argv.Store(args);
  334. }
  335. std::vector<std::string> cmSystemTools::HandleResponseFile(
  336. std::vector<std::string>::const_iterator argBeg,
  337. std::vector<std::string>::const_iterator argEnd)
  338. {
  339. std::vector<std::string> arg_full;
  340. for (std::string const& arg : cmMakeRange(argBeg, argEnd)) {
  341. if (cmHasLiteralPrefix(arg, "@")) {
  342. cmsys::ifstream responseFile(arg.substr(1).c_str(), std::ios::in);
  343. if (!responseFile) {
  344. std::string error = cmStrCat("failed to open for reading (",
  345. cmSystemTools::GetLastSystemError(),
  346. "):\n ", cm::string_view(arg).substr(1));
  347. cmSystemTools::Error(error);
  348. } else {
  349. std::string line;
  350. cmSystemTools::GetLineFromStream(responseFile, line);
  351. std::vector<std::string> args2;
  352. #ifdef _WIN32
  353. cmSystemTools::ParseWindowsCommandLine(line.c_str(), args2);
  354. #else
  355. cmSystemTools::ParseUnixCommandLine(line.c_str(), args2);
  356. #endif
  357. cm::append(arg_full, args2);
  358. }
  359. } else {
  360. arg_full.push_back(arg);
  361. }
  362. }
  363. return arg_full;
  364. }
  365. std::vector<std::string> cmSystemTools::ParseArguments(const std::string& cmd)
  366. {
  367. std::vector<std::string> args;
  368. std::string arg;
  369. bool win_path = false;
  370. const char* command = cmd.c_str();
  371. if (command[0] && command[1] &&
  372. ((command[0] != '/' && command[1] == ':' && command[2] == '\\') ||
  373. (command[0] == '\"' && command[1] != '/' && command[2] == ':' &&
  374. command[3] == '\\') ||
  375. (command[0] == '\'' && command[1] != '/' && command[2] == ':' &&
  376. command[3] == '\\') ||
  377. (command[0] == '\\' && command[1] == '\\'))) {
  378. win_path = true;
  379. }
  380. // Split the command into an argv array.
  381. for (const char* c = command; *c;) {
  382. // Skip over whitespace.
  383. while (*c == ' ' || *c == '\t') {
  384. ++c;
  385. }
  386. arg.clear();
  387. if (*c == '"') {
  388. // Parse a quoted argument.
  389. ++c;
  390. while (*c && *c != '"') {
  391. arg.append(1, *c);
  392. ++c;
  393. }
  394. if (*c) {
  395. ++c;
  396. }
  397. args.push_back(arg);
  398. } else if (*c == '\'') {
  399. // Parse a quoted argument.
  400. ++c;
  401. while (*c && *c != '\'') {
  402. arg.append(1, *c);
  403. ++c;
  404. }
  405. if (*c) {
  406. ++c;
  407. }
  408. args.push_back(arg);
  409. } else if (*c) {
  410. // Parse an unquoted argument.
  411. while (*c && *c != ' ' && *c != '\t') {
  412. if (*c == '\\' && !win_path) {
  413. ++c;
  414. if (*c) {
  415. arg.append(1, *c);
  416. ++c;
  417. }
  418. } else {
  419. arg.append(1, *c);
  420. ++c;
  421. }
  422. }
  423. args.push_back(arg);
  424. }
  425. }
  426. return args;
  427. }
  428. bool cmSystemTools::SplitProgramFromArgs(std::string const& command,
  429. std::string& program,
  430. std::string& args)
  431. {
  432. const char* c = command.c_str();
  433. // Skip leading whitespace.
  434. while (cmIsSpace(*c)) {
  435. ++c;
  436. }
  437. // Parse one command-line element up to an unquoted space.
  438. bool in_escape = false;
  439. bool in_double = false;
  440. bool in_single = false;
  441. for (; *c; ++c) {
  442. if (in_single) {
  443. if (*c == '\'') {
  444. in_single = false;
  445. } else {
  446. program += *c;
  447. }
  448. } else if (in_escape) {
  449. in_escape = false;
  450. program += *c;
  451. } else if (*c == '\\') {
  452. in_escape = true;
  453. } else if (in_double) {
  454. if (*c == '"') {
  455. in_double = false;
  456. } else {
  457. program += *c;
  458. }
  459. } else if (*c == '"') {
  460. in_double = true;
  461. } else if (*c == '\'') {
  462. in_single = true;
  463. } else if (cmIsSpace(*c)) {
  464. break;
  465. } else {
  466. program += *c;
  467. }
  468. }
  469. // The remainder of the command line holds unparsed arguments.
  470. args = c;
  471. return !in_single && !in_escape && !in_double;
  472. }
  473. std::size_t cmSystemTools::CalculateCommandLineLengthLimit()
  474. {
  475. size_t sz =
  476. #ifdef _WIN32
  477. // There's a maximum of 65536 bytes and thus 32768 WCHARs on Windows
  478. // However, cmd.exe itself can only handle 8191 WCHARs and Ninja for
  479. // example uses it to spawn processes.
  480. size_t(8191);
  481. #elif defined(__linux)
  482. // MAX_ARG_STRLEN is the maximum length of a string permissible for
  483. // the execve() syscall on Linux. It's defined as (PAGE_SIZE * 32)
  484. // in Linux's binfmts.h
  485. static_cast<size_t>(sysconf(_SC_PAGESIZE) * 32);
  486. #else
  487. size_t(0);
  488. #endif
  489. #if defined(_SC_ARG_MAX)
  490. // ARG_MAX is the maximum size of the command and environment
  491. // that can be passed to the exec functions on UNIX.
  492. // The value in climits does not need to be present and may
  493. // depend upon runtime memory constraints, hence sysconf()
  494. // should be used to query it.
  495. long szArgMax = sysconf(_SC_ARG_MAX);
  496. // A return value of -1 signifies an undetermined limit, but
  497. // it does not imply an infinite limit, and thus is ignored.
  498. if (szArgMax != -1) {
  499. // We estimate the size of the environment block to be 1000.
  500. // This isn't accurate at all, but leaves some headroom.
  501. szArgMax = szArgMax < 1000 ? 0 : szArgMax - 1000;
  502. # if defined(_WIN32) || defined(__linux)
  503. sz = std::min(sz, static_cast<size_t>(szArgMax));
  504. # else
  505. sz = static_cast<size_t>(szArgMax);
  506. # endif
  507. }
  508. #endif
  509. return sz;
  510. }
  511. bool cmSystemTools::RunSingleCommand(std::vector<std::string> const& command,
  512. std::string* captureStdOut,
  513. std::string* captureStdErr, int* retVal,
  514. const char* dir, OutputOption outputflag,
  515. cmDuration timeout, Encoding encoding)
  516. {
  517. cmUVProcessChainBuilder builder;
  518. builder
  519. .SetExternalStream(cmUVProcessChainBuilder::Stream_INPUT, cm_fileno(stdin))
  520. .AddCommand(command);
  521. if (dir) {
  522. builder.SetWorkingDirectory(dir);
  523. }
  524. if (outputflag == OUTPUT_PASSTHROUGH) {
  525. captureStdOut = nullptr;
  526. captureStdErr = nullptr;
  527. builder
  528. .SetExternalStream(cmUVProcessChainBuilder::Stream_OUTPUT,
  529. cm_fileno(stdout))
  530. .SetExternalStream(cmUVProcessChainBuilder::Stream_ERROR,
  531. cm_fileno(stderr));
  532. } else if (outputflag == OUTPUT_MERGE ||
  533. (captureStdErr && captureStdErr == captureStdOut)) {
  534. builder.SetMergedBuiltinStreams();
  535. captureStdErr = nullptr;
  536. } else {
  537. builder.SetBuiltinStream(cmUVProcessChainBuilder::Stream_OUTPUT)
  538. .SetBuiltinStream(cmUVProcessChainBuilder::Stream_ERROR);
  539. }
  540. assert(!captureStdErr || captureStdErr != captureStdOut);
  541. auto chain = builder.Start();
  542. bool timedOut = false;
  543. cm::uv_timer_ptr timer;
  544. if (timeout.count()) {
  545. timer.init(chain.GetLoop(), &timedOut);
  546. timer.start(
  547. [](uv_timer_t* t) {
  548. auto* timedOutPtr = static_cast<bool*>(t->data);
  549. *timedOutPtr = true;
  550. },
  551. static_cast<uint64_t>(timeout.count() * 1000.0), 0);
  552. }
  553. std::vector<char> tempStdOut;
  554. std::vector<char> tempStdErr;
  555. cm::uv_pipe_ptr outStream;
  556. bool outFinished = true;
  557. cm::uv_pipe_ptr errStream;
  558. bool errFinished = true;
  559. cmProcessOutput processOutput(encoding);
  560. std::unique_ptr<cmUVStreamReadHandle> outputHandle;
  561. std::unique_ptr<cmUVStreamReadHandle> errorHandle;
  562. if (outputflag != OUTPUT_PASSTHROUGH &&
  563. (captureStdOut || captureStdErr || outputflag != OUTPUT_NONE)) {
  564. auto startRead =
  565. [&outputflag, &processOutput,
  566. &chain](cm::uv_pipe_ptr& pipe, int stream, std::string* captureStd,
  567. std::vector<char>& tempStd, int id,
  568. void (*outputFunc)(const std::string&),
  569. bool& finished) -> std::unique_ptr<cmUVStreamReadHandle> {
  570. if (stream < 0) {
  571. return nullptr;
  572. }
  573. pipe.init(chain.GetLoop(), 0);
  574. uv_pipe_open(pipe, stream);
  575. finished = false;
  576. return cmUVStreamRead(
  577. pipe,
  578. [outputflag, &processOutput, captureStd, &tempStd, id,
  579. outputFunc](std::vector<char> data) {
  580. // Translate NULL characters in the output into valid text.
  581. for (auto& c : data) {
  582. if (c == '\0') {
  583. c = ' ';
  584. }
  585. }
  586. if (outputflag != OUTPUT_NONE) {
  587. std::string strdata;
  588. processOutput.DecodeText(data.data(), data.size(), strdata, id);
  589. outputFunc(strdata);
  590. }
  591. if (captureStd) {
  592. cm::append(tempStd, data.data(), data.data() + data.size());
  593. }
  594. },
  595. [&finished, outputflag, &processOutput, id, outputFunc]() {
  596. finished = true;
  597. if (outputflag != OUTPUT_NONE) {
  598. std::string strdata;
  599. processOutput.DecodeText(std::string(), strdata, id);
  600. if (!strdata.empty()) {
  601. outputFunc(strdata);
  602. }
  603. }
  604. });
  605. };
  606. outputHandle =
  607. startRead(outStream, chain.OutputStream(), captureStdOut, tempStdOut, 1,
  608. cmSystemTools::Stdout, outFinished);
  609. if (chain.OutputStream() != chain.ErrorStream()) {
  610. errorHandle =
  611. startRead(errStream, chain.ErrorStream(), captureStdErr, tempStdErr, 2,
  612. cmSystemTools::Stderr, errFinished);
  613. }
  614. }
  615. while (!timedOut && !(chain.Finished() && outFinished && errFinished)) {
  616. uv_run(&chain.GetLoop(), UV_RUN_ONCE);
  617. }
  618. if (captureStdOut) {
  619. captureStdOut->assign(tempStdOut.begin(), tempStdOut.end());
  620. processOutput.DecodeText(*captureStdOut, *captureStdOut);
  621. }
  622. if (captureStdErr) {
  623. captureStdErr->assign(tempStdErr.begin(), tempStdErr.end());
  624. processOutput.DecodeText(*captureStdErr, *captureStdErr);
  625. }
  626. bool result = true;
  627. if (timedOut) {
  628. const char* error_str = "Process terminated due to timeout\n";
  629. if (outputflag != OUTPUT_NONE) {
  630. std::cerr << error_str << std::endl;
  631. }
  632. if (captureStdErr) {
  633. captureStdErr->append(error_str, strlen(error_str));
  634. }
  635. result = false;
  636. } else {
  637. auto const& status = chain.GetStatus(0);
  638. auto exception = status.GetException();
  639. switch (exception.first) {
  640. case cmUVProcessChain::ExceptionCode::None:
  641. if (retVal) {
  642. *retVal = static_cast<int>(status.ExitStatus);
  643. } else {
  644. if (status.ExitStatus != 0) {
  645. result = false;
  646. }
  647. }
  648. break;
  649. default: {
  650. if (outputflag != OUTPUT_NONE) {
  651. std::cerr << exception.second << std::endl;
  652. }
  653. if (captureStdErr) {
  654. captureStdErr->append(exception.second);
  655. } else if (captureStdOut) {
  656. captureStdOut->append(exception.second);
  657. }
  658. result = false;
  659. } break;
  660. }
  661. }
  662. return result;
  663. }
  664. bool cmSystemTools::RunSingleCommand(const std::string& command,
  665. std::string* captureStdOut,
  666. std::string* captureStdErr, int* retVal,
  667. const char* dir, OutputOption outputflag,
  668. cmDuration timeout)
  669. {
  670. if (s_DisableRunCommandOutput) {
  671. outputflag = OUTPUT_NONE;
  672. }
  673. std::vector<std::string> args = cmSystemTools::ParseArguments(command);
  674. if (args.empty()) {
  675. return false;
  676. }
  677. return cmSystemTools::RunSingleCommand(args, captureStdOut, captureStdErr,
  678. retVal, dir, outputflag, timeout);
  679. }
  680. std::string cmSystemTools::PrintSingleCommand(
  681. std::vector<std::string> const& command)
  682. {
  683. if (command.empty()) {
  684. return std::string();
  685. }
  686. return cmWrap('"', command, '"', " ");
  687. }
  688. bool cmSystemTools::DoesFileExistWithExtensions(
  689. const std::string& name, const std::vector<std::string>& headerExts)
  690. {
  691. std::string hname;
  692. for (std::string const& headerExt : headerExts) {
  693. hname = cmStrCat(name, '.', headerExt);
  694. if (cmSystemTools::FileExists(hname)) {
  695. return true;
  696. }
  697. }
  698. return false;
  699. }
  700. std::string cmSystemTools::FileExistsInParentDirectories(
  701. const std::string& fname, const std::string& directory,
  702. const std::string& toplevel)
  703. {
  704. std::string file = fname;
  705. cmSystemTools::ConvertToUnixSlashes(file);
  706. std::string dir = directory;
  707. cmSystemTools::ConvertToUnixSlashes(dir);
  708. std::string prevDir;
  709. while (dir != prevDir) {
  710. std::string path = cmStrCat(dir, "/", file);
  711. if (cmSystemTools::FileExists(path)) {
  712. return path;
  713. }
  714. if (dir.size() < toplevel.size()) {
  715. break;
  716. }
  717. prevDir = dir;
  718. dir = cmSystemTools::GetParentDirectory(dir);
  719. }
  720. return "";
  721. }
  722. #ifdef _WIN32
  723. namespace {
  724. /* Helper class to save and restore the specified file (or directory)
  725. attribute bits. Instantiate this class as an automatic variable on the
  726. stack. Its constructor saves a copy of the file attributes, and then its
  727. destructor restores the original attribute settings. */
  728. class SaveRestoreFileAttributes
  729. {
  730. public:
  731. SaveRestoreFileAttributes(std::wstring const& path,
  732. uint32_t file_attrs_to_set);
  733. ~SaveRestoreFileAttributes();
  734. SaveRestoreFileAttributes(SaveRestoreFileAttributes const&) = delete;
  735. SaveRestoreFileAttributes& operator=(SaveRestoreFileAttributes const&) =
  736. delete;
  737. void SetPath(std::wstring const& path) { path_ = path; }
  738. private:
  739. std::wstring path_;
  740. uint32_t original_attr_bits_;
  741. };
  742. SaveRestoreFileAttributes::SaveRestoreFileAttributes(
  743. std::wstring const& path, uint32_t file_attrs_to_set)
  744. : path_(path)
  745. , original_attr_bits_(0)
  746. {
  747. // Set the specified attributes for the source file/directory.
  748. original_attr_bits_ = GetFileAttributesW(path_.c_str());
  749. if ((INVALID_FILE_ATTRIBUTES != original_attr_bits_) &&
  750. ((file_attrs_to_set & original_attr_bits_) != file_attrs_to_set)) {
  751. SetFileAttributesW(path_.c_str(), original_attr_bits_ | file_attrs_to_set);
  752. }
  753. }
  754. // We set attribute bits. Now we need to restore their original state.
  755. SaveRestoreFileAttributes::~SaveRestoreFileAttributes()
  756. {
  757. DWORD last_error = GetLastError();
  758. // Verify or restore the original attributes.
  759. const DWORD source_attr_bits = GetFileAttributesW(path_.c_str());
  760. if (INVALID_FILE_ATTRIBUTES != source_attr_bits) {
  761. if (original_attr_bits_ != source_attr_bits) {
  762. // The file still exists, and its attributes aren't our saved values.
  763. // Time to restore them.
  764. SetFileAttributesW(path_.c_str(), original_attr_bits_);
  765. }
  766. }
  767. SetLastError(last_error);
  768. }
  769. struct WindowsFileRetryInit
  770. {
  771. cmSystemTools::WindowsFileRetry Retry;
  772. bool Explicit;
  773. };
  774. WindowsFileRetryInit InitWindowsFileRetry(wchar_t const* const values[2],
  775. unsigned int const defaults[2])
  776. {
  777. unsigned int data[2] = { 0, 0 };
  778. HKEY const keys[2] = { HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE };
  779. for (int k = 0; k < 2; ++k) {
  780. HKEY hKey;
  781. if (RegOpenKeyExW(keys[k], L"Software\\Kitware\\CMake\\Config", 0,
  782. KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS) {
  783. for (int v = 0; v < 2; ++v) {
  784. DWORD dwData, dwType, dwSize = 4;
  785. if (!data[v] &&
  786. RegQueryValueExW(hKey, values[v], 0, &dwType, (BYTE*)&dwData,
  787. &dwSize) == ERROR_SUCCESS &&
  788. dwType == REG_DWORD && dwSize == 4) {
  789. data[v] = static_cast<unsigned int>(dwData);
  790. }
  791. }
  792. RegCloseKey(hKey);
  793. }
  794. }
  795. WindowsFileRetryInit init;
  796. init.Explicit = data[0] || data[1];
  797. init.Retry.Count = data[0] ? data[0] : defaults[0];
  798. init.Retry.Delay = data[1] ? data[1] : defaults[1];
  799. return init;
  800. }
  801. WindowsFileRetryInit InitWindowsFileRetry()
  802. {
  803. static wchar_t const* const values[2] = { L"FilesystemRetryCount",
  804. L"FilesystemRetryDelay" };
  805. static unsigned int const defaults[2] = { 5, 500 };
  806. return InitWindowsFileRetry(values, defaults);
  807. }
  808. WindowsFileRetryInit InitWindowsDirectoryRetry()
  809. {
  810. static wchar_t const* const values[2] = { L"FilesystemDirectoryRetryCount",
  811. L"FilesystemDirectoryRetryDelay" };
  812. static unsigned int const defaults[2] = { 120, 500 };
  813. WindowsFileRetryInit dirInit = InitWindowsFileRetry(values, defaults);
  814. if (dirInit.Explicit) {
  815. return dirInit;
  816. }
  817. WindowsFileRetryInit fileInit = InitWindowsFileRetry();
  818. if (fileInit.Explicit) {
  819. return fileInit;
  820. }
  821. return dirInit;
  822. }
  823. cmSystemTools::WindowsFileRetry GetWindowsRetry(std::wstring const& path)
  824. {
  825. // If we are performing a directory operation, then try and get the
  826. // appropriate timing info.
  827. DWORD const attrs = GetFileAttributesW(path.c_str());
  828. if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY)) {
  829. return cmSystemTools::GetWindowsDirectoryRetry();
  830. }
  831. return cmSystemTools::GetWindowsFileRetry();
  832. }
  833. } // end of anonymous namespace
  834. cmSystemTools::WindowsFileRetry cmSystemTools::GetWindowsFileRetry()
  835. {
  836. static WindowsFileRetry retry = InitWindowsFileRetry().Retry;
  837. return retry;
  838. }
  839. cmSystemTools::WindowsFileRetry cmSystemTools::GetWindowsDirectoryRetry()
  840. {
  841. static cmSystemTools::WindowsFileRetry retry =
  842. InitWindowsDirectoryRetry().Retry;
  843. return retry;
  844. }
  845. cmSystemTools::WindowsVersion cmSystemTools::GetWindowsVersion()
  846. {
  847. /* Windows version number data. */
  848. OSVERSIONINFOEXW osviex;
  849. ZeroMemory(&osviex, sizeof(osviex));
  850. osviex.dwOSVersionInfoSize = sizeof(osviex);
  851. # ifdef CM_WINDOWS_DEPRECATED_GetVersionEx
  852. # pragma warning(push)
  853. # ifdef __INTEL_COMPILER
  854. # pragma warning(disable : 1478)
  855. # elif defined __clang__
  856. # pragma clang diagnostic push
  857. # pragma clang diagnostic ignored "-Wdeprecated-declarations"
  858. # else
  859. # pragma warning(disable : 4996)
  860. # endif
  861. # endif
  862. GetVersionExW((OSVERSIONINFOW*)&osviex);
  863. # ifdef CM_WINDOWS_DEPRECATED_GetVersionEx
  864. # ifdef __clang__
  865. # pragma clang diagnostic pop
  866. # else
  867. # pragma warning(pop)
  868. # endif
  869. # endif
  870. WindowsVersion result;
  871. result.dwMajorVersion = osviex.dwMajorVersion;
  872. result.dwMinorVersion = osviex.dwMinorVersion;
  873. result.dwBuildNumber = osviex.dwBuildNumber;
  874. return result;
  875. }
  876. #endif
  877. std::string cmSystemTools::GetRealPathResolvingWindowsSubst(
  878. const std::string& path, std::string* errorMessage)
  879. {
  880. #ifdef _WIN32
  881. // uv_fs_realpath uses Windows Vista API so fallback to kwsys if not found
  882. std::string resolved_path;
  883. uv_fs_t req;
  884. int err = uv_fs_realpath(nullptr, &req, path.c_str(), nullptr);
  885. if (!err) {
  886. resolved_path = std::string((char*)req.ptr);
  887. cmSystemTools::ConvertToUnixSlashes(resolved_path);
  888. // Normalize to upper-case drive letter as GetActualCaseForPath does.
  889. if (resolved_path.size() > 1 && resolved_path[1] == ':') {
  890. resolved_path[0] = toupper(resolved_path[0]);
  891. }
  892. } else if (err == UV_ENOSYS) {
  893. resolved_path = cmsys::SystemTools::GetRealPath(path, errorMessage);
  894. } else if (errorMessage) {
  895. LPSTR message = nullptr;
  896. DWORD size = FormatMessageA(
  897. FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
  898. FORMAT_MESSAGE_IGNORE_INSERTS,
  899. nullptr, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&message,
  900. 0, nullptr);
  901. *errorMessage = std::string(message, size);
  902. LocalFree(message);
  903. resolved_path = "";
  904. } else {
  905. resolved_path = path;
  906. }
  907. return resolved_path;
  908. #else
  909. return cmsys::SystemTools::GetRealPath(path, errorMessage);
  910. #endif
  911. }
  912. void cmSystemTools::InitializeLibUV()
  913. {
  914. #if defined(_WIN32)
  915. // Perform libuv one-time initialization now, and then un-do its
  916. // global _fmode setting so that using libuv does not change the
  917. // default file text/binary mode. See libuv issue 840.
  918. if (uv_loop_t* loop = uv_default_loop()) {
  919. uv_loop_close(loop);
  920. }
  921. # ifdef _MSC_VER
  922. _set_fmode(_O_TEXT);
  923. # else
  924. _fmode = _O_TEXT;
  925. # endif
  926. // Replace libuv's report handler with our own to suppress popups.
  927. cmSystemTools::EnableMSVCDebugHook();
  928. #endif
  929. }
  930. #if defined(_WIN32)
  931. # include <random>
  932. # include <wctype.h>
  933. # ifdef _MSC_VER
  934. using mode_t = cmSystemTools::SystemTools::mode_t;
  935. # endif
  936. #else
  937. # include <sys/stat.h>
  938. #endif
  939. inline int Mkdir(const char* dir, const mode_t* mode)
  940. {
  941. #if defined(_WIN32)
  942. int ret = _wmkdir(cmSystemTools::ConvertToWindowsExtendedPath(dir).c_str());
  943. if (ret == 0 && mode)
  944. cmSystemTools::SystemTools::SetPermissions(dir, *mode);
  945. return ret;
  946. #else
  947. return mkdir(dir, mode ? *mode : 0777);
  948. #endif
  949. }
  950. cmsys::Status cmSystemTools::MakeTempDirectory(std::string& path,
  951. const mode_t* mode)
  952. {
  953. if (path.empty()) {
  954. return cmsys::Status::POSIX(EINVAL);
  955. }
  956. return cmSystemTools::MakeTempDirectory(&path.front(), mode);
  957. }
  958. cmsys::Status cmSystemTools::MakeTempDirectory(char* path, const mode_t* mode)
  959. {
  960. if (!path) {
  961. return cmsys::Status::POSIX(EINVAL);
  962. }
  963. // verify that path ends with "XXXXXX"
  964. const auto l = std::strlen(path);
  965. if (!cmHasLiteralSuffix(cm::string_view{ path, l }, "XXXXXX")) {
  966. return cmsys::Status::POSIX(EINVAL);
  967. }
  968. // create parent directories
  969. auto* sep = path;
  970. while ((sep = strchr(sep, '/'))) {
  971. // all underlying functions use C strings,
  972. // so temporarily end the string here
  973. *sep = '\0';
  974. Mkdir(path, mode);
  975. *sep = '/';
  976. ++sep;
  977. }
  978. #ifdef _WIN32
  979. const int nchars = 36;
  980. const char chars[nchars + 1] = "abcdefghijklmnopqrstuvwxyz0123456789";
  981. std::random_device rd;
  982. std::mt19937 rg{ rd() };
  983. std::uniform_int_distribution<int> dist{ 0, nchars - 1 };
  984. for (auto tries = 100; tries; --tries) {
  985. for (auto n = l - 6; n < l; ++n) {
  986. path[n] = chars[dist(rg)];
  987. }
  988. if (Mkdir(path, mode) == 0) {
  989. return cmsys::Status::Success();
  990. } else if (errno != EEXIST) {
  991. return cmsys::Status::POSIX_errno();
  992. }
  993. }
  994. return cmsys::Status::POSIX(EAGAIN);
  995. #else
  996. if (mkdtemp(path)) {
  997. if (mode) {
  998. chmod(path, *mode);
  999. }
  1000. } else {
  1001. return cmsys::Status::POSIX_errno();
  1002. }
  1003. return cmsys::Status::Success();
  1004. #endif
  1005. }
  1006. #ifdef _WIN32
  1007. namespace {
  1008. bool cmMoveFile(std::wstring const& oldname, std::wstring const& newname,
  1009. cmSystemTools::Replace replace)
  1010. {
  1011. // Not only ignore any previous error, but clear any memory of it.
  1012. SetLastError(0);
  1013. DWORD flags = 0;
  1014. if (replace == cmSystemTools::Replace::Yes) {
  1015. // Use MOVEFILE_REPLACE_EXISTING to replace an existing destination file.
  1016. flags = flags | MOVEFILE_REPLACE_EXISTING;
  1017. }
  1018. return MoveFileExW(oldname.c_str(), newname.c_str(), flags);
  1019. }
  1020. }
  1021. #endif
  1022. cmSystemTools::CopyResult cmSystemTools::CopySingleFile(
  1023. std::string const& oldname, std::string const& newname, CopyWhen when,
  1024. CopyInputRecent inputRecent, std::string* err)
  1025. {
  1026. switch (when) {
  1027. case CopyWhen::Always:
  1028. break;
  1029. case CopyWhen::OnlyIfDifferent:
  1030. if (!FilesDiffer(oldname, newname)) {
  1031. return CopyResult::Success;
  1032. }
  1033. break;
  1034. }
  1035. mode_t perm = 0;
  1036. cmsys::Status perms = SystemTools::GetPermissions(oldname, perm);
  1037. // If files are the same do not copy
  1038. if (SystemTools::SameFile(oldname, newname)) {
  1039. return CopyResult::Success;
  1040. }
  1041. cmsys::SystemTools::CopyStatus status;
  1042. status = cmsys::SystemTools::CloneFileContent(oldname, newname);
  1043. if (!status) {
  1044. // if cloning did not succeed, fall back to blockwise copy
  1045. #ifdef _WIN32
  1046. if (inputRecent == CopyInputRecent::Yes) {
  1047. // Windows sometimes locks a file immediately after creation.
  1048. // Retry a few times.
  1049. WindowsFileRetry retry = cmSystemTools::GetWindowsFileRetry();
  1050. while ((status =
  1051. cmsys::SystemTools::CopyFileContentBlockwise(oldname, newname),
  1052. status.Path == cmsys::SystemTools::CopyStatus::SourcePath &&
  1053. status.GetPOSIX() == EACCES && --retry.Count)) {
  1054. cmSystemTools::Delay(retry.Delay);
  1055. }
  1056. } else {
  1057. status = cmsys::SystemTools::CopyFileContentBlockwise(oldname, newname);
  1058. }
  1059. #else
  1060. static_cast<void>(inputRecent);
  1061. status = cmsys::SystemTools::CopyFileContentBlockwise(oldname, newname);
  1062. #endif
  1063. }
  1064. if (!status) {
  1065. if (err) {
  1066. *err = status.GetString();
  1067. switch (status.Path) {
  1068. case cmsys::SystemTools::CopyStatus::SourcePath:
  1069. *err = cmStrCat(*err, " (input)");
  1070. break;
  1071. case cmsys::SystemTools::CopyStatus::DestPath:
  1072. *err = cmStrCat(*err, " (output)");
  1073. break;
  1074. default:
  1075. break;
  1076. }
  1077. }
  1078. return CopyResult::Failure;
  1079. }
  1080. if (perms) {
  1081. perms = SystemTools::SetPermissions(newname, perm);
  1082. if (!perms) {
  1083. if (err) {
  1084. *err = cmStrCat(perms.GetString(), " (output)");
  1085. }
  1086. return CopyResult::Failure;
  1087. }
  1088. }
  1089. return CopyResult::Success;
  1090. }
  1091. bool cmSystemTools::RenameFile(const std::string& oldname,
  1092. const std::string& newname)
  1093. {
  1094. return cmSystemTools::RenameFile(oldname, newname, Replace::Yes) ==
  1095. RenameResult::Success;
  1096. }
  1097. cmSystemTools::RenameResult cmSystemTools::RenameFile(
  1098. std::string const& oldname, std::string const& newname, Replace replace,
  1099. std::string* err)
  1100. {
  1101. #ifdef _WIN32
  1102. # ifndef INVALID_FILE_ATTRIBUTES
  1103. # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
  1104. # endif
  1105. std::wstring const oldname_wstr =
  1106. SystemTools::ConvertToWindowsExtendedPath(oldname);
  1107. std::wstring const newname_wstr =
  1108. SystemTools::ConvertToWindowsExtendedPath(newname);
  1109. /* Windows MoveFileEx may not replace read-only or in-use files. If it
  1110. fails then remove the read-only attribute from any existing destination.
  1111. Try multiple times since we may be racing against another process
  1112. creating/opening the destination file just before our MoveFileEx. */
  1113. WindowsFileRetry retry = GetWindowsRetry(oldname_wstr);
  1114. // Use RAII to set the attribute bit blocking Microsoft Search Indexing,
  1115. // and restore the previous value upon return.
  1116. SaveRestoreFileAttributes save_restore_file_attributes(
  1117. oldname_wstr, FILE_ATTRIBUTE_NOT_CONTENT_INDEXED);
  1118. DWORD move_last_error = 0;
  1119. while (!cmMoveFile(oldname_wstr, newname_wstr, replace) && --retry.Count) {
  1120. move_last_error = GetLastError();
  1121. // There was no error ==> the operation is not yet complete.
  1122. if (move_last_error == NO_ERROR) {
  1123. break;
  1124. }
  1125. // Try again only if failure was due to access/sharing permissions.
  1126. // Most often ERROR_ACCESS_DENIED (a.k.a. I/O error) for a directory, and
  1127. // ERROR_SHARING_VIOLATION for a file, are caused by one of the following:
  1128. // 1) Anti-Virus Software
  1129. // 2) Windows Search Indexer
  1130. // 3) Windows Explorer has an associated directory already opened.
  1131. if (move_last_error != ERROR_ACCESS_DENIED &&
  1132. move_last_error != ERROR_SHARING_VIOLATION) {
  1133. if (replace == Replace::No && move_last_error == ERROR_ALREADY_EXISTS) {
  1134. return RenameResult::NoReplace;
  1135. }
  1136. if (err) {
  1137. *err = cmsys::Status::Windows(move_last_error).GetString();
  1138. }
  1139. return RenameResult::Failure;
  1140. }
  1141. DWORD const attrs = GetFileAttributesW(newname_wstr.c_str());
  1142. if ((attrs != INVALID_FILE_ATTRIBUTES) &&
  1143. (attrs & FILE_ATTRIBUTE_READONLY) &&
  1144. // FILE_ATTRIBUTE_READONLY is not honored on directories.
  1145. !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {
  1146. // Remove the read-only attribute from the destination file.
  1147. SetFileAttributesW(newname_wstr.c_str(),
  1148. attrs & ~FILE_ATTRIBUTE_READONLY);
  1149. } else {
  1150. // The file may be temporarily in use so wait a bit.
  1151. cmSystemTools::Delay(retry.Delay);
  1152. }
  1153. }
  1154. // If we were successful, then there was no error.
  1155. if (retry.Count > 0) {
  1156. move_last_error = 0;
  1157. // Restore the attributes on the new name.
  1158. save_restore_file_attributes.SetPath(newname_wstr);
  1159. }
  1160. SetLastError(move_last_error);
  1161. if (retry.Count > 0) {
  1162. return RenameResult::Success;
  1163. }
  1164. if (replace == Replace::No && GetLastError() == ERROR_ALREADY_EXISTS) {
  1165. return RenameResult::NoReplace;
  1166. }
  1167. if (err) {
  1168. *err = cmsys::Status::Windows_GetLastError().GetString();
  1169. }
  1170. return RenameResult::Failure;
  1171. #else
  1172. // On UNIX we have OS-provided calls to create 'newname' atomically.
  1173. if (replace == Replace::No) {
  1174. if (link(oldname.c_str(), newname.c_str()) == 0) {
  1175. return RenameResult::Success;
  1176. }
  1177. if (errno == EEXIST) {
  1178. return RenameResult::NoReplace;
  1179. }
  1180. if (err) {
  1181. *err = cmsys::Status::POSIX_errno().GetString();
  1182. }
  1183. return RenameResult::Failure;
  1184. }
  1185. if (rename(oldname.c_str(), newname.c_str()) == 0) {
  1186. return RenameResult::Success;
  1187. }
  1188. if (err) {
  1189. *err = cmsys::Status::POSIX_errno().GetString();
  1190. }
  1191. return RenameResult::Failure;
  1192. #endif
  1193. }
  1194. void cmSystemTools::MoveFileIfDifferent(const std::string& source,
  1195. const std::string& destination)
  1196. {
  1197. if (FilesDiffer(source, destination)) {
  1198. if (RenameFile(source, destination)) {
  1199. return;
  1200. }
  1201. CopyFileAlways(source, destination);
  1202. }
  1203. RemoveFile(source);
  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(DWORD fd)
  2172. {
  2173. if (GetStdHandle(fd) != INVALID_HANDLE_VALUE) {
  2174. return;
  2175. }
  2176. SECURITY_ATTRIBUTES sa;
  2177. sa.nLength = sizeof(sa);
  2178. sa.lpSecurityDescriptor = nullptr;
  2179. sa.bInheritHandle = TRUE;
  2180. HANDLE h = CreateFileW(
  2181. L"NUL",
  2182. fd == STD_INPUT_HANDLE ? FILE_GENERIC_READ
  2183. : FILE_GENERIC_WRITE | FILE_READ_ATTRIBUTES,
  2184. FILE_SHARE_READ | FILE_SHARE_WRITE, &sa, OPEN_EXISTING, 0, nullptr);
  2185. if (h == INVALID_HANDLE_VALUE) {
  2186. LPSTR message = nullptr;
  2187. DWORD size = FormatMessageA(
  2188. FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
  2189. FORMAT_MESSAGE_IGNORE_INSERTS,
  2190. nullptr, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  2191. (LPSTR)&message, 0, nullptr);
  2192. std::string msg = std::string(message, size);
  2193. LocalFree(message);
  2194. std::cerr << "failed to open NUL for missing stdio pipe: " << msg;
  2195. abort();
  2196. }
  2197. SetStdHandle(fd, h);
  2198. }
  2199. void cmSystemTools::EnsureStdPipes()
  2200. {
  2201. EnsureStdPipe(STD_INPUT_HANDLE);
  2202. EnsureStdPipe(STD_OUTPUT_HANDLE);
  2203. EnsureStdPipe(STD_ERROR_HANDLE);
  2204. }
  2205. #else
  2206. static void EnsureStdPipe(int fd)
  2207. {
  2208. if (fcntl(fd, F_GETFD) != -1 || errno != EBADF) {
  2209. return;
  2210. }
  2211. int f = open("/dev/null", fd == STDIN_FILENO ? O_RDONLY : O_WRONLY);
  2212. if (f == -1) {
  2213. perror("failed to open /dev/null for missing stdio pipe");
  2214. abort();
  2215. }
  2216. if (f != fd) {
  2217. dup2(f, fd);
  2218. close(f);
  2219. }
  2220. }
  2221. void cmSystemTools::EnsureStdPipes()
  2222. {
  2223. EnsureStdPipe(STDIN_FILENO);
  2224. EnsureStdPipe(STDOUT_FILENO);
  2225. EnsureStdPipe(STDERR_FILENO);
  2226. }
  2227. #endif
  2228. void cmSystemTools::DoNotInheritStdPipes()
  2229. {
  2230. #ifdef _WIN32
  2231. // Check to see if we are attached to a console
  2232. // if so, then do not stop the inherited pipes
  2233. // or stdout and stderr will not show up in dos
  2234. // shell windows
  2235. CONSOLE_SCREEN_BUFFER_INFO hOutInfo;
  2236. HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
  2237. if (GetConsoleScreenBufferInfo(hOut, &hOutInfo)) {
  2238. return;
  2239. }
  2240. {
  2241. HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
  2242. DuplicateHandle(GetCurrentProcess(), out, GetCurrentProcess(), &out, 0,
  2243. FALSE, DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
  2244. SetStdHandle(STD_OUTPUT_HANDLE, out);
  2245. }
  2246. {
  2247. HANDLE out = GetStdHandle(STD_ERROR_HANDLE);
  2248. DuplicateHandle(GetCurrentProcess(), out, GetCurrentProcess(), &out, 0,
  2249. FALSE, DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
  2250. SetStdHandle(STD_ERROR_HANDLE, out);
  2251. }
  2252. #endif
  2253. }
  2254. #ifdef _WIN32
  2255. # ifndef CRYPT_SILENT
  2256. # define CRYPT_SILENT 0x40 /* Not defined by VS 6 version of header. */
  2257. # endif
  2258. static int WinCryptRandom(void* data, size_t size)
  2259. {
  2260. int result = 0;
  2261. HCRYPTPROV hProvider = 0;
  2262. if (CryptAcquireContextW(&hProvider, 0, 0, PROV_RSA_FULL,
  2263. CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) {
  2264. result = CryptGenRandom(hProvider, (DWORD)size, (BYTE*)data) ? 1 : 0;
  2265. CryptReleaseContext(hProvider, 0);
  2266. }
  2267. return result;
  2268. }
  2269. #endif
  2270. unsigned int cmSystemTools::RandomSeed()
  2271. {
  2272. #if defined(_WIN32) && !defined(__CYGWIN__)
  2273. unsigned int seed = 0;
  2274. // Try using a real random source.
  2275. if (WinCryptRandom(&seed, sizeof(seed))) {
  2276. return seed;
  2277. }
  2278. // Fall back to the time and pid.
  2279. FILETIME ft;
  2280. GetSystemTimeAsFileTime(&ft);
  2281. unsigned int t1 = static_cast<unsigned int>(ft.dwHighDateTime);
  2282. unsigned int t2 = static_cast<unsigned int>(ft.dwLowDateTime);
  2283. unsigned int pid = static_cast<unsigned int>(GetCurrentProcessId());
  2284. return t1 ^ t2 ^ pid;
  2285. #else
  2286. union
  2287. {
  2288. unsigned int integer;
  2289. char bytes[sizeof(unsigned int)];
  2290. } seed;
  2291. // Try using a real random source.
  2292. cmsys::ifstream fin;
  2293. fin.rdbuf()->pubsetbuf(nullptr, 0); // Unbuffered read.
  2294. fin.open("/dev/urandom");
  2295. if (fin.good() && fin.read(seed.bytes, sizeof(seed)) &&
  2296. fin.gcount() == sizeof(seed)) {
  2297. return seed.integer;
  2298. }
  2299. // Fall back to the time and pid.
  2300. struct timeval t;
  2301. gettimeofday(&t, nullptr);
  2302. unsigned int pid = static_cast<unsigned int>(getpid());
  2303. unsigned int tv_sec = static_cast<unsigned int>(t.tv_sec);
  2304. unsigned int tv_usec = static_cast<unsigned int>(t.tv_usec);
  2305. // Since tv_usec never fills more than 11 bits we shift it to fill
  2306. // in the slow-changing high-order bits of tv_sec.
  2307. return tv_sec ^ (tv_usec << 21) ^ pid;
  2308. #endif
  2309. }
  2310. static std::string cmSystemToolsCMakeCommand;
  2311. static std::string cmSystemToolsCTestCommand;
  2312. static std::string cmSystemToolsCPackCommand;
  2313. static std::string cmSystemToolsCMakeCursesCommand;
  2314. static std::string cmSystemToolsCMakeGUICommand;
  2315. static std::string cmSystemToolsCMClDepsCommand;
  2316. static std::string cmSystemToolsCMakeRoot;
  2317. static std::string cmSystemToolsHTMLDoc;
  2318. void cmSystemTools::FindCMakeResources(const char* argv0)
  2319. {
  2320. std::string exe_dir;
  2321. #if defined(_WIN32) && !defined(__CYGWIN__)
  2322. (void)argv0; // ignore this on windows
  2323. wchar_t modulepath[_MAX_PATH];
  2324. ::GetModuleFileNameW(nullptr, modulepath, sizeof(modulepath));
  2325. std::string path = cmsys::Encoding::ToNarrow(modulepath);
  2326. std::string realPath =
  2327. cmSystemTools::GetRealPathResolvingWindowsSubst(path, nullptr);
  2328. if (realPath.empty()) {
  2329. realPath = path;
  2330. }
  2331. exe_dir = cmSystemTools::GetFilenamePath(realPath);
  2332. #elif defined(__APPLE__)
  2333. (void)argv0; // ignore this on OS X
  2334. # define CM_EXE_PATH_LOCAL_SIZE 16384
  2335. char exe_path_local[CM_EXE_PATH_LOCAL_SIZE];
  2336. # if defined(MAC_OS_X_VERSION_10_3) && !defined(MAC_OS_X_VERSION_10_4)
  2337. unsigned long exe_path_size = CM_EXE_PATH_LOCAL_SIZE;
  2338. # else
  2339. uint32_t exe_path_size = CM_EXE_PATH_LOCAL_SIZE;
  2340. # endif
  2341. # undef CM_EXE_PATH_LOCAL_SIZE
  2342. char* exe_path = exe_path_local;
  2343. if (_NSGetExecutablePath(exe_path, &exe_path_size) < 0) {
  2344. exe_path = static_cast<char*>(malloc(exe_path_size));
  2345. _NSGetExecutablePath(exe_path, &exe_path_size);
  2346. }
  2347. exe_dir =
  2348. cmSystemTools::GetFilenamePath(cmSystemTools::GetRealPath(exe_path));
  2349. if (exe_path != exe_path_local) {
  2350. free(exe_path);
  2351. }
  2352. if (cmSystemTools::GetFilenameName(exe_dir) == "MacOS") {
  2353. // The executable is inside an application bundle.
  2354. // Look for ..<CMAKE_BIN_DIR> (install tree) and then fall back to
  2355. // ../../../bin (build tree).
  2356. exe_dir = cmSystemTools::GetFilenamePath(exe_dir);
  2357. if (cmSystemTools::FileExists(exe_dir + CMAKE_BIN_DIR "/cmake")) {
  2358. exe_dir += CMAKE_BIN_DIR;
  2359. } else {
  2360. exe_dir = cmSystemTools::GetFilenamePath(exe_dir);
  2361. exe_dir = cmSystemTools::GetFilenamePath(exe_dir);
  2362. }
  2363. }
  2364. #else
  2365. std::string errorMsg;
  2366. std::string exe;
  2367. if (cmSystemTools::FindProgramPath(argv0, exe, errorMsg)) {
  2368. // remove symlinks
  2369. exe = cmSystemTools::GetRealPath(exe);
  2370. exe_dir = cmSystemTools::GetFilenamePath(exe);
  2371. } else {
  2372. // ???
  2373. }
  2374. #endif
  2375. exe_dir = cmSystemTools::GetActualCaseForPath(exe_dir);
  2376. cmSystemToolsCMakeCommand =
  2377. cmStrCat(exe_dir, "/cmake", cmSystemTools::GetExecutableExtension());
  2378. #ifdef CMAKE_BOOTSTRAP
  2379. // The bootstrap cmake does not provide the other tools,
  2380. // so use the directory where they are about to be built.
  2381. exe_dir = CMAKE_BOOTSTRAP_BINARY_DIR "/bin";
  2382. #endif
  2383. cmSystemToolsCTestCommand =
  2384. cmStrCat(exe_dir, "/ctest", cmSystemTools::GetExecutableExtension());
  2385. cmSystemToolsCPackCommand =
  2386. cmStrCat(exe_dir, "/cpack", cmSystemTools::GetExecutableExtension());
  2387. cmSystemToolsCMakeGUICommand =
  2388. cmStrCat(exe_dir, "/cmake-gui", cmSystemTools::GetExecutableExtension());
  2389. if (!cmSystemTools::FileExists(cmSystemToolsCMakeGUICommand)) {
  2390. cmSystemToolsCMakeGUICommand.clear();
  2391. }
  2392. cmSystemToolsCMakeCursesCommand =
  2393. cmStrCat(exe_dir, "/ccmake", cmSystemTools::GetExecutableExtension());
  2394. if (!cmSystemTools::FileExists(cmSystemToolsCMakeCursesCommand)) {
  2395. cmSystemToolsCMakeCursesCommand.clear();
  2396. }
  2397. cmSystemToolsCMClDepsCommand =
  2398. cmStrCat(exe_dir, "/cmcldeps", cmSystemTools::GetExecutableExtension());
  2399. if (!cmSystemTools::FileExists(cmSystemToolsCMClDepsCommand)) {
  2400. cmSystemToolsCMClDepsCommand.clear();
  2401. }
  2402. #ifndef CMAKE_BOOTSTRAP
  2403. // Install tree has
  2404. // - "<prefix><CMAKE_BIN_DIR>/cmake"
  2405. // - "<prefix><CMAKE_DATA_DIR>"
  2406. // - "<prefix><CMAKE_DOC_DIR>"
  2407. if (cmHasLiteralSuffix(exe_dir, CMAKE_BIN_DIR)) {
  2408. std::string const prefix =
  2409. exe_dir.substr(0, exe_dir.size() - cmStrLen(CMAKE_BIN_DIR));
  2410. cmSystemToolsCMakeRoot = cmStrCat(prefix, CMAKE_DATA_DIR);
  2411. if (cmSystemTools::FileExists(
  2412. cmStrCat(prefix, CMAKE_DOC_DIR "/html/index.html"))) {
  2413. cmSystemToolsHTMLDoc = cmStrCat(prefix, CMAKE_DOC_DIR "/html");
  2414. }
  2415. }
  2416. if (cmSystemToolsCMakeRoot.empty() ||
  2417. !cmSystemTools::FileExists(
  2418. cmStrCat(cmSystemToolsCMakeRoot, "/Modules/CMake.cmake"))) {
  2419. // Build tree has "<build>/bin[/<config>]/cmake" and
  2420. // "<build>/CMakeFiles/CMakeSourceDir.txt".
  2421. std::string dir = cmSystemTools::GetFilenamePath(exe_dir);
  2422. std::string src_dir_txt = cmStrCat(dir, "/CMakeFiles/CMakeSourceDir.txt");
  2423. cmsys::ifstream fin(src_dir_txt.c_str());
  2424. std::string src_dir;
  2425. if (fin && cmSystemTools::GetLineFromStream(fin, src_dir) &&
  2426. cmSystemTools::FileIsDirectory(src_dir)) {
  2427. cmSystemToolsCMakeRoot = src_dir;
  2428. } else {
  2429. dir = cmSystemTools::GetFilenamePath(dir);
  2430. src_dir_txt = cmStrCat(dir, "/CMakeFiles/CMakeSourceDir.txt");
  2431. cmsys::ifstream fin2(src_dir_txt.c_str());
  2432. if (fin2 && cmSystemTools::GetLineFromStream(fin2, src_dir) &&
  2433. cmSystemTools::FileIsDirectory(src_dir)) {
  2434. cmSystemToolsCMakeRoot = src_dir;
  2435. }
  2436. }
  2437. if (!cmSystemToolsCMakeRoot.empty() && cmSystemToolsHTMLDoc.empty() &&
  2438. cmSystemTools::FileExists(
  2439. cmStrCat(dir, "/Utilities/Sphinx/html/index.html"))) {
  2440. cmSystemToolsHTMLDoc = cmStrCat(dir, "/Utilities/Sphinx/html");
  2441. }
  2442. }
  2443. #else
  2444. // Bootstrap build knows its source.
  2445. cmSystemToolsCMakeRoot = CMAKE_BOOTSTRAP_SOURCE_DIR;
  2446. #endif
  2447. }
  2448. std::string const& cmSystemTools::GetCMakeCommand()
  2449. {
  2450. return cmSystemToolsCMakeCommand;
  2451. }
  2452. std::string const& cmSystemTools::GetCTestCommand()
  2453. {
  2454. return cmSystemToolsCTestCommand;
  2455. }
  2456. std::string const& cmSystemTools::GetCPackCommand()
  2457. {
  2458. return cmSystemToolsCPackCommand;
  2459. }
  2460. std::string const& cmSystemTools::GetCMakeCursesCommand()
  2461. {
  2462. return cmSystemToolsCMakeCursesCommand;
  2463. }
  2464. std::string const& cmSystemTools::GetCMakeGUICommand()
  2465. {
  2466. return cmSystemToolsCMakeGUICommand;
  2467. }
  2468. std::string const& cmSystemTools::GetCMClDepsCommand()
  2469. {
  2470. return cmSystemToolsCMClDepsCommand;
  2471. }
  2472. std::string const& cmSystemTools::GetCMakeRoot()
  2473. {
  2474. return cmSystemToolsCMakeRoot;
  2475. }
  2476. std::string const& cmSystemTools::GetHTMLDoc()
  2477. {
  2478. return cmSystemToolsHTMLDoc;
  2479. }
  2480. std::string cmSystemTools::GetCurrentWorkingDirectory()
  2481. {
  2482. return cmSystemTools::CollapseFullPath(
  2483. cmsys::SystemTools::GetCurrentWorkingDirectory());
  2484. }
  2485. void cmSystemTools::MakefileColorEcho(int color, const char* message,
  2486. bool newline, bool enabled)
  2487. {
  2488. // On some platforms (an MSYS prompt) cmsysTerminal may not be able
  2489. // to determine whether the stream is displayed on a tty. In this
  2490. // case it assumes no unless we tell it otherwise. Since we want
  2491. // color messages to be displayed for users we will assume yes.
  2492. // However, we can test for some situations when the answer is most
  2493. // likely no.
  2494. int assumeTTY = cmsysTerminal_Color_AssumeTTY;
  2495. if (cmSystemTools::HasEnv("DART_TEST_FROM_DART") ||
  2496. cmSystemTools::HasEnv("DASHBOARD_TEST_FROM_CTEST") ||
  2497. cmSystemTools::HasEnv("CTEST_INTERACTIVE_DEBUG_MODE")) {
  2498. // Avoid printing color escapes during dashboard builds.
  2499. assumeTTY = 0;
  2500. }
  2501. if (enabled && color != cmsysTerminal_Color_Normal) {
  2502. // Print with color. Delay the newline until later so that
  2503. // all color restore sequences appear before it.
  2504. cmsysTerminal_cfprintf(color | assumeTTY, stdout, "%s", message);
  2505. } else {
  2506. // Color is disabled. Print without color.
  2507. fprintf(stdout, "%s", message);
  2508. }
  2509. if (newline) {
  2510. fprintf(stdout, "\n");
  2511. }
  2512. }
  2513. bool cmSystemTools::GuessLibrarySOName(std::string const& fullPath,
  2514. std::string& soname)
  2515. {
  2516. // For ELF shared libraries use a real parser to get the correct
  2517. // soname.
  2518. cmELF elf(fullPath.c_str());
  2519. if (elf) {
  2520. return elf.GetSOName(soname);
  2521. }
  2522. // If the file is not a symlink we have no guess for its soname.
  2523. if (!cmSystemTools::FileIsSymlink(fullPath)) {
  2524. return false;
  2525. }
  2526. if (!cmSystemTools::ReadSymlink(fullPath, soname)) {
  2527. return false;
  2528. }
  2529. // If the symlink has a path component we have no guess for the soname.
  2530. if (!cmSystemTools::GetFilenamePath(soname).empty()) {
  2531. return false;
  2532. }
  2533. // If the symlink points at an extended version of the same name
  2534. // assume it is the soname.
  2535. std::string name = cmSystemTools::GetFilenameName(fullPath);
  2536. return soname.length() > name.length() &&
  2537. soname.compare(0, name.length(), name) == 0;
  2538. }
  2539. bool cmSystemTools::GuessLibraryInstallName(std::string const& fullPath,
  2540. std::string& soname)
  2541. {
  2542. #if defined(CMake_USE_MACH_PARSER)
  2543. cmMachO macho(fullPath.c_str());
  2544. if (macho) {
  2545. return macho.GetInstallName(soname);
  2546. }
  2547. #else
  2548. (void)fullPath;
  2549. (void)soname;
  2550. #endif
  2551. return false;
  2552. }
  2553. static std::string::size_type cmSystemToolsFindRPath(
  2554. cm::string_view const& have, cm::string_view const& want)
  2555. {
  2556. std::string::size_type pos = 0;
  2557. while (pos < have.size()) {
  2558. // Look for an occurrence of the string.
  2559. std::string::size_type const beg = have.find(want, pos);
  2560. if (beg == std::string::npos) {
  2561. return std::string::npos;
  2562. }
  2563. // Make sure it is separated from preceding entries.
  2564. if (beg > 0 && have[beg - 1] != ':') {
  2565. pos = beg + 1;
  2566. continue;
  2567. }
  2568. // Make sure it is separated from following entries.
  2569. std::string::size_type const end = beg + want.size();
  2570. if (end < have.size() && have[end] != ':') {
  2571. pos = beg + 1;
  2572. continue;
  2573. }
  2574. // Return the position of the path portion.
  2575. return beg;
  2576. }
  2577. // The desired rpath was not found.
  2578. return std::string::npos;
  2579. }
  2580. namespace {
  2581. struct cmSystemToolsRPathInfo
  2582. {
  2583. unsigned long Position;
  2584. unsigned long Size;
  2585. std::string Name;
  2586. std::string Value;
  2587. };
  2588. using EmptyCallback = std::function<bool(std::string*, const cmELF&)>;
  2589. using AdjustCallback = std::function<bool(
  2590. cm::optional<std::string>&, const std::string&, const char*, std::string*)>;
  2591. cm::optional<bool> AdjustRPathELF(std::string const& file,
  2592. const EmptyCallback& emptyCallback,
  2593. const AdjustCallback& adjustCallback,
  2594. std::string* emsg, bool* changed)
  2595. {
  2596. if (changed) {
  2597. *changed = false;
  2598. }
  2599. int rp_count = 0;
  2600. bool remove_rpath = true;
  2601. cmSystemToolsRPathInfo rp[2];
  2602. {
  2603. // Parse the ELF binary.
  2604. cmELF elf(file.c_str());
  2605. if (!elf) {
  2606. return cm::nullopt; // Not a valid ELF file.
  2607. }
  2608. // Get the RPATH and RUNPATH entries from it.
  2609. int se_count = 0;
  2610. cmELF::StringEntry const* se[2] = { nullptr, nullptr };
  2611. const char* se_name[2] = { nullptr, nullptr };
  2612. if (cmELF::StringEntry const* se_rpath = elf.GetRPath()) {
  2613. se[se_count] = se_rpath;
  2614. se_name[se_count] = "RPATH";
  2615. ++se_count;
  2616. }
  2617. if (cmELF::StringEntry const* se_runpath = elf.GetRunPath()) {
  2618. se[se_count] = se_runpath;
  2619. se_name[se_count] = "RUNPATH";
  2620. ++se_count;
  2621. }
  2622. if (se_count == 0) {
  2623. return emptyCallback(emsg, elf);
  2624. }
  2625. for (int i = 0; i < se_count; ++i) {
  2626. // If both RPATH and RUNPATH refer to the same string literal it
  2627. // needs to be changed only once.
  2628. if (rp_count && rp[0].Position == se[i]->Position) {
  2629. continue;
  2630. }
  2631. // Store information about the entry in the file.
  2632. rp[rp_count].Position = se[i]->Position;
  2633. rp[rp_count].Size = se[i]->Size;
  2634. rp[rp_count].Name = se_name[i];
  2635. // Adjust the rpath.
  2636. cm::optional<std::string> outRPath;
  2637. if (!adjustCallback(outRPath, se[i]->Value, se_name[i], emsg)) {
  2638. return false;
  2639. }
  2640. if (outRPath) {
  2641. if (!outRPath->empty()) {
  2642. remove_rpath = false;
  2643. }
  2644. // Make sure there is enough room to store the new rpath and at
  2645. // least one null terminator.
  2646. if (rp[rp_count].Size < outRPath->length() + 1) {
  2647. if (emsg) {
  2648. *emsg = cmStrCat("The replacement path is too long for the ",
  2649. se_name[i], " entry.");
  2650. }
  2651. return false;
  2652. }
  2653. // This entry is ready for update.
  2654. rp[rp_count].Value = std::move(*outRPath);
  2655. ++rp_count;
  2656. } else {
  2657. remove_rpath = false;
  2658. }
  2659. }
  2660. }
  2661. // If no runtime path needs to be changed, we are done.
  2662. if (rp_count == 0) {
  2663. return true;
  2664. }
  2665. // If the resulting rpath is empty, just remove the entire entry instead.
  2666. if (remove_rpath) {
  2667. return cmSystemTools::RemoveRPath(file, emsg, changed);
  2668. }
  2669. {
  2670. // Open the file for update.
  2671. cmsys::ofstream f(file.c_str(),
  2672. std::ios::in | std::ios::out | std::ios::binary);
  2673. if (!f) {
  2674. if (emsg) {
  2675. *emsg = "Error opening file for update.";
  2676. }
  2677. return false;
  2678. }
  2679. // Store the new RPATH and RUNPATH strings.
  2680. for (int i = 0; i < rp_count; ++i) {
  2681. // Seek to the RPATH position.
  2682. if (!f.seekp(rp[i].Position)) {
  2683. if (emsg) {
  2684. *emsg = cmStrCat("Error seeking to ", rp[i].Name, " position.");
  2685. }
  2686. return false;
  2687. }
  2688. // Write the new rpath. Follow it with enough null terminators to
  2689. // fill the string table entry.
  2690. f << rp[i].Value;
  2691. for (unsigned long j = rp[i].Value.length(); j < rp[i].Size; ++j) {
  2692. f << '\0';
  2693. }
  2694. // Make sure it wrote correctly.
  2695. if (!f) {
  2696. if (emsg) {
  2697. *emsg = cmStrCat("Error writing the new ", rp[i].Name,
  2698. " string to the file.");
  2699. }
  2700. return false;
  2701. }
  2702. }
  2703. }
  2704. // Everything was updated successfully.
  2705. if (changed) {
  2706. *changed = true;
  2707. }
  2708. return true;
  2709. }
  2710. std::function<bool(std::string*, const cmELF&)> MakeEmptyCallback(
  2711. const std::string& newRPath)
  2712. {
  2713. return [newRPath](std::string* emsg, const cmELF& elf) -> bool {
  2714. if (newRPath.empty()) {
  2715. // The new rpath is empty and there is no rpath anyway so it is
  2716. // okay.
  2717. return true;
  2718. }
  2719. if (emsg) {
  2720. *emsg =
  2721. cmStrCat("No valid ELF RPATH or RUNPATH entry exists in the file; ",
  2722. elf.GetErrorMessage());
  2723. }
  2724. return false;
  2725. };
  2726. }
  2727. }
  2728. static cm::optional<bool> ChangeRPathELF(std::string const& file,
  2729. std::string const& oldRPath,
  2730. std::string const& newRPath,
  2731. bool removeEnvironmentRPath,
  2732. std::string* emsg, bool* changed)
  2733. {
  2734. auto adjustCallback = [oldRPath, newRPath, removeEnvironmentRPath](
  2735. cm::optional<std::string>& outRPath,
  2736. const std::string& inRPath, const char* se_name,
  2737. std::string* emsg2) -> bool {
  2738. // Make sure the current rpath contains the old rpath.
  2739. std::string::size_type pos = cmSystemToolsFindRPath(inRPath, oldRPath);
  2740. if (pos == std::string::npos) {
  2741. // If it contains the new rpath instead then it is okay.
  2742. if (cmSystemToolsFindRPath(inRPath, newRPath) != std::string::npos) {
  2743. return true;
  2744. }
  2745. if (emsg2) {
  2746. std::ostringstream e;
  2747. /* clang-format off */
  2748. e << "The current " << se_name << " is:\n"
  2749. << " " << inRPath << "\n"
  2750. << "which does not contain:\n"
  2751. << " " << oldRPath << "\n"
  2752. << "as was expected.";
  2753. /* clang-format on */
  2754. *emsg2 = e.str();
  2755. }
  2756. return false;
  2757. }
  2758. std::string::size_type prefix_len = pos;
  2759. // If oldRPath was at the end of the file's RPath, and newRPath is empty,
  2760. // we should remove the unnecessary ':' at the end.
  2761. if (newRPath.empty() && pos > 0 && inRPath[pos - 1] == ':' &&
  2762. pos + oldRPath.length() == inRPath.length()) {
  2763. prefix_len--;
  2764. }
  2765. // Construct the new value which preserves the part of the path
  2766. // not being changed.
  2767. outRPath.emplace();
  2768. if (!removeEnvironmentRPath) {
  2769. *outRPath += inRPath.substr(0, prefix_len);
  2770. }
  2771. *outRPath += newRPath;
  2772. *outRPath += inRPath.substr(pos + oldRPath.length());
  2773. return true;
  2774. };
  2775. return AdjustRPathELF(file, MakeEmptyCallback(newRPath), adjustCallback,
  2776. emsg, changed);
  2777. }
  2778. static cm::optional<bool> SetRPathELF(std::string const& file,
  2779. std::string const& newRPath,
  2780. std::string* emsg, bool* changed)
  2781. {
  2782. auto adjustCallback = [newRPath](cm::optional<std::string>& outRPath,
  2783. const std::string& inRPath,
  2784. const char* /*se_name*/, std::string*
  2785. /*emsg*/) -> bool {
  2786. if (inRPath != newRPath) {
  2787. outRPath = newRPath;
  2788. }
  2789. return true;
  2790. };
  2791. return AdjustRPathELF(file, MakeEmptyCallback(newRPath), adjustCallback,
  2792. emsg, changed);
  2793. }
  2794. static cm::optional<bool> ChangeRPathXCOFF(std::string const& file,
  2795. std::string const& oldRPath,
  2796. std::string const& newRPath,
  2797. bool removeEnvironmentRPath,
  2798. std::string* emsg, bool* changed)
  2799. {
  2800. if (changed) {
  2801. *changed = false;
  2802. }
  2803. #if !defined(CMake_USE_XCOFF_PARSER)
  2804. (void)file;
  2805. (void)oldRPath;
  2806. (void)newRPath;
  2807. (void)removeEnvironmentRPath;
  2808. (void)emsg;
  2809. return cm::nullopt;
  2810. #else
  2811. bool chg = false;
  2812. cmXCOFF xcoff(file.c_str(), cmXCOFF::Mode::ReadWrite);
  2813. if (!xcoff) {
  2814. return cm::nullopt; // Not a valid XCOFF file
  2815. }
  2816. if (cm::optional<cm::string_view> maybeLibPath = xcoff.GetLibPath()) {
  2817. cm::string_view libPath = *maybeLibPath;
  2818. // Make sure the current rpath contains the old rpath.
  2819. std::string::size_type pos = cmSystemToolsFindRPath(libPath, oldRPath);
  2820. if (pos == std::string::npos) {
  2821. // If it contains the new rpath instead then it is okay.
  2822. if (cmSystemToolsFindRPath(libPath, newRPath) != std::string::npos) {
  2823. return true;
  2824. }
  2825. if (emsg) {
  2826. std::ostringstream e;
  2827. /* clang-format off */
  2828. e << "The current RPATH is:\n"
  2829. << " " << libPath << "\n"
  2830. << "which does not contain:\n"
  2831. << " " << oldRPath << "\n"
  2832. << "as was expected.";
  2833. /* clang-format on */
  2834. *emsg = e.str();
  2835. }
  2836. return false;
  2837. }
  2838. // The prefix is either empty or ends in a ':'.
  2839. cm::string_view prefix = libPath.substr(0, pos);
  2840. if (newRPath.empty() && !prefix.empty()) {
  2841. prefix.remove_suffix(1);
  2842. }
  2843. // The suffix is either empty or starts in a ':'.
  2844. cm::string_view suffix = libPath.substr(pos + oldRPath.length());
  2845. // Construct the new value which preserves the part of the path
  2846. // not being changed.
  2847. std::string newLibPath;
  2848. if (!removeEnvironmentRPath) {
  2849. newLibPath = std::string(prefix);
  2850. }
  2851. newLibPath += newRPath;
  2852. newLibPath += suffix;
  2853. chg = xcoff.SetLibPath(newLibPath);
  2854. }
  2855. if (!xcoff) {
  2856. if (emsg) {
  2857. *emsg = xcoff.GetErrorMessage();
  2858. }
  2859. return false;
  2860. }
  2861. // Everything was updated successfully.
  2862. if (changed) {
  2863. *changed = chg;
  2864. }
  2865. return true;
  2866. #endif
  2867. }
  2868. static cm::optional<bool> SetRPathXCOFF(std::string const& /*file*/,
  2869. std::string const& /*newRPath*/,
  2870. std::string* /*emsg*/,
  2871. bool* /*changed*/)
  2872. {
  2873. return cm::nullopt; // Not implemented.
  2874. }
  2875. bool cmSystemTools::ChangeRPath(std::string const& file,
  2876. std::string const& oldRPath,
  2877. std::string const& newRPath,
  2878. bool removeEnvironmentRPath, std::string* emsg,
  2879. bool* changed)
  2880. {
  2881. if (cm::optional<bool> result = ChangeRPathELF(
  2882. file, oldRPath, newRPath, removeEnvironmentRPath, emsg, changed)) {
  2883. return result.value();
  2884. }
  2885. if (cm::optional<bool> result = ChangeRPathXCOFF(
  2886. file, oldRPath, newRPath, removeEnvironmentRPath, emsg, changed)) {
  2887. return result.value();
  2888. }
  2889. // The file format is not recognized. Assume it has no RPATH.
  2890. if (newRPath.empty()) {
  2891. // The caller wanted no RPATH anyway.
  2892. return true;
  2893. }
  2894. if (emsg) {
  2895. *emsg = "The file format is not recognized.";
  2896. }
  2897. return false;
  2898. }
  2899. bool cmSystemTools::SetRPath(std::string const& file,
  2900. std::string const& newRPath, std::string* emsg,
  2901. bool* changed)
  2902. {
  2903. if (cm::optional<bool> result = SetRPathELF(file, newRPath, emsg, changed)) {
  2904. return result.value();
  2905. }
  2906. if (cm::optional<bool> result =
  2907. SetRPathXCOFF(file, newRPath, emsg, changed)) {
  2908. return result.value();
  2909. }
  2910. // The file format is not recognized. Assume it has no RPATH.
  2911. if (newRPath.empty()) {
  2912. // The caller wanted no RPATH anyway.
  2913. return true;
  2914. }
  2915. if (emsg) {
  2916. *emsg = "The file format is not recognized.";
  2917. }
  2918. return false;
  2919. }
  2920. namespace {
  2921. bool VersionCompare(cmSystemTools::CompareOp op, const char* lhss,
  2922. const char* rhss)
  2923. {
  2924. const char* endl = lhss;
  2925. const char* endr = rhss;
  2926. while (((*endl >= '0') && (*endl <= '9')) ||
  2927. ((*endr >= '0') && (*endr <= '9'))) {
  2928. // Do component-wise comparison, ignoring leading zeros
  2929. // (components are treated as integers, not as mantissas)
  2930. while (*endl == '0') {
  2931. endl++;
  2932. }
  2933. while (*endr == '0') {
  2934. endr++;
  2935. }
  2936. const char* beginl = endl;
  2937. const char* beginr = endr;
  2938. // count significant digits
  2939. while ((*endl >= '0') && (*endl <= '9')) {
  2940. endl++;
  2941. }
  2942. while ((*endr >= '0') && (*endr <= '9')) {
  2943. endr++;
  2944. }
  2945. // compare number of digits first
  2946. ptrdiff_t r = ((endl - beginl) - (endr - beginr));
  2947. if (r == 0) {
  2948. // compare the digits if number of digits is equal
  2949. r = strncmp(beginl, beginr, endl - beginl);
  2950. }
  2951. if (r < 0) {
  2952. // lhs < rhs, so true if operation is LESS
  2953. return (op & cmSystemTools::OP_LESS) != 0;
  2954. }
  2955. if (r > 0) {
  2956. // lhs > rhs, so true if operation is GREATER
  2957. return (op & cmSystemTools::OP_GREATER) != 0;
  2958. }
  2959. if (*endr == '.') {
  2960. endr++;
  2961. }
  2962. if (*endl == '.') {
  2963. endl++;
  2964. }
  2965. }
  2966. // lhs == rhs, so true if operation is EQUAL
  2967. return (op & cmSystemTools::OP_EQUAL) != 0;
  2968. }
  2969. }
  2970. bool cmSystemTools::VersionCompare(cmSystemTools::CompareOp op,
  2971. const std::string& lhs,
  2972. const std::string& rhs)
  2973. {
  2974. return ::VersionCompare(op, lhs.c_str(), rhs.c_str());
  2975. }
  2976. bool cmSystemTools::VersionCompare(cmSystemTools::CompareOp op,
  2977. const std::string& lhs, const char rhs[])
  2978. {
  2979. return ::VersionCompare(op, lhs.c_str(), rhs);
  2980. }
  2981. bool cmSystemTools::VersionCompareEqual(std::string const& lhs,
  2982. std::string const& rhs)
  2983. {
  2984. return cmSystemTools::VersionCompare(cmSystemTools::OP_EQUAL, lhs, rhs);
  2985. }
  2986. bool cmSystemTools::VersionCompareGreater(std::string const& lhs,
  2987. std::string const& rhs)
  2988. {
  2989. return cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER, lhs, rhs);
  2990. }
  2991. bool cmSystemTools::VersionCompareGreaterEq(std::string const& lhs,
  2992. std::string const& rhs)
  2993. {
  2994. return cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER_EQUAL, lhs,
  2995. rhs);
  2996. }
  2997. static size_t cm_strverscmp_find_first_difference_or_end(const char* lhs,
  2998. const char* rhs)
  2999. {
  3000. size_t i = 0;
  3001. /* Step forward until we find a difference or both strings end together.
  3002. The difference may lie on the null-terminator of one string. */
  3003. while (lhs[i] == rhs[i] && lhs[i] != 0) {
  3004. ++i;
  3005. }
  3006. return i;
  3007. }
  3008. static size_t cm_strverscmp_find_digits_begin(const char* s, size_t i)
  3009. {
  3010. /* Step back until we are not preceded by a digit. */
  3011. while (i > 0 && isdigit(s[i - 1])) {
  3012. --i;
  3013. }
  3014. return i;
  3015. }
  3016. static size_t cm_strverscmp_find_digits_end(const char* s, size_t i)
  3017. {
  3018. /* Step forward over digits. */
  3019. while (isdigit(s[i])) {
  3020. ++i;
  3021. }
  3022. return i;
  3023. }
  3024. static size_t cm_strverscmp_count_leading_zeros(const char* s, size_t b)
  3025. {
  3026. size_t i = b;
  3027. /* Step forward over zeros that are followed by another digit. */
  3028. while (s[i] == '0' && isdigit(s[i + 1])) {
  3029. ++i;
  3030. }
  3031. return i - b;
  3032. }
  3033. static int cm_strverscmp(const char* lhs, const char* rhs)
  3034. {
  3035. size_t const i = cm_strverscmp_find_first_difference_or_end(lhs, rhs);
  3036. if (lhs[i] != rhs[i]) {
  3037. /* The strings differ starting at 'i'. Check for a digit sequence. */
  3038. size_t const b = cm_strverscmp_find_digits_begin(lhs, i);
  3039. if (b != i || (isdigit(lhs[i]) && isdigit(rhs[i]))) {
  3040. /* A digit sequence starts at 'b', preceding or at 'i'. */
  3041. /* Look for leading zeros, implying a leading decimal point. */
  3042. size_t const lhs_zeros = cm_strverscmp_count_leading_zeros(lhs, b);
  3043. size_t const rhs_zeros = cm_strverscmp_count_leading_zeros(rhs, b);
  3044. if (lhs_zeros != rhs_zeros) {
  3045. /* The side with more leading zeros orders first. */
  3046. return rhs_zeros > lhs_zeros ? 1 : -1;
  3047. }
  3048. if (lhs_zeros == 0) {
  3049. /* No leading zeros; compare digit sequence lengths. */
  3050. size_t const lhs_end = cm_strverscmp_find_digits_end(lhs, i);
  3051. size_t const rhs_end = cm_strverscmp_find_digits_end(rhs, i);
  3052. if (lhs_end != rhs_end) {
  3053. /* The side with fewer digits orders first. */
  3054. return lhs_end > rhs_end ? 1 : -1;
  3055. }
  3056. }
  3057. }
  3058. }
  3059. /* Ordering was not decided by digit sequence lengths; compare bytes. */
  3060. return lhs[i] - rhs[i];
  3061. }
  3062. int cmSystemTools::strverscmp(std::string const& lhs, std::string const& rhs)
  3063. {
  3064. return cm_strverscmp(lhs.c_str(), rhs.c_str());
  3065. }
  3066. static cm::optional<bool> RemoveRPathELF(std::string const& file,
  3067. std::string* emsg, bool* removed)
  3068. {
  3069. if (removed) {
  3070. *removed = false;
  3071. }
  3072. int zeroCount = 0;
  3073. unsigned long zeroPosition[2] = { 0, 0 };
  3074. unsigned long zeroSize[2] = { 0, 0 };
  3075. unsigned long bytesBegin = 0;
  3076. std::vector<char> bytes;
  3077. {
  3078. // Parse the ELF binary.
  3079. cmELF elf(file.c_str());
  3080. if (!elf) {
  3081. return cm::nullopt; // Not a valid ELF file.
  3082. }
  3083. // Get the RPATH and RUNPATH entries from it and sort them by index
  3084. // in the dynamic section header.
  3085. int se_count = 0;
  3086. cmELF::StringEntry const* se[2] = { nullptr, nullptr };
  3087. if (cmELF::StringEntry const* se_rpath = elf.GetRPath()) {
  3088. se[se_count++] = se_rpath;
  3089. }
  3090. if (cmELF::StringEntry const* se_runpath = elf.GetRunPath()) {
  3091. se[se_count++] = se_runpath;
  3092. }
  3093. if (se_count == 0) {
  3094. // There is no RPATH or RUNPATH anyway.
  3095. return true;
  3096. }
  3097. if (se_count == 2 && se[1]->IndexInSection < se[0]->IndexInSection) {
  3098. std::swap(se[0], se[1]);
  3099. }
  3100. // Obtain a copy of the dynamic entries
  3101. cmELF::DynamicEntryList dentries = elf.GetDynamicEntries();
  3102. if (dentries.empty()) {
  3103. // This should happen only for invalid ELF files where a DT_NULL
  3104. // appears before the end of the table.
  3105. if (emsg) {
  3106. *emsg = "DYNAMIC section contains a DT_NULL before the end.";
  3107. }
  3108. return false;
  3109. }
  3110. // Save information about the string entries to be zeroed.
  3111. zeroCount = se_count;
  3112. for (int i = 0; i < se_count; ++i) {
  3113. zeroPosition[i] = se[i]->Position;
  3114. zeroSize[i] = se[i]->Size;
  3115. }
  3116. // Get size of one DYNAMIC entry
  3117. unsigned long const sizeof_dentry =
  3118. elf.GetDynamicEntryPosition(1) - elf.GetDynamicEntryPosition(0);
  3119. // Adjust the entry list as necessary to remove the run path
  3120. unsigned long entriesErased = 0;
  3121. for (auto it = dentries.begin(); it != dentries.end();) {
  3122. if (it->first == cmELF::TagRPath || it->first == cmELF::TagRunPath) {
  3123. it = dentries.erase(it);
  3124. entriesErased++;
  3125. continue;
  3126. }
  3127. if (it->first == cmELF::TagMipsRldMapRel && elf.IsMIPS()) {
  3128. // Background: debuggers need to know the "linker map" which contains
  3129. // the addresses each dynamic object is loaded at. Most arches use
  3130. // the DT_DEBUG tag which the dynamic linker writes to (directly) and
  3131. // contain the location of the linker map, however on MIPS the
  3132. // .dynamic section is always read-only so this is not possible. MIPS
  3133. // objects instead contain a DT_MIPS_RLD_MAP tag which contains the
  3134. // address where the dynamic linker will write to (an indirect
  3135. // version of DT_DEBUG). Since this doesn't work when using PIE, a
  3136. // relative equivalent was created - DT_MIPS_RLD_MAP_REL. Since this
  3137. // version contains a relative offset, moving it changes the
  3138. // calculated address. This may cause the dynamic linker to write
  3139. // into memory it should not be changing.
  3140. //
  3141. // To fix this, we adjust the value of DT_MIPS_RLD_MAP_REL here. If
  3142. // we move it up by n bytes, we add n bytes to the value of this tag.
  3143. it->second += entriesErased * sizeof_dentry;
  3144. }
  3145. it++;
  3146. }
  3147. // Encode new entries list
  3148. bytes = elf.EncodeDynamicEntries(dentries);
  3149. bytesBegin = elf.GetDynamicEntryPosition(0);
  3150. }
  3151. // Open the file for update.
  3152. cmsys::ofstream f(file.c_str(),
  3153. std::ios::in | std::ios::out | std::ios::binary);
  3154. if (!f) {
  3155. if (emsg) {
  3156. *emsg = "Error opening file for update.";
  3157. }
  3158. return false;
  3159. }
  3160. // Write the new DYNAMIC table header.
  3161. if (!f.seekp(bytesBegin)) {
  3162. if (emsg) {
  3163. *emsg = "Error seeking to DYNAMIC table header for RPATH.";
  3164. }
  3165. return false;
  3166. }
  3167. if (!f.write(bytes.data(), bytes.size())) {
  3168. if (emsg) {
  3169. *emsg = "Error replacing DYNAMIC table header.";
  3170. }
  3171. return false;
  3172. }
  3173. // Fill the RPATH and RUNPATH strings with zero bytes.
  3174. for (int i = 0; i < zeroCount; ++i) {
  3175. if (!f.seekp(zeroPosition[i])) {
  3176. if (emsg) {
  3177. *emsg = "Error seeking to RPATH position.";
  3178. }
  3179. return false;
  3180. }
  3181. for (unsigned long j = 0; j < zeroSize[i]; ++j) {
  3182. f << '\0';
  3183. }
  3184. if (!f) {
  3185. if (emsg) {
  3186. *emsg = "Error writing the empty rpath string to the file.";
  3187. }
  3188. return false;
  3189. }
  3190. }
  3191. // Everything was updated successfully.
  3192. if (removed) {
  3193. *removed = true;
  3194. }
  3195. return true;
  3196. }
  3197. static cm::optional<bool> RemoveRPathXCOFF(std::string const& file,
  3198. std::string* emsg, bool* removed)
  3199. {
  3200. if (removed) {
  3201. *removed = false;
  3202. }
  3203. #if !defined(CMake_USE_XCOFF_PARSER)
  3204. (void)file;
  3205. (void)emsg;
  3206. return cm::nullopt; // Cannot handle XCOFF files.
  3207. #else
  3208. cmXCOFF xcoff(file.c_str(), cmXCOFF::Mode::ReadWrite);
  3209. if (!xcoff) {
  3210. return cm::nullopt; // Not a valid XCOFF file.
  3211. }
  3212. bool rm = xcoff.RemoveLibPath();
  3213. if (!xcoff) {
  3214. if (emsg) {
  3215. *emsg = xcoff.GetErrorMessage();
  3216. }
  3217. return false;
  3218. }
  3219. if (removed) {
  3220. *removed = rm;
  3221. }
  3222. return true;
  3223. #endif
  3224. }
  3225. bool cmSystemTools::RemoveRPath(std::string const& file, std::string* emsg,
  3226. bool* removed)
  3227. {
  3228. if (cm::optional<bool> result = RemoveRPathELF(file, emsg, removed)) {
  3229. return result.value();
  3230. }
  3231. if (cm::optional<bool> result = RemoveRPathXCOFF(file, emsg, removed)) {
  3232. return result.value();
  3233. }
  3234. // The file format is not recognized. Assume it has no RPATH.
  3235. return true;
  3236. }
  3237. bool cmSystemTools::CheckRPath(std::string const& file,
  3238. std::string const& newRPath)
  3239. {
  3240. // Parse the ELF binary.
  3241. cmELF elf(file.c_str());
  3242. if (elf) {
  3243. // Get the RPATH or RUNPATH entry from it.
  3244. cmELF::StringEntry const* se = elf.GetRPath();
  3245. if (!se) {
  3246. se = elf.GetRunPath();
  3247. }
  3248. // Make sure the current rpath contains the new rpath.
  3249. if (newRPath.empty()) {
  3250. if (!se) {
  3251. return true;
  3252. }
  3253. } else {
  3254. if (se &&
  3255. cmSystemToolsFindRPath(se->Value, newRPath) != std::string::npos) {
  3256. return true;
  3257. }
  3258. }
  3259. return false;
  3260. }
  3261. #if defined(CMake_USE_XCOFF_PARSER)
  3262. // Parse the XCOFF binary.
  3263. cmXCOFF xcoff(file.c_str());
  3264. if (xcoff) {
  3265. if (cm::optional<cm::string_view> libPath = xcoff.GetLibPath()) {
  3266. if (cmSystemToolsFindRPath(*libPath, newRPath) != std::string::npos) {
  3267. return true;
  3268. }
  3269. }
  3270. return false;
  3271. }
  3272. #endif
  3273. // The file format is not recognized. Assume it has no RPATH.
  3274. // Therefore we succeed if the new rpath is empty anyway.
  3275. return newRPath.empty();
  3276. }
  3277. bool cmSystemTools::RepeatedRemoveDirectory(const std::string& dir)
  3278. {
  3279. #ifdef _WIN32
  3280. // Windows sometimes locks files temporarily so try a few times.
  3281. WindowsFileRetry retry = cmSystemTools::GetWindowsFileRetry();
  3282. for (unsigned int i = 0; i < retry.Count; ++i) {
  3283. if (cmSystemTools::RemoveADirectory(dir)) {
  3284. return true;
  3285. }
  3286. cmSystemTools::Delay(retry.Delay);
  3287. }
  3288. return false;
  3289. #else
  3290. return static_cast<bool>(cmSystemTools::RemoveADirectory(dir));
  3291. #endif
  3292. }
  3293. std::string cmSystemTools::EncodeURL(std::string const& in, bool escapeSlashes)
  3294. {
  3295. std::string out;
  3296. for (char c : in) {
  3297. char hexCh[4] = { 0, 0, 0, 0 };
  3298. hexCh[0] = c;
  3299. switch (c) {
  3300. case '+':
  3301. case '?':
  3302. case '\\':
  3303. case '&':
  3304. case ' ':
  3305. case '=':
  3306. case '%':
  3307. snprintf(hexCh, sizeof(hexCh), "%%%02X", static_cast<int>(c));
  3308. break;
  3309. case '/':
  3310. if (escapeSlashes) {
  3311. strcpy(hexCh, "%2F");
  3312. }
  3313. break;
  3314. default:
  3315. break;
  3316. }
  3317. out.append(hexCh);
  3318. }
  3319. return out;
  3320. }
  3321. cmsys::Status cmSystemTools::CreateSymlink(std::string const& origName,
  3322. std::string const& newName)
  3323. {
  3324. cmsys::Status status =
  3325. cmSystemTools::CreateSymlinkQuietly(origName, newName);
  3326. if (!status) {
  3327. cmSystemTools::Error(cmStrCat("failed to create symbolic link '", newName,
  3328. "': ", status.GetString()));
  3329. }
  3330. return status;
  3331. }
  3332. cmsys::Status cmSystemTools::CreateSymlinkQuietly(std::string const& origName,
  3333. std::string const& newName)
  3334. {
  3335. uv_fs_t req;
  3336. int flags = 0;
  3337. #if defined(_WIN32)
  3338. if (cmsys::SystemTools::FileIsDirectory(origName)) {
  3339. flags |= UV_FS_SYMLINK_DIR;
  3340. }
  3341. #endif
  3342. int err = uv_fs_symlink(nullptr, &req, origName.c_str(), newName.c_str(),
  3343. flags, nullptr);
  3344. cmsys::Status status;
  3345. if (err) {
  3346. #if defined(_WIN32)
  3347. status = cmsys::Status::Windows(uv_fs_get_system_error(&req));
  3348. #elif UV_VERSION_MAJOR > 1 || (UV_VERSION_MAJOR == 1 && UV_VERSION_MINOR >= 38)
  3349. status = cmsys::Status::POSIX(uv_fs_get_system_error(&req));
  3350. #else
  3351. status = cmsys::Status::POSIX(-err);
  3352. #endif
  3353. }
  3354. return status;
  3355. }
  3356. cmsys::Status cmSystemTools::CreateLink(std::string const& origName,
  3357. std::string const& newName)
  3358. {
  3359. cmsys::Status status = cmSystemTools::CreateLinkQuietly(origName, newName);
  3360. if (!status) {
  3361. cmSystemTools::Error(
  3362. cmStrCat("failed to create link '", newName, "': ", status.GetString()));
  3363. }
  3364. return status;
  3365. }
  3366. cmsys::Status cmSystemTools::CreateLinkQuietly(std::string const& origName,
  3367. std::string const& newName)
  3368. {
  3369. uv_fs_t req;
  3370. int err =
  3371. uv_fs_link(nullptr, &req, origName.c_str(), newName.c_str(), nullptr);
  3372. cmsys::Status status;
  3373. if (err) {
  3374. #if defined(_WIN32)
  3375. status = cmsys::Status::Windows(uv_fs_get_system_error(&req));
  3376. #elif UV_VERSION_MAJOR > 1 || (UV_VERSION_MAJOR == 1 && UV_VERSION_MINOR >= 38)
  3377. status = cmsys::Status::POSIX(uv_fs_get_system_error(&req));
  3378. #else
  3379. status = cmsys::Status::POSIX(-err);
  3380. #endif
  3381. }
  3382. return status;
  3383. }
  3384. cm::string_view cmSystemTools::GetSystemName()
  3385. {
  3386. #if defined(_WIN32)
  3387. return "Windows";
  3388. #elif defined(__ANDROID__)
  3389. return "Android";
  3390. #else
  3391. static struct utsname uts_name;
  3392. static bool initialized = false;
  3393. static cm::string_view systemName;
  3394. if (initialized) {
  3395. return systemName;
  3396. }
  3397. if (uname(&uts_name) >= 0) {
  3398. initialized = true;
  3399. systemName = uts_name.sysname;
  3400. if (cmIsOff(systemName)) {
  3401. systemName = "UnknownOS";
  3402. }
  3403. // fix for BSD/OS, remove the /
  3404. static const cmsys::RegularExpression bsdOsRegex("BSD.OS");
  3405. cmsys::RegularExpressionMatch match;
  3406. if (bsdOsRegex.find(uts_name.sysname, match)) {
  3407. systemName = "BSDOS";
  3408. }
  3409. // fix for GNU/kFreeBSD, remove the GNU/
  3410. if (systemName.find("kFreeBSD") != cm::string_view::npos) {
  3411. systemName = "kFreeBSD";
  3412. }
  3413. // fix for CYGWIN and MSYS which have windows version in them
  3414. if (systemName.find("CYGWIN") != cm::string_view::npos) {
  3415. systemName = "CYGWIN";
  3416. }
  3417. if (systemName.find("MSYS") != cm::string_view::npos) {
  3418. systemName = "MSYS";
  3419. }
  3420. return systemName;
  3421. }
  3422. return "";
  3423. #endif
  3424. }
  3425. char cmSystemTools::GetSystemPathlistSeparator()
  3426. {
  3427. #if defined(_WIN32)
  3428. return ';';
  3429. #else
  3430. return ':';
  3431. #endif
  3432. }