cmSystemTools.cxx 122 KB

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