cmSystemTools.cxx 80 KB

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