cmSystemTools.cxx 109 KB

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