cmSystemTools.cxx 126 KB

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