cmSystemTools.cxx 107 KB

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