cmSystemTools.cxx 120 KB

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