cmSystemTools.cxx 123 KB

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