cmSystemTools.cxx 81 KB

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