cmSystemTools.cxx 108 KB

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