cmSystemTools.cxx 109 KB

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