cmSystemTools.cxx 110 KB

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