cmSystemTools.cxx 125 KB

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