cmSystemTools.cxx 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104
  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)
  4. // POSIX APIs are needed
  5. // NOLINTNEXTLINE(bugprone-reserved-identifier)
  6. # define _POSIX_C_SOURCE 200809L
  7. #endif
  8. #if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) || \
  9. defined(__QNX__)
  10. // For isascii
  11. // NOLINTNEXTLINE(bugprone-reserved-identifier)
  12. # define _XOPEN_SOURCE 700
  13. #endif
  14. #include "cmSystemTools.h"
  15. #include <cmext/algorithm>
  16. #include <cm3p/uv.h>
  17. #include "cmDuration.h"
  18. #include "cmProcessOutput.h"
  19. #include "cmRange.h"
  20. #include "cmStringAlgorithms.h"
  21. #if !defined(CMAKE_BOOTSTRAP)
  22. # include <cm3p/archive.h>
  23. # include <cm3p/archive_entry.h>
  24. # include "cmArchiveWrite.h"
  25. # include "cmLocale.h"
  26. # ifndef __LA_INT64_T
  27. # define __LA_INT64_T la_int64_t
  28. # endif
  29. # ifndef __LA_SSIZE_T
  30. # define __LA_SSIZE_T la_ssize_t
  31. # endif
  32. #endif
  33. #if !defined(CMAKE_BOOTSTRAP)
  34. # if defined(_WIN32)
  35. # include <cm/memory>
  36. # endif
  37. # include "cmCryptoHash.h"
  38. #endif
  39. #if defined(CMake_USE_ELF_PARSER)
  40. # include "cmELF.h"
  41. #endif
  42. #if defined(CMake_USE_MACH_PARSER)
  43. # include "cmMachO.h"
  44. #endif
  45. #if defined(CMake_USE_XCOFF_PARSER)
  46. # include "cmXCOFF.h"
  47. #endif
  48. #include <algorithm>
  49. #include <cassert>
  50. #include <cctype>
  51. #include <cerrno>
  52. #include <cstdio>
  53. #include <cstdlib>
  54. #include <cstring>
  55. #include <ctime>
  56. #include <iostream>
  57. #include <sstream>
  58. #include <utility>
  59. #include <vector>
  60. #include <fcntl.h>
  61. #include "cmsys/Directory.hxx"
  62. #include "cmsys/Encoding.hxx"
  63. #include "cmsys/FStream.hxx"
  64. #include "cmsys/RegularExpression.hxx"
  65. #include "cmsys/System.h"
  66. #include "cmsys/Terminal.h"
  67. #if defined(_WIN32)
  68. # include <windows.h>
  69. // include wincrypt.h after windows.h
  70. # include <wincrypt.h>
  71. #else
  72. # include <unistd.h>
  73. # include <sys/time.h>
  74. #endif
  75. #if defined(_WIN32) && \
  76. (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__MINGW32__))
  77. # include <io.h>
  78. #endif
  79. #if defined(__APPLE__)
  80. # include <mach-o/dyld.h>
  81. #endif
  82. #ifdef __QNX__
  83. # include <malloc.h> /* for malloc/free on QNX */
  84. #endif
  85. namespace {
  86. cmSystemTools::InterruptCallback s_InterruptCallback;
  87. cmSystemTools::MessageCallback s_MessageCallback;
  88. cmSystemTools::OutputCallback s_StderrCallback;
  89. cmSystemTools::OutputCallback s_StdoutCallback;
  90. } // namespace
  91. #if !defined(HAVE_ENVIRON_NOT_REQUIRE_PROTOTYPE)
  92. // For GetEnvironmentVariables
  93. # if defined(_WIN32)
  94. extern __declspec(dllimport) char** environ;
  95. # else
  96. extern char** environ;
  97. # endif
  98. #endif
  99. #if !defined(CMAKE_BOOTSTRAP)
  100. static std::string cm_archive_entry_pathname(struct archive_entry* entry)
  101. {
  102. # if cmsys_STL_HAS_WSTRING
  103. return cmsys::Encoding::ToNarrow(archive_entry_pathname_w(entry));
  104. # else
  105. return archive_entry_pathname(entry);
  106. # endif
  107. }
  108. static int cm_archive_read_open_file(struct archive* a, const char* file,
  109. int block_size)
  110. {
  111. # if cmsys_STL_HAS_WSTRING
  112. std::wstring wfile = cmsys::Encoding::ToWide(file);
  113. return archive_read_open_filename_w(a, wfile.c_str(), block_size);
  114. # else
  115. return archive_read_open_filename(a, file, block_size);
  116. # endif
  117. }
  118. #endif
  119. #ifdef _WIN32
  120. #elif defined(__APPLE__)
  121. # include <crt_externs.h>
  122. # define environ (*_NSGetEnviron())
  123. #endif
  124. bool cmSystemTools::s_RunCommandHideConsole = false;
  125. bool cmSystemTools::s_DisableRunCommandOutput = false;
  126. bool cmSystemTools::s_ErrorOccured = false;
  127. bool cmSystemTools::s_FatalErrorOccured = false;
  128. bool cmSystemTools::s_ForceUnixPaths = false;
  129. // replace replace with with as many times as it shows up in source.
  130. // write the result into source.
  131. #if defined(_WIN32) && !defined(__CYGWIN__)
  132. void cmSystemTools::ExpandRegistryValues(std::string& source, KeyWOW64 view)
  133. {
  134. // Regular expression to match anything inside [...] that begins in HKEY.
  135. // Note that there is a special rule for regular expressions to match a
  136. // close square-bracket inside a list delimited by square brackets.
  137. // The "[^]]" part of this expression will match any character except
  138. // a close square-bracket. The ']' character must be the first in the
  139. // list of characters inside the [^...] block of the expression.
  140. cmsys::RegularExpression regEntry("\\[(HKEY[^]]*)\\]");
  141. // check for black line or comment
  142. while (regEntry.find(source)) {
  143. // the arguments are the second match
  144. std::string key = regEntry.match(1);
  145. std::string val;
  146. if (ReadRegistryValue(key.c_str(), val, view)) {
  147. std::string reg = cmStrCat('[', key, ']');
  148. cmSystemTools::ReplaceString(source, reg.c_str(), val.c_str());
  149. } else {
  150. std::string reg = cmStrCat('[', key, ']');
  151. cmSystemTools::ReplaceString(source, reg.c_str(), "/registry");
  152. }
  153. }
  154. }
  155. #else
  156. void cmSystemTools::ExpandRegistryValues(std::string& source,
  157. KeyWOW64 /*unused*/)
  158. {
  159. cmsys::RegularExpression regEntry("\\[(HKEY[^]]*)\\]");
  160. while (regEntry.find(source)) {
  161. // the arguments are the second match
  162. std::string key = regEntry.match(1);
  163. std::string reg = cmStrCat('[', key, ']');
  164. cmSystemTools::ReplaceString(source, reg.c_str(), "/registry");
  165. }
  166. }
  167. #endif
  168. std::string cmSystemTools::HelpFileName(cm::string_view str)
  169. {
  170. std::string name(str);
  171. cmSystemTools::ReplaceString(name, "<", "");
  172. cmSystemTools::ReplaceString(name, ">", "");
  173. return name;
  174. }
  175. void cmSystemTools::Error(const std::string& m)
  176. {
  177. std::string message = "CMake Error: " + m;
  178. cmSystemTools::s_ErrorOccured = true;
  179. cmSystemTools::Message(message, "Error");
  180. }
  181. void cmSystemTools::SetInterruptCallback(InterruptCallback f)
  182. {
  183. s_InterruptCallback = std::move(f);
  184. }
  185. bool cmSystemTools::GetInterruptFlag()
  186. {
  187. if (s_InterruptCallback) {
  188. return s_InterruptCallback();
  189. }
  190. return false;
  191. }
  192. void cmSystemTools::SetMessageCallback(MessageCallback f)
  193. {
  194. s_MessageCallback = std::move(f);
  195. }
  196. void cmSystemTools::SetStdoutCallback(OutputCallback f)
  197. {
  198. s_StdoutCallback = std::move(f);
  199. }
  200. void cmSystemTools::SetStderrCallback(OutputCallback f)
  201. {
  202. s_StderrCallback = std::move(f);
  203. }
  204. void cmSystemTools::Stderr(const std::string& s)
  205. {
  206. if (s_StderrCallback) {
  207. s_StderrCallback(s);
  208. } else {
  209. std::cerr << s << std::flush;
  210. }
  211. }
  212. void cmSystemTools::Stdout(const std::string& s)
  213. {
  214. if (s_StdoutCallback) {
  215. s_StdoutCallback(s);
  216. } else {
  217. std::cout << s << std::flush;
  218. }
  219. }
  220. void cmSystemTools::Message(const std::string& m, const char* title)
  221. {
  222. if (s_MessageCallback) {
  223. s_MessageCallback(m, title);
  224. } else {
  225. std::cerr << m << std::endl;
  226. }
  227. }
  228. void cmSystemTools::ReportLastSystemError(const char* msg)
  229. {
  230. std::string m =
  231. cmStrCat(msg, ": System Error: ", Superclass::GetLastSystemError());
  232. cmSystemTools::Error(m);
  233. }
  234. void cmSystemTools::ParseWindowsCommandLine(const char* command,
  235. std::vector<std::string>& args)
  236. {
  237. // See the MSDN document "Parsing C Command-Line Arguments" at
  238. // http://msdn2.microsoft.com/en-us/library/a1y7w461.aspx for rules
  239. // of parsing the windows command line.
  240. bool in_argument = false;
  241. bool in_quotes = false;
  242. int backslashes = 0;
  243. std::string arg;
  244. for (const char* c = command; *c; ++c) {
  245. if (*c == '\\') {
  246. ++backslashes;
  247. in_argument = true;
  248. } else if (*c == '"') {
  249. int backslash_pairs = backslashes >> 1;
  250. int backslash_escaped = backslashes & 1;
  251. arg.append(backslash_pairs, '\\');
  252. backslashes = 0;
  253. if (backslash_escaped) {
  254. /* An odd number of backslashes precede this quote.
  255. It is escaped. */
  256. arg.append(1, '"');
  257. } else {
  258. /* An even number of backslashes precede this quote.
  259. It is not escaped. */
  260. in_quotes = !in_quotes;
  261. }
  262. in_argument = true;
  263. } else {
  264. arg.append(backslashes, '\\');
  265. backslashes = 0;
  266. if (cmIsSpace(*c)) {
  267. if (in_quotes) {
  268. arg.append(1, *c);
  269. } else if (in_argument) {
  270. args.push_back(arg);
  271. arg.clear();
  272. in_argument = false;
  273. }
  274. } else {
  275. in_argument = true;
  276. arg.append(1, *c);
  277. }
  278. }
  279. }
  280. arg.append(backslashes, '\\');
  281. if (in_argument) {
  282. args.push_back(arg);
  283. }
  284. }
  285. class cmSystemToolsArgV
  286. {
  287. char** ArgV;
  288. public:
  289. cmSystemToolsArgV(char** argv)
  290. : ArgV(argv)
  291. {
  292. }
  293. ~cmSystemToolsArgV()
  294. {
  295. for (char** arg = this->ArgV; arg && *arg; ++arg) {
  296. free(*arg);
  297. }
  298. free(this->ArgV);
  299. }
  300. cmSystemToolsArgV(const cmSystemToolsArgV&) = delete;
  301. cmSystemToolsArgV& operator=(const cmSystemToolsArgV&) = delete;
  302. void Store(std::vector<std::string>& args) const
  303. {
  304. for (char** arg = this->ArgV; arg && *arg; ++arg) {
  305. args.emplace_back(*arg);
  306. }
  307. }
  308. };
  309. void cmSystemTools::ParseUnixCommandLine(const char* command,
  310. std::vector<std::string>& args)
  311. {
  312. // Invoke the underlying parser.
  313. cmSystemToolsArgV argv(cmsysSystem_Parse_CommandForUnix(command, 0));
  314. argv.Store(args);
  315. }
  316. std::vector<std::string> cmSystemTools::HandleResponseFile(
  317. std::vector<std::string>::const_iterator argBeg,
  318. std::vector<std::string>::const_iterator argEnd)
  319. {
  320. std::vector<std::string> arg_full;
  321. for (std::string const& arg : cmMakeRange(argBeg, argEnd)) {
  322. if (cmHasLiteralPrefix(arg, "@")) {
  323. cmsys::ifstream responseFile(arg.substr(1).c_str(), std::ios::in);
  324. if (!responseFile) {
  325. std::string error = cmStrCat("failed to open for reading (",
  326. cmSystemTools::GetLastSystemError(),
  327. "):\n ", cm::string_view(arg).substr(1));
  328. cmSystemTools::Error(error);
  329. } else {
  330. std::string line;
  331. cmSystemTools::GetLineFromStream(responseFile, line);
  332. std::vector<std::string> args2;
  333. #ifdef _WIN32
  334. cmSystemTools::ParseWindowsCommandLine(line.c_str(), args2);
  335. #else
  336. cmSystemTools::ParseUnixCommandLine(line.c_str(), args2);
  337. #endif
  338. cm::append(arg_full, args2);
  339. }
  340. } else {
  341. arg_full.push_back(arg);
  342. }
  343. }
  344. return arg_full;
  345. }
  346. std::vector<std::string> cmSystemTools::ParseArguments(const std::string& cmd)
  347. {
  348. std::vector<std::string> args;
  349. std::string arg;
  350. bool win_path = false;
  351. const char* command = cmd.c_str();
  352. if (command[0] && command[1] &&
  353. ((command[0] != '/' && command[1] == ':' && command[2] == '\\') ||
  354. (command[0] == '\"' && command[1] != '/' && command[2] == ':' &&
  355. command[3] == '\\') ||
  356. (command[0] == '\'' && command[1] != '/' && command[2] == ':' &&
  357. command[3] == '\\') ||
  358. (command[0] == '\\' && command[1] == '\\'))) {
  359. win_path = true;
  360. }
  361. // Split the command into an argv array.
  362. for (const char* c = command; *c;) {
  363. // Skip over whitespace.
  364. while (*c == ' ' || *c == '\t') {
  365. ++c;
  366. }
  367. arg.clear();
  368. if (*c == '"') {
  369. // Parse a quoted argument.
  370. ++c;
  371. while (*c && *c != '"') {
  372. arg.append(1, *c);
  373. ++c;
  374. }
  375. if (*c) {
  376. ++c;
  377. }
  378. args.push_back(arg);
  379. } else if (*c == '\'') {
  380. // Parse a quoted argument.
  381. ++c;
  382. while (*c && *c != '\'') {
  383. arg.append(1, *c);
  384. ++c;
  385. }
  386. if (*c) {
  387. ++c;
  388. }
  389. args.push_back(arg);
  390. } else if (*c) {
  391. // Parse an unquoted argument.
  392. while (*c && *c != ' ' && *c != '\t') {
  393. if (*c == '\\' && !win_path) {
  394. ++c;
  395. if (*c) {
  396. arg.append(1, *c);
  397. ++c;
  398. }
  399. } else {
  400. arg.append(1, *c);
  401. ++c;
  402. }
  403. }
  404. args.push_back(arg);
  405. }
  406. }
  407. return args;
  408. }
  409. bool cmSystemTools::SplitProgramFromArgs(std::string const& command,
  410. std::string& program,
  411. std::string& args)
  412. {
  413. const char* c = command.c_str();
  414. // Skip leading whitespace.
  415. while (isspace(static_cast<unsigned char>(*c))) {
  416. ++c;
  417. }
  418. // Parse one command-line element up to an unquoted space.
  419. bool in_escape = false;
  420. bool in_double = false;
  421. bool in_single = false;
  422. for (; *c; ++c) {
  423. if (in_single) {
  424. if (*c == '\'') {
  425. in_single = false;
  426. } else {
  427. program += *c;
  428. }
  429. } else if (in_escape) {
  430. in_escape = false;
  431. program += *c;
  432. } else if (*c == '\\') {
  433. in_escape = true;
  434. } else if (in_double) {
  435. if (*c == '"') {
  436. in_double = false;
  437. } else {
  438. program += *c;
  439. }
  440. } else if (*c == '"') {
  441. in_double = true;
  442. } else if (*c == '\'') {
  443. in_single = true;
  444. } else if (isspace(static_cast<unsigned char>(*c))) {
  445. break;
  446. } else {
  447. program += *c;
  448. }
  449. }
  450. // The remainder of the command line holds unparsed arguments.
  451. args = c;
  452. return !in_single && !in_escape && !in_double;
  453. }
  454. size_t cmSystemTools::CalculateCommandLineLengthLimit()
  455. {
  456. size_t sz =
  457. #ifdef _WIN32
  458. // There's a maximum of 65536 bytes and thus 32768 WCHARs on Windows
  459. // However, cmd.exe itself can only handle 8191 WCHARs and Ninja for
  460. // example uses it to spawn processes.
  461. size_t(8191);
  462. #elif defined(__linux)
  463. // MAX_ARG_STRLEN is the maximum length of a string permissible for
  464. // the execve() syscall on Linux. It's defined as (PAGE_SIZE * 32)
  465. // in Linux's binfmts.h
  466. static_cast<size_t>(sysconf(_SC_PAGESIZE) * 32);
  467. #else
  468. size_t(0);
  469. #endif
  470. #if defined(_SC_ARG_MAX)
  471. // ARG_MAX is the maximum size of the command and environment
  472. // that can be passed to the exec functions on UNIX.
  473. // The value in limits.h does not need to be present and may
  474. // depend upon runtime memory constraints, hence sysconf()
  475. // should be used to query it.
  476. long szArgMax = sysconf(_SC_ARG_MAX);
  477. // A return value of -1 signifies an undetermined limit, but
  478. // it does not imply an infinite limit, and thus is ignored.
  479. if (szArgMax != -1) {
  480. // We estimate the size of the environment block to be 1000.
  481. // This isn't accurate at all, but leaves some headroom.
  482. szArgMax = szArgMax < 1000 ? 0 : szArgMax - 1000;
  483. # if defined(_WIN32) || defined(__linux)
  484. sz = std::min(sz, static_cast<size_t>(szArgMax));
  485. # else
  486. sz = static_cast<size_t>(szArgMax);
  487. # endif
  488. }
  489. #endif
  490. return sz;
  491. }
  492. bool cmSystemTools::RunSingleCommand(std::vector<std::string> const& command,
  493. std::string* captureStdOut,
  494. std::string* captureStdErr, int* retVal,
  495. const char* dir, OutputOption outputflag,
  496. cmDuration timeout, Encoding encoding)
  497. {
  498. std::vector<const char*> argv;
  499. argv.reserve(command.size() + 1);
  500. for (std::string const& cmd : command) {
  501. argv.push_back(cmd.c_str());
  502. }
  503. argv.push_back(nullptr);
  504. cmsysProcess* cp = cmsysProcess_New();
  505. cmsysProcess_SetCommand(cp, argv.data());
  506. cmsysProcess_SetWorkingDirectory(cp, dir);
  507. if (cmSystemTools::GetRunCommandHideConsole()) {
  508. cmsysProcess_SetOption(cp, cmsysProcess_Option_HideWindow, 1);
  509. }
  510. if (outputflag == OUTPUT_PASSTHROUGH) {
  511. cmsysProcess_SetPipeShared(cp, cmsysProcess_Pipe_STDOUT, 1);
  512. cmsysProcess_SetPipeShared(cp, cmsysProcess_Pipe_STDERR, 1);
  513. captureStdOut = nullptr;
  514. captureStdErr = nullptr;
  515. } else if (outputflag == OUTPUT_MERGE ||
  516. (captureStdErr && captureStdErr == captureStdOut)) {
  517. cmsysProcess_SetOption(cp, cmsysProcess_Option_MergeOutput, 1);
  518. captureStdErr = nullptr;
  519. }
  520. assert(!captureStdErr || captureStdErr != captureStdOut);
  521. cmsysProcess_SetTimeout(cp, timeout.count());
  522. cmsysProcess_Execute(cp);
  523. std::vector<char> tempStdOut;
  524. std::vector<char> tempStdErr;
  525. char* data;
  526. int length;
  527. int pipe;
  528. cmProcessOutput processOutput(encoding);
  529. std::string strdata;
  530. if (outputflag != OUTPUT_PASSTHROUGH &&
  531. (captureStdOut || captureStdErr || outputflag != OUTPUT_NONE)) {
  532. while ((pipe = cmsysProcess_WaitForData(cp, &data, &length, nullptr)) >
  533. 0) {
  534. // Translate NULL characters in the output into valid text.
  535. for (int i = 0; i < length; ++i) {
  536. if (data[i] == '\0') {
  537. data[i] = ' ';
  538. }
  539. }
  540. if (pipe == cmsysProcess_Pipe_STDOUT) {
  541. if (outputflag != OUTPUT_NONE) {
  542. processOutput.DecodeText(data, length, strdata, 1);
  543. cmSystemTools::Stdout(strdata);
  544. }
  545. if (captureStdOut) {
  546. cm::append(tempStdOut, data, data + length);
  547. }
  548. } else if (pipe == cmsysProcess_Pipe_STDERR) {
  549. if (outputflag != OUTPUT_NONE) {
  550. processOutput.DecodeText(data, length, strdata, 2);
  551. cmSystemTools::Stderr(strdata);
  552. }
  553. if (captureStdErr) {
  554. cm::append(tempStdErr, data, data + length);
  555. }
  556. }
  557. }
  558. if (outputflag != OUTPUT_NONE) {
  559. processOutput.DecodeText(std::string(), strdata, 1);
  560. if (!strdata.empty()) {
  561. cmSystemTools::Stdout(strdata);
  562. }
  563. processOutput.DecodeText(std::string(), strdata, 2);
  564. if (!strdata.empty()) {
  565. cmSystemTools::Stderr(strdata);
  566. }
  567. }
  568. }
  569. cmsysProcess_WaitForExit(cp, nullptr);
  570. if (captureStdOut) {
  571. captureStdOut->assign(tempStdOut.begin(), tempStdOut.end());
  572. processOutput.DecodeText(*captureStdOut, *captureStdOut);
  573. }
  574. if (captureStdErr) {
  575. captureStdErr->assign(tempStdErr.begin(), tempStdErr.end());
  576. processOutput.DecodeText(*captureStdErr, *captureStdErr);
  577. }
  578. bool result = true;
  579. if (cmsysProcess_GetState(cp) == cmsysProcess_State_Exited) {
  580. if (retVal) {
  581. *retVal = cmsysProcess_GetExitValue(cp);
  582. } else {
  583. if (cmsysProcess_GetExitValue(cp) != 0) {
  584. result = false;
  585. }
  586. }
  587. } else if (cmsysProcess_GetState(cp) == cmsysProcess_State_Exception) {
  588. const char* exception_str = cmsysProcess_GetExceptionString(cp);
  589. if (outputflag != OUTPUT_NONE) {
  590. std::cerr << exception_str << std::endl;
  591. }
  592. if (captureStdErr) {
  593. captureStdErr->append(exception_str, strlen(exception_str));
  594. } else if (captureStdOut) {
  595. captureStdOut->append(exception_str, strlen(exception_str));
  596. }
  597. result = false;
  598. } else if (cmsysProcess_GetState(cp) == cmsysProcess_State_Error) {
  599. const char* error_str = cmsysProcess_GetErrorString(cp);
  600. if (outputflag != OUTPUT_NONE) {
  601. std::cerr << error_str << std::endl;
  602. }
  603. if (captureStdErr) {
  604. captureStdErr->append(error_str, strlen(error_str));
  605. } else if (captureStdOut) {
  606. captureStdOut->append(error_str, strlen(error_str));
  607. }
  608. result = false;
  609. } else if (cmsysProcess_GetState(cp) == cmsysProcess_State_Expired) {
  610. const char* error_str = "Process terminated due to timeout\n";
  611. if (outputflag != OUTPUT_NONE) {
  612. std::cerr << error_str << std::endl;
  613. }
  614. if (captureStdErr) {
  615. captureStdErr->append(error_str, strlen(error_str));
  616. }
  617. result = false;
  618. }
  619. cmsysProcess_Delete(cp);
  620. return result;
  621. }
  622. bool cmSystemTools::RunSingleCommand(const std::string& command,
  623. std::string* captureStdOut,
  624. std::string* captureStdErr, int* retVal,
  625. const char* dir, OutputOption outputflag,
  626. cmDuration timeout)
  627. {
  628. if (s_DisableRunCommandOutput) {
  629. outputflag = OUTPUT_NONE;
  630. }
  631. std::vector<std::string> args = cmSystemTools::ParseArguments(command);
  632. if (args.empty()) {
  633. return false;
  634. }
  635. return cmSystemTools::RunSingleCommand(args, captureStdOut, captureStdErr,
  636. retVal, dir, outputflag, timeout);
  637. }
  638. std::string cmSystemTools::PrintSingleCommand(
  639. std::vector<std::string> const& command)
  640. {
  641. if (command.empty()) {
  642. return std::string();
  643. }
  644. return cmWrap('"', command, '"', " ");
  645. }
  646. bool cmSystemTools::DoesFileExistWithExtensions(
  647. const std::string& name, const std::vector<std::string>& headerExts)
  648. {
  649. std::string hname;
  650. for (std::string const& headerExt : headerExts) {
  651. hname = cmStrCat(name, '.', headerExt);
  652. if (cmSystemTools::FileExists(hname)) {
  653. return true;
  654. }
  655. }
  656. return false;
  657. }
  658. std::string cmSystemTools::FileExistsInParentDirectories(
  659. const std::string& fname, const std::string& directory,
  660. const std::string& toplevel)
  661. {
  662. std::string file = fname;
  663. cmSystemTools::ConvertToUnixSlashes(file);
  664. std::string dir = directory;
  665. cmSystemTools::ConvertToUnixSlashes(dir);
  666. std::string prevDir;
  667. while (dir != prevDir) {
  668. std::string path = cmStrCat(dir, "/", file);
  669. if (cmSystemTools::FileExists(path)) {
  670. return path;
  671. }
  672. if (dir.size() < toplevel.size()) {
  673. break;
  674. }
  675. prevDir = dir;
  676. dir = cmSystemTools::GetParentDirectory(dir);
  677. }
  678. return "";
  679. }
  680. #ifdef _WIN32
  681. namespace {
  682. /* Helper class to save and restore the specified file (or directory)
  683. attribute bits. Instantiate this class as an automatic variable on the
  684. stack. Its constructor saves a copy of the file attributes, and then its
  685. destructor restores the original attribute settings. */
  686. class SaveRestoreFileAttributes
  687. {
  688. public:
  689. SaveRestoreFileAttributes(std::wstring const& path,
  690. uint32_t file_attrs_to_set);
  691. ~SaveRestoreFileAttributes();
  692. SaveRestoreFileAttributes(SaveRestoreFileAttributes const&) = delete;
  693. SaveRestoreFileAttributes& operator=(SaveRestoreFileAttributes const&) =
  694. delete;
  695. void SetPath(std::wstring const& path) { path_ = path; }
  696. private:
  697. std::wstring path_;
  698. uint32_t original_attr_bits_;
  699. };
  700. SaveRestoreFileAttributes::SaveRestoreFileAttributes(
  701. std::wstring const& path, uint32_t file_attrs_to_set)
  702. : path_(path)
  703. , original_attr_bits_(0)
  704. {
  705. // Set the specified attributes for the source file/directory.
  706. original_attr_bits_ = GetFileAttributesW(path_.c_str());
  707. if ((INVALID_FILE_ATTRIBUTES != original_attr_bits_) &&
  708. ((file_attrs_to_set & original_attr_bits_) != file_attrs_to_set)) {
  709. SetFileAttributesW(path_.c_str(), original_attr_bits_ | file_attrs_to_set);
  710. }
  711. }
  712. // We set attribute bits. Now we need to restore their original state.
  713. SaveRestoreFileAttributes::~SaveRestoreFileAttributes()
  714. {
  715. DWORD last_error = GetLastError();
  716. // Verify or restore the original attributes.
  717. const DWORD source_attr_bits = GetFileAttributesW(path_.c_str());
  718. if (INVALID_FILE_ATTRIBUTES != source_attr_bits) {
  719. if (original_attr_bits_ != source_attr_bits) {
  720. // The file still exists, and its attributes aren't our saved values.
  721. // Time to restore them.
  722. SetFileAttributesW(path_.c_str(), original_attr_bits_);
  723. }
  724. }
  725. SetLastError(last_error);
  726. }
  727. struct WindowsFileRetryInit
  728. {
  729. cmSystemTools::WindowsFileRetry Retry;
  730. bool Explicit;
  731. };
  732. WindowsFileRetryInit InitWindowsFileRetry(wchar_t const* const values[2],
  733. unsigned int const defaults[2])
  734. {
  735. unsigned int data[2] = { 0, 0 };
  736. HKEY const keys[2] = { HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE };
  737. for (int k = 0; k < 2; ++k) {
  738. HKEY hKey;
  739. if (RegOpenKeyExW(keys[k], L"Software\\Kitware\\CMake\\Config", 0,
  740. KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS) {
  741. for (int v = 0; v < 2; ++v) {
  742. DWORD dwData, dwType, dwSize = 4;
  743. if (!data[v] &&
  744. RegQueryValueExW(hKey, values[v], 0, &dwType, (BYTE*)&dwData,
  745. &dwSize) == ERROR_SUCCESS &&
  746. dwType == REG_DWORD && dwSize == 4) {
  747. data[v] = static_cast<unsigned int>(dwData);
  748. }
  749. }
  750. RegCloseKey(hKey);
  751. }
  752. }
  753. WindowsFileRetryInit init;
  754. init.Explicit = data[0] || data[1];
  755. init.Retry.Count = data[0] ? data[0] : defaults[0];
  756. init.Retry.Delay = data[1] ? data[1] : defaults[1];
  757. return init;
  758. }
  759. WindowsFileRetryInit InitWindowsFileRetry()
  760. {
  761. static wchar_t const* const values[2] = { L"FilesystemRetryCount",
  762. L"FilesystemRetryDelay" };
  763. static unsigned int const defaults[2] = { 5, 500 };
  764. return InitWindowsFileRetry(values, defaults);
  765. }
  766. WindowsFileRetryInit InitWindowsDirectoryRetry()
  767. {
  768. static wchar_t const* const values[2] = { L"FilesystemDirectoryRetryCount",
  769. L"FilesystemDirectoryRetryDelay" };
  770. static unsigned int const defaults[2] = { 120, 500 };
  771. WindowsFileRetryInit dirInit = InitWindowsFileRetry(values, defaults);
  772. if (dirInit.Explicit) {
  773. return dirInit;
  774. }
  775. WindowsFileRetryInit fileInit = InitWindowsFileRetry();
  776. if (fileInit.Explicit) {
  777. return fileInit;
  778. }
  779. return dirInit;
  780. }
  781. cmSystemTools::WindowsFileRetry GetWindowsRetry(std::wstring const& path)
  782. {
  783. // If we are performing a directory operation, then try and get the
  784. // appropriate timing info.
  785. DWORD const attrs = GetFileAttributesW(path.c_str());
  786. if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY)) {
  787. return cmSystemTools::GetWindowsDirectoryRetry();
  788. }
  789. return cmSystemTools::GetWindowsFileRetry();
  790. }
  791. } // end of anonymous namespace
  792. cmSystemTools::WindowsFileRetry cmSystemTools::GetWindowsFileRetry()
  793. {
  794. static WindowsFileRetry retry = InitWindowsFileRetry().Retry;
  795. return retry;
  796. }
  797. cmSystemTools::WindowsFileRetry cmSystemTools::GetWindowsDirectoryRetry()
  798. {
  799. static cmSystemTools::WindowsFileRetry retry =
  800. InitWindowsDirectoryRetry().Retry;
  801. return retry;
  802. }
  803. #endif
  804. std::string cmSystemTools::GetRealPathResolvingWindowsSubst(
  805. const std::string& path, std::string* errorMessage)
  806. {
  807. #ifdef _WIN32
  808. // uv_fs_realpath uses Windows Vista API so fallback to kwsys if not found
  809. std::string resolved_path;
  810. uv_fs_t req;
  811. int err = uv_fs_realpath(NULL, &req, path.c_str(), NULL);
  812. if (!err) {
  813. resolved_path = std::string((char*)req.ptr);
  814. cmSystemTools::ConvertToUnixSlashes(resolved_path);
  815. // Normalize to upper-case drive letter as GetActualCaseForPath does.
  816. if (resolved_path.size() > 1 && resolved_path[1] == ':') {
  817. resolved_path[0] = toupper(resolved_path[0]);
  818. }
  819. } else if (err == UV_ENOSYS) {
  820. resolved_path = cmsys::SystemTools::GetRealPath(path, errorMessage);
  821. } else if (errorMessage) {
  822. LPSTR message = NULL;
  823. DWORD size = FormatMessageA(
  824. FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
  825. FORMAT_MESSAGE_IGNORE_INSERTS,
  826. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&message, 0,
  827. NULL);
  828. *errorMessage = std::string(message, size);
  829. LocalFree(message);
  830. resolved_path = "";
  831. } else {
  832. resolved_path = path;
  833. }
  834. return resolved_path;
  835. #else
  836. return cmsys::SystemTools::GetRealPath(path, errorMessage);
  837. #endif
  838. }
  839. void cmSystemTools::InitializeLibUV()
  840. {
  841. #if defined(_WIN32)
  842. // Perform libuv one-time initialization now, and then un-do its
  843. // global _fmode setting so that using libuv does not change the
  844. // default file text/binary mode. See libuv issue 840.
  845. if (uv_loop_t* loop = uv_default_loop()) {
  846. uv_loop_close(loop);
  847. }
  848. # ifdef _MSC_VER
  849. _set_fmode(_O_TEXT);
  850. # else
  851. _fmode = _O_TEXT;
  852. # endif
  853. // Replace libuv's report handler with our own to suppress popups.
  854. cmSystemTools::EnableMSVCDebugHook();
  855. #endif
  856. }
  857. #ifdef _WIN32
  858. namespace {
  859. bool cmMoveFile(std::wstring const& oldname, std::wstring const& newname)
  860. {
  861. // Not only ignore any previous error, but clear any memory of it.
  862. SetLastError(0);
  863. // Use MOVEFILE_REPLACE_EXISTING to replace an existing destination file.
  864. return MoveFileExW(oldname.c_str(), newname.c_str(),
  865. MOVEFILE_REPLACE_EXISTING);
  866. }
  867. }
  868. #endif
  869. bool cmSystemTools::RenameFile(const std::string& oldname,
  870. const std::string& newname)
  871. {
  872. #ifdef _WIN32
  873. # ifndef INVALID_FILE_ATTRIBUTES
  874. # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
  875. # endif
  876. std::wstring const oldname_wstr =
  877. SystemTools::ConvertToWindowsExtendedPath(oldname);
  878. std::wstring const newname_wstr =
  879. SystemTools::ConvertToWindowsExtendedPath(newname);
  880. /* Windows MoveFileEx may not replace read-only or in-use files. If it
  881. fails then remove the read-only attribute from any existing destination.
  882. Try multiple times since we may be racing against another process
  883. creating/opening the destination file just before our MoveFileEx. */
  884. WindowsFileRetry retry = GetWindowsRetry(oldname_wstr);
  885. // Use RAII to set the attribute bit blocking Microsoft Search Indexing,
  886. // and restore the previous value upon return.
  887. SaveRestoreFileAttributes save_restore_file_attributes(
  888. oldname_wstr, FILE_ATTRIBUTE_NOT_CONTENT_INDEXED);
  889. DWORD move_last_error = 0;
  890. while (!cmMoveFile(oldname_wstr, newname_wstr) && --retry.Count) {
  891. move_last_error = GetLastError();
  892. // There was no error ==> the operation is not yet complete.
  893. if (move_last_error == NO_ERROR) {
  894. break;
  895. }
  896. // Try again only if failure was due to access/sharing permissions.
  897. // Most often ERROR_ACCESS_DENIED (a.k.a. I/O error) for a directory, and
  898. // ERROR_SHARING_VIOLATION for a file, are caused by one of the following:
  899. // 1) Anti-Virus Software
  900. // 2) Windows Search Indexer
  901. // 3) Windows Explorer has an associated directory already opened.
  902. if (move_last_error != ERROR_ACCESS_DENIED &&
  903. move_last_error != ERROR_SHARING_VIOLATION) {
  904. return false;
  905. }
  906. DWORD const attrs = GetFileAttributesW(newname_wstr.c_str());
  907. if ((attrs != INVALID_FILE_ATTRIBUTES) &&
  908. (attrs & FILE_ATTRIBUTE_READONLY) &&
  909. // FILE_ATTRIBUTE_READONLY is not honored on directories.
  910. !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {
  911. // Remove the read-only attribute from the destination file.
  912. SetFileAttributesW(newname_wstr.c_str(),
  913. attrs & ~FILE_ATTRIBUTE_READONLY);
  914. } else {
  915. // The file may be temporarily in use so wait a bit.
  916. cmSystemTools::Delay(retry.Delay);
  917. }
  918. }
  919. // If we were successful, then there was no error.
  920. if (retry.Count > 0) {
  921. move_last_error = 0;
  922. // Restore the attributes on the new name.
  923. save_restore_file_attributes.SetPath(newname_wstr);
  924. }
  925. SetLastError(move_last_error);
  926. return retry.Count > 0;
  927. #else
  928. /* On UNIX we have an OS-provided call to do this atomically. */
  929. return rename(oldname.c_str(), newname.c_str()) == 0;
  930. #endif
  931. }
  932. void cmSystemTools::MoveFileIfDifferent(const std::string& source,
  933. const std::string& destination)
  934. {
  935. if (FilesDiffer(source, destination)) {
  936. if (RenameFile(source, destination)) {
  937. return;
  938. }
  939. CopyFileAlways(source, destination);
  940. }
  941. RemoveFile(source);
  942. }
  943. std::string cmSystemTools::ComputeFileHash(const std::string& source,
  944. cmCryptoHash::Algo algo)
  945. {
  946. #if !defined(CMAKE_BOOTSTRAP)
  947. cmCryptoHash hash(algo);
  948. return hash.HashFile(source);
  949. #else
  950. (void)source;
  951. cmSystemTools::Message("hashsum not supported in bootstrapping mode",
  952. "Error");
  953. return std::string();
  954. #endif
  955. }
  956. std::string cmSystemTools::ComputeStringMD5(const std::string& input)
  957. {
  958. #if !defined(CMAKE_BOOTSTRAP)
  959. cmCryptoHash md5(cmCryptoHash::AlgoMD5);
  960. return md5.HashString(input);
  961. #else
  962. (void)input;
  963. cmSystemTools::Message("md5sum not supported in bootstrapping mode",
  964. "Error");
  965. return "";
  966. #endif
  967. }
  968. std::string cmSystemTools::ComputeCertificateThumbprint(
  969. const std::string& source)
  970. {
  971. std::string thumbprint;
  972. #if !defined(CMAKE_BOOTSTRAP) && defined(_WIN32)
  973. CRYPT_INTEGER_BLOB cryptBlob;
  974. HCERTSTORE certStore = NULL;
  975. PCCERT_CONTEXT certContext = NULL;
  976. HANDLE certFile = CreateFileW(
  977. cmsys::Encoding::ToWide(source.c_str()).c_str(), GENERIC_READ,
  978. FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  979. if (certFile != INVALID_HANDLE_VALUE && certFile != NULL) {
  980. DWORD fileSize = GetFileSize(certFile, NULL);
  981. if (fileSize != INVALID_FILE_SIZE) {
  982. auto certData = cm::make_unique<BYTE[]>(fileSize);
  983. if (certData != NULL) {
  984. DWORD dwRead = 0;
  985. if (ReadFile(certFile, certData.get(), fileSize, &dwRead, NULL)) {
  986. cryptBlob.cbData = fileSize;
  987. cryptBlob.pbData = certData.get();
  988. // Verify that this is a valid cert
  989. if (PFXIsPFXBlob(&cryptBlob)) {
  990. // Open the certificate as a store
  991. certStore = PFXImportCertStore(&cryptBlob, NULL, CRYPT_EXPORTABLE);
  992. if (certStore != NULL) {
  993. // There should only be 1 cert.
  994. certContext =
  995. CertEnumCertificatesInStore(certStore, certContext);
  996. if (certContext != NULL) {
  997. // The hash is 20 bytes
  998. BYTE hashData[20];
  999. DWORD hashLength = 20;
  1000. // Buffer to print the hash. Each byte takes 2 chars +
  1001. // terminating character
  1002. char hashPrint[41];
  1003. char* pHashPrint = hashPrint;
  1004. // Get the hash property from the certificate
  1005. if (CertGetCertificateContextProperty(
  1006. certContext, CERT_HASH_PROP_ID, hashData, &hashLength)) {
  1007. for (DWORD i = 0; i < hashLength; i++) {
  1008. // Convert each byte to hexadecimal
  1009. sprintf(pHashPrint, "%02X", hashData[i]);
  1010. pHashPrint += 2;
  1011. }
  1012. *pHashPrint = '\0';
  1013. thumbprint = hashPrint;
  1014. }
  1015. CertFreeCertificateContext(certContext);
  1016. }
  1017. CertCloseStore(certStore, 0);
  1018. }
  1019. }
  1020. }
  1021. }
  1022. }
  1023. CloseHandle(certFile);
  1024. }
  1025. #else
  1026. (void)source;
  1027. cmSystemTools::Message("ComputeCertificateThumbprint is not implemented",
  1028. "Error");
  1029. #endif
  1030. return thumbprint;
  1031. }
  1032. void cmSystemTools::Glob(const std::string& directory,
  1033. const std::string& regexp,
  1034. std::vector<std::string>& files)
  1035. {
  1036. cmsys::Directory d;
  1037. cmsys::RegularExpression reg(regexp.c_str());
  1038. if (d.Load(directory)) {
  1039. size_t numf;
  1040. unsigned int i;
  1041. numf = d.GetNumberOfFiles();
  1042. for (i = 0; i < numf; i++) {
  1043. std::string fname = d.GetFile(i);
  1044. if (reg.find(fname)) {
  1045. files.push_back(std::move(fname));
  1046. }
  1047. }
  1048. }
  1049. }
  1050. void cmSystemTools::GlobDirs(const std::string& path,
  1051. std::vector<std::string>& files)
  1052. {
  1053. std::string::size_type pos = path.find("/*");
  1054. if (pos == std::string::npos) {
  1055. files.push_back(path);
  1056. return;
  1057. }
  1058. std::string startPath = path.substr(0, pos);
  1059. std::string finishPath = path.substr(pos + 2);
  1060. cmsys::Directory d;
  1061. if (d.Load(startPath)) {
  1062. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i) {
  1063. if ((std::string(d.GetFile(i)) != ".") &&
  1064. (std::string(d.GetFile(i)) != "..")) {
  1065. std::string fname = cmStrCat(startPath, '/', d.GetFile(i));
  1066. if (cmSystemTools::FileIsDirectory(fname)) {
  1067. fname += finishPath;
  1068. cmSystemTools::GlobDirs(fname, files);
  1069. }
  1070. }
  1071. }
  1072. }
  1073. }
  1074. bool cmSystemTools::SimpleGlob(const std::string& glob,
  1075. std::vector<std::string>& files,
  1076. int type /* = 0 */)
  1077. {
  1078. files.clear();
  1079. if (glob.back() != '*') {
  1080. return false;
  1081. }
  1082. std::string path = cmSystemTools::GetFilenamePath(glob);
  1083. std::string ppath = cmSystemTools::GetFilenameName(glob);
  1084. ppath = ppath.substr(0, ppath.size() - 1);
  1085. if (path.empty()) {
  1086. path = "/";
  1087. }
  1088. bool res = false;
  1089. cmsys::Directory d;
  1090. if (d.Load(path)) {
  1091. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i) {
  1092. if ((std::string(d.GetFile(i)) != ".") &&
  1093. (std::string(d.GetFile(i)) != "..")) {
  1094. std::string fname = path;
  1095. if (path.back() != '/') {
  1096. fname += "/";
  1097. }
  1098. fname += d.GetFile(i);
  1099. std::string sfname = d.GetFile(i);
  1100. if (type > 0 && cmSystemTools::FileIsDirectory(fname)) {
  1101. continue;
  1102. }
  1103. if (type < 0 && !cmSystemTools::FileIsDirectory(fname)) {
  1104. continue;
  1105. }
  1106. if (cmHasPrefix(sfname, ppath)) {
  1107. files.push_back(fname);
  1108. res = true;
  1109. }
  1110. }
  1111. }
  1112. }
  1113. return res;
  1114. }
  1115. std::string cmSystemTools::ConvertToOutputPath(std::string const& path)
  1116. {
  1117. #if defined(_WIN32) && !defined(__CYGWIN__)
  1118. if (s_ForceUnixPaths) {
  1119. return cmSystemTools::ConvertToUnixOutputPath(path);
  1120. }
  1121. return cmSystemTools::ConvertToWindowsOutputPath(path);
  1122. #else
  1123. return cmSystemTools::ConvertToUnixOutputPath(path);
  1124. #endif
  1125. }
  1126. void cmSystemTools::ConvertToOutputSlashes(std::string& path)
  1127. {
  1128. #if defined(_WIN32) && !defined(__CYGWIN__)
  1129. if (!s_ForceUnixPaths) {
  1130. // Convert to windows slashes.
  1131. std::string::size_type pos = 0;
  1132. while ((pos = path.find('/', pos)) != std::string::npos) {
  1133. path[pos++] = '\\';
  1134. }
  1135. }
  1136. #else
  1137. static_cast<void>(path);
  1138. #endif
  1139. }
  1140. void cmSystemTools::ConvertToLongPath(std::string& path)
  1141. {
  1142. #if defined(_WIN32) && !defined(__CYGWIN__)
  1143. // Try to convert path to a long path only if the path contains character '~'
  1144. if (path.find('~') == std::string::npos) {
  1145. return;
  1146. }
  1147. std::wstring wPath = cmsys::Encoding::ToWide(path);
  1148. DWORD ret = GetLongPathNameW(wPath.c_str(), nullptr, 0);
  1149. std::vector<wchar_t> buffer(ret);
  1150. if (ret != 0) {
  1151. ret = GetLongPathNameW(wPath.c_str(), buffer.data(),
  1152. static_cast<DWORD>(buffer.size()));
  1153. }
  1154. if (ret != 0) {
  1155. path = cmsys::Encoding::ToNarrow(buffer.data());
  1156. }
  1157. #else
  1158. static_cast<void>(path);
  1159. #endif
  1160. }
  1161. std::string cmSystemTools::ConvertToRunCommandPath(const std::string& path)
  1162. {
  1163. #if defined(_WIN32) && !defined(__CYGWIN__)
  1164. return cmSystemTools::ConvertToWindowsOutputPath(path);
  1165. #else
  1166. return cmSystemTools::ConvertToUnixOutputPath(path);
  1167. #endif
  1168. }
  1169. // compute the relative path from here to there
  1170. std::string cmSystemTools::RelativePath(std::string const& local,
  1171. std::string const& remote)
  1172. {
  1173. if (!cmSystemTools::FileIsFullPath(local)) {
  1174. cmSystemTools::Error("RelativePath must be passed a full path to local: " +
  1175. local);
  1176. }
  1177. if (!cmSystemTools::FileIsFullPath(remote)) {
  1178. cmSystemTools::Error(
  1179. "RelativePath must be passed a full path to remote: " + remote);
  1180. }
  1181. return cmsys::SystemTools::RelativePath(local, remote);
  1182. }
  1183. std::string cmSystemTools::ForceToRelativePath(std::string const& local_path,
  1184. std::string const& remote_path)
  1185. {
  1186. // The paths should never be quoted.
  1187. assert(local_path.front() != '\"');
  1188. assert(remote_path.front() != '\"');
  1189. // The local path should never have a trailing slash except if it is just the
  1190. // bare root directory
  1191. assert(local_path.empty() || local_path.back() != '/' ||
  1192. local_path.size() == 1 ||
  1193. (local_path.size() == 3 && local_path[1] == ':' &&
  1194. ((local_path[0] >= 'A' && local_path[0] <= 'Z') ||
  1195. (local_path[0] >= 'a' && local_path[0] <= 'z'))));
  1196. // If the path is already relative then just return the path.
  1197. if (!cmSystemTools::FileIsFullPath(remote_path)) {
  1198. return remote_path;
  1199. }
  1200. // Identify the longest shared path component between the remote
  1201. // path and the local path.
  1202. std::vector<std::string> local;
  1203. cmSystemTools::SplitPath(local_path, local);
  1204. std::vector<std::string> remote;
  1205. cmSystemTools::SplitPath(remote_path, remote);
  1206. unsigned int common = 0;
  1207. while (common < remote.size() && common < local.size() &&
  1208. cmSystemTools::ComparePath(remote[common], local[common])) {
  1209. ++common;
  1210. }
  1211. // If no part of the path is in common then return the full path.
  1212. if (common == 0) {
  1213. return remote_path;
  1214. }
  1215. // If the entire path is in common then just return a ".".
  1216. if (common == remote.size() && common == local.size()) {
  1217. return ".";
  1218. }
  1219. // If the entire path is in common except for a trailing slash then
  1220. // just return a "./".
  1221. if (common + 1 == remote.size() && remote[common].empty() &&
  1222. common == local.size()) {
  1223. return "./";
  1224. }
  1225. // Construct the relative path.
  1226. std::string relative;
  1227. // First add enough ../ to get up to the level of the shared portion
  1228. // of the path. Leave off the trailing slash. Note that the last
  1229. // component of local will never be empty because local should never
  1230. // have a trailing slash.
  1231. for (unsigned int i = common; i < local.size(); ++i) {
  1232. relative += "..";
  1233. if (i < local.size() - 1) {
  1234. relative += "/";
  1235. }
  1236. }
  1237. // Now add the portion of the destination path that is not included
  1238. // in the shared portion of the path. Add a slash the first time
  1239. // only if there was already something in the path. If there was a
  1240. // trailing slash in the input then the last iteration of the loop
  1241. // will add a slash followed by an empty string which will preserve
  1242. // the trailing slash in the output.
  1243. if (!relative.empty() && !remote.empty()) {
  1244. relative += "/";
  1245. }
  1246. relative += cmJoin(cmMakeRange(remote).advance(common), "/");
  1247. // Finally return the path.
  1248. return relative;
  1249. }
  1250. #ifndef CMAKE_BOOTSTRAP
  1251. bool cmSystemTools::UnsetEnv(const char* value)
  1252. {
  1253. # if !defined(HAVE_UNSETENV)
  1254. std::string var = cmStrCat(value, '=');
  1255. return cmSystemTools::PutEnv(var);
  1256. # else
  1257. unsetenv(value);
  1258. return true;
  1259. # endif
  1260. }
  1261. std::vector<std::string> cmSystemTools::GetEnvironmentVariables()
  1262. {
  1263. std::vector<std::string> env;
  1264. int cc;
  1265. for (cc = 0; environ[cc]; ++cc) {
  1266. env.emplace_back(environ[cc]);
  1267. }
  1268. return env;
  1269. }
  1270. void cmSystemTools::AppendEnv(std::vector<std::string> const& env)
  1271. {
  1272. for (std::string const& eit : env) {
  1273. cmSystemTools::PutEnv(eit);
  1274. }
  1275. }
  1276. cmSystemTools::SaveRestoreEnvironment::SaveRestoreEnvironment()
  1277. {
  1278. this->Env = cmSystemTools::GetEnvironmentVariables();
  1279. }
  1280. cmSystemTools::SaveRestoreEnvironment::~SaveRestoreEnvironment()
  1281. {
  1282. // First clear everything in the current environment:
  1283. std::vector<std::string> currentEnv = GetEnvironmentVariables();
  1284. for (std::string var : currentEnv) {
  1285. std::string::size_type pos = var.find('=');
  1286. if (pos != std::string::npos) {
  1287. var = var.substr(0, pos);
  1288. }
  1289. cmSystemTools::UnsetEnv(var.c_str());
  1290. }
  1291. // Then put back each entry from the original environment:
  1292. cmSystemTools::AppendEnv(this->Env);
  1293. }
  1294. #endif
  1295. void cmSystemTools::EnableVSConsoleOutput()
  1296. {
  1297. #ifdef _WIN32
  1298. // Visual Studio tools like devenv may not
  1299. // display output to the console unless this environment variable is
  1300. // set. We need it to capture the output of these build tools.
  1301. // Note for future work that one could pass "/out \\.\pipe\NAME" to
  1302. // either of these executables where NAME is created with
  1303. // CreateNamedPipe. This would bypass the internal buffering of the
  1304. // output and allow it to be captured on the fly.
  1305. cmSystemTools::PutEnv("vsconsoleoutput=1");
  1306. # ifndef CMAKE_BOOTSTRAP
  1307. // VS sets an environment variable to tell MS tools like "cl" to report
  1308. // output through a backdoor pipe instead of stdout/stderr. Unset the
  1309. // environment variable to close this backdoor for any path of process
  1310. // invocations that passes through CMake so we can capture the output.
  1311. cmSystemTools::UnsetEnv("VS_UNICODE_OUTPUT");
  1312. # endif
  1313. #endif
  1314. }
  1315. bool cmSystemTools::IsPathToFramework(const std::string& path)
  1316. {
  1317. return (cmSystemTools::FileIsFullPath(path) &&
  1318. cmHasLiteralSuffix(path, ".framework"));
  1319. }
  1320. bool cmSystemTools::CreateTar(const std::string& outFileName,
  1321. const std::vector<std::string>& files,
  1322. cmTarCompression compressType, bool verbose,
  1323. std::string const& mtime,
  1324. std::string const& format, int compressionLevel)
  1325. {
  1326. #if !defined(CMAKE_BOOTSTRAP)
  1327. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1328. cmsys::ofstream fout(outFileName.c_str(), std::ios::out | std::ios::binary);
  1329. if (!fout) {
  1330. std::string e = cmStrCat("Cannot open output file \"", outFileName,
  1331. "\": ", cmSystemTools::GetLastSystemError());
  1332. cmSystemTools::Error(e);
  1333. return false;
  1334. }
  1335. cmArchiveWrite::Compress compress = cmArchiveWrite::CompressNone;
  1336. switch (compressType) {
  1337. case TarCompressGZip:
  1338. compress = cmArchiveWrite::CompressGZip;
  1339. break;
  1340. case TarCompressBZip2:
  1341. compress = cmArchiveWrite::CompressBZip2;
  1342. break;
  1343. case TarCompressXZ:
  1344. compress = cmArchiveWrite::CompressXZ;
  1345. break;
  1346. case TarCompressZstd:
  1347. compress = cmArchiveWrite::CompressZstd;
  1348. break;
  1349. case TarCompressNone:
  1350. compress = cmArchiveWrite::CompressNone;
  1351. break;
  1352. }
  1353. cmArchiveWrite a(fout, compress, format.empty() ? "paxr" : format,
  1354. compressionLevel);
  1355. a.Open();
  1356. a.SetMTime(mtime);
  1357. a.SetVerbose(verbose);
  1358. bool tarCreatedSuccessfully = true;
  1359. for (auto path : files) {
  1360. if (cmSystemTools::FileIsFullPath(path)) {
  1361. // Get the relative path to the file.
  1362. path = cmSystemTools::RelativePath(cwd, path);
  1363. }
  1364. if (!a.Add(path)) {
  1365. cmSystemTools::Error(a.GetError());
  1366. tarCreatedSuccessfully = false;
  1367. }
  1368. }
  1369. return tarCreatedSuccessfully;
  1370. #else
  1371. (void)outFileName;
  1372. (void)files;
  1373. (void)verbose;
  1374. return false;
  1375. #endif
  1376. }
  1377. #if !defined(CMAKE_BOOTSTRAP)
  1378. namespace {
  1379. # define BSDTAR_FILESIZE_PRINTF "%lu"
  1380. # define BSDTAR_FILESIZE_TYPE unsigned long
  1381. void list_item_verbose(FILE* out, struct archive_entry* entry)
  1382. {
  1383. char tmp[100];
  1384. size_t w;
  1385. const char* p;
  1386. const char* fmt;
  1387. time_t tim;
  1388. static time_t now;
  1389. size_t u_width = 6;
  1390. size_t gs_width = 13;
  1391. /*
  1392. * We avoid collecting the entire list in memory at once by
  1393. * listing things as we see them. However, that also means we can't
  1394. * just pre-compute the field widths. Instead, we start with guesses
  1395. * and just widen them as necessary. These numbers are completely
  1396. * arbitrary.
  1397. */
  1398. if (!now) {
  1399. time(&now);
  1400. }
  1401. fprintf(out, "%s %d ", archive_entry_strmode(entry),
  1402. archive_entry_nlink(entry));
  1403. /* Use uname if it's present, else uid. */
  1404. p = archive_entry_uname(entry);
  1405. if ((p == nullptr) || (*p == '\0')) {
  1406. sprintf(tmp, "%lu ", static_cast<unsigned long>(archive_entry_uid(entry)));
  1407. p = tmp;
  1408. }
  1409. w = strlen(p);
  1410. if (w > u_width) {
  1411. u_width = w;
  1412. }
  1413. fprintf(out, "%-*s ", static_cast<int>(u_width), p);
  1414. /* Use gname if it's present, else gid. */
  1415. p = archive_entry_gname(entry);
  1416. if (p != nullptr && p[0] != '\0') {
  1417. fprintf(out, "%s", p);
  1418. w = strlen(p);
  1419. } else {
  1420. sprintf(tmp, "%lu", static_cast<unsigned long>(archive_entry_gid(entry)));
  1421. w = strlen(tmp);
  1422. fprintf(out, "%s", tmp);
  1423. }
  1424. /*
  1425. * Print device number or file size, right-aligned so as to make
  1426. * total width of group and devnum/filesize fields be gs_width.
  1427. * If gs_width is too small, grow it.
  1428. */
  1429. if (archive_entry_filetype(entry) == AE_IFCHR ||
  1430. archive_entry_filetype(entry) == AE_IFBLK) {
  1431. unsigned long rdevmajor = archive_entry_rdevmajor(entry);
  1432. unsigned long rdevminor = archive_entry_rdevminor(entry);
  1433. sprintf(tmp, "%lu,%lu", rdevmajor, rdevminor);
  1434. } else {
  1435. /*
  1436. * Note the use of platform-dependent macros to format
  1437. * the filesize here. We need the format string and the
  1438. * corresponding type for the cast.
  1439. */
  1440. sprintf(tmp, BSDTAR_FILESIZE_PRINTF,
  1441. static_cast<BSDTAR_FILESIZE_TYPE>(archive_entry_size(entry)));
  1442. }
  1443. if (w + strlen(tmp) >= gs_width) {
  1444. gs_width = w + strlen(tmp) + 1;
  1445. }
  1446. fprintf(out, "%*s", static_cast<int>(gs_width - w), tmp);
  1447. /* Format the time using 'ls -l' conventions. */
  1448. tim = archive_entry_mtime(entry);
  1449. # define HALF_YEAR ((time_t)365 * 86400 / 2)
  1450. # if defined(_WIN32) && !defined(__CYGWIN__)
  1451. /* Windows' strftime function does not support %e format. */
  1452. # define DAY_FMT "%d"
  1453. # else
  1454. # define DAY_FMT "%e" /* Day number without leading zeros */
  1455. # endif
  1456. if (tim < now - HALF_YEAR || tim > now + HALF_YEAR) {
  1457. fmt = DAY_FMT " %b %Y";
  1458. } else {
  1459. fmt = DAY_FMT " %b %H:%M";
  1460. }
  1461. strftime(tmp, sizeof(tmp), fmt, localtime(&tim));
  1462. fprintf(out, " %s ", tmp);
  1463. fprintf(out, "%s", cm_archive_entry_pathname(entry).c_str());
  1464. /* Extra information for links. */
  1465. if (archive_entry_hardlink(entry)) /* Hard link */
  1466. {
  1467. fprintf(out, " link to %s", archive_entry_hardlink(entry));
  1468. } else if (archive_entry_symlink(entry)) /* Symbolic link */
  1469. {
  1470. fprintf(out, " -> %s", archive_entry_symlink(entry));
  1471. }
  1472. fflush(out);
  1473. }
  1474. void ArchiveError(const char* m1, struct archive* a)
  1475. {
  1476. std::string message(m1);
  1477. const char* m2 = archive_error_string(a);
  1478. if (m2) {
  1479. message += m2;
  1480. }
  1481. cmSystemTools::Error(message);
  1482. }
  1483. bool la_diagnostic(struct archive* ar, __LA_SSIZE_T r)
  1484. {
  1485. // See archive.h definition of ARCHIVE_OK for return values.
  1486. if (r >= ARCHIVE_OK) {
  1487. return true;
  1488. }
  1489. if (r >= ARCHIVE_WARN) {
  1490. const char* warn = archive_error_string(ar);
  1491. if (!warn) {
  1492. warn = "unknown warning";
  1493. }
  1494. std::cerr << "cmake -E tar: warning: " << warn << '\n';
  1495. return true;
  1496. }
  1497. // Error.
  1498. const char* err = archive_error_string(ar);
  1499. if (!err) {
  1500. err = "unknown error";
  1501. }
  1502. std::cerr << "cmake -E tar: error: " << err << '\n';
  1503. return false;
  1504. }
  1505. // Return 'true' on success
  1506. bool copy_data(struct archive* ar, struct archive* aw)
  1507. {
  1508. long r;
  1509. const void* buff;
  1510. size_t size;
  1511. # if defined(ARCHIVE_VERSION_NUMBER) && ARCHIVE_VERSION_NUMBER >= 3000000
  1512. __LA_INT64_T offset;
  1513. # else
  1514. off_t offset;
  1515. # endif
  1516. for (;;) {
  1517. // See archive.h definition of ARCHIVE_OK for return values.
  1518. r = archive_read_data_block(ar, &buff, &size, &offset);
  1519. if (r == ARCHIVE_EOF) {
  1520. return true;
  1521. }
  1522. if (!la_diagnostic(ar, r)) {
  1523. return false;
  1524. }
  1525. // See archive.h definition of ARCHIVE_OK for return values.
  1526. __LA_SSIZE_T const w = archive_write_data_block(aw, buff, size, offset);
  1527. if (!la_diagnostic(ar, w)) {
  1528. return false;
  1529. }
  1530. }
  1531. # if !defined(__clang__) && !defined(__HP_aCC)
  1532. return false; /* this should not happen but it quiets some compilers */
  1533. # endif
  1534. }
  1535. bool extract_tar(const std::string& outFileName,
  1536. const std::vector<std::string>& files, bool verbose,
  1537. bool extract)
  1538. {
  1539. cmLocaleRAII localeRAII;
  1540. static_cast<void>(localeRAII);
  1541. struct archive* a = archive_read_new();
  1542. struct archive* ext = archive_write_disk_new();
  1543. archive_read_support_filter_all(a);
  1544. archive_read_support_format_all(a);
  1545. struct archive_entry* entry;
  1546. struct archive* matching = archive_match_new();
  1547. if (matching == nullptr) {
  1548. cmSystemTools::Error("Out of memory");
  1549. return false;
  1550. }
  1551. for (const auto& filename : files) {
  1552. if (archive_match_include_pattern(matching, filename.c_str()) !=
  1553. ARCHIVE_OK) {
  1554. cmSystemTools::Error("Failed to add to inclusion list: " + filename);
  1555. return false;
  1556. }
  1557. }
  1558. int r = cm_archive_read_open_file(a, outFileName.c_str(), 10240);
  1559. if (r) {
  1560. ArchiveError("Problem with archive_read_open_file(): ", a);
  1561. archive_write_free(ext);
  1562. archive_read_close(a);
  1563. return false;
  1564. }
  1565. for (;;) {
  1566. r = archive_read_next_header(a, &entry);
  1567. if (r == ARCHIVE_EOF) {
  1568. break;
  1569. }
  1570. if (r != ARCHIVE_OK) {
  1571. ArchiveError("Problem with archive_read_next_header(): ", a);
  1572. break;
  1573. }
  1574. if (archive_match_excluded(matching, entry)) {
  1575. continue;
  1576. }
  1577. if (verbose) {
  1578. if (extract) {
  1579. cmSystemTools::Stdout("x ");
  1580. cmSystemTools::Stdout(cm_archive_entry_pathname(entry));
  1581. } else {
  1582. list_item_verbose(stdout, entry);
  1583. }
  1584. cmSystemTools::Stdout("\n");
  1585. } else if (!extract) {
  1586. cmSystemTools::Stdout(cm_archive_entry_pathname(entry));
  1587. cmSystemTools::Stdout("\n");
  1588. }
  1589. if (extract) {
  1590. r = archive_write_disk_set_options(ext, ARCHIVE_EXTRACT_TIME);
  1591. if (r != ARCHIVE_OK) {
  1592. ArchiveError("Problem with archive_write_disk_set_options(): ", ext);
  1593. break;
  1594. }
  1595. r = archive_write_header(ext, entry);
  1596. if (r == ARCHIVE_OK) {
  1597. if (!copy_data(a, ext)) {
  1598. break;
  1599. }
  1600. r = archive_write_finish_entry(ext);
  1601. if (r != ARCHIVE_OK) {
  1602. ArchiveError("Problem with archive_write_finish_entry(): ", ext);
  1603. break;
  1604. }
  1605. }
  1606. # ifdef _WIN32
  1607. else if (const char* linktext = archive_entry_symlink(entry)) {
  1608. std::cerr << "cmake -E tar: warning: skipping symbolic link \""
  1609. << cm_archive_entry_pathname(entry) << "\" -> \"" << linktext
  1610. << "\"." << std::endl;
  1611. }
  1612. # endif
  1613. else {
  1614. ArchiveError("Problem with archive_write_header(): ", ext);
  1615. cmSystemTools::Error("Current file: " +
  1616. cm_archive_entry_pathname(entry));
  1617. break;
  1618. }
  1619. }
  1620. }
  1621. bool error_occured = false;
  1622. if (matching != nullptr) {
  1623. const char* p;
  1624. int ar;
  1625. while ((ar = archive_match_path_unmatched_inclusions_next(matching, &p)) ==
  1626. ARCHIVE_OK) {
  1627. cmSystemTools::Error("tar: " + std::string(p) +
  1628. ": Not found in archive");
  1629. error_occured = true;
  1630. }
  1631. if (error_occured) {
  1632. return false;
  1633. }
  1634. if (ar == ARCHIVE_FATAL) {
  1635. cmSystemTools::Error("tar: Out of memory");
  1636. return false;
  1637. }
  1638. }
  1639. archive_match_free(matching);
  1640. archive_write_free(ext);
  1641. archive_read_close(a);
  1642. archive_read_free(a);
  1643. return r == ARCHIVE_EOF || r == ARCHIVE_OK;
  1644. }
  1645. }
  1646. #endif
  1647. bool cmSystemTools::ExtractTar(const std::string& outFileName,
  1648. const std::vector<std::string>& files,
  1649. bool verbose)
  1650. {
  1651. #if !defined(CMAKE_BOOTSTRAP)
  1652. return extract_tar(outFileName, files, verbose, true);
  1653. #else
  1654. (void)outFileName;
  1655. (void)files;
  1656. (void)verbose;
  1657. return false;
  1658. #endif
  1659. }
  1660. bool cmSystemTools::ListTar(const std::string& outFileName,
  1661. const std::vector<std::string>& files,
  1662. bool verbose)
  1663. {
  1664. #if !defined(CMAKE_BOOTSTRAP)
  1665. return extract_tar(outFileName, files, verbose, false);
  1666. #else
  1667. (void)outFileName;
  1668. (void)files;
  1669. (void)verbose;
  1670. return false;
  1671. #endif
  1672. }
  1673. int cmSystemTools::WaitForLine(cmsysProcess* process, std::string& line,
  1674. cmDuration timeout, std::vector<char>& out,
  1675. std::vector<char>& err)
  1676. {
  1677. line.clear();
  1678. auto outiter = out.begin();
  1679. auto erriter = err.begin();
  1680. cmProcessOutput processOutput;
  1681. std::string strdata;
  1682. while (true) {
  1683. // Check for a newline in stdout.
  1684. for (; outiter != out.end(); ++outiter) {
  1685. if ((*outiter == '\r') && ((outiter + 1) == out.end())) {
  1686. break;
  1687. }
  1688. if (*outiter == '\n' || *outiter == '\0') {
  1689. std::vector<char>::size_type length = outiter - out.begin();
  1690. if (length > 1 && *(outiter - 1) == '\r') {
  1691. --length;
  1692. }
  1693. if (length > 0) {
  1694. line.append(&out[0], length);
  1695. }
  1696. out.erase(out.begin(), outiter + 1);
  1697. return cmsysProcess_Pipe_STDOUT;
  1698. }
  1699. }
  1700. // Check for a newline in stderr.
  1701. for (; erriter != err.end(); ++erriter) {
  1702. if ((*erriter == '\r') && ((erriter + 1) == err.end())) {
  1703. break;
  1704. }
  1705. if (*erriter == '\n' || *erriter == '\0') {
  1706. std::vector<char>::size_type length = erriter - err.begin();
  1707. if (length > 1 && *(erriter - 1) == '\r') {
  1708. --length;
  1709. }
  1710. if (length > 0) {
  1711. line.append(&err[0], length);
  1712. }
  1713. err.erase(err.begin(), erriter + 1);
  1714. return cmsysProcess_Pipe_STDERR;
  1715. }
  1716. }
  1717. // No newlines found. Wait for more data from the process.
  1718. int length;
  1719. char* data;
  1720. double timeoutAsDbl = timeout.count();
  1721. int pipe =
  1722. cmsysProcess_WaitForData(process, &data, &length, &timeoutAsDbl);
  1723. if (pipe == cmsysProcess_Pipe_Timeout) {
  1724. // Timeout has been exceeded.
  1725. return pipe;
  1726. }
  1727. if (pipe == cmsysProcess_Pipe_STDOUT) {
  1728. processOutput.DecodeText(data, length, strdata, 1);
  1729. // Append to the stdout buffer.
  1730. std::vector<char>::size_type size = out.size();
  1731. cm::append(out, strdata);
  1732. outiter = out.begin() + size;
  1733. } else if (pipe == cmsysProcess_Pipe_STDERR) {
  1734. processOutput.DecodeText(data, length, strdata, 2);
  1735. // Append to the stderr buffer.
  1736. std::vector<char>::size_type size = err.size();
  1737. cm::append(err, strdata);
  1738. erriter = err.begin() + size;
  1739. } else if (pipe == cmsysProcess_Pipe_None) {
  1740. // Both stdout and stderr pipes have broken. Return leftover data.
  1741. processOutput.DecodeText(std::string(), strdata, 1);
  1742. if (!strdata.empty()) {
  1743. std::vector<char>::size_type size = out.size();
  1744. cm::append(out, strdata);
  1745. outiter = out.begin() + size;
  1746. }
  1747. processOutput.DecodeText(std::string(), strdata, 2);
  1748. if (!strdata.empty()) {
  1749. std::vector<char>::size_type size = err.size();
  1750. cm::append(err, strdata);
  1751. erriter = err.begin() + size;
  1752. }
  1753. if (!out.empty()) {
  1754. line.append(&out[0], outiter - out.begin());
  1755. out.erase(out.begin(), out.end());
  1756. return cmsysProcess_Pipe_STDOUT;
  1757. }
  1758. if (!err.empty()) {
  1759. line.append(&err[0], erriter - err.begin());
  1760. err.erase(err.begin(), err.end());
  1761. return cmsysProcess_Pipe_STDERR;
  1762. }
  1763. return cmsysProcess_Pipe_None;
  1764. }
  1765. }
  1766. }
  1767. #ifdef _WIN32
  1768. static void EnsureStdPipe(DWORD fd)
  1769. {
  1770. if (GetStdHandle(fd) != INVALID_HANDLE_VALUE) {
  1771. return;
  1772. }
  1773. SECURITY_ATTRIBUTES sa;
  1774. sa.nLength = sizeof(sa);
  1775. sa.lpSecurityDescriptor = NULL;
  1776. sa.bInheritHandle = TRUE;
  1777. HANDLE h = CreateFileW(
  1778. L"NUL",
  1779. fd == STD_INPUT_HANDLE ? FILE_GENERIC_READ
  1780. : FILE_GENERIC_WRITE | FILE_READ_ATTRIBUTES,
  1781. FILE_SHARE_READ | FILE_SHARE_WRITE, &sa, OPEN_EXISTING, 0, NULL);
  1782. if (h == INVALID_HANDLE_VALUE) {
  1783. LPSTR message = NULL;
  1784. DWORD size = FormatMessageA(
  1785. FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
  1786. FORMAT_MESSAGE_IGNORE_INSERTS,
  1787. NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  1788. (LPSTR)&message, 0, NULL);
  1789. std::string msg = std::string(message, size);
  1790. LocalFree(message);
  1791. std::cerr << "failed to open NUL for missing stdio pipe: " << msg;
  1792. abort();
  1793. }
  1794. SetStdHandle(fd, h);
  1795. }
  1796. void cmSystemTools::EnsureStdPipes()
  1797. {
  1798. EnsureStdPipe(STD_INPUT_HANDLE);
  1799. EnsureStdPipe(STD_OUTPUT_HANDLE);
  1800. EnsureStdPipe(STD_ERROR_HANDLE);
  1801. }
  1802. #else
  1803. static void EnsureStdPipe(int fd)
  1804. {
  1805. if (fcntl(fd, F_GETFD) != -1 || errno != EBADF) {
  1806. return;
  1807. }
  1808. int f = open("/dev/null", fd == STDIN_FILENO ? O_RDONLY : O_WRONLY);
  1809. if (f == -1) {
  1810. perror("failed to open /dev/null for missing stdio pipe");
  1811. abort();
  1812. }
  1813. if (f != fd) {
  1814. dup2(f, fd);
  1815. close(f);
  1816. }
  1817. }
  1818. void cmSystemTools::EnsureStdPipes()
  1819. {
  1820. EnsureStdPipe(STDIN_FILENO);
  1821. EnsureStdPipe(STDOUT_FILENO);
  1822. EnsureStdPipe(STDERR_FILENO);
  1823. }
  1824. #endif
  1825. void cmSystemTools::DoNotInheritStdPipes()
  1826. {
  1827. #ifdef _WIN32
  1828. // Check to see if we are attached to a console
  1829. // if so, then do not stop the inherited pipes
  1830. // or stdout and stderr will not show up in dos
  1831. // shell windows
  1832. CONSOLE_SCREEN_BUFFER_INFO hOutInfo;
  1833. HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
  1834. if (GetConsoleScreenBufferInfo(hOut, &hOutInfo)) {
  1835. return;
  1836. }
  1837. {
  1838. HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
  1839. DuplicateHandle(GetCurrentProcess(), out, GetCurrentProcess(), &out, 0,
  1840. FALSE, DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
  1841. SetStdHandle(STD_OUTPUT_HANDLE, out);
  1842. }
  1843. {
  1844. HANDLE out = GetStdHandle(STD_ERROR_HANDLE);
  1845. DuplicateHandle(GetCurrentProcess(), out, GetCurrentProcess(), &out, 0,
  1846. FALSE, DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
  1847. SetStdHandle(STD_ERROR_HANDLE, out);
  1848. }
  1849. #endif
  1850. }
  1851. #ifdef _WIN32
  1852. # ifndef CRYPT_SILENT
  1853. # define CRYPT_SILENT 0x40 /* Not defined by VS 6 version of header. */
  1854. # endif
  1855. static int WinCryptRandom(void* data, size_t size)
  1856. {
  1857. int result = 0;
  1858. HCRYPTPROV hProvider = 0;
  1859. if (CryptAcquireContextW(&hProvider, 0, 0, PROV_RSA_FULL,
  1860. CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) {
  1861. result = CryptGenRandom(hProvider, (DWORD)size, (BYTE*)data) ? 1 : 0;
  1862. CryptReleaseContext(hProvider, 0);
  1863. }
  1864. return result;
  1865. }
  1866. #endif
  1867. unsigned int cmSystemTools::RandomSeed()
  1868. {
  1869. #if defined(_WIN32) && !defined(__CYGWIN__)
  1870. unsigned int seed = 0;
  1871. // Try using a real random source.
  1872. if (WinCryptRandom(&seed, sizeof(seed))) {
  1873. return seed;
  1874. }
  1875. // Fall back to the time and pid.
  1876. FILETIME ft;
  1877. GetSystemTimeAsFileTime(&ft);
  1878. unsigned int t1 = static_cast<unsigned int>(ft.dwHighDateTime);
  1879. unsigned int t2 = static_cast<unsigned int>(ft.dwLowDateTime);
  1880. unsigned int pid = static_cast<unsigned int>(GetCurrentProcessId());
  1881. return t1 ^ t2 ^ pid;
  1882. #else
  1883. union
  1884. {
  1885. unsigned int integer;
  1886. char bytes[sizeof(unsigned int)];
  1887. } seed;
  1888. // Try using a real random source.
  1889. cmsys::ifstream fin;
  1890. fin.rdbuf()->pubsetbuf(nullptr, 0); // Unbuffered read.
  1891. fin.open("/dev/urandom");
  1892. if (fin.good() && fin.read(seed.bytes, sizeof(seed)) &&
  1893. fin.gcount() == sizeof(seed)) {
  1894. return seed.integer;
  1895. }
  1896. // Fall back to the time and pid.
  1897. struct timeval t;
  1898. gettimeofday(&t, nullptr);
  1899. unsigned int pid = static_cast<unsigned int>(getpid());
  1900. unsigned int tv_sec = static_cast<unsigned int>(t.tv_sec);
  1901. unsigned int tv_usec = static_cast<unsigned int>(t.tv_usec);
  1902. // Since tv_usec never fills more than 11 bits we shift it to fill
  1903. // in the slow-changing high-order bits of tv_sec.
  1904. return tv_sec ^ (tv_usec << 21) ^ pid;
  1905. #endif
  1906. }
  1907. static std::string cmSystemToolsCMakeCommand;
  1908. static std::string cmSystemToolsCTestCommand;
  1909. static std::string cmSystemToolsCPackCommand;
  1910. static std::string cmSystemToolsCMakeCursesCommand;
  1911. static std::string cmSystemToolsCMakeGUICommand;
  1912. static std::string cmSystemToolsCMClDepsCommand;
  1913. static std::string cmSystemToolsCMakeRoot;
  1914. static std::string cmSystemToolsHTMLDoc;
  1915. void cmSystemTools::FindCMakeResources(const char* argv0)
  1916. {
  1917. std::string exe_dir;
  1918. #if defined(_WIN32) && !defined(__CYGWIN__)
  1919. (void)argv0; // ignore this on windows
  1920. wchar_t modulepath[_MAX_PATH];
  1921. ::GetModuleFileNameW(NULL, modulepath, sizeof(modulepath));
  1922. std::string path = cmsys::Encoding::ToNarrow(modulepath);
  1923. std::string realPath =
  1924. cmSystemTools::GetRealPathResolvingWindowsSubst(path, NULL);
  1925. if (realPath.empty()) {
  1926. realPath = path;
  1927. }
  1928. exe_dir = cmSystemTools::GetFilenamePath(realPath);
  1929. #elif defined(__APPLE__)
  1930. (void)argv0; // ignore this on OS X
  1931. # define CM_EXE_PATH_LOCAL_SIZE 16384
  1932. char exe_path_local[CM_EXE_PATH_LOCAL_SIZE];
  1933. # if defined(MAC_OS_X_VERSION_10_3) && !defined(MAC_OS_X_VERSION_10_4)
  1934. unsigned long exe_path_size = CM_EXE_PATH_LOCAL_SIZE;
  1935. # else
  1936. uint32_t exe_path_size = CM_EXE_PATH_LOCAL_SIZE;
  1937. # endif
  1938. # undef CM_EXE_PATH_LOCAL_SIZE
  1939. char* exe_path = exe_path_local;
  1940. if (_NSGetExecutablePath(exe_path, &exe_path_size) < 0) {
  1941. exe_path = static_cast<char*>(malloc(exe_path_size));
  1942. _NSGetExecutablePath(exe_path, &exe_path_size);
  1943. }
  1944. exe_dir =
  1945. cmSystemTools::GetFilenamePath(cmSystemTools::GetRealPath(exe_path));
  1946. if (exe_path != exe_path_local) {
  1947. free(exe_path);
  1948. }
  1949. if (cmSystemTools::GetFilenameName(exe_dir) == "MacOS") {
  1950. // The executable is inside an application bundle.
  1951. // Look for ..<CMAKE_BIN_DIR> (install tree) and then fall back to
  1952. // ../../../bin (build tree).
  1953. exe_dir = cmSystemTools::GetFilenamePath(exe_dir);
  1954. if (cmSystemTools::FileExists(exe_dir + CMAKE_BIN_DIR "/cmake")) {
  1955. exe_dir += CMAKE_BIN_DIR;
  1956. } else {
  1957. exe_dir = cmSystemTools::GetFilenamePath(exe_dir);
  1958. exe_dir = cmSystemTools::GetFilenamePath(exe_dir);
  1959. }
  1960. }
  1961. #else
  1962. std::string errorMsg;
  1963. std::string exe;
  1964. if (cmSystemTools::FindProgramPath(argv0, exe, errorMsg)) {
  1965. // remove symlinks
  1966. exe = cmSystemTools::GetRealPath(exe);
  1967. exe_dir = cmSystemTools::GetFilenamePath(exe);
  1968. } else {
  1969. // ???
  1970. }
  1971. #endif
  1972. exe_dir = cmSystemTools::GetActualCaseForPath(exe_dir);
  1973. cmSystemToolsCMakeCommand =
  1974. cmStrCat(exe_dir, "/cmake", cmSystemTools::GetExecutableExtension());
  1975. #ifdef CMAKE_BOOTSTRAP
  1976. // The bootstrap cmake does not provide the other tools,
  1977. // so use the directory where they are about to be built.
  1978. exe_dir = CMAKE_BOOTSTRAP_BINARY_DIR "/bin";
  1979. #endif
  1980. cmSystemToolsCTestCommand =
  1981. cmStrCat(exe_dir, "/ctest", cmSystemTools::GetExecutableExtension());
  1982. cmSystemToolsCPackCommand =
  1983. cmStrCat(exe_dir, "/cpack", cmSystemTools::GetExecutableExtension());
  1984. cmSystemToolsCMakeGUICommand =
  1985. cmStrCat(exe_dir, "/cmake-gui", cmSystemTools::GetExecutableExtension());
  1986. if (!cmSystemTools::FileExists(cmSystemToolsCMakeGUICommand)) {
  1987. cmSystemToolsCMakeGUICommand.clear();
  1988. }
  1989. cmSystemToolsCMakeCursesCommand =
  1990. cmStrCat(exe_dir, "/ccmake", cmSystemTools::GetExecutableExtension());
  1991. if (!cmSystemTools::FileExists(cmSystemToolsCMakeCursesCommand)) {
  1992. cmSystemToolsCMakeCursesCommand.clear();
  1993. }
  1994. cmSystemToolsCMClDepsCommand =
  1995. cmStrCat(exe_dir, "/cmcldeps", cmSystemTools::GetExecutableExtension());
  1996. if (!cmSystemTools::FileExists(cmSystemToolsCMClDepsCommand)) {
  1997. cmSystemToolsCMClDepsCommand.clear();
  1998. }
  1999. #ifndef CMAKE_BOOTSTRAP
  2000. // Install tree has
  2001. // - "<prefix><CMAKE_BIN_DIR>/cmake"
  2002. // - "<prefix><CMAKE_DATA_DIR>"
  2003. // - "<prefix><CMAKE_DOC_DIR>"
  2004. if (cmHasLiteralSuffix(exe_dir, CMAKE_BIN_DIR)) {
  2005. std::string const prefix =
  2006. exe_dir.substr(0, exe_dir.size() - cmStrLen(CMAKE_BIN_DIR));
  2007. cmSystemToolsCMakeRoot = cmStrCat(prefix, CMAKE_DATA_DIR);
  2008. if (cmSystemTools::FileExists(
  2009. cmStrCat(prefix, CMAKE_DOC_DIR "/html/index.html"))) {
  2010. cmSystemToolsHTMLDoc = cmStrCat(prefix, CMAKE_DOC_DIR "/html");
  2011. }
  2012. }
  2013. if (cmSystemToolsCMakeRoot.empty() ||
  2014. !cmSystemTools::FileExists(
  2015. cmStrCat(cmSystemToolsCMakeRoot, "/Modules/CMake.cmake"))) {
  2016. // Build tree has "<build>/bin[/<config>]/cmake" and
  2017. // "<build>/CMakeFiles/CMakeSourceDir.txt".
  2018. std::string dir = cmSystemTools::GetFilenamePath(exe_dir);
  2019. std::string src_dir_txt = cmStrCat(dir, "/CMakeFiles/CMakeSourceDir.txt");
  2020. cmsys::ifstream fin(src_dir_txt.c_str());
  2021. std::string src_dir;
  2022. if (fin && cmSystemTools::GetLineFromStream(fin, src_dir) &&
  2023. cmSystemTools::FileIsDirectory(src_dir)) {
  2024. cmSystemToolsCMakeRoot = src_dir;
  2025. } else {
  2026. dir = cmSystemTools::GetFilenamePath(dir);
  2027. src_dir_txt = cmStrCat(dir, "/CMakeFiles/CMakeSourceDir.txt");
  2028. cmsys::ifstream fin2(src_dir_txt.c_str());
  2029. if (fin2 && cmSystemTools::GetLineFromStream(fin2, src_dir) &&
  2030. cmSystemTools::FileIsDirectory(src_dir)) {
  2031. cmSystemToolsCMakeRoot = src_dir;
  2032. }
  2033. }
  2034. if (!cmSystemToolsCMakeRoot.empty() && cmSystemToolsHTMLDoc.empty() &&
  2035. cmSystemTools::FileExists(
  2036. cmStrCat(dir, "/Utilities/Sphinx/html/index.html"))) {
  2037. cmSystemToolsHTMLDoc = cmStrCat(dir, "/Utilities/Sphinx/html");
  2038. }
  2039. }
  2040. #else
  2041. // Bootstrap build knows its source.
  2042. cmSystemToolsCMakeRoot = CMAKE_BOOTSTRAP_SOURCE_DIR;
  2043. #endif
  2044. }
  2045. std::string const& cmSystemTools::GetCMakeCommand()
  2046. {
  2047. return cmSystemToolsCMakeCommand;
  2048. }
  2049. std::string const& cmSystemTools::GetCTestCommand()
  2050. {
  2051. return cmSystemToolsCTestCommand;
  2052. }
  2053. std::string const& cmSystemTools::GetCPackCommand()
  2054. {
  2055. return cmSystemToolsCPackCommand;
  2056. }
  2057. std::string const& cmSystemTools::GetCMakeCursesCommand()
  2058. {
  2059. return cmSystemToolsCMakeCursesCommand;
  2060. }
  2061. std::string const& cmSystemTools::GetCMakeGUICommand()
  2062. {
  2063. return cmSystemToolsCMakeGUICommand;
  2064. }
  2065. std::string const& cmSystemTools::GetCMClDepsCommand()
  2066. {
  2067. return cmSystemToolsCMClDepsCommand;
  2068. }
  2069. std::string const& cmSystemTools::GetCMakeRoot()
  2070. {
  2071. return cmSystemToolsCMakeRoot;
  2072. }
  2073. std::string const& cmSystemTools::GetHTMLDoc()
  2074. {
  2075. return cmSystemToolsHTMLDoc;
  2076. }
  2077. std::string cmSystemTools::GetCurrentWorkingDirectory()
  2078. {
  2079. return cmSystemTools::CollapseFullPath(
  2080. cmsys::SystemTools::GetCurrentWorkingDirectory());
  2081. }
  2082. void cmSystemTools::MakefileColorEcho(int color, const char* message,
  2083. bool newline, bool enabled)
  2084. {
  2085. // On some platforms (an MSYS prompt) cmsysTerminal may not be able
  2086. // to determine whether the stream is displayed on a tty. In this
  2087. // case it assumes no unless we tell it otherwise. Since we want
  2088. // color messages to be displayed for users we will assume yes.
  2089. // However, we can test for some situations when the answer is most
  2090. // likely no.
  2091. int assumeTTY = cmsysTerminal_Color_AssumeTTY;
  2092. if (cmSystemTools::HasEnv("DART_TEST_FROM_DART") ||
  2093. cmSystemTools::HasEnv("DASHBOARD_TEST_FROM_CTEST") ||
  2094. cmSystemTools::HasEnv("CTEST_INTERACTIVE_DEBUG_MODE")) {
  2095. // Avoid printing color escapes during dashboard builds.
  2096. assumeTTY = 0;
  2097. }
  2098. if (enabled && color != cmsysTerminal_Color_Normal) {
  2099. // Print with color. Delay the newline until later so that
  2100. // all color restore sequences appear before it.
  2101. cmsysTerminal_cfprintf(color | assumeTTY, stdout, "%s", message);
  2102. } else {
  2103. // Color is disabled. Print without color.
  2104. fprintf(stdout, "%s", message);
  2105. }
  2106. if (newline) {
  2107. fprintf(stdout, "\n");
  2108. }
  2109. }
  2110. bool cmSystemTools::GuessLibrarySOName(std::string const& fullPath,
  2111. std::string& soname)
  2112. {
  2113. // For ELF shared libraries use a real parser to get the correct
  2114. // soname.
  2115. #if defined(CMake_USE_ELF_PARSER)
  2116. cmELF elf(fullPath.c_str());
  2117. if (elf) {
  2118. return elf.GetSOName(soname);
  2119. }
  2120. #endif
  2121. // If the file is not a symlink we have no guess for its soname.
  2122. if (!cmSystemTools::FileIsSymlink(fullPath)) {
  2123. return false;
  2124. }
  2125. if (!cmSystemTools::ReadSymlink(fullPath, soname)) {
  2126. return false;
  2127. }
  2128. // If the symlink has a path component we have no guess for the soname.
  2129. if (!cmSystemTools::GetFilenamePath(soname).empty()) {
  2130. return false;
  2131. }
  2132. // If the symlink points at an extended version of the same name
  2133. // assume it is the soname.
  2134. std::string name = cmSystemTools::GetFilenameName(fullPath);
  2135. return soname.length() > name.length() &&
  2136. soname.compare(0, name.length(), name) == 0;
  2137. }
  2138. bool cmSystemTools::GuessLibraryInstallName(std::string const& fullPath,
  2139. std::string& soname)
  2140. {
  2141. #if defined(CMake_USE_MACH_PARSER)
  2142. cmMachO macho(fullPath.c_str());
  2143. if (macho) {
  2144. return macho.GetInstallName(soname);
  2145. }
  2146. #else
  2147. (void)fullPath;
  2148. (void)soname;
  2149. #endif
  2150. return false;
  2151. }
  2152. #if defined(CMake_USE_ELF_PARSER) || defined(CMake_USE_XCOFF_PARSER)
  2153. std::string::size_type cmSystemToolsFindRPath(cm::string_view const& have,
  2154. cm::string_view const& want)
  2155. {
  2156. std::string::size_type pos = 0;
  2157. while (pos < have.size()) {
  2158. // Look for an occurrence of the string.
  2159. std::string::size_type const beg = have.find(want, pos);
  2160. if (beg == std::string::npos) {
  2161. return std::string::npos;
  2162. }
  2163. // Make sure it is separated from preceding entries.
  2164. if (beg > 0 && have[beg - 1] != ':') {
  2165. pos = beg + 1;
  2166. continue;
  2167. }
  2168. // Make sure it is separated from following entries.
  2169. std::string::size_type const end = beg + want.size();
  2170. if (end < have.size() && have[end] != ':') {
  2171. pos = beg + 1;
  2172. continue;
  2173. }
  2174. // Return the position of the path portion.
  2175. return beg;
  2176. }
  2177. // The desired rpath was not found.
  2178. return std::string::npos;
  2179. }
  2180. #endif
  2181. #if defined(CMake_USE_ELF_PARSER)
  2182. struct cmSystemToolsRPathInfo
  2183. {
  2184. unsigned long Position;
  2185. unsigned long Size;
  2186. std::string Name;
  2187. std::string Value;
  2188. };
  2189. #endif
  2190. // FIXME: Dispatch if multiple formats are supported.
  2191. #if defined(CMake_USE_ELF_PARSER)
  2192. bool cmSystemTools::ChangeRPath(std::string const& file,
  2193. std::string const& oldRPath,
  2194. std::string const& newRPath,
  2195. bool removeEnvironmentRPath, std::string* emsg,
  2196. bool* changed)
  2197. {
  2198. if (changed) {
  2199. *changed = false;
  2200. }
  2201. int rp_count = 0;
  2202. bool remove_rpath = true;
  2203. cmSystemToolsRPathInfo rp[2];
  2204. {
  2205. // Parse the ELF binary.
  2206. cmELF elf(file.c_str());
  2207. // Get the RPATH and RUNPATH entries from it.
  2208. int se_count = 0;
  2209. cmELF::StringEntry const* se[2] = { nullptr, nullptr };
  2210. const char* se_name[2] = { nullptr, nullptr };
  2211. if (cmELF::StringEntry const* se_rpath = elf.GetRPath()) {
  2212. se[se_count] = se_rpath;
  2213. se_name[se_count] = "RPATH";
  2214. ++se_count;
  2215. }
  2216. if (cmELF::StringEntry const* se_runpath = elf.GetRunPath()) {
  2217. se[se_count] = se_runpath;
  2218. se_name[se_count] = "RUNPATH";
  2219. ++se_count;
  2220. }
  2221. if (se_count == 0) {
  2222. if (newRPath.empty()) {
  2223. // The new rpath is empty and there is no rpath anyway so it is
  2224. // okay.
  2225. return true;
  2226. }
  2227. if (emsg) {
  2228. *emsg =
  2229. cmStrCat("No valid ELF RPATH or RUNPATH entry exists in the file; ",
  2230. elf.GetErrorMessage());
  2231. }
  2232. return false;
  2233. }
  2234. for (int i = 0; i < se_count; ++i) {
  2235. // If both RPATH and RUNPATH refer to the same string literal it
  2236. // needs to be changed only once.
  2237. if (rp_count && rp[0].Position == se[i]->Position) {
  2238. continue;
  2239. }
  2240. // Make sure the current rpath contains the old rpath.
  2241. std::string::size_type pos =
  2242. cmSystemToolsFindRPath(se[i]->Value, oldRPath);
  2243. if (pos == std::string::npos) {
  2244. // If it contains the new rpath instead then it is okay.
  2245. if (cmSystemToolsFindRPath(se[i]->Value, newRPath) !=
  2246. std::string::npos) {
  2247. remove_rpath = false;
  2248. continue;
  2249. }
  2250. if (emsg) {
  2251. std::ostringstream e;
  2252. /* clang-format off */
  2253. e << "The current " << se_name[i] << " is:\n"
  2254. << " " << se[i]->Value << "\n"
  2255. << "which does not contain:\n"
  2256. << " " << oldRPath << "\n"
  2257. << "as was expected.";
  2258. /* clang-format on */
  2259. *emsg = e.str();
  2260. }
  2261. return false;
  2262. }
  2263. // Store information about the entry in the file.
  2264. rp[rp_count].Position = se[i]->Position;
  2265. rp[rp_count].Size = se[i]->Size;
  2266. rp[rp_count].Name = se_name[i];
  2267. std::string::size_type prefix_len = pos;
  2268. // If oldRPath was at the end of the file's RPath, and newRPath is empty,
  2269. // we should remove the unnecessary ':' at the end.
  2270. if (newRPath.empty() && pos > 0 && se[i]->Value[pos - 1] == ':' &&
  2271. pos + oldRPath.length() == se[i]->Value.length()) {
  2272. prefix_len--;
  2273. }
  2274. // Construct the new value which preserves the part of the path
  2275. // not being changed.
  2276. if (!removeEnvironmentRPath) {
  2277. rp[rp_count].Value = se[i]->Value.substr(0, prefix_len);
  2278. }
  2279. rp[rp_count].Value += newRPath;
  2280. rp[rp_count].Value += se[i]->Value.substr(pos + oldRPath.length());
  2281. if (!rp[rp_count].Value.empty()) {
  2282. remove_rpath = false;
  2283. }
  2284. // Make sure there is enough room to store the new rpath and at
  2285. // least one null terminator.
  2286. if (rp[rp_count].Size < rp[rp_count].Value.length() + 1) {
  2287. if (emsg) {
  2288. *emsg = cmStrCat("The replacement path is too long for the ",
  2289. se_name[i], " entry.");
  2290. }
  2291. return false;
  2292. }
  2293. // This entry is ready for update.
  2294. ++rp_count;
  2295. }
  2296. }
  2297. // If no runtime path needs to be changed, we are done.
  2298. if (rp_count == 0) {
  2299. return true;
  2300. }
  2301. // If the resulting rpath is empty, just remove the entire entry instead.
  2302. if (remove_rpath) {
  2303. return cmSystemTools::RemoveRPath(file, emsg, changed);
  2304. }
  2305. {
  2306. // Open the file for update.
  2307. cmsys::ofstream f(file.c_str(),
  2308. std::ios::in | std::ios::out | std::ios::binary);
  2309. if (!f) {
  2310. if (emsg) {
  2311. *emsg = "Error opening file for update.";
  2312. }
  2313. return false;
  2314. }
  2315. // Store the new RPATH and RUNPATH strings.
  2316. for (int i = 0; i < rp_count; ++i) {
  2317. // Seek to the RPATH position.
  2318. if (!f.seekp(rp[i].Position)) {
  2319. if (emsg) {
  2320. *emsg = cmStrCat("Error seeking to ", rp[i].Name, " position.");
  2321. }
  2322. return false;
  2323. }
  2324. // Write the new rpath. Follow it with enough null terminators to
  2325. // fill the string table entry.
  2326. f << rp[i].Value;
  2327. for (unsigned long j = rp[i].Value.length(); j < rp[i].Size; ++j) {
  2328. f << '\0';
  2329. }
  2330. // Make sure it wrote correctly.
  2331. if (!f) {
  2332. if (emsg) {
  2333. *emsg = cmStrCat("Error writing the new ", rp[i].Name,
  2334. " string to the file.");
  2335. }
  2336. return false;
  2337. }
  2338. }
  2339. }
  2340. // Everything was updated successfully.
  2341. if (changed) {
  2342. *changed = true;
  2343. }
  2344. return true;
  2345. }
  2346. #elif defined(CMake_USE_XCOFF_PARSER)
  2347. bool cmSystemTools::ChangeRPath(std::string const& file,
  2348. std::string const& oldRPath,
  2349. std::string const& newRPath,
  2350. bool removeEnvironmentRPath, std::string* emsg,
  2351. bool* changed)
  2352. {
  2353. if (changed) {
  2354. *changed = false;
  2355. }
  2356. bool chg = false;
  2357. cmXCOFF xcoff(file.c_str(), cmXCOFF::Mode::ReadWrite);
  2358. if (cm::optional<cm::string_view> maybeLibPath = xcoff.GetLibPath()) {
  2359. cm::string_view libPath = *maybeLibPath;
  2360. // Make sure the current rpath contains the old rpath.
  2361. std::string::size_type pos = cmSystemToolsFindRPath(libPath, oldRPath);
  2362. if (pos == std::string::npos) {
  2363. // If it contains the new rpath instead then it is okay.
  2364. if (cmSystemToolsFindRPath(libPath, newRPath) != std::string::npos) {
  2365. return true;
  2366. }
  2367. if (emsg) {
  2368. std::ostringstream e;
  2369. /* clang-format off */
  2370. e << "The current RPATH is:\n"
  2371. << " " << libPath << "\n"
  2372. << "which does not contain:\n"
  2373. << " " << oldRPath << "\n"
  2374. << "as was expected.";
  2375. /* clang-format on */
  2376. *emsg = e.str();
  2377. }
  2378. return false;
  2379. }
  2380. // The prefix is either empty or ends in a ':'.
  2381. cm::string_view prefix = libPath.substr(0, pos);
  2382. if (newRPath.empty() && !prefix.empty()) {
  2383. prefix.remove_suffix(1);
  2384. }
  2385. // The suffix is either empty or starts in a ':'.
  2386. cm::string_view suffix = libPath.substr(pos + oldRPath.length());
  2387. // Construct the new value which preserves the part of the path
  2388. // not being changed.
  2389. std::string newLibPath;
  2390. if (!removeEnvironmentRPath) {
  2391. newLibPath = std::string(prefix);
  2392. }
  2393. newLibPath += newRPath;
  2394. newLibPath += suffix;
  2395. chg = xcoff.SetLibPath(newLibPath);
  2396. }
  2397. if (!xcoff) {
  2398. if (emsg) {
  2399. *emsg = xcoff.GetErrorMessage();
  2400. }
  2401. return false;
  2402. }
  2403. // Everything was updated successfully.
  2404. if (changed) {
  2405. *changed = chg;
  2406. }
  2407. return true;
  2408. }
  2409. #else
  2410. bool cmSystemTools::ChangeRPath(std::string const& /*file*/,
  2411. std::string const& /*oldRPath*/,
  2412. std::string const& /*newRPath*/,
  2413. bool /*removeEnvironmentRPath*/,
  2414. std::string* /*emsg*/, bool* /*changed*/)
  2415. {
  2416. return false;
  2417. }
  2418. #endif
  2419. bool cmSystemTools::VersionCompare(cmSystemTools::CompareOp op,
  2420. const char* lhss, const char* rhss)
  2421. {
  2422. const char* endl = lhss;
  2423. const char* endr = rhss;
  2424. unsigned long lhs;
  2425. unsigned long rhs;
  2426. while (((*endl >= '0') && (*endl <= '9')) ||
  2427. ((*endr >= '0') && (*endr <= '9'))) {
  2428. // Do component-wise comparison.
  2429. lhs = strtoul(endl, const_cast<char**>(&endl), 10);
  2430. rhs = strtoul(endr, const_cast<char**>(&endr), 10);
  2431. if (lhs < rhs) {
  2432. // lhs < rhs, so true if operation is LESS
  2433. return (op & cmSystemTools::OP_LESS) != 0;
  2434. }
  2435. if (lhs > rhs) {
  2436. // lhs > rhs, so true if operation is GREATER
  2437. return (op & cmSystemTools::OP_GREATER) != 0;
  2438. }
  2439. if (*endr == '.') {
  2440. endr++;
  2441. }
  2442. if (*endl == '.') {
  2443. endl++;
  2444. }
  2445. }
  2446. // lhs == rhs, so true if operation is EQUAL
  2447. return (op & cmSystemTools::OP_EQUAL) != 0;
  2448. }
  2449. bool cmSystemTools::VersionCompareEqual(std::string const& lhs,
  2450. std::string const& rhs)
  2451. {
  2452. return cmSystemTools::VersionCompare(cmSystemTools::OP_EQUAL, lhs.c_str(),
  2453. rhs.c_str());
  2454. }
  2455. bool cmSystemTools::VersionCompareGreater(std::string const& lhs,
  2456. std::string const& rhs)
  2457. {
  2458. return cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER, lhs.c_str(),
  2459. rhs.c_str());
  2460. }
  2461. bool cmSystemTools::VersionCompareGreaterEq(std::string const& lhs,
  2462. std::string const& rhs)
  2463. {
  2464. return cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER_EQUAL,
  2465. lhs.c_str(), rhs.c_str());
  2466. }
  2467. static size_t cm_strverscmp_find_first_difference_or_end(const char* lhs,
  2468. const char* rhs)
  2469. {
  2470. size_t i = 0;
  2471. /* Step forward until we find a difference or both strings end together.
  2472. The difference may lie on the null-terminator of one string. */
  2473. while (lhs[i] == rhs[i] && lhs[i] != 0) {
  2474. ++i;
  2475. }
  2476. return i;
  2477. }
  2478. static size_t cm_strverscmp_find_digits_begin(const char* s, size_t i)
  2479. {
  2480. /* Step back until we are not preceded by a digit. */
  2481. while (i > 0 && isdigit(s[i - 1])) {
  2482. --i;
  2483. }
  2484. return i;
  2485. }
  2486. static size_t cm_strverscmp_find_digits_end(const char* s, size_t i)
  2487. {
  2488. /* Step forward over digits. */
  2489. while (isdigit(s[i])) {
  2490. ++i;
  2491. }
  2492. return i;
  2493. }
  2494. static size_t cm_strverscmp_count_leading_zeros(const char* s, size_t b)
  2495. {
  2496. size_t i = b;
  2497. /* Step forward over zeros that are followed by another digit. */
  2498. while (s[i] == '0' && isdigit(s[i + 1])) {
  2499. ++i;
  2500. }
  2501. return i - b;
  2502. }
  2503. static int cm_strverscmp(const char* lhs, const char* rhs)
  2504. {
  2505. size_t const i = cm_strverscmp_find_first_difference_or_end(lhs, rhs);
  2506. if (lhs[i] != rhs[i]) {
  2507. /* The strings differ starting at 'i'. Check for a digit sequence. */
  2508. size_t const b = cm_strverscmp_find_digits_begin(lhs, i);
  2509. if (b != i || (isdigit(lhs[i]) && isdigit(rhs[i]))) {
  2510. /* A digit sequence starts at 'b', preceding or at 'i'. */
  2511. /* Look for leading zeros, implying a leading decimal point. */
  2512. size_t const lhs_zeros = cm_strverscmp_count_leading_zeros(lhs, b);
  2513. size_t const rhs_zeros = cm_strverscmp_count_leading_zeros(rhs, b);
  2514. if (lhs_zeros != rhs_zeros) {
  2515. /* The side with more leading zeros orders first. */
  2516. return rhs_zeros > lhs_zeros ? 1 : -1;
  2517. }
  2518. if (lhs_zeros == 0) {
  2519. /* No leading zeros; compare digit sequence lengths. */
  2520. size_t const lhs_end = cm_strverscmp_find_digits_end(lhs, i);
  2521. size_t const rhs_end = cm_strverscmp_find_digits_end(rhs, i);
  2522. if (lhs_end != rhs_end) {
  2523. /* The side with fewer digits orders first. */
  2524. return lhs_end > rhs_end ? 1 : -1;
  2525. }
  2526. }
  2527. }
  2528. }
  2529. /* Ordering was not decided by digit sequence lengths; compare bytes. */
  2530. return lhs[i] - rhs[i];
  2531. }
  2532. int cmSystemTools::strverscmp(std::string const& lhs, std::string const& rhs)
  2533. {
  2534. return cm_strverscmp(lhs.c_str(), rhs.c_str());
  2535. }
  2536. // FIXME: Dispatch if multiple formats are supported.
  2537. #if defined(CMake_USE_ELF_PARSER)
  2538. bool cmSystemTools::RemoveRPath(std::string const& file, std::string* emsg,
  2539. bool* removed)
  2540. {
  2541. if (removed) {
  2542. *removed = false;
  2543. }
  2544. int zeroCount = 0;
  2545. unsigned long zeroPosition[2] = { 0, 0 };
  2546. unsigned long zeroSize[2] = { 0, 0 };
  2547. unsigned long bytesBegin = 0;
  2548. std::vector<char> bytes;
  2549. {
  2550. // Parse the ELF binary.
  2551. cmELF elf(file.c_str());
  2552. // Get the RPATH and RUNPATH entries from it and sort them by index
  2553. // in the dynamic section header.
  2554. int se_count = 0;
  2555. cmELF::StringEntry const* se[2] = { nullptr, nullptr };
  2556. if (cmELF::StringEntry const* se_rpath = elf.GetRPath()) {
  2557. se[se_count++] = se_rpath;
  2558. }
  2559. if (cmELF::StringEntry const* se_runpath = elf.GetRunPath()) {
  2560. se[se_count++] = se_runpath;
  2561. }
  2562. if (se_count == 0) {
  2563. // There is no RPATH or RUNPATH anyway.
  2564. return true;
  2565. }
  2566. if (se_count == 2 && se[1]->IndexInSection < se[0]->IndexInSection) {
  2567. std::swap(se[0], se[1]);
  2568. }
  2569. // Obtain a copy of the dynamic entries
  2570. cmELF::DynamicEntryList dentries = elf.GetDynamicEntries();
  2571. if (dentries.empty()) {
  2572. // This should happen only for invalid ELF files where a DT_NULL
  2573. // appears before the end of the table.
  2574. if (emsg) {
  2575. *emsg = "DYNAMIC section contains a DT_NULL before the end.";
  2576. }
  2577. return false;
  2578. }
  2579. // Save information about the string entries to be zeroed.
  2580. zeroCount = se_count;
  2581. for (int i = 0; i < se_count; ++i) {
  2582. zeroPosition[i] = se[i]->Position;
  2583. zeroSize[i] = se[i]->Size;
  2584. }
  2585. // Get size of one DYNAMIC entry
  2586. unsigned long const sizeof_dentry =
  2587. elf.GetDynamicEntryPosition(1) - elf.GetDynamicEntryPosition(0);
  2588. // Adjust the entry list as necessary to remove the run path
  2589. unsigned long entriesErased = 0;
  2590. for (auto it = dentries.begin(); it != dentries.end();) {
  2591. if (it->first == cmELF::TagRPath || it->first == cmELF::TagRunPath) {
  2592. it = dentries.erase(it);
  2593. entriesErased++;
  2594. continue;
  2595. }
  2596. if (cmELF::TagMipsRldMapRel != 0 &&
  2597. it->first == cmELF::TagMipsRldMapRel) {
  2598. // Background: debuggers need to know the "linker map" which contains
  2599. // the addresses each dynamic object is loaded at. Most arches use
  2600. // the DT_DEBUG tag which the dynamic linker writes to (directly) and
  2601. // contain the location of the linker map, however on MIPS the
  2602. // .dynamic section is always read-only so this is not possible. MIPS
  2603. // objects instead contain a DT_MIPS_RLD_MAP tag which contains the
  2604. // address where the dynamic linker will write to (an indirect
  2605. // version of DT_DEBUG). Since this doesn't work when using PIE, a
  2606. // relative equivalent was created - DT_MIPS_RLD_MAP_REL. Since this
  2607. // version contains a relative offset, moving it changes the
  2608. // calculated address. This may cause the dynamic linker to write
  2609. // into memory it should not be changing.
  2610. //
  2611. // To fix this, we adjust the value of DT_MIPS_RLD_MAP_REL here. If
  2612. // we move it up by n bytes, we add n bytes to the value of this tag.
  2613. it->second += entriesErased * sizeof_dentry;
  2614. }
  2615. it++;
  2616. }
  2617. // Encode new entries list
  2618. bytes = elf.EncodeDynamicEntries(dentries);
  2619. bytesBegin = elf.GetDynamicEntryPosition(0);
  2620. }
  2621. // Open the file for update.
  2622. cmsys::ofstream f(file.c_str(),
  2623. std::ios::in | std::ios::out | std::ios::binary);
  2624. if (!f) {
  2625. if (emsg) {
  2626. *emsg = "Error opening file for update.";
  2627. }
  2628. return false;
  2629. }
  2630. // Write the new DYNAMIC table header.
  2631. if (!f.seekp(bytesBegin)) {
  2632. if (emsg) {
  2633. *emsg = "Error seeking to DYNAMIC table header for RPATH.";
  2634. }
  2635. return false;
  2636. }
  2637. if (!f.write(&bytes[0], bytes.size())) {
  2638. if (emsg) {
  2639. *emsg = "Error replacing DYNAMIC table header.";
  2640. }
  2641. return false;
  2642. }
  2643. // Fill the RPATH and RUNPATH strings with zero bytes.
  2644. for (int i = 0; i < zeroCount; ++i) {
  2645. if (!f.seekp(zeroPosition[i])) {
  2646. if (emsg) {
  2647. *emsg = "Error seeking to RPATH position.";
  2648. }
  2649. return false;
  2650. }
  2651. for (unsigned long j = 0; j < zeroSize[i]; ++j) {
  2652. f << '\0';
  2653. }
  2654. if (!f) {
  2655. if (emsg) {
  2656. *emsg = "Error writing the empty rpath string to the file.";
  2657. }
  2658. return false;
  2659. }
  2660. }
  2661. // Everything was updated successfully.
  2662. if (removed) {
  2663. *removed = true;
  2664. }
  2665. return true;
  2666. }
  2667. #elif defined(CMake_USE_XCOFF_PARSER)
  2668. bool cmSystemTools::RemoveRPath(std::string const& file, std::string* emsg,
  2669. bool* removed)
  2670. {
  2671. if (removed) {
  2672. *removed = false;
  2673. }
  2674. cmXCOFF xcoff(file.c_str(), cmXCOFF::Mode::ReadWrite);
  2675. bool rm = xcoff.RemoveLibPath();
  2676. if (!xcoff) {
  2677. if (emsg) {
  2678. *emsg = xcoff.GetErrorMessage();
  2679. }
  2680. return false;
  2681. }
  2682. if (removed) {
  2683. *removed = rm;
  2684. }
  2685. return true;
  2686. }
  2687. #else
  2688. bool cmSystemTools::RemoveRPath(std::string const& /*file*/,
  2689. std::string* /*emsg*/, bool* /*removed*/)
  2690. {
  2691. return false;
  2692. }
  2693. #endif
  2694. // FIXME: Dispatch if multiple formats are supported.
  2695. bool cmSystemTools::CheckRPath(std::string const& file,
  2696. std::string const& newRPath)
  2697. {
  2698. #if defined(CMake_USE_ELF_PARSER)
  2699. // Parse the ELF binary.
  2700. cmELF elf(file.c_str());
  2701. // Get the RPATH or RUNPATH entry from it.
  2702. cmELF::StringEntry const* se = elf.GetRPath();
  2703. if (!se) {
  2704. se = elf.GetRunPath();
  2705. }
  2706. // Make sure the current rpath contains the new rpath.
  2707. if (newRPath.empty()) {
  2708. if (!se) {
  2709. return true;
  2710. }
  2711. } else {
  2712. if (se &&
  2713. cmSystemToolsFindRPath(se->Value, newRPath) != std::string::npos) {
  2714. return true;
  2715. }
  2716. }
  2717. return false;
  2718. #elif defined(CMake_USE_XCOFF_PARSER)
  2719. // Parse the XCOFF binary.
  2720. cmXCOFF xcoff(file.c_str());
  2721. if (cm::optional<cm::string_view> libPath = xcoff.GetLibPath()) {
  2722. if (cmSystemToolsFindRPath(*libPath, newRPath) != std::string::npos) {
  2723. return true;
  2724. }
  2725. }
  2726. return false;
  2727. #else
  2728. (void)file;
  2729. (void)newRPath;
  2730. return false;
  2731. #endif
  2732. }
  2733. bool cmSystemTools::RepeatedRemoveDirectory(const std::string& dir)
  2734. {
  2735. #ifdef _WIN32
  2736. // Windows sometimes locks files temporarily so try a few times.
  2737. WindowsFileRetry retry = cmSystemTools::GetWindowsFileRetry();
  2738. for (unsigned int i = 0; i < retry.Count; ++i) {
  2739. if (cmSystemTools::RemoveADirectory(dir)) {
  2740. return true;
  2741. }
  2742. cmSystemTools::Delay(retry.Delay);
  2743. }
  2744. return false;
  2745. #else
  2746. return cmSystemTools::RemoveADirectory(dir);
  2747. #endif
  2748. }
  2749. std::string cmSystemTools::EncodeURL(std::string const& in, bool escapeSlashes)
  2750. {
  2751. std::string out;
  2752. for (char c : in) {
  2753. char hexCh[4] = { 0, 0, 0, 0 };
  2754. hexCh[0] = c;
  2755. switch (c) {
  2756. case '+':
  2757. case '?':
  2758. case '\\':
  2759. case '&':
  2760. case ' ':
  2761. case '=':
  2762. case '%':
  2763. sprintf(hexCh, "%%%02X", static_cast<int>(c));
  2764. break;
  2765. case '/':
  2766. if (escapeSlashes) {
  2767. strcpy(hexCh, "%2F");
  2768. }
  2769. break;
  2770. default:
  2771. break;
  2772. }
  2773. out.append(hexCh);
  2774. }
  2775. return out;
  2776. }
  2777. bool cmSystemTools::CreateSymlink(const std::string& origName,
  2778. const std::string& newName,
  2779. std::string* errorMessage)
  2780. {
  2781. uv_fs_t req;
  2782. int flags = 0;
  2783. #if defined(_WIN32)
  2784. if (cmsys::SystemTools::FileIsDirectory(origName)) {
  2785. flags |= UV_FS_SYMLINK_DIR;
  2786. }
  2787. #endif
  2788. int err = uv_fs_symlink(nullptr, &req, origName.c_str(), newName.c_str(),
  2789. flags, nullptr);
  2790. if (err) {
  2791. std::string e =
  2792. "failed to create symbolic link '" + newName + "': " + uv_strerror(err);
  2793. if (errorMessage) {
  2794. *errorMessage = std::move(e);
  2795. } else {
  2796. cmSystemTools::Error(e);
  2797. }
  2798. return false;
  2799. }
  2800. return true;
  2801. }
  2802. bool cmSystemTools::CreateLink(const std::string& origName,
  2803. const std::string& newName,
  2804. std::string* errorMessage)
  2805. {
  2806. uv_fs_t req;
  2807. int err =
  2808. uv_fs_link(nullptr, &req, origName.c_str(), newName.c_str(), nullptr);
  2809. if (err) {
  2810. std::string e =
  2811. "failed to create link '" + newName + "': " + uv_strerror(err);
  2812. if (errorMessage) {
  2813. *errorMessage = std::move(e);
  2814. } else {
  2815. cmSystemTools::Error(e);
  2816. }
  2817. return false;
  2818. }
  2819. return true;
  2820. }