cmSystemTools.cxx 108 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733
  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(NULL, &req, path.c_str(), NULL);
  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 = NULL;
  873. DWORD size = FormatMessageA(
  874. FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
  875. FORMAT_MESSAGE_IGNORE_INSERTS,
  876. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&message, 0,
  877. NULL);
  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 = NULL;
  1201. PCCERT_CONTEXT certContext = NULL;
  1202. HANDLE certFile = CreateFileW(
  1203. cmsys::Encoding::ToWide(source.c_str()).c_str(), GENERIC_READ,
  1204. FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  1205. if (certFile != INVALID_HANDLE_VALUE && certFile != NULL) {
  1206. DWORD fileSize = GetFileSize(certFile, NULL);
  1207. if (fileSize != INVALID_FILE_SIZE) {
  1208. auto certData = cm::make_unique<BYTE[]>(fileSize);
  1209. if (certData != NULL) {
  1210. DWORD dwRead = 0;
  1211. if (ReadFile(certFile, certData.get(), fileSize, &dwRead, NULL)) {
  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 = PFXImportCertStore(&cryptBlob, NULL, CRYPT_EXPORTABLE);
  1218. if (certStore != NULL) {
  1219. // There should only be 1 cert.
  1220. certContext =
  1221. CertEnumCertificatesInStore(certStore, certContext);
  1222. if (certContext != NULL) {
  1223. // The hash is 20 bytes
  1224. BYTE hashData[20];
  1225. DWORD hashLength = 20;
  1226. // Buffer to print the hash. Each byte takes 2 chars +
  1227. // terminating character
  1228. char hashPrint[41];
  1229. char* pHashPrint = hashPrint;
  1230. // Get the hash property from the certificate
  1231. if (CertGetCertificateContextProperty(
  1232. certContext, CERT_HASH_PROP_ID, hashData, &hashLength)) {
  1233. for (DWORD i = 0; i < hashLength; i++) {
  1234. // Convert each byte to hexadecimal
  1235. snprintf(pHashPrint, 3, "%02X", hashData[i]);
  1236. pHashPrint += 2;
  1237. }
  1238. *pHashPrint = '\0';
  1239. thumbprint = hashPrint;
  1240. }
  1241. CertFreeCertificateContext(certContext);
  1242. }
  1243. CertCloseStore(certStore, 0);
  1244. }
  1245. }
  1246. }
  1247. }
  1248. }
  1249. CloseHandle(certFile);
  1250. }
  1251. return thumbprint;
  1252. }
  1253. # endif
  1254. #endif
  1255. void cmSystemTools::Glob(const std::string& directory,
  1256. const std::string& regexp,
  1257. std::vector<std::string>& files)
  1258. {
  1259. cmsys::Directory d;
  1260. cmsys::RegularExpression reg(regexp.c_str());
  1261. if (d.Load(directory)) {
  1262. size_t numf;
  1263. unsigned int i;
  1264. numf = d.GetNumberOfFiles();
  1265. for (i = 0; i < numf; i++) {
  1266. std::string fname = d.GetFile(i);
  1267. if (reg.find(fname)) {
  1268. files.push_back(std::move(fname));
  1269. }
  1270. }
  1271. }
  1272. }
  1273. void cmSystemTools::GlobDirs(const std::string& path,
  1274. std::vector<std::string>& files)
  1275. {
  1276. std::string::size_type pos = path.find("/*");
  1277. if (pos == std::string::npos) {
  1278. files.push_back(path);
  1279. return;
  1280. }
  1281. std::string startPath = path.substr(0, pos);
  1282. std::string finishPath = path.substr(pos + 2);
  1283. cmsys::Directory d;
  1284. if (d.Load(startPath)) {
  1285. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i) {
  1286. if ((std::string(d.GetFile(i)) != ".") &&
  1287. (std::string(d.GetFile(i)) != "..")) {
  1288. std::string fname = cmStrCat(startPath, '/', d.GetFile(i));
  1289. if (cmSystemTools::FileIsDirectory(fname)) {
  1290. fname += finishPath;
  1291. cmSystemTools::GlobDirs(fname, files);
  1292. }
  1293. }
  1294. }
  1295. }
  1296. }
  1297. bool cmSystemTools::SimpleGlob(const std::string& glob,
  1298. std::vector<std::string>& files,
  1299. int type /* = 0 */)
  1300. {
  1301. files.clear();
  1302. if (glob.back() != '*') {
  1303. return false;
  1304. }
  1305. std::string path = cmSystemTools::GetFilenamePath(glob);
  1306. std::string ppath = cmSystemTools::GetFilenameName(glob);
  1307. ppath = ppath.substr(0, ppath.size() - 1);
  1308. if (path.empty()) {
  1309. path = "/";
  1310. }
  1311. bool res = false;
  1312. cmsys::Directory d;
  1313. if (d.Load(path)) {
  1314. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i) {
  1315. if ((std::string(d.GetFile(i)) != ".") &&
  1316. (std::string(d.GetFile(i)) != "..")) {
  1317. std::string fname = path;
  1318. if (path.back() != '/') {
  1319. fname += "/";
  1320. }
  1321. fname += d.GetFile(i);
  1322. std::string sfname = d.GetFile(i);
  1323. if (type > 0 && cmSystemTools::FileIsDirectory(fname)) {
  1324. continue;
  1325. }
  1326. if (type < 0 && !cmSystemTools::FileIsDirectory(fname)) {
  1327. continue;
  1328. }
  1329. if (cmHasPrefix(sfname, ppath)) {
  1330. files.push_back(fname);
  1331. res = true;
  1332. }
  1333. }
  1334. }
  1335. }
  1336. return res;
  1337. }
  1338. std::string cmSystemTools::ConvertToOutputPath(std::string const& path)
  1339. {
  1340. #if defined(_WIN32) && !defined(__CYGWIN__)
  1341. if (s_ForceUnixPaths) {
  1342. return cmSystemTools::ConvertToUnixOutputPath(path);
  1343. }
  1344. return cmSystemTools::ConvertToWindowsOutputPath(path);
  1345. #else
  1346. return cmSystemTools::ConvertToUnixOutputPath(path);
  1347. #endif
  1348. }
  1349. void cmSystemTools::ConvertToOutputSlashes(std::string& path)
  1350. {
  1351. #if defined(_WIN32) && !defined(__CYGWIN__)
  1352. if (!s_ForceUnixPaths) {
  1353. // Convert to windows slashes.
  1354. std::string::size_type pos = 0;
  1355. while ((pos = path.find('/', pos)) != std::string::npos) {
  1356. path[pos++] = '\\';
  1357. }
  1358. }
  1359. #else
  1360. static_cast<void>(path);
  1361. #endif
  1362. }
  1363. void cmSystemTools::ConvertToLongPath(std::string& path)
  1364. {
  1365. #if defined(_WIN32) && !defined(__CYGWIN__)
  1366. // Try to convert path to a long path only if the path contains character '~'
  1367. if (path.find('~') == std::string::npos) {
  1368. return;
  1369. }
  1370. std::wstring wPath = cmsys::Encoding::ToWide(path);
  1371. DWORD ret = GetLongPathNameW(wPath.c_str(), nullptr, 0);
  1372. std::vector<wchar_t> buffer(ret);
  1373. if (ret != 0) {
  1374. ret = GetLongPathNameW(wPath.c_str(), buffer.data(),
  1375. static_cast<DWORD>(buffer.size()));
  1376. }
  1377. if (ret != 0) {
  1378. path = cmsys::Encoding::ToNarrow(buffer.data());
  1379. }
  1380. #else
  1381. static_cast<void>(path);
  1382. #endif
  1383. }
  1384. std::string cmSystemTools::ConvertToRunCommandPath(const std::string& path)
  1385. {
  1386. #if defined(_WIN32) && !defined(__CYGWIN__)
  1387. return cmSystemTools::ConvertToWindowsOutputPath(path);
  1388. #else
  1389. return cmSystemTools::ConvertToUnixOutputPath(path);
  1390. #endif
  1391. }
  1392. // compute the relative path from here to there
  1393. std::string cmSystemTools::RelativePath(std::string const& local,
  1394. std::string const& remote)
  1395. {
  1396. if (!cmSystemTools::FileIsFullPath(local)) {
  1397. cmSystemTools::Error("RelativePath must be passed a full path to local: " +
  1398. local);
  1399. }
  1400. if (!cmSystemTools::FileIsFullPath(remote)) {
  1401. cmSystemTools::Error(
  1402. "RelativePath must be passed a full path to remote: " + remote);
  1403. }
  1404. return cmsys::SystemTools::RelativePath(local, remote);
  1405. }
  1406. std::string cmSystemTools::ForceToRelativePath(std::string const& local_path,
  1407. std::string const& remote_path)
  1408. {
  1409. // The paths should never be quoted.
  1410. assert(local_path.front() != '\"');
  1411. assert(remote_path.front() != '\"');
  1412. // The local path should never have a trailing slash except if it is just the
  1413. // bare root directory
  1414. assert(local_path.empty() || local_path.back() != '/' ||
  1415. local_path.size() == 1 ||
  1416. (local_path.size() == 3 && local_path[1] == ':' &&
  1417. ((local_path[0] >= 'A' && local_path[0] <= 'Z') ||
  1418. (local_path[0] >= 'a' && local_path[0] <= 'z'))));
  1419. // If the path is already relative then just return the path.
  1420. if (!cmSystemTools::FileIsFullPath(remote_path)) {
  1421. return remote_path;
  1422. }
  1423. // Identify the longest shared path component between the remote
  1424. // path and the local path.
  1425. std::vector<std::string> local;
  1426. cmSystemTools::SplitPath(local_path, local);
  1427. std::vector<std::string> remote;
  1428. cmSystemTools::SplitPath(remote_path, remote);
  1429. unsigned int common = 0;
  1430. while (common < remote.size() && common < local.size() &&
  1431. cmSystemTools::ComparePath(remote[common], local[common])) {
  1432. ++common;
  1433. }
  1434. // If no part of the path is in common then return the full path.
  1435. if (common == 0) {
  1436. return remote_path;
  1437. }
  1438. // If the entire path is in common then just return a ".".
  1439. if (common == remote.size() && common == local.size()) {
  1440. return ".";
  1441. }
  1442. // If the entire path is in common except for a trailing slash then
  1443. // just return a "./".
  1444. if (common + 1 == remote.size() && remote[common].empty() &&
  1445. common == local.size()) {
  1446. return "./";
  1447. }
  1448. // Construct the relative path.
  1449. std::string relative;
  1450. // First add enough ../ to get up to the level of the shared portion
  1451. // of the path. Leave off the trailing slash. Note that the last
  1452. // component of local will never be empty because local should never
  1453. // have a trailing slash.
  1454. for (unsigned int i = common; i < local.size(); ++i) {
  1455. relative += "..";
  1456. if (i < local.size() - 1) {
  1457. relative += "/";
  1458. }
  1459. }
  1460. // Now add the portion of the destination path that is not included
  1461. // in the shared portion of the path. Add a slash the first time
  1462. // only if there was already something in the path. If there was a
  1463. // trailing slash in the input then the last iteration of the loop
  1464. // will add a slash followed by an empty string which will preserve
  1465. // the trailing slash in the output.
  1466. if (!relative.empty() && !remote.empty()) {
  1467. relative += "/";
  1468. }
  1469. relative += cmJoin(cmMakeRange(remote).advance(common), "/");
  1470. // Finally return the path.
  1471. return relative;
  1472. }
  1473. std::string cmSystemTools::RelativeIfUnder(std::string const& top,
  1474. std::string const& in)
  1475. {
  1476. std::string out;
  1477. if (in == top) {
  1478. out = ".";
  1479. } else if (cmSystemTools::IsSubDirectory(in, top)) {
  1480. out = in.substr(top.size() + 1);
  1481. } else {
  1482. out = in;
  1483. }
  1484. return out;
  1485. }
  1486. #ifndef CMAKE_BOOTSTRAP
  1487. bool cmSystemTools::UnsetEnv(const char* value)
  1488. {
  1489. # if !defined(HAVE_UNSETENV)
  1490. return cmSystemTools::UnPutEnv(value);
  1491. # else
  1492. unsetenv(value);
  1493. return true;
  1494. # endif
  1495. }
  1496. std::vector<std::string> cmSystemTools::GetEnvironmentVariables()
  1497. {
  1498. std::vector<std::string> env;
  1499. int cc;
  1500. # ifdef _WIN32
  1501. // if program starts with main, _wenviron is initially NULL, call to
  1502. // _wgetenv and create wide-character string environment
  1503. _wgetenv(L"");
  1504. for (cc = 0; _wenviron[cc]; ++cc) {
  1505. env.emplace_back(cmsys::Encoding::ToNarrow(_wenviron[cc]));
  1506. }
  1507. # else
  1508. for (cc = 0; environ[cc]; ++cc) {
  1509. env.emplace_back(environ[cc]);
  1510. }
  1511. # endif
  1512. return env;
  1513. }
  1514. void cmSystemTools::AppendEnv(std::vector<std::string> const& env)
  1515. {
  1516. for (std::string const& eit : env) {
  1517. cmSystemTools::PutEnv(eit);
  1518. }
  1519. }
  1520. void cmSystemTools::EnvDiff::AppendEnv(std::vector<std::string> const& env)
  1521. {
  1522. for (std::string const& eit : env) {
  1523. this->PutEnv(eit);
  1524. }
  1525. }
  1526. void cmSystemTools::EnvDiff::PutEnv(const std::string& env)
  1527. {
  1528. auto const eq_loc = env.find('=');
  1529. if (eq_loc != std::string::npos) {
  1530. std::string name = env.substr(0, eq_loc);
  1531. diff[name] = env.substr(eq_loc + 1);
  1532. } else {
  1533. this->UnPutEnv(env);
  1534. }
  1535. }
  1536. void cmSystemTools::EnvDiff::UnPutEnv(const std::string& env)
  1537. {
  1538. diff[env] = {};
  1539. }
  1540. bool cmSystemTools::EnvDiff::ParseOperation(const std::string& envmod)
  1541. {
  1542. char path_sep = GetSystemPathlistSeparator();
  1543. auto apply_diff = [this](const std::string& name,
  1544. std::function<void(std::string&)> const& apply) {
  1545. cm::optional<std::string> old_value = diff[name];
  1546. std::string output;
  1547. if (old_value) {
  1548. output = *old_value;
  1549. } else {
  1550. const char* curval = cmSystemTools::GetEnv(name);
  1551. if (curval) {
  1552. output = curval;
  1553. }
  1554. }
  1555. apply(output);
  1556. diff[name] = output;
  1557. };
  1558. // Split on `=`
  1559. auto const eq_loc = envmod.find_first_of('=');
  1560. if (eq_loc == std::string::npos) {
  1561. cmSystemTools::Error(cmStrCat(
  1562. "Error: Missing `=` after the variable name in: ", envmod, '\n'));
  1563. return false;
  1564. }
  1565. auto const name = envmod.substr(0, eq_loc);
  1566. // Split value on `:`
  1567. auto const op_value_start = eq_loc + 1;
  1568. auto const colon_loc = envmod.find_first_of(':', op_value_start);
  1569. if (colon_loc == std::string::npos) {
  1570. cmSystemTools::Error(
  1571. cmStrCat("Error: Missing `:` after the operation in: ", envmod, '\n'));
  1572. return false;
  1573. }
  1574. auto const op = envmod.substr(op_value_start, colon_loc - op_value_start);
  1575. auto const value_start = colon_loc + 1;
  1576. auto const value = envmod.substr(value_start);
  1577. // Determine what to do with the operation.
  1578. if (op == "reset"_s) {
  1579. auto entry = diff.find(name);
  1580. if (entry != diff.end()) {
  1581. diff.erase(entry);
  1582. }
  1583. } else if (op == "set"_s) {
  1584. diff[name] = value;
  1585. } else if (op == "unset"_s) {
  1586. diff[name] = {};
  1587. } else if (op == "string_append"_s) {
  1588. apply_diff(name, [&value](std::string& output) { output += value; });
  1589. } else if (op == "string_prepend"_s) {
  1590. apply_diff(name,
  1591. [&value](std::string& output) { output.insert(0, value); });
  1592. } else if (op == "path_list_append"_s) {
  1593. apply_diff(name, [&value, path_sep](std::string& output) {
  1594. if (!output.empty()) {
  1595. output += path_sep;
  1596. }
  1597. output += value;
  1598. });
  1599. } else if (op == "path_list_prepend"_s) {
  1600. apply_diff(name, [&value, path_sep](std::string& output) {
  1601. if (!output.empty()) {
  1602. output.insert(output.begin(), path_sep);
  1603. }
  1604. output.insert(0, value);
  1605. });
  1606. } else if (op == "cmake_list_append"_s) {
  1607. apply_diff(name, [&value](std::string& output) {
  1608. if (!output.empty()) {
  1609. output += ';';
  1610. }
  1611. output += value;
  1612. });
  1613. } else if (op == "cmake_list_prepend"_s) {
  1614. apply_diff(name, [&value](std::string& output) {
  1615. if (!output.empty()) {
  1616. output.insert(output.begin(), ';');
  1617. }
  1618. output.insert(0, value);
  1619. });
  1620. } else {
  1621. cmSystemTools::Error(cmStrCat(
  1622. "Error: Unrecognized environment manipulation argument: ", op, '\n'));
  1623. return false;
  1624. }
  1625. return true;
  1626. }
  1627. void cmSystemTools::EnvDiff::ApplyToCurrentEnv(std::ostringstream* measurement)
  1628. {
  1629. for (auto const& env_apply : diff) {
  1630. if (env_apply.second) {
  1631. auto const env_update =
  1632. cmStrCat(env_apply.first, '=', *env_apply.second);
  1633. cmSystemTools::PutEnv(env_update);
  1634. if (measurement) {
  1635. *measurement << env_update << std::endl;
  1636. }
  1637. } else {
  1638. cmSystemTools::UnsetEnv(env_apply.first.c_str());
  1639. if (measurement) {
  1640. // Signify that this variable is being actively unset
  1641. *measurement << '#' << env_apply.first << "=\n";
  1642. }
  1643. }
  1644. }
  1645. }
  1646. cmSystemTools::SaveRestoreEnvironment::SaveRestoreEnvironment()
  1647. {
  1648. this->Env = cmSystemTools::GetEnvironmentVariables();
  1649. }
  1650. cmSystemTools::SaveRestoreEnvironment::~SaveRestoreEnvironment()
  1651. {
  1652. // First clear everything in the current environment:
  1653. std::vector<std::string> currentEnv = GetEnvironmentVariables();
  1654. for (std::string var : currentEnv) {
  1655. std::string::size_type pos = var.find('=');
  1656. if (pos != std::string::npos) {
  1657. var = var.substr(0, pos);
  1658. }
  1659. cmSystemTools::UnsetEnv(var.c_str());
  1660. }
  1661. // Then put back each entry from the original environment:
  1662. cmSystemTools::AppendEnv(this->Env);
  1663. }
  1664. #endif
  1665. void cmSystemTools::EnableVSConsoleOutput()
  1666. {
  1667. #ifdef _WIN32
  1668. // Visual Studio tools like devenv may not
  1669. // display output to the console unless this environment variable is
  1670. // set. We need it to capture the output of these build tools.
  1671. // Note for future work that one could pass "/out \\.\pipe\NAME" to
  1672. // either of these executables where NAME is created with
  1673. // CreateNamedPipe. This would bypass the internal buffering of the
  1674. // output and allow it to be captured on the fly.
  1675. cmSystemTools::PutEnv("vsconsoleoutput=1");
  1676. # ifndef CMAKE_BOOTSTRAP
  1677. // VS sets an environment variable to tell MS tools like "cl" to report
  1678. // output through a backdoor pipe instead of stdout/stderr. Unset the
  1679. // environment variable to close this backdoor for any path of process
  1680. // invocations that passes through CMake so we can capture the output.
  1681. cmSystemTools::UnsetEnv("VS_UNICODE_OUTPUT");
  1682. # endif
  1683. #endif
  1684. }
  1685. bool cmSystemTools::IsPathToFramework(const std::string& path)
  1686. {
  1687. return (cmSystemTools::FileIsFullPath(path) &&
  1688. cmHasLiteralSuffix(path, ".framework"));
  1689. }
  1690. bool cmSystemTools::IsPathToMacOSSharedLibrary(const std::string& path)
  1691. {
  1692. return (cmSystemTools::FileIsFullPath(path) &&
  1693. cmHasLiteralSuffix(path, ".dylib"));
  1694. }
  1695. bool cmSystemTools::CreateTar(const std::string& outFileName,
  1696. const std::vector<std::string>& files,
  1697. cmTarCompression compressType, bool verbose,
  1698. std::string const& mtime,
  1699. std::string const& format, int compressionLevel)
  1700. {
  1701. #if !defined(CMAKE_BOOTSTRAP)
  1702. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1703. cmsys::ofstream fout(outFileName.c_str(), std::ios::out | std::ios::binary);
  1704. if (!fout) {
  1705. std::string e = cmStrCat("Cannot open output file \"", outFileName,
  1706. "\": ", cmSystemTools::GetLastSystemError());
  1707. cmSystemTools::Error(e);
  1708. return false;
  1709. }
  1710. cmArchiveWrite::Compress compress = cmArchiveWrite::CompressNone;
  1711. switch (compressType) {
  1712. case TarCompressGZip:
  1713. compress = cmArchiveWrite::CompressGZip;
  1714. break;
  1715. case TarCompressBZip2:
  1716. compress = cmArchiveWrite::CompressBZip2;
  1717. break;
  1718. case TarCompressXZ:
  1719. compress = cmArchiveWrite::CompressXZ;
  1720. break;
  1721. case TarCompressZstd:
  1722. compress = cmArchiveWrite::CompressZstd;
  1723. break;
  1724. case TarCompressNone:
  1725. compress = cmArchiveWrite::CompressNone;
  1726. break;
  1727. }
  1728. cmArchiveWrite a(fout, compress, format.empty() ? "paxr" : format,
  1729. compressionLevel);
  1730. if (!a.Open()) {
  1731. cmSystemTools::Error(a.GetError());
  1732. return false;
  1733. }
  1734. a.SetMTime(mtime);
  1735. a.SetVerbose(verbose);
  1736. bool tarCreatedSuccessfully = true;
  1737. for (auto path : files) {
  1738. if (cmSystemTools::FileIsFullPath(path)) {
  1739. // Get the relative path to the file.
  1740. path = cmSystemTools::RelativePath(cwd, path);
  1741. }
  1742. if (!a.Add(path)) {
  1743. cmSystemTools::Error(a.GetError());
  1744. tarCreatedSuccessfully = false;
  1745. }
  1746. }
  1747. return tarCreatedSuccessfully;
  1748. #else
  1749. (void)outFileName;
  1750. (void)files;
  1751. (void)verbose;
  1752. return false;
  1753. #endif
  1754. }
  1755. #if !defined(CMAKE_BOOTSTRAP)
  1756. namespace {
  1757. # define BSDTAR_FILESIZE_PRINTF "%lu"
  1758. # define BSDTAR_FILESIZE_TYPE unsigned long
  1759. void list_item_verbose(FILE* out, struct archive_entry* entry)
  1760. {
  1761. char tmp[100];
  1762. size_t w;
  1763. const char* p;
  1764. const char* fmt;
  1765. time_t tim;
  1766. static time_t now;
  1767. size_t u_width = 6;
  1768. size_t gs_width = 13;
  1769. /*
  1770. * We avoid collecting the entire list in memory at once by
  1771. * listing things as we see them. However, that also means we can't
  1772. * just pre-compute the field widths. Instead, we start with guesses
  1773. * and just widen them as necessary. These numbers are completely
  1774. * arbitrary.
  1775. */
  1776. if (!now) {
  1777. time(&now);
  1778. }
  1779. fprintf(out, "%s %d ", archive_entry_strmode(entry),
  1780. archive_entry_nlink(entry));
  1781. /* Use uname if it's present, else uid. */
  1782. p = archive_entry_uname(entry);
  1783. if ((p == nullptr) || (*p == '\0')) {
  1784. snprintf(tmp, sizeof(tmp), "%lu ",
  1785. static_cast<unsigned long>(archive_entry_uid(entry)));
  1786. p = tmp;
  1787. }
  1788. w = strlen(p);
  1789. if (w > u_width) {
  1790. u_width = w;
  1791. }
  1792. fprintf(out, "%-*s ", static_cast<int>(u_width), p);
  1793. /* Use gname if it's present, else gid. */
  1794. p = archive_entry_gname(entry);
  1795. if (p != nullptr && p[0] != '\0') {
  1796. fprintf(out, "%s", p);
  1797. w = strlen(p);
  1798. } else {
  1799. snprintf(tmp, sizeof(tmp), "%lu",
  1800. static_cast<unsigned long>(archive_entry_gid(entry)));
  1801. w = strlen(tmp);
  1802. fprintf(out, "%s", tmp);
  1803. }
  1804. /*
  1805. * Print device number or file size, right-aligned so as to make
  1806. * total width of group and devnum/filesize fields be gs_width.
  1807. * If gs_width is too small, grow it.
  1808. */
  1809. if (archive_entry_filetype(entry) == AE_IFCHR ||
  1810. archive_entry_filetype(entry) == AE_IFBLK) {
  1811. unsigned long rdevmajor = archive_entry_rdevmajor(entry);
  1812. unsigned long rdevminor = archive_entry_rdevminor(entry);
  1813. snprintf(tmp, sizeof(tmp), "%lu,%lu", rdevmajor, rdevminor);
  1814. } else {
  1815. /*
  1816. * Note the use of platform-dependent macros to format
  1817. * the filesize here. We need the format string and the
  1818. * corresponding type for the cast.
  1819. */
  1820. snprintf(tmp, sizeof(tmp), BSDTAR_FILESIZE_PRINTF,
  1821. static_cast<BSDTAR_FILESIZE_TYPE>(archive_entry_size(entry)));
  1822. }
  1823. if (w + strlen(tmp) >= gs_width) {
  1824. gs_width = w + strlen(tmp) + 1;
  1825. }
  1826. fprintf(out, "%*s", static_cast<int>(gs_width - w), tmp);
  1827. /* Format the time using 'ls -l' conventions. */
  1828. tim = archive_entry_mtime(entry);
  1829. # define HALF_YEAR ((time_t)365 * 86400 / 2)
  1830. # if defined(_WIN32) && !defined(__CYGWIN__)
  1831. /* Windows' strftime function does not support %e format. */
  1832. # define DAY_FMT "%d"
  1833. # else
  1834. # define DAY_FMT "%e" /* Day number without leading zeros */
  1835. # endif
  1836. if (tim < now - HALF_YEAR || tim > now + HALF_YEAR) {
  1837. fmt = DAY_FMT " %b %Y";
  1838. } else {
  1839. fmt = DAY_FMT " %b %H:%M";
  1840. }
  1841. strftime(tmp, sizeof(tmp), fmt, localtime(&tim));
  1842. fprintf(out, " %s ", tmp);
  1843. fprintf(out, "%s", cm_archive_entry_pathname(entry).c_str());
  1844. /* Extra information for links. */
  1845. if (archive_entry_hardlink(entry)) /* Hard link */
  1846. {
  1847. fprintf(out, " link to %s", archive_entry_hardlink(entry));
  1848. } else if (archive_entry_symlink(entry)) /* Symbolic link */
  1849. {
  1850. fprintf(out, " -> %s", archive_entry_symlink(entry));
  1851. }
  1852. fflush(out);
  1853. }
  1854. void ArchiveError(const char* m1, struct archive* a)
  1855. {
  1856. std::string message(m1);
  1857. const char* m2 = archive_error_string(a);
  1858. if (m2) {
  1859. message += m2;
  1860. }
  1861. cmSystemTools::Error(message);
  1862. }
  1863. bool la_diagnostic(struct archive* ar, __LA_SSIZE_T r)
  1864. {
  1865. // See archive.h definition of ARCHIVE_OK for return values.
  1866. if (r >= ARCHIVE_OK) {
  1867. return true;
  1868. }
  1869. if (r >= ARCHIVE_WARN) {
  1870. const char* warn = archive_error_string(ar);
  1871. if (!warn) {
  1872. warn = "unknown warning";
  1873. }
  1874. std::cerr << "cmake -E tar: warning: " << warn << '\n';
  1875. return true;
  1876. }
  1877. // Error.
  1878. const char* err = archive_error_string(ar);
  1879. if (!err) {
  1880. err = "unknown error";
  1881. }
  1882. std::cerr << "cmake -E tar: error: " << err << '\n';
  1883. return false;
  1884. }
  1885. // Return 'true' on success
  1886. bool copy_data(struct archive* ar, struct archive* aw)
  1887. {
  1888. long r;
  1889. const void* buff;
  1890. size_t size;
  1891. # if defined(ARCHIVE_VERSION_NUMBER) && ARCHIVE_VERSION_NUMBER >= 3000000
  1892. __LA_INT64_T offset;
  1893. # else
  1894. off_t offset;
  1895. # endif
  1896. for (;;) {
  1897. // See archive.h definition of ARCHIVE_OK for return values.
  1898. r = archive_read_data_block(ar, &buff, &size, &offset);
  1899. if (r == ARCHIVE_EOF) {
  1900. return true;
  1901. }
  1902. if (!la_diagnostic(ar, r)) {
  1903. return false;
  1904. }
  1905. // See archive.h definition of ARCHIVE_OK for return values.
  1906. __LA_SSIZE_T const w = archive_write_data_block(aw, buff, size, offset);
  1907. if (!la_diagnostic(ar, w)) {
  1908. return false;
  1909. }
  1910. }
  1911. # if !defined(__clang__) && !defined(__NVCOMPILER) && !defined(__HP_aCC)
  1912. return false; /* this should not happen but it quiets some compilers */
  1913. # endif
  1914. }
  1915. bool extract_tar(const std::string& outFileName,
  1916. const std::vector<std::string>& files, bool verbose,
  1917. cmSystemTools::cmTarExtractTimestamps extractTimestamps,
  1918. bool extract)
  1919. {
  1920. cmLocaleRAII localeRAII;
  1921. static_cast<void>(localeRAII);
  1922. struct archive* a = archive_read_new();
  1923. struct archive* ext = archive_write_disk_new();
  1924. archive_read_support_filter_all(a);
  1925. archive_read_support_format_all(a);
  1926. struct archive_entry* entry;
  1927. struct archive* matching = archive_match_new();
  1928. if (matching == nullptr) {
  1929. cmSystemTools::Error("Out of memory");
  1930. return false;
  1931. }
  1932. for (const auto& filename : files) {
  1933. if (archive_match_include_pattern(matching, filename.c_str()) !=
  1934. ARCHIVE_OK) {
  1935. cmSystemTools::Error("Failed to add to inclusion list: " + filename);
  1936. return false;
  1937. }
  1938. }
  1939. int r = cm_archive_read_open_file(a, outFileName.c_str(), 10240);
  1940. if (r) {
  1941. ArchiveError("Problem with archive_read_open_file(): ", a);
  1942. archive_write_free(ext);
  1943. archive_read_close(a);
  1944. return false;
  1945. }
  1946. for (;;) {
  1947. r = archive_read_next_header(a, &entry);
  1948. if (r == ARCHIVE_EOF) {
  1949. break;
  1950. }
  1951. if (r != ARCHIVE_OK) {
  1952. ArchiveError("Problem with archive_read_next_header(): ", a);
  1953. break;
  1954. }
  1955. if (archive_match_excluded(matching, entry)) {
  1956. continue;
  1957. }
  1958. if (verbose) {
  1959. if (extract) {
  1960. cmSystemTools::Stdout("x ");
  1961. cmSystemTools::Stdout(cm_archive_entry_pathname(entry));
  1962. } else {
  1963. list_item_verbose(stdout, entry);
  1964. }
  1965. cmSystemTools::Stdout("\n");
  1966. } else if (!extract) {
  1967. cmSystemTools::Stdout(cm_archive_entry_pathname(entry));
  1968. cmSystemTools::Stdout("\n");
  1969. }
  1970. if (extract) {
  1971. if (extractTimestamps == cmSystemTools::cmTarExtractTimestamps::Yes) {
  1972. r = archive_write_disk_set_options(ext, ARCHIVE_EXTRACT_TIME);
  1973. if (r != ARCHIVE_OK) {
  1974. ArchiveError("Problem with archive_write_disk_set_options(): ", ext);
  1975. break;
  1976. }
  1977. }
  1978. r = archive_write_header(ext, entry);
  1979. if (r == ARCHIVE_OK) {
  1980. if (!copy_data(a, ext)) {
  1981. break;
  1982. }
  1983. r = archive_write_finish_entry(ext);
  1984. if (r != ARCHIVE_OK) {
  1985. ArchiveError("Problem with archive_write_finish_entry(): ", ext);
  1986. break;
  1987. }
  1988. }
  1989. # ifdef _WIN32
  1990. else if (const char* linktext = archive_entry_symlink(entry)) {
  1991. std::cerr << "cmake -E tar: warning: skipping symbolic link \""
  1992. << cm_archive_entry_pathname(entry) << "\" -> \"" << linktext
  1993. << "\"." << std::endl;
  1994. }
  1995. # endif
  1996. else {
  1997. ArchiveError("Problem with archive_write_header(): ", ext);
  1998. cmSystemTools::Error("Current file: " +
  1999. cm_archive_entry_pathname(entry));
  2000. break;
  2001. }
  2002. }
  2003. }
  2004. bool error_occured = false;
  2005. if (matching != nullptr) {
  2006. const char* p;
  2007. int ar;
  2008. while ((ar = archive_match_path_unmatched_inclusions_next(matching, &p)) ==
  2009. ARCHIVE_OK) {
  2010. cmSystemTools::Error("tar: " + std::string(p) +
  2011. ": Not found in archive");
  2012. error_occured = true;
  2013. }
  2014. if (error_occured) {
  2015. return false;
  2016. }
  2017. if (ar == ARCHIVE_FATAL) {
  2018. cmSystemTools::Error("tar: Out of memory");
  2019. return false;
  2020. }
  2021. }
  2022. archive_match_free(matching);
  2023. archive_write_free(ext);
  2024. archive_read_close(a);
  2025. archive_read_free(a);
  2026. return r == ARCHIVE_EOF || r == ARCHIVE_OK;
  2027. }
  2028. }
  2029. #endif
  2030. bool cmSystemTools::ExtractTar(const std::string& outFileName,
  2031. const std::vector<std::string>& files,
  2032. cmTarExtractTimestamps extractTimestamps,
  2033. bool verbose)
  2034. {
  2035. #if !defined(CMAKE_BOOTSTRAP)
  2036. return extract_tar(outFileName, files, verbose, extractTimestamps, true);
  2037. #else
  2038. (void)outFileName;
  2039. (void)files;
  2040. (void)extractTimestamps;
  2041. (void)verbose;
  2042. return false;
  2043. #endif
  2044. }
  2045. bool cmSystemTools::ListTar(const std::string& outFileName,
  2046. const std::vector<std::string>& files,
  2047. bool verbose)
  2048. {
  2049. #if !defined(CMAKE_BOOTSTRAP)
  2050. return extract_tar(outFileName, files, verbose, cmTarExtractTimestamps::Yes,
  2051. false);
  2052. #else
  2053. (void)outFileName;
  2054. (void)files;
  2055. (void)verbose;
  2056. return false;
  2057. #endif
  2058. }
  2059. int cmSystemTools::WaitForLine(cmsysProcess* process, std::string& line,
  2060. cmDuration timeout, std::vector<char>& out,
  2061. std::vector<char>& err)
  2062. {
  2063. line.clear();
  2064. auto outiter = out.begin();
  2065. auto erriter = err.begin();
  2066. cmProcessOutput processOutput;
  2067. std::string strdata;
  2068. while (true) {
  2069. // Check for a newline in stdout.
  2070. for (; outiter != out.end(); ++outiter) {
  2071. if ((*outiter == '\r') && ((outiter + 1) == out.end())) {
  2072. break;
  2073. }
  2074. if (*outiter == '\n' || *outiter == '\0') {
  2075. std::vector<char>::size_type length = outiter - out.begin();
  2076. if (length > 1 && *(outiter - 1) == '\r') {
  2077. --length;
  2078. }
  2079. if (length > 0) {
  2080. line.append(out.data(), length);
  2081. }
  2082. out.erase(out.begin(), outiter + 1);
  2083. return cmsysProcess_Pipe_STDOUT;
  2084. }
  2085. }
  2086. // Check for a newline in stderr.
  2087. for (; erriter != err.end(); ++erriter) {
  2088. if ((*erriter == '\r') && ((erriter + 1) == err.end())) {
  2089. break;
  2090. }
  2091. if (*erriter == '\n' || *erriter == '\0') {
  2092. std::vector<char>::size_type length = erriter - err.begin();
  2093. if (length > 1 && *(erriter - 1) == '\r') {
  2094. --length;
  2095. }
  2096. if (length > 0) {
  2097. line.append(err.data(), length);
  2098. }
  2099. err.erase(err.begin(), erriter + 1);
  2100. return cmsysProcess_Pipe_STDERR;
  2101. }
  2102. }
  2103. // No newlines found. Wait for more data from the process.
  2104. int length;
  2105. char* data;
  2106. double timeoutAsDbl = timeout.count();
  2107. int pipe =
  2108. cmsysProcess_WaitForData(process, &data, &length, &timeoutAsDbl);
  2109. if (pipe == cmsysProcess_Pipe_Timeout) {
  2110. // Timeout has been exceeded.
  2111. return pipe;
  2112. }
  2113. if (pipe == cmsysProcess_Pipe_STDOUT) {
  2114. processOutput.DecodeText(data, length, strdata, 1);
  2115. // Append to the stdout buffer.
  2116. std::vector<char>::size_type size = out.size();
  2117. cm::append(out, strdata);
  2118. outiter = out.begin() + size;
  2119. } else if (pipe == cmsysProcess_Pipe_STDERR) {
  2120. processOutput.DecodeText(data, length, strdata, 2);
  2121. // Append to the stderr buffer.
  2122. std::vector<char>::size_type size = err.size();
  2123. cm::append(err, strdata);
  2124. erriter = err.begin() + size;
  2125. } else if (pipe == cmsysProcess_Pipe_None) {
  2126. // Both stdout and stderr pipes have broken. Return leftover data.
  2127. processOutput.DecodeText(std::string(), strdata, 1);
  2128. if (!strdata.empty()) {
  2129. std::vector<char>::size_type size = out.size();
  2130. cm::append(out, strdata);
  2131. outiter = out.begin() + size;
  2132. }
  2133. processOutput.DecodeText(std::string(), strdata, 2);
  2134. if (!strdata.empty()) {
  2135. std::vector<char>::size_type size = err.size();
  2136. cm::append(err, strdata);
  2137. erriter = err.begin() + size;
  2138. }
  2139. if (!out.empty()) {
  2140. line.append(out.data(), outiter - out.begin());
  2141. out.erase(out.begin(), out.end());
  2142. return cmsysProcess_Pipe_STDOUT;
  2143. }
  2144. if (!err.empty()) {
  2145. line.append(err.data(), erriter - err.begin());
  2146. err.erase(err.begin(), err.end());
  2147. return cmsysProcess_Pipe_STDERR;
  2148. }
  2149. return cmsysProcess_Pipe_None;
  2150. }
  2151. }
  2152. }
  2153. #ifdef _WIN32
  2154. static void EnsureStdPipe(DWORD fd)
  2155. {
  2156. if (GetStdHandle(fd) != INVALID_HANDLE_VALUE) {
  2157. return;
  2158. }
  2159. SECURITY_ATTRIBUTES sa;
  2160. sa.nLength = sizeof(sa);
  2161. sa.lpSecurityDescriptor = NULL;
  2162. sa.bInheritHandle = TRUE;
  2163. HANDLE h = CreateFileW(
  2164. L"NUL",
  2165. fd == STD_INPUT_HANDLE ? FILE_GENERIC_READ
  2166. : FILE_GENERIC_WRITE | FILE_READ_ATTRIBUTES,
  2167. FILE_SHARE_READ | FILE_SHARE_WRITE, &sa, OPEN_EXISTING, 0, NULL);
  2168. if (h == INVALID_HANDLE_VALUE) {
  2169. LPSTR message = NULL;
  2170. DWORD size = FormatMessageA(
  2171. FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
  2172. FORMAT_MESSAGE_IGNORE_INSERTS,
  2173. NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  2174. (LPSTR)&message, 0, NULL);
  2175. std::string msg = std::string(message, size);
  2176. LocalFree(message);
  2177. std::cerr << "failed to open NUL for missing stdio pipe: " << msg;
  2178. abort();
  2179. }
  2180. SetStdHandle(fd, h);
  2181. }
  2182. void cmSystemTools::EnsureStdPipes()
  2183. {
  2184. EnsureStdPipe(STD_INPUT_HANDLE);
  2185. EnsureStdPipe(STD_OUTPUT_HANDLE);
  2186. EnsureStdPipe(STD_ERROR_HANDLE);
  2187. }
  2188. #else
  2189. static void EnsureStdPipe(int fd)
  2190. {
  2191. if (fcntl(fd, F_GETFD) != -1 || errno != EBADF) {
  2192. return;
  2193. }
  2194. int f = open("/dev/null", fd == STDIN_FILENO ? O_RDONLY : O_WRONLY);
  2195. if (f == -1) {
  2196. perror("failed to open /dev/null for missing stdio pipe");
  2197. abort();
  2198. }
  2199. if (f != fd) {
  2200. dup2(f, fd);
  2201. close(f);
  2202. }
  2203. }
  2204. void cmSystemTools::EnsureStdPipes()
  2205. {
  2206. EnsureStdPipe(STDIN_FILENO);
  2207. EnsureStdPipe(STDOUT_FILENO);
  2208. EnsureStdPipe(STDERR_FILENO);
  2209. }
  2210. #endif
  2211. void cmSystemTools::DoNotInheritStdPipes()
  2212. {
  2213. #ifdef _WIN32
  2214. // Check to see if we are attached to a console
  2215. // if so, then do not stop the inherited pipes
  2216. // or stdout and stderr will not show up in dos
  2217. // shell windows
  2218. CONSOLE_SCREEN_BUFFER_INFO hOutInfo;
  2219. HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
  2220. if (GetConsoleScreenBufferInfo(hOut, &hOutInfo)) {
  2221. return;
  2222. }
  2223. {
  2224. HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
  2225. DuplicateHandle(GetCurrentProcess(), out, GetCurrentProcess(), &out, 0,
  2226. FALSE, DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
  2227. SetStdHandle(STD_OUTPUT_HANDLE, out);
  2228. }
  2229. {
  2230. HANDLE out = GetStdHandle(STD_ERROR_HANDLE);
  2231. DuplicateHandle(GetCurrentProcess(), out, GetCurrentProcess(), &out, 0,
  2232. FALSE, DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
  2233. SetStdHandle(STD_ERROR_HANDLE, out);
  2234. }
  2235. #endif
  2236. }
  2237. #ifdef _WIN32
  2238. # ifndef CRYPT_SILENT
  2239. # define CRYPT_SILENT 0x40 /* Not defined by VS 6 version of header. */
  2240. # endif
  2241. static int WinCryptRandom(void* data, size_t size)
  2242. {
  2243. int result = 0;
  2244. HCRYPTPROV hProvider = 0;
  2245. if (CryptAcquireContextW(&hProvider, 0, 0, PROV_RSA_FULL,
  2246. CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) {
  2247. result = CryptGenRandom(hProvider, (DWORD)size, (BYTE*)data) ? 1 : 0;
  2248. CryptReleaseContext(hProvider, 0);
  2249. }
  2250. return result;
  2251. }
  2252. #endif
  2253. unsigned int cmSystemTools::RandomSeed()
  2254. {
  2255. #if defined(_WIN32) && !defined(__CYGWIN__)
  2256. unsigned int seed = 0;
  2257. // Try using a real random source.
  2258. if (WinCryptRandom(&seed, sizeof(seed))) {
  2259. return seed;
  2260. }
  2261. // Fall back to the time and pid.
  2262. FILETIME ft;
  2263. GetSystemTimeAsFileTime(&ft);
  2264. unsigned int t1 = static_cast<unsigned int>(ft.dwHighDateTime);
  2265. unsigned int t2 = static_cast<unsigned int>(ft.dwLowDateTime);
  2266. unsigned int pid = static_cast<unsigned int>(GetCurrentProcessId());
  2267. return t1 ^ t2 ^ pid;
  2268. #else
  2269. union
  2270. {
  2271. unsigned int integer;
  2272. char bytes[sizeof(unsigned int)];
  2273. } seed;
  2274. // Try using a real random source.
  2275. cmsys::ifstream fin;
  2276. fin.rdbuf()->pubsetbuf(nullptr, 0); // Unbuffered read.
  2277. fin.open("/dev/urandom");
  2278. if (fin.good() && fin.read(seed.bytes, sizeof(seed)) &&
  2279. fin.gcount() == sizeof(seed)) {
  2280. return seed.integer;
  2281. }
  2282. // Fall back to the time and pid.
  2283. struct timeval t;
  2284. gettimeofday(&t, nullptr);
  2285. unsigned int pid = static_cast<unsigned int>(getpid());
  2286. unsigned int tv_sec = static_cast<unsigned int>(t.tv_sec);
  2287. unsigned int tv_usec = static_cast<unsigned int>(t.tv_usec);
  2288. // Since tv_usec never fills more than 11 bits we shift it to fill
  2289. // in the slow-changing high-order bits of tv_sec.
  2290. return tv_sec ^ (tv_usec << 21) ^ pid;
  2291. #endif
  2292. }
  2293. static std::string cmSystemToolsCMakeCommand;
  2294. static std::string cmSystemToolsCTestCommand;
  2295. static std::string cmSystemToolsCPackCommand;
  2296. static std::string cmSystemToolsCMakeCursesCommand;
  2297. static std::string cmSystemToolsCMakeGUICommand;
  2298. static std::string cmSystemToolsCMClDepsCommand;
  2299. static std::string cmSystemToolsCMakeRoot;
  2300. static std::string cmSystemToolsHTMLDoc;
  2301. void cmSystemTools::FindCMakeResources(const char* argv0)
  2302. {
  2303. std::string exe_dir;
  2304. #if defined(_WIN32) && !defined(__CYGWIN__)
  2305. (void)argv0; // ignore this on windows
  2306. wchar_t modulepath[_MAX_PATH];
  2307. ::GetModuleFileNameW(NULL, modulepath, sizeof(modulepath));
  2308. std::string path = cmsys::Encoding::ToNarrow(modulepath);
  2309. std::string realPath =
  2310. cmSystemTools::GetRealPathResolvingWindowsSubst(path, NULL);
  2311. if (realPath.empty()) {
  2312. realPath = path;
  2313. }
  2314. exe_dir = cmSystemTools::GetFilenamePath(realPath);
  2315. #elif defined(__APPLE__)
  2316. (void)argv0; // ignore this on OS X
  2317. # define CM_EXE_PATH_LOCAL_SIZE 16384
  2318. char exe_path_local[CM_EXE_PATH_LOCAL_SIZE];
  2319. # if defined(MAC_OS_X_VERSION_10_3) && !defined(MAC_OS_X_VERSION_10_4)
  2320. unsigned long exe_path_size = CM_EXE_PATH_LOCAL_SIZE;
  2321. # else
  2322. uint32_t exe_path_size = CM_EXE_PATH_LOCAL_SIZE;
  2323. # endif
  2324. # undef CM_EXE_PATH_LOCAL_SIZE
  2325. char* exe_path = exe_path_local;
  2326. if (_NSGetExecutablePath(exe_path, &exe_path_size) < 0) {
  2327. exe_path = static_cast<char*>(malloc(exe_path_size));
  2328. _NSGetExecutablePath(exe_path, &exe_path_size);
  2329. }
  2330. exe_dir =
  2331. cmSystemTools::GetFilenamePath(cmSystemTools::GetRealPath(exe_path));
  2332. if (exe_path != exe_path_local) {
  2333. free(exe_path);
  2334. }
  2335. if (cmSystemTools::GetFilenameName(exe_dir) == "MacOS") {
  2336. // The executable is inside an application bundle.
  2337. // Look for ..<CMAKE_BIN_DIR> (install tree) and then fall back to
  2338. // ../../../bin (build tree).
  2339. exe_dir = cmSystemTools::GetFilenamePath(exe_dir);
  2340. if (cmSystemTools::FileExists(exe_dir + CMAKE_BIN_DIR "/cmake")) {
  2341. exe_dir += CMAKE_BIN_DIR;
  2342. } else {
  2343. exe_dir = cmSystemTools::GetFilenamePath(exe_dir);
  2344. exe_dir = cmSystemTools::GetFilenamePath(exe_dir);
  2345. }
  2346. }
  2347. #else
  2348. std::string errorMsg;
  2349. std::string exe;
  2350. if (cmSystemTools::FindProgramPath(argv0, exe, errorMsg)) {
  2351. // remove symlinks
  2352. exe = cmSystemTools::GetRealPath(exe);
  2353. exe_dir = cmSystemTools::GetFilenamePath(exe);
  2354. } else {
  2355. // ???
  2356. }
  2357. #endif
  2358. exe_dir = cmSystemTools::GetActualCaseForPath(exe_dir);
  2359. cmSystemToolsCMakeCommand =
  2360. cmStrCat(exe_dir, "/cmake", cmSystemTools::GetExecutableExtension());
  2361. #ifdef CMAKE_BOOTSTRAP
  2362. // The bootstrap cmake does not provide the other tools,
  2363. // so use the directory where they are about to be built.
  2364. exe_dir = CMAKE_BOOTSTRAP_BINARY_DIR "/bin";
  2365. #endif
  2366. cmSystemToolsCTestCommand =
  2367. cmStrCat(exe_dir, "/ctest", cmSystemTools::GetExecutableExtension());
  2368. cmSystemToolsCPackCommand =
  2369. cmStrCat(exe_dir, "/cpack", cmSystemTools::GetExecutableExtension());
  2370. cmSystemToolsCMakeGUICommand =
  2371. cmStrCat(exe_dir, "/cmake-gui", cmSystemTools::GetExecutableExtension());
  2372. if (!cmSystemTools::FileExists(cmSystemToolsCMakeGUICommand)) {
  2373. cmSystemToolsCMakeGUICommand.clear();
  2374. }
  2375. cmSystemToolsCMakeCursesCommand =
  2376. cmStrCat(exe_dir, "/ccmake", cmSystemTools::GetExecutableExtension());
  2377. if (!cmSystemTools::FileExists(cmSystemToolsCMakeCursesCommand)) {
  2378. cmSystemToolsCMakeCursesCommand.clear();
  2379. }
  2380. cmSystemToolsCMClDepsCommand =
  2381. cmStrCat(exe_dir, "/cmcldeps", cmSystemTools::GetExecutableExtension());
  2382. if (!cmSystemTools::FileExists(cmSystemToolsCMClDepsCommand)) {
  2383. cmSystemToolsCMClDepsCommand.clear();
  2384. }
  2385. #ifndef CMAKE_BOOTSTRAP
  2386. // Install tree has
  2387. // - "<prefix><CMAKE_BIN_DIR>/cmake"
  2388. // - "<prefix><CMAKE_DATA_DIR>"
  2389. // - "<prefix><CMAKE_DOC_DIR>"
  2390. if (cmHasLiteralSuffix(exe_dir, CMAKE_BIN_DIR)) {
  2391. std::string const prefix =
  2392. exe_dir.substr(0, exe_dir.size() - cmStrLen(CMAKE_BIN_DIR));
  2393. cmSystemToolsCMakeRoot = cmStrCat(prefix, CMAKE_DATA_DIR);
  2394. if (cmSystemTools::FileExists(
  2395. cmStrCat(prefix, CMAKE_DOC_DIR "/html/index.html"))) {
  2396. cmSystemToolsHTMLDoc = cmStrCat(prefix, CMAKE_DOC_DIR "/html");
  2397. }
  2398. }
  2399. if (cmSystemToolsCMakeRoot.empty() ||
  2400. !cmSystemTools::FileExists(
  2401. cmStrCat(cmSystemToolsCMakeRoot, "/Modules/CMake.cmake"))) {
  2402. // Build tree has "<build>/bin[/<config>]/cmake" and
  2403. // "<build>/CMakeFiles/CMakeSourceDir.txt".
  2404. std::string dir = cmSystemTools::GetFilenamePath(exe_dir);
  2405. std::string src_dir_txt = cmStrCat(dir, "/CMakeFiles/CMakeSourceDir.txt");
  2406. cmsys::ifstream fin(src_dir_txt.c_str());
  2407. std::string src_dir;
  2408. if (fin && cmSystemTools::GetLineFromStream(fin, src_dir) &&
  2409. cmSystemTools::FileIsDirectory(src_dir)) {
  2410. cmSystemToolsCMakeRoot = src_dir;
  2411. } else {
  2412. dir = cmSystemTools::GetFilenamePath(dir);
  2413. src_dir_txt = cmStrCat(dir, "/CMakeFiles/CMakeSourceDir.txt");
  2414. cmsys::ifstream fin2(src_dir_txt.c_str());
  2415. if (fin2 && cmSystemTools::GetLineFromStream(fin2, src_dir) &&
  2416. cmSystemTools::FileIsDirectory(src_dir)) {
  2417. cmSystemToolsCMakeRoot = src_dir;
  2418. }
  2419. }
  2420. if (!cmSystemToolsCMakeRoot.empty() && cmSystemToolsHTMLDoc.empty() &&
  2421. cmSystemTools::FileExists(
  2422. cmStrCat(dir, "/Utilities/Sphinx/html/index.html"))) {
  2423. cmSystemToolsHTMLDoc = cmStrCat(dir, "/Utilities/Sphinx/html");
  2424. }
  2425. }
  2426. #else
  2427. // Bootstrap build knows its source.
  2428. cmSystemToolsCMakeRoot = CMAKE_BOOTSTRAP_SOURCE_DIR;
  2429. #endif
  2430. }
  2431. std::string const& cmSystemTools::GetCMakeCommand()
  2432. {
  2433. return cmSystemToolsCMakeCommand;
  2434. }
  2435. std::string const& cmSystemTools::GetCTestCommand()
  2436. {
  2437. return cmSystemToolsCTestCommand;
  2438. }
  2439. std::string const& cmSystemTools::GetCPackCommand()
  2440. {
  2441. return cmSystemToolsCPackCommand;
  2442. }
  2443. std::string const& cmSystemTools::GetCMakeCursesCommand()
  2444. {
  2445. return cmSystemToolsCMakeCursesCommand;
  2446. }
  2447. std::string const& cmSystemTools::GetCMakeGUICommand()
  2448. {
  2449. return cmSystemToolsCMakeGUICommand;
  2450. }
  2451. std::string const& cmSystemTools::GetCMClDepsCommand()
  2452. {
  2453. return cmSystemToolsCMClDepsCommand;
  2454. }
  2455. std::string const& cmSystemTools::GetCMakeRoot()
  2456. {
  2457. return cmSystemToolsCMakeRoot;
  2458. }
  2459. std::string const& cmSystemTools::GetHTMLDoc()
  2460. {
  2461. return cmSystemToolsHTMLDoc;
  2462. }
  2463. std::string cmSystemTools::GetCurrentWorkingDirectory()
  2464. {
  2465. return cmSystemTools::CollapseFullPath(
  2466. cmsys::SystemTools::GetCurrentWorkingDirectory());
  2467. }
  2468. void cmSystemTools::MakefileColorEcho(int color, const char* message,
  2469. bool newline, bool enabled)
  2470. {
  2471. // On some platforms (an MSYS prompt) cmsysTerminal may not be able
  2472. // to determine whether the stream is displayed on a tty. In this
  2473. // case it assumes no unless we tell it otherwise. Since we want
  2474. // color messages to be displayed for users we will assume yes.
  2475. // However, we can test for some situations when the answer is most
  2476. // likely no.
  2477. int assumeTTY = cmsysTerminal_Color_AssumeTTY;
  2478. if (cmSystemTools::HasEnv("DART_TEST_FROM_DART") ||
  2479. cmSystemTools::HasEnv("DASHBOARD_TEST_FROM_CTEST") ||
  2480. cmSystemTools::HasEnv("CTEST_INTERACTIVE_DEBUG_MODE")) {
  2481. // Avoid printing color escapes during dashboard builds.
  2482. assumeTTY = 0;
  2483. }
  2484. if (enabled && color != cmsysTerminal_Color_Normal) {
  2485. // Print with color. Delay the newline until later so that
  2486. // all color restore sequences appear before it.
  2487. cmsysTerminal_cfprintf(color | assumeTTY, stdout, "%s", message);
  2488. } else {
  2489. // Color is disabled. Print without color.
  2490. fprintf(stdout, "%s", message);
  2491. }
  2492. if (newline) {
  2493. fprintf(stdout, "\n");
  2494. }
  2495. }
  2496. bool cmSystemTools::GuessLibrarySOName(std::string const& fullPath,
  2497. std::string& soname)
  2498. {
  2499. // For ELF shared libraries use a real parser to get the correct
  2500. // soname.
  2501. cmELF elf(fullPath.c_str());
  2502. if (elf) {
  2503. return elf.GetSOName(soname);
  2504. }
  2505. // If the file is not a symlink we have no guess for its soname.
  2506. if (!cmSystemTools::FileIsSymlink(fullPath)) {
  2507. return false;
  2508. }
  2509. if (!cmSystemTools::ReadSymlink(fullPath, soname)) {
  2510. return false;
  2511. }
  2512. // If the symlink has a path component we have no guess for the soname.
  2513. if (!cmSystemTools::GetFilenamePath(soname).empty()) {
  2514. return false;
  2515. }
  2516. // If the symlink points at an extended version of the same name
  2517. // assume it is the soname.
  2518. std::string name = cmSystemTools::GetFilenameName(fullPath);
  2519. return soname.length() > name.length() &&
  2520. soname.compare(0, name.length(), name) == 0;
  2521. }
  2522. bool cmSystemTools::GuessLibraryInstallName(std::string const& fullPath,
  2523. std::string& soname)
  2524. {
  2525. #if defined(CMake_USE_MACH_PARSER)
  2526. cmMachO macho(fullPath.c_str());
  2527. if (macho) {
  2528. return macho.GetInstallName(soname);
  2529. }
  2530. #else
  2531. (void)fullPath;
  2532. (void)soname;
  2533. #endif
  2534. return false;
  2535. }
  2536. static std::string::size_type cmSystemToolsFindRPath(
  2537. cm::string_view const& have, cm::string_view const& want)
  2538. {
  2539. std::string::size_type pos = 0;
  2540. while (pos < have.size()) {
  2541. // Look for an occurrence of the string.
  2542. std::string::size_type const beg = have.find(want, pos);
  2543. if (beg == std::string::npos) {
  2544. return std::string::npos;
  2545. }
  2546. // Make sure it is separated from preceding entries.
  2547. if (beg > 0 && have[beg - 1] != ':') {
  2548. pos = beg + 1;
  2549. continue;
  2550. }
  2551. // Make sure it is separated from following entries.
  2552. std::string::size_type const end = beg + want.size();
  2553. if (end < have.size() && have[end] != ':') {
  2554. pos = beg + 1;
  2555. continue;
  2556. }
  2557. // Return the position of the path portion.
  2558. return beg;
  2559. }
  2560. // The desired rpath was not found.
  2561. return std::string::npos;
  2562. }
  2563. namespace {
  2564. struct cmSystemToolsRPathInfo
  2565. {
  2566. unsigned long Position;
  2567. unsigned long Size;
  2568. std::string Name;
  2569. std::string Value;
  2570. };
  2571. using EmptyCallback = std::function<bool(std::string*, const cmELF&)>;
  2572. using AdjustCallback = std::function<bool(
  2573. cm::optional<std::string>&, const std::string&, const char*, std::string*)>;
  2574. cm::optional<bool> AdjustRPathELF(std::string const& file,
  2575. const EmptyCallback& emptyCallback,
  2576. const AdjustCallback& adjustCallback,
  2577. std::string* emsg, bool* changed)
  2578. {
  2579. if (changed) {
  2580. *changed = false;
  2581. }
  2582. int rp_count = 0;
  2583. bool remove_rpath = true;
  2584. cmSystemToolsRPathInfo rp[2];
  2585. {
  2586. // Parse the ELF binary.
  2587. cmELF elf(file.c_str());
  2588. if (!elf) {
  2589. return cm::nullopt; // Not a valid ELF file.
  2590. }
  2591. // Get the RPATH and RUNPATH entries from it.
  2592. int se_count = 0;
  2593. cmELF::StringEntry const* se[2] = { nullptr, nullptr };
  2594. const char* se_name[2] = { nullptr, nullptr };
  2595. if (cmELF::StringEntry const* se_rpath = elf.GetRPath()) {
  2596. se[se_count] = se_rpath;
  2597. se_name[se_count] = "RPATH";
  2598. ++se_count;
  2599. }
  2600. if (cmELF::StringEntry const* se_runpath = elf.GetRunPath()) {
  2601. se[se_count] = se_runpath;
  2602. se_name[se_count] = "RUNPATH";
  2603. ++se_count;
  2604. }
  2605. if (se_count == 0) {
  2606. return emptyCallback(emsg, elf);
  2607. }
  2608. for (int i = 0; i < se_count; ++i) {
  2609. // If both RPATH and RUNPATH refer to the same string literal it
  2610. // needs to be changed only once.
  2611. if (rp_count && rp[0].Position == se[i]->Position) {
  2612. continue;
  2613. }
  2614. // Store information about the entry in the file.
  2615. rp[rp_count].Position = se[i]->Position;
  2616. rp[rp_count].Size = se[i]->Size;
  2617. rp[rp_count].Name = se_name[i];
  2618. // Adjust the rpath.
  2619. cm::optional<std::string> outRPath;
  2620. if (!adjustCallback(outRPath, se[i]->Value, se_name[i], emsg)) {
  2621. return false;
  2622. }
  2623. if (outRPath) {
  2624. if (!outRPath->empty()) {
  2625. remove_rpath = false;
  2626. }
  2627. // Make sure there is enough room to store the new rpath and at
  2628. // least one null terminator.
  2629. if (rp[rp_count].Size < outRPath->length() + 1) {
  2630. if (emsg) {
  2631. *emsg = cmStrCat("The replacement path is too long for the ",
  2632. se_name[i], " entry.");
  2633. }
  2634. return false;
  2635. }
  2636. // This entry is ready for update.
  2637. rp[rp_count].Value = std::move(*outRPath);
  2638. ++rp_count;
  2639. } else {
  2640. remove_rpath = false;
  2641. }
  2642. }
  2643. }
  2644. // If no runtime path needs to be changed, we are done.
  2645. if (rp_count == 0) {
  2646. return true;
  2647. }
  2648. // If the resulting rpath is empty, just remove the entire entry instead.
  2649. if (remove_rpath) {
  2650. return cmSystemTools::RemoveRPath(file, emsg, changed);
  2651. }
  2652. {
  2653. // Open the file for update.
  2654. cmsys::ofstream f(file.c_str(),
  2655. std::ios::in | std::ios::out | std::ios::binary);
  2656. if (!f) {
  2657. if (emsg) {
  2658. *emsg = "Error opening file for update.";
  2659. }
  2660. return false;
  2661. }
  2662. // Store the new RPATH and RUNPATH strings.
  2663. for (int i = 0; i < rp_count; ++i) {
  2664. // Seek to the RPATH position.
  2665. if (!f.seekp(rp[i].Position)) {
  2666. if (emsg) {
  2667. *emsg = cmStrCat("Error seeking to ", rp[i].Name, " position.");
  2668. }
  2669. return false;
  2670. }
  2671. // Write the new rpath. Follow it with enough null terminators to
  2672. // fill the string table entry.
  2673. f << rp[i].Value;
  2674. for (unsigned long j = rp[i].Value.length(); j < rp[i].Size; ++j) {
  2675. f << '\0';
  2676. }
  2677. // Make sure it wrote correctly.
  2678. if (!f) {
  2679. if (emsg) {
  2680. *emsg = cmStrCat("Error writing the new ", rp[i].Name,
  2681. " string to the file.");
  2682. }
  2683. return false;
  2684. }
  2685. }
  2686. }
  2687. // Everything was updated successfully.
  2688. if (changed) {
  2689. *changed = true;
  2690. }
  2691. return true;
  2692. }
  2693. std::function<bool(std::string*, const cmELF&)> MakeEmptyCallback(
  2694. const std::string& newRPath)
  2695. {
  2696. return [newRPath](std::string* emsg, const cmELF& elf) -> bool {
  2697. if (newRPath.empty()) {
  2698. // The new rpath is empty and there is no rpath anyway so it is
  2699. // okay.
  2700. return true;
  2701. }
  2702. if (emsg) {
  2703. *emsg =
  2704. cmStrCat("No valid ELF RPATH or RUNPATH entry exists in the file; ",
  2705. elf.GetErrorMessage());
  2706. }
  2707. return false;
  2708. };
  2709. }
  2710. }
  2711. static cm::optional<bool> ChangeRPathELF(std::string const& file,
  2712. std::string const& oldRPath,
  2713. std::string const& newRPath,
  2714. bool removeEnvironmentRPath,
  2715. std::string* emsg, bool* changed)
  2716. {
  2717. auto adjustCallback = [oldRPath, newRPath, removeEnvironmentRPath](
  2718. cm::optional<std::string>& outRPath,
  2719. const std::string& inRPath, const char* se_name,
  2720. std::string* emsg2) -> bool {
  2721. // Make sure the current rpath contains the old rpath.
  2722. std::string::size_type pos = cmSystemToolsFindRPath(inRPath, oldRPath);
  2723. if (pos == std::string::npos) {
  2724. // If it contains the new rpath instead then it is okay.
  2725. if (cmSystemToolsFindRPath(inRPath, newRPath) != std::string::npos) {
  2726. return true;
  2727. }
  2728. if (emsg2) {
  2729. std::ostringstream e;
  2730. /* clang-format off */
  2731. e << "The current " << se_name << " is:\n"
  2732. << " " << inRPath << "\n"
  2733. << "which does not contain:\n"
  2734. << " " << oldRPath << "\n"
  2735. << "as was expected.";
  2736. /* clang-format on */
  2737. *emsg2 = e.str();
  2738. }
  2739. return false;
  2740. }
  2741. std::string::size_type prefix_len = pos;
  2742. // If oldRPath was at the end of the file's RPath, and newRPath is empty,
  2743. // we should remove the unnecessary ':' at the end.
  2744. if (newRPath.empty() && pos > 0 && inRPath[pos - 1] == ':' &&
  2745. pos + oldRPath.length() == inRPath.length()) {
  2746. prefix_len--;
  2747. }
  2748. // Construct the new value which preserves the part of the path
  2749. // not being changed.
  2750. outRPath.emplace();
  2751. if (!removeEnvironmentRPath) {
  2752. *outRPath += inRPath.substr(0, prefix_len);
  2753. }
  2754. *outRPath += newRPath;
  2755. *outRPath += inRPath.substr(pos + oldRPath.length());
  2756. return true;
  2757. };
  2758. return AdjustRPathELF(file, MakeEmptyCallback(newRPath), adjustCallback,
  2759. emsg, changed);
  2760. }
  2761. static cm::optional<bool> SetRPathELF(std::string const& file,
  2762. std::string const& newRPath,
  2763. std::string* emsg, bool* changed)
  2764. {
  2765. auto adjustCallback = [newRPath](cm::optional<std::string>& outRPath,
  2766. const std::string& inRPath,
  2767. const char* /*se_name*/, std::string *
  2768. /*emsg*/) -> bool {
  2769. if (inRPath != newRPath) {
  2770. outRPath = newRPath;
  2771. }
  2772. return true;
  2773. };
  2774. return AdjustRPathELF(file, MakeEmptyCallback(newRPath), adjustCallback,
  2775. emsg, changed);
  2776. }
  2777. static cm::optional<bool> ChangeRPathXCOFF(std::string const& file,
  2778. std::string const& oldRPath,
  2779. std::string const& newRPath,
  2780. bool removeEnvironmentRPath,
  2781. std::string* emsg, bool* changed)
  2782. {
  2783. if (changed) {
  2784. *changed = false;
  2785. }
  2786. #if !defined(CMake_USE_XCOFF_PARSER)
  2787. (void)file;
  2788. (void)oldRPath;
  2789. (void)newRPath;
  2790. (void)removeEnvironmentRPath;
  2791. (void)emsg;
  2792. return cm::nullopt;
  2793. #else
  2794. bool chg = false;
  2795. cmXCOFF xcoff(file.c_str(), cmXCOFF::Mode::ReadWrite);
  2796. if (!xcoff) {
  2797. return cm::nullopt; // Not a valid XCOFF file
  2798. }
  2799. if (cm::optional<cm::string_view> maybeLibPath = xcoff.GetLibPath()) {
  2800. cm::string_view libPath = *maybeLibPath;
  2801. // Make sure the current rpath contains the old rpath.
  2802. std::string::size_type pos = cmSystemToolsFindRPath(libPath, oldRPath);
  2803. if (pos == std::string::npos) {
  2804. // If it contains the new rpath instead then it is okay.
  2805. if (cmSystemToolsFindRPath(libPath, newRPath) != std::string::npos) {
  2806. return true;
  2807. }
  2808. if (emsg) {
  2809. std::ostringstream e;
  2810. /* clang-format off */
  2811. e << "The current RPATH is:\n"
  2812. << " " << libPath << "\n"
  2813. << "which does not contain:\n"
  2814. << " " << oldRPath << "\n"
  2815. << "as was expected.";
  2816. /* clang-format on */
  2817. *emsg = e.str();
  2818. }
  2819. return false;
  2820. }
  2821. // The prefix is either empty or ends in a ':'.
  2822. cm::string_view prefix = libPath.substr(0, pos);
  2823. if (newRPath.empty() && !prefix.empty()) {
  2824. prefix.remove_suffix(1);
  2825. }
  2826. // The suffix is either empty or starts in a ':'.
  2827. cm::string_view suffix = libPath.substr(pos + oldRPath.length());
  2828. // Construct the new value which preserves the part of the path
  2829. // not being changed.
  2830. std::string newLibPath;
  2831. if (!removeEnvironmentRPath) {
  2832. newLibPath = std::string(prefix);
  2833. }
  2834. newLibPath += newRPath;
  2835. newLibPath += suffix;
  2836. chg = xcoff.SetLibPath(newLibPath);
  2837. }
  2838. if (!xcoff) {
  2839. if (emsg) {
  2840. *emsg = xcoff.GetErrorMessage();
  2841. }
  2842. return false;
  2843. }
  2844. // Everything was updated successfully.
  2845. if (changed) {
  2846. *changed = chg;
  2847. }
  2848. return true;
  2849. #endif
  2850. }
  2851. static cm::optional<bool> SetRPathXCOFF(std::string const& /*file*/,
  2852. std::string const& /*newRPath*/,
  2853. std::string* /*emsg*/,
  2854. bool* /*changed*/)
  2855. {
  2856. return cm::nullopt; // Not implemented.
  2857. }
  2858. bool cmSystemTools::ChangeRPath(std::string const& file,
  2859. std::string const& oldRPath,
  2860. std::string const& newRPath,
  2861. bool removeEnvironmentRPath, std::string* emsg,
  2862. bool* changed)
  2863. {
  2864. if (cm::optional<bool> result = ChangeRPathELF(
  2865. file, oldRPath, newRPath, removeEnvironmentRPath, emsg, changed)) {
  2866. return result.value();
  2867. }
  2868. if (cm::optional<bool> result = ChangeRPathXCOFF(
  2869. file, oldRPath, newRPath, removeEnvironmentRPath, emsg, changed)) {
  2870. return result.value();
  2871. }
  2872. // The file format is not recognized. Assume it has no RPATH.
  2873. if (newRPath.empty()) {
  2874. // The caller wanted no RPATH anyway.
  2875. return true;
  2876. }
  2877. if (emsg) {
  2878. *emsg = "The file format is not recognized.";
  2879. }
  2880. return false;
  2881. }
  2882. bool cmSystemTools::SetRPath(std::string const& file,
  2883. std::string const& newRPath, std::string* emsg,
  2884. bool* changed)
  2885. {
  2886. if (cm::optional<bool> result = SetRPathELF(file, newRPath, emsg, changed)) {
  2887. return result.value();
  2888. }
  2889. if (cm::optional<bool> result =
  2890. SetRPathXCOFF(file, newRPath, emsg, changed)) {
  2891. return result.value();
  2892. }
  2893. // The file format is not recognized. Assume it has no RPATH.
  2894. if (newRPath.empty()) {
  2895. // The caller wanted no RPATH anyway.
  2896. return true;
  2897. }
  2898. if (emsg) {
  2899. *emsg = "The file format is not recognized.";
  2900. }
  2901. return false;
  2902. }
  2903. namespace {
  2904. bool VersionCompare(cmSystemTools::CompareOp op, const char* lhss,
  2905. const char* rhss)
  2906. {
  2907. const char* endl = lhss;
  2908. const char* endr = rhss;
  2909. unsigned long lhs;
  2910. unsigned long rhs;
  2911. while (((*endl >= '0') && (*endl <= '9')) ||
  2912. ((*endr >= '0') && (*endr <= '9'))) {
  2913. // Do component-wise comparison.
  2914. lhs = strtoul(endl, const_cast<char**>(&endl), 10);
  2915. rhs = strtoul(endr, const_cast<char**>(&endr), 10);
  2916. if (lhs < rhs) {
  2917. // lhs < rhs, so true if operation is LESS
  2918. return (op & cmSystemTools::OP_LESS) != 0;
  2919. }
  2920. if (lhs > rhs) {
  2921. // lhs > rhs, so true if operation is GREATER
  2922. return (op & cmSystemTools::OP_GREATER) != 0;
  2923. }
  2924. if (*endr == '.') {
  2925. endr++;
  2926. }
  2927. if (*endl == '.') {
  2928. endl++;
  2929. }
  2930. }
  2931. // lhs == rhs, so true if operation is EQUAL
  2932. return (op & cmSystemTools::OP_EQUAL) != 0;
  2933. }
  2934. }
  2935. bool cmSystemTools::VersionCompare(cmSystemTools::CompareOp op,
  2936. const std::string& lhs,
  2937. const std::string& rhs)
  2938. {
  2939. return ::VersionCompare(op, lhs.c_str(), rhs.c_str());
  2940. }
  2941. bool cmSystemTools::VersionCompare(cmSystemTools::CompareOp op,
  2942. const std::string& lhs, const char rhs[])
  2943. {
  2944. return ::VersionCompare(op, lhs.c_str(), rhs);
  2945. }
  2946. bool cmSystemTools::VersionCompareEqual(std::string const& lhs,
  2947. std::string const& rhs)
  2948. {
  2949. return cmSystemTools::VersionCompare(cmSystemTools::OP_EQUAL, lhs, rhs);
  2950. }
  2951. bool cmSystemTools::VersionCompareGreater(std::string const& lhs,
  2952. std::string const& rhs)
  2953. {
  2954. return cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER, lhs, rhs);
  2955. }
  2956. bool cmSystemTools::VersionCompareGreaterEq(std::string const& lhs,
  2957. std::string const& rhs)
  2958. {
  2959. return cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER_EQUAL, lhs,
  2960. rhs);
  2961. }
  2962. static size_t cm_strverscmp_find_first_difference_or_end(const char* lhs,
  2963. const char* rhs)
  2964. {
  2965. size_t i = 0;
  2966. /* Step forward until we find a difference or both strings end together.
  2967. The difference may lie on the null-terminator of one string. */
  2968. while (lhs[i] == rhs[i] && lhs[i] != 0) {
  2969. ++i;
  2970. }
  2971. return i;
  2972. }
  2973. static size_t cm_strverscmp_find_digits_begin(const char* s, size_t i)
  2974. {
  2975. /* Step back until we are not preceded by a digit. */
  2976. while (i > 0 && isdigit(s[i - 1])) {
  2977. --i;
  2978. }
  2979. return i;
  2980. }
  2981. static size_t cm_strverscmp_find_digits_end(const char* s, size_t i)
  2982. {
  2983. /* Step forward over digits. */
  2984. while (isdigit(s[i])) {
  2985. ++i;
  2986. }
  2987. return i;
  2988. }
  2989. static size_t cm_strverscmp_count_leading_zeros(const char* s, size_t b)
  2990. {
  2991. size_t i = b;
  2992. /* Step forward over zeros that are followed by another digit. */
  2993. while (s[i] == '0' && isdigit(s[i + 1])) {
  2994. ++i;
  2995. }
  2996. return i - b;
  2997. }
  2998. static int cm_strverscmp(const char* lhs, const char* rhs)
  2999. {
  3000. size_t const i = cm_strverscmp_find_first_difference_or_end(lhs, rhs);
  3001. if (lhs[i] != rhs[i]) {
  3002. /* The strings differ starting at 'i'. Check for a digit sequence. */
  3003. size_t const b = cm_strverscmp_find_digits_begin(lhs, i);
  3004. if (b != i || (isdigit(lhs[i]) && isdigit(rhs[i]))) {
  3005. /* A digit sequence starts at 'b', preceding or at 'i'. */
  3006. /* Look for leading zeros, implying a leading decimal point. */
  3007. size_t const lhs_zeros = cm_strverscmp_count_leading_zeros(lhs, b);
  3008. size_t const rhs_zeros = cm_strverscmp_count_leading_zeros(rhs, b);
  3009. if (lhs_zeros != rhs_zeros) {
  3010. /* The side with more leading zeros orders first. */
  3011. return rhs_zeros > lhs_zeros ? 1 : -1;
  3012. }
  3013. if (lhs_zeros == 0) {
  3014. /* No leading zeros; compare digit sequence lengths. */
  3015. size_t const lhs_end = cm_strverscmp_find_digits_end(lhs, i);
  3016. size_t const rhs_end = cm_strverscmp_find_digits_end(rhs, i);
  3017. if (lhs_end != rhs_end) {
  3018. /* The side with fewer digits orders first. */
  3019. return lhs_end > rhs_end ? 1 : -1;
  3020. }
  3021. }
  3022. }
  3023. }
  3024. /* Ordering was not decided by digit sequence lengths; compare bytes. */
  3025. return lhs[i] - rhs[i];
  3026. }
  3027. int cmSystemTools::strverscmp(std::string const& lhs, std::string const& rhs)
  3028. {
  3029. return cm_strverscmp(lhs.c_str(), rhs.c_str());
  3030. }
  3031. static cm::optional<bool> RemoveRPathELF(std::string const& file,
  3032. std::string* emsg, bool* removed)
  3033. {
  3034. if (removed) {
  3035. *removed = false;
  3036. }
  3037. int zeroCount = 0;
  3038. unsigned long zeroPosition[2] = { 0, 0 };
  3039. unsigned long zeroSize[2] = { 0, 0 };
  3040. unsigned long bytesBegin = 0;
  3041. std::vector<char> bytes;
  3042. {
  3043. // Parse the ELF binary.
  3044. cmELF elf(file.c_str());
  3045. if (!elf) {
  3046. return cm::nullopt; // Not a valid ELF file.
  3047. }
  3048. // Get the RPATH and RUNPATH entries from it and sort them by index
  3049. // in the dynamic section header.
  3050. int se_count = 0;
  3051. cmELF::StringEntry const* se[2] = { nullptr, nullptr };
  3052. if (cmELF::StringEntry const* se_rpath = elf.GetRPath()) {
  3053. se[se_count++] = se_rpath;
  3054. }
  3055. if (cmELF::StringEntry const* se_runpath = elf.GetRunPath()) {
  3056. se[se_count++] = se_runpath;
  3057. }
  3058. if (se_count == 0) {
  3059. // There is no RPATH or RUNPATH anyway.
  3060. return true;
  3061. }
  3062. if (se_count == 2 && se[1]->IndexInSection < se[0]->IndexInSection) {
  3063. std::swap(se[0], se[1]);
  3064. }
  3065. // Obtain a copy of the dynamic entries
  3066. cmELF::DynamicEntryList dentries = elf.GetDynamicEntries();
  3067. if (dentries.empty()) {
  3068. // This should happen only for invalid ELF files where a DT_NULL
  3069. // appears before the end of the table.
  3070. if (emsg) {
  3071. *emsg = "DYNAMIC section contains a DT_NULL before the end.";
  3072. }
  3073. return false;
  3074. }
  3075. // Save information about the string entries to be zeroed.
  3076. zeroCount = se_count;
  3077. for (int i = 0; i < se_count; ++i) {
  3078. zeroPosition[i] = se[i]->Position;
  3079. zeroSize[i] = se[i]->Size;
  3080. }
  3081. // Get size of one DYNAMIC entry
  3082. unsigned long const sizeof_dentry =
  3083. elf.GetDynamicEntryPosition(1) - elf.GetDynamicEntryPosition(0);
  3084. // Adjust the entry list as necessary to remove the run path
  3085. unsigned long entriesErased = 0;
  3086. for (auto it = dentries.begin(); it != dentries.end();) {
  3087. if (it->first == cmELF::TagRPath || it->first == cmELF::TagRunPath) {
  3088. it = dentries.erase(it);
  3089. entriesErased++;
  3090. continue;
  3091. }
  3092. if (it->first == cmELF::TagMipsRldMapRel && elf.IsMIPS()) {
  3093. // Background: debuggers need to know the "linker map" which contains
  3094. // the addresses each dynamic object is loaded at. Most arches use
  3095. // the DT_DEBUG tag which the dynamic linker writes to (directly) and
  3096. // contain the location of the linker map, however on MIPS the
  3097. // .dynamic section is always read-only so this is not possible. MIPS
  3098. // objects instead contain a DT_MIPS_RLD_MAP tag which contains the
  3099. // address where the dynamic linker will write to (an indirect
  3100. // version of DT_DEBUG). Since this doesn't work when using PIE, a
  3101. // relative equivalent was created - DT_MIPS_RLD_MAP_REL. Since this
  3102. // version contains a relative offset, moving it changes the
  3103. // calculated address. This may cause the dynamic linker to write
  3104. // into memory it should not be changing.
  3105. //
  3106. // To fix this, we adjust the value of DT_MIPS_RLD_MAP_REL here. If
  3107. // we move it up by n bytes, we add n bytes to the value of this tag.
  3108. it->second += entriesErased * sizeof_dentry;
  3109. }
  3110. it++;
  3111. }
  3112. // Encode new entries list
  3113. bytes = elf.EncodeDynamicEntries(dentries);
  3114. bytesBegin = elf.GetDynamicEntryPosition(0);
  3115. }
  3116. // Open the file for update.
  3117. cmsys::ofstream f(file.c_str(),
  3118. std::ios::in | std::ios::out | std::ios::binary);
  3119. if (!f) {
  3120. if (emsg) {
  3121. *emsg = "Error opening file for update.";
  3122. }
  3123. return false;
  3124. }
  3125. // Write the new DYNAMIC table header.
  3126. if (!f.seekp(bytesBegin)) {
  3127. if (emsg) {
  3128. *emsg = "Error seeking to DYNAMIC table header for RPATH.";
  3129. }
  3130. return false;
  3131. }
  3132. if (!f.write(bytes.data(), bytes.size())) {
  3133. if (emsg) {
  3134. *emsg = "Error replacing DYNAMIC table header.";
  3135. }
  3136. return false;
  3137. }
  3138. // Fill the RPATH and RUNPATH strings with zero bytes.
  3139. for (int i = 0; i < zeroCount; ++i) {
  3140. if (!f.seekp(zeroPosition[i])) {
  3141. if (emsg) {
  3142. *emsg = "Error seeking to RPATH position.";
  3143. }
  3144. return false;
  3145. }
  3146. for (unsigned long j = 0; j < zeroSize[i]; ++j) {
  3147. f << '\0';
  3148. }
  3149. if (!f) {
  3150. if (emsg) {
  3151. *emsg = "Error writing the empty rpath string to the file.";
  3152. }
  3153. return false;
  3154. }
  3155. }
  3156. // Everything was updated successfully.
  3157. if (removed) {
  3158. *removed = true;
  3159. }
  3160. return true;
  3161. }
  3162. static cm::optional<bool> RemoveRPathXCOFF(std::string const& file,
  3163. std::string* emsg, bool* removed)
  3164. {
  3165. if (removed) {
  3166. *removed = false;
  3167. }
  3168. #if !defined(CMake_USE_XCOFF_PARSER)
  3169. (void)file;
  3170. (void)emsg;
  3171. return cm::nullopt; // Cannot handle XCOFF files.
  3172. #else
  3173. cmXCOFF xcoff(file.c_str(), cmXCOFF::Mode::ReadWrite);
  3174. if (!xcoff) {
  3175. return cm::nullopt; // Not a valid XCOFF file.
  3176. }
  3177. bool rm = xcoff.RemoveLibPath();
  3178. if (!xcoff) {
  3179. if (emsg) {
  3180. *emsg = xcoff.GetErrorMessage();
  3181. }
  3182. return false;
  3183. }
  3184. if (removed) {
  3185. *removed = rm;
  3186. }
  3187. return true;
  3188. #endif
  3189. }
  3190. bool cmSystemTools::RemoveRPath(std::string const& file, std::string* emsg,
  3191. bool* removed)
  3192. {
  3193. if (cm::optional<bool> result = RemoveRPathELF(file, emsg, removed)) {
  3194. return result.value();
  3195. }
  3196. if (cm::optional<bool> result = RemoveRPathXCOFF(file, emsg, removed)) {
  3197. return result.value();
  3198. }
  3199. // The file format is not recognized. Assume it has no RPATH.
  3200. return true;
  3201. }
  3202. bool cmSystemTools::CheckRPath(std::string const& file,
  3203. std::string const& newRPath)
  3204. {
  3205. // Parse the ELF binary.
  3206. cmELF elf(file.c_str());
  3207. if (elf) {
  3208. // Get the RPATH or RUNPATH entry from it.
  3209. cmELF::StringEntry const* se = elf.GetRPath();
  3210. if (!se) {
  3211. se = elf.GetRunPath();
  3212. }
  3213. // Make sure the current rpath contains the new rpath.
  3214. if (newRPath.empty()) {
  3215. if (!se) {
  3216. return true;
  3217. }
  3218. } else {
  3219. if (se &&
  3220. cmSystemToolsFindRPath(se->Value, newRPath) != std::string::npos) {
  3221. return true;
  3222. }
  3223. }
  3224. return false;
  3225. }
  3226. #if defined(CMake_USE_XCOFF_PARSER)
  3227. // Parse the XCOFF binary.
  3228. cmXCOFF xcoff(file.c_str());
  3229. if (xcoff) {
  3230. if (cm::optional<cm::string_view> libPath = xcoff.GetLibPath()) {
  3231. if (cmSystemToolsFindRPath(*libPath, newRPath) != std::string::npos) {
  3232. return true;
  3233. }
  3234. }
  3235. return false;
  3236. }
  3237. #endif
  3238. // The file format is not recognized. Assume it has no RPATH.
  3239. // Therefore we succeed if the new rpath is empty anyway.
  3240. return newRPath.empty();
  3241. }
  3242. bool cmSystemTools::RepeatedRemoveDirectory(const std::string& dir)
  3243. {
  3244. #ifdef _WIN32
  3245. // Windows sometimes locks files temporarily so try a few times.
  3246. WindowsFileRetry retry = cmSystemTools::GetWindowsFileRetry();
  3247. for (unsigned int i = 0; i < retry.Count; ++i) {
  3248. if (cmSystemTools::RemoveADirectory(dir)) {
  3249. return true;
  3250. }
  3251. cmSystemTools::Delay(retry.Delay);
  3252. }
  3253. return false;
  3254. #else
  3255. return static_cast<bool>(cmSystemTools::RemoveADirectory(dir));
  3256. #endif
  3257. }
  3258. std::string cmSystemTools::EncodeURL(std::string const& in, bool escapeSlashes)
  3259. {
  3260. std::string out;
  3261. for (char c : in) {
  3262. char hexCh[4] = { 0, 0, 0, 0 };
  3263. hexCh[0] = c;
  3264. switch (c) {
  3265. case '+':
  3266. case '?':
  3267. case '\\':
  3268. case '&':
  3269. case ' ':
  3270. case '=':
  3271. case '%':
  3272. snprintf(hexCh, sizeof(hexCh), "%%%02X", static_cast<int>(c));
  3273. break;
  3274. case '/':
  3275. if (escapeSlashes) {
  3276. strcpy(hexCh, "%2F");
  3277. }
  3278. break;
  3279. default:
  3280. break;
  3281. }
  3282. out.append(hexCh);
  3283. }
  3284. return out;
  3285. }
  3286. cmsys::Status cmSystemTools::CreateSymlink(std::string const& origName,
  3287. std::string const& newName)
  3288. {
  3289. cmsys::Status status =
  3290. cmSystemTools::CreateSymlinkQuietly(origName, newName);
  3291. if (!status) {
  3292. cmSystemTools::Error(cmStrCat("failed to create symbolic link '", newName,
  3293. "': ", status.GetString()));
  3294. }
  3295. return status;
  3296. }
  3297. cmsys::Status cmSystemTools::CreateSymlinkQuietly(std::string const& origName,
  3298. std::string const& newName)
  3299. {
  3300. uv_fs_t req;
  3301. int flags = 0;
  3302. #if defined(_WIN32)
  3303. if (cmsys::SystemTools::FileIsDirectory(origName)) {
  3304. flags |= UV_FS_SYMLINK_DIR;
  3305. }
  3306. #endif
  3307. int err = uv_fs_symlink(nullptr, &req, origName.c_str(), newName.c_str(),
  3308. flags, nullptr);
  3309. cmsys::Status status;
  3310. if (err) {
  3311. #if defined(_WIN32)
  3312. status = cmsys::Status::Windows(uv_fs_get_system_error(&req));
  3313. #elif UV_VERSION_MAJOR > 1 || (UV_VERSION_MAJOR == 1 && UV_VERSION_MINOR >= 38)
  3314. status = cmsys::Status::POSIX(uv_fs_get_system_error(&req));
  3315. #else
  3316. status = cmsys::Status::POSIX(-err);
  3317. #endif
  3318. }
  3319. return status;
  3320. }
  3321. cmsys::Status cmSystemTools::CreateLink(std::string const& origName,
  3322. std::string const& newName)
  3323. {
  3324. cmsys::Status status = cmSystemTools::CreateLinkQuietly(origName, newName);
  3325. if (!status) {
  3326. cmSystemTools::Error(
  3327. cmStrCat("failed to create link '", newName, "': ", status.GetString()));
  3328. }
  3329. return status;
  3330. }
  3331. cmsys::Status cmSystemTools::CreateLinkQuietly(std::string const& origName,
  3332. std::string const& newName)
  3333. {
  3334. uv_fs_t req;
  3335. int err =
  3336. uv_fs_link(nullptr, &req, origName.c_str(), newName.c_str(), nullptr);
  3337. cmsys::Status status;
  3338. if (err) {
  3339. #if defined(_WIN32)
  3340. status = cmsys::Status::Windows(uv_fs_get_system_error(&req));
  3341. #elif UV_VERSION_MAJOR > 1 || (UV_VERSION_MAJOR == 1 && UV_VERSION_MINOR >= 38)
  3342. status = cmsys::Status::POSIX(uv_fs_get_system_error(&req));
  3343. #else
  3344. status = cmsys::Status::POSIX(-err);
  3345. #endif
  3346. }
  3347. return status;
  3348. }
  3349. cm::string_view cmSystemTools::GetSystemName()
  3350. {
  3351. #if defined(_WIN32)
  3352. return "Windows";
  3353. #elif defined(__ANDROID__)
  3354. return "Android";
  3355. #else
  3356. static struct utsname uts_name;
  3357. static bool initialized = false;
  3358. static cm::string_view systemName;
  3359. if (initialized) {
  3360. return systemName;
  3361. }
  3362. if (uname(&uts_name) >= 0) {
  3363. initialized = true;
  3364. systemName = uts_name.sysname;
  3365. if (cmIsOff(systemName)) {
  3366. systemName = "UnknownOS";
  3367. }
  3368. // fix for BSD/OS, remove the /
  3369. static const cmsys::RegularExpression bsdOsRegex("BSD.OS");
  3370. cmsys::RegularExpressionMatch match;
  3371. if (bsdOsRegex.find(uts_name.sysname, match)) {
  3372. systemName = "BSDOS";
  3373. }
  3374. // fix for GNU/kFreeBSD, remove the GNU/
  3375. if (systemName.find("kFreeBSD") != cm::string_view::npos) {
  3376. systemName = "kFreeBSD";
  3377. }
  3378. // fix for CYGWIN and MSYS which have windows version in them
  3379. if (systemName.find("CYGWIN") != cm::string_view::npos) {
  3380. systemName = "CYGWIN";
  3381. }
  3382. if (systemName.find("MSYS") != cm::string_view::npos) {
  3383. systemName = "MSYS";
  3384. }
  3385. return systemName;
  3386. }
  3387. return "";
  3388. #endif
  3389. }
  3390. char cmSystemTools::GetSystemPathlistSeparator()
  3391. {
  3392. #if defined(_WIN32)
  3393. return ';';
  3394. #else
  3395. return ':';
  3396. #endif
  3397. }