cmSystemTools.cxx 108 KB

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