cmSystemTools.cxx 114 KB

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