cmSystemTools.cxx 116 KB

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