cmSystemTools.cxx 125 KB

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