cmSystemTools.cxx 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771
  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. void cmSystemTools::MoveFileIfDifferent(const std::string& source,
  785. const std::string& destination)
  786. {
  787. if (FilesDiffer(source, destination)) {
  788. if (RenameFile(source, destination)) {
  789. return;
  790. }
  791. CopyFileAlways(source, destination);
  792. }
  793. RemoveFile(source);
  794. }
  795. std::string cmSystemTools::ComputeFileHash(const std::string& source,
  796. cmCryptoHash::Algo algo)
  797. {
  798. #if !defined(CMAKE_BOOTSTRAP)
  799. cmCryptoHash hash(algo);
  800. return hash.HashFile(source);
  801. #else
  802. (void)source;
  803. cmSystemTools::Message("hashsum not supported in bootstrapping mode",
  804. "Error");
  805. return std::string();
  806. #endif
  807. }
  808. std::string cmSystemTools::ComputeStringMD5(const std::string& input)
  809. {
  810. #if !defined(CMAKE_BOOTSTRAP)
  811. cmCryptoHash md5(cmCryptoHash::AlgoMD5);
  812. return md5.HashString(input);
  813. #else
  814. (void)input;
  815. cmSystemTools::Message("md5sum not supported in bootstrapping mode",
  816. "Error");
  817. return "";
  818. #endif
  819. }
  820. std::string cmSystemTools::ComputeCertificateThumbprint(
  821. const std::string& source)
  822. {
  823. std::string thumbprint;
  824. #if !defined(CMAKE_BOOTSTRAP) && defined(_WIN32)
  825. BYTE* certData = NULL;
  826. CRYPT_INTEGER_BLOB cryptBlob;
  827. HCERTSTORE certStore = NULL;
  828. PCCERT_CONTEXT certContext = NULL;
  829. HANDLE certFile = CreateFileW(
  830. cmsys::Encoding::ToWide(source.c_str()).c_str(), GENERIC_READ,
  831. FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  832. if (certFile != INVALID_HANDLE_VALUE && certFile != NULL) {
  833. DWORD fileSize = GetFileSize(certFile, NULL);
  834. if (fileSize != INVALID_FILE_SIZE) {
  835. certData = new BYTE[fileSize];
  836. if (certData != NULL) {
  837. DWORD dwRead = 0;
  838. if (ReadFile(certFile, certData, fileSize, &dwRead, NULL)) {
  839. cryptBlob.cbData = fileSize;
  840. cryptBlob.pbData = certData;
  841. // Verify that this is a valid cert
  842. if (PFXIsPFXBlob(&cryptBlob)) {
  843. // Open the certificate as a store
  844. certStore = PFXImportCertStore(&cryptBlob, NULL, CRYPT_EXPORTABLE);
  845. if (certStore != NULL) {
  846. // There should only be 1 cert.
  847. certContext =
  848. CertEnumCertificatesInStore(certStore, certContext);
  849. if (certContext != NULL) {
  850. // The hash is 20 bytes
  851. BYTE hashData[20];
  852. DWORD hashLength = 20;
  853. // Buffer to print the hash. Each byte takes 2 chars +
  854. // terminating character
  855. char hashPrint[41];
  856. char* pHashPrint = hashPrint;
  857. // Get the hash property from the certificate
  858. if (CertGetCertificateContextProperty(
  859. certContext, CERT_HASH_PROP_ID, hashData, &hashLength)) {
  860. for (DWORD i = 0; i < hashLength; i++) {
  861. // Convert each byte to hexadecimal
  862. sprintf(pHashPrint, "%02X", hashData[i]);
  863. pHashPrint += 2;
  864. }
  865. *pHashPrint = '\0';
  866. thumbprint = hashPrint;
  867. }
  868. CertFreeCertificateContext(certContext);
  869. }
  870. CertCloseStore(certStore, 0);
  871. }
  872. }
  873. }
  874. delete[] certData;
  875. }
  876. }
  877. CloseHandle(certFile);
  878. }
  879. #else
  880. (void)source;
  881. cmSystemTools::Message("ComputeCertificateThumbprint is not implemented",
  882. "Error");
  883. #endif
  884. return thumbprint;
  885. }
  886. void cmSystemTools::Glob(const std::string& directory,
  887. const std::string& regexp,
  888. std::vector<std::string>& files)
  889. {
  890. cmsys::Directory d;
  891. cmsys::RegularExpression reg(regexp.c_str());
  892. if (d.Load(directory)) {
  893. size_t numf;
  894. unsigned int i;
  895. numf = d.GetNumberOfFiles();
  896. for (i = 0; i < numf; i++) {
  897. std::string fname = d.GetFile(i);
  898. if (reg.find(fname)) {
  899. files.push_back(std::move(fname));
  900. }
  901. }
  902. }
  903. }
  904. void cmSystemTools::GlobDirs(const std::string& path,
  905. std::vector<std::string>& files)
  906. {
  907. std::string::size_type pos = path.find("/*");
  908. if (pos == std::string::npos) {
  909. files.push_back(path);
  910. return;
  911. }
  912. std::string startPath = path.substr(0, pos);
  913. std::string finishPath = path.substr(pos + 2);
  914. cmsys::Directory d;
  915. if (d.Load(startPath)) {
  916. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i) {
  917. if ((std::string(d.GetFile(i)) != ".") &&
  918. (std::string(d.GetFile(i)) != "..")) {
  919. std::string fname = cmStrCat(startPath, '/', d.GetFile(i));
  920. if (cmSystemTools::FileIsDirectory(fname)) {
  921. fname += finishPath;
  922. cmSystemTools::GlobDirs(fname, files);
  923. }
  924. }
  925. }
  926. }
  927. }
  928. bool cmSystemTools::SimpleGlob(const std::string& glob,
  929. std::vector<std::string>& files,
  930. int type /* = 0 */)
  931. {
  932. files.clear();
  933. if (glob.back() != '*') {
  934. return false;
  935. }
  936. std::string path = cmSystemTools::GetFilenamePath(glob);
  937. std::string ppath = cmSystemTools::GetFilenameName(glob);
  938. ppath = ppath.substr(0, ppath.size() - 1);
  939. if (path.empty()) {
  940. path = "/";
  941. }
  942. bool res = false;
  943. cmsys::Directory d;
  944. if (d.Load(path)) {
  945. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i) {
  946. if ((std::string(d.GetFile(i)) != ".") &&
  947. (std::string(d.GetFile(i)) != "..")) {
  948. std::string fname = path;
  949. if (path.back() != '/') {
  950. fname += "/";
  951. }
  952. fname += d.GetFile(i);
  953. std::string sfname = d.GetFile(i);
  954. if (type > 0 && cmSystemTools::FileIsDirectory(fname)) {
  955. continue;
  956. }
  957. if (type < 0 && !cmSystemTools::FileIsDirectory(fname)) {
  958. continue;
  959. }
  960. if (sfname.size() >= ppath.size() &&
  961. sfname.substr(0, ppath.size()) == ppath) {
  962. files.push_back(fname);
  963. res = true;
  964. }
  965. }
  966. }
  967. }
  968. return res;
  969. }
  970. std::string cmSystemTools::ConvertToOutputPath(std::string const& path)
  971. {
  972. #if defined(_WIN32) && !defined(__CYGWIN__)
  973. if (s_ForceUnixPaths) {
  974. return cmSystemTools::ConvertToUnixOutputPath(path);
  975. }
  976. return cmSystemTools::ConvertToWindowsOutputPath(path);
  977. #else
  978. return cmSystemTools::ConvertToUnixOutputPath(path);
  979. #endif
  980. }
  981. void cmSystemTools::ConvertToOutputSlashes(std::string& path)
  982. {
  983. #if defined(_WIN32) && !defined(__CYGWIN__)
  984. if (!s_ForceUnixPaths) {
  985. // Convert to windows slashes.
  986. std::string::size_type pos = 0;
  987. while ((pos = path.find('/', pos)) != std::string::npos) {
  988. path[pos++] = '\\';
  989. }
  990. }
  991. #else
  992. static_cast<void>(path);
  993. #endif
  994. }
  995. std::string cmSystemTools::ConvertToRunCommandPath(const std::string& path)
  996. {
  997. #if defined(_WIN32) && !defined(__CYGWIN__)
  998. return cmSystemTools::ConvertToWindowsOutputPath(path);
  999. #else
  1000. return cmSystemTools::ConvertToUnixOutputPath(path);
  1001. #endif
  1002. }
  1003. // compute the relative path from here to there
  1004. std::string cmSystemTools::RelativePath(std::string const& local,
  1005. std::string const& remote)
  1006. {
  1007. if (!cmSystemTools::FileIsFullPath(local)) {
  1008. cmSystemTools::Error("RelativePath must be passed a full path to local: " +
  1009. local);
  1010. }
  1011. if (!cmSystemTools::FileIsFullPath(remote)) {
  1012. cmSystemTools::Error(
  1013. "RelativePath must be passed a full path to remote: " + remote);
  1014. }
  1015. return cmsys::SystemTools::RelativePath(local, remote);
  1016. }
  1017. std::string cmSystemTools::ForceToRelativePath(std::string const& local_path,
  1018. std::string const& remote_path)
  1019. {
  1020. // The paths should never be quoted.
  1021. assert(local_path.front() != '\"');
  1022. assert(remote_path.front() != '\"');
  1023. // The local path should never have a trailing slash.
  1024. assert(local_path.empty() || local_path.back() != '/');
  1025. // If the path is already relative then just return the path.
  1026. if (!cmSystemTools::FileIsFullPath(remote_path)) {
  1027. return remote_path;
  1028. }
  1029. // Identify the longest shared path component between the remote
  1030. // path and the local path.
  1031. std::vector<std::string> local;
  1032. cmSystemTools::SplitPath(local_path, local);
  1033. std::vector<std::string> remote;
  1034. cmSystemTools::SplitPath(remote_path, remote);
  1035. unsigned int common = 0;
  1036. while (common < remote.size() && common < local.size() &&
  1037. cmSystemTools::ComparePath(remote[common], local[common])) {
  1038. ++common;
  1039. }
  1040. // If no part of the path is in common then return the full path.
  1041. if (common == 0) {
  1042. return remote_path;
  1043. }
  1044. // If the entire path is in common then just return a ".".
  1045. if (common == remote.size() && common == local.size()) {
  1046. return ".";
  1047. }
  1048. // If the entire path is in common except for a trailing slash then
  1049. // just return a "./".
  1050. if (common + 1 == remote.size() && remote[common].empty() &&
  1051. common == local.size()) {
  1052. return "./";
  1053. }
  1054. // Construct the relative path.
  1055. std::string relative;
  1056. // First add enough ../ to get up to the level of the shared portion
  1057. // of the path. Leave off the trailing slash. Note that the last
  1058. // component of local will never be empty because local should never
  1059. // have a trailing slash.
  1060. for (unsigned int i = common; i < local.size(); ++i) {
  1061. relative += "..";
  1062. if (i < local.size() - 1) {
  1063. relative += "/";
  1064. }
  1065. }
  1066. // Now add the portion of the destination path that is not included
  1067. // in the shared portion of the path. Add a slash the first time
  1068. // only if there was already something in the path. If there was a
  1069. // trailing slash in the input then the last iteration of the loop
  1070. // will add a slash followed by an empty string which will preserve
  1071. // the trailing slash in the output.
  1072. if (!relative.empty() && !remote.empty()) {
  1073. relative += "/";
  1074. }
  1075. relative += cmJoin(cmMakeRange(remote).advance(common), "/");
  1076. // Finally return the path.
  1077. return relative;
  1078. }
  1079. #ifndef CMAKE_BOOTSTRAP
  1080. bool cmSystemTools::UnsetEnv(const char* value)
  1081. {
  1082. # if !defined(HAVE_UNSETENV)
  1083. std::string var = cmStrCat(value, '=');
  1084. return cmSystemTools::PutEnv(var.c_str());
  1085. # else
  1086. unsetenv(value);
  1087. return true;
  1088. # endif
  1089. }
  1090. std::vector<std::string> cmSystemTools::GetEnvironmentVariables()
  1091. {
  1092. std::vector<std::string> env;
  1093. int cc;
  1094. for (cc = 0; environ[cc]; ++cc) {
  1095. env.emplace_back(environ[cc]);
  1096. }
  1097. return env;
  1098. }
  1099. void cmSystemTools::AppendEnv(std::vector<std::string> const& env)
  1100. {
  1101. for (std::string const& eit : env) {
  1102. cmSystemTools::PutEnv(eit);
  1103. }
  1104. }
  1105. cmSystemTools::SaveRestoreEnvironment::SaveRestoreEnvironment()
  1106. {
  1107. this->Env = cmSystemTools::GetEnvironmentVariables();
  1108. }
  1109. cmSystemTools::SaveRestoreEnvironment::~SaveRestoreEnvironment()
  1110. {
  1111. // First clear everything in the current environment:
  1112. std::vector<std::string> currentEnv = GetEnvironmentVariables();
  1113. for (std::string var : currentEnv) {
  1114. std::string::size_type pos = var.find('=');
  1115. if (pos != std::string::npos) {
  1116. var = var.substr(0, pos);
  1117. }
  1118. cmSystemTools::UnsetEnv(var.c_str());
  1119. }
  1120. // Then put back each entry from the original environment:
  1121. cmSystemTools::AppendEnv(this->Env);
  1122. }
  1123. #endif
  1124. void cmSystemTools::EnableVSConsoleOutput()
  1125. {
  1126. #ifdef _WIN32
  1127. // Visual Studio tools like devenv may not
  1128. // display output to the console unless this environment variable is
  1129. // set. We need it to capture the output of these build tools.
  1130. // Note for future work that one could pass "/out \\.\pipe\NAME" to
  1131. // either of these executables where NAME is created with
  1132. // CreateNamedPipe. This would bypass the internal buffering of the
  1133. // output and allow it to be captured on the fly.
  1134. cmSystemTools::PutEnv("vsconsoleoutput=1");
  1135. # ifndef CMAKE_BOOTSTRAP
  1136. // VS sets an environment variable to tell MS tools like "cl" to report
  1137. // output through a backdoor pipe instead of stdout/stderr. Unset the
  1138. // environment variable to close this backdoor for any path of process
  1139. // invocations that passes through CMake so we can capture the output.
  1140. cmSystemTools::UnsetEnv("VS_UNICODE_OUTPUT");
  1141. # endif
  1142. #endif
  1143. }
  1144. bool cmSystemTools::IsPathToFramework(const std::string& path)
  1145. {
  1146. return (cmSystemTools::FileIsFullPath(path) &&
  1147. cmHasLiteralSuffix(path, ".framework"));
  1148. }
  1149. bool cmSystemTools::CreateTar(const std::string& outFileName,
  1150. const std::vector<std::string>& files,
  1151. cmTarCompression compressType, bool verbose,
  1152. std::string const& mtime,
  1153. std::string const& format)
  1154. {
  1155. #if !defined(CMAKE_BOOTSTRAP)
  1156. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1157. cmsys::ofstream fout(outFileName.c_str(), std::ios::out | std::ios::binary);
  1158. if (!fout) {
  1159. std::string e = cmStrCat("Cannot open output file \"", outFileName,
  1160. "\": ", cmSystemTools::GetLastSystemError());
  1161. cmSystemTools::Error(e);
  1162. return false;
  1163. }
  1164. cmArchiveWrite::Compress compress = cmArchiveWrite::CompressNone;
  1165. switch (compressType) {
  1166. case TarCompressGZip:
  1167. compress = cmArchiveWrite::CompressGZip;
  1168. break;
  1169. case TarCompressBZip2:
  1170. compress = cmArchiveWrite::CompressBZip2;
  1171. break;
  1172. case TarCompressXZ:
  1173. compress = cmArchiveWrite::CompressXZ;
  1174. break;
  1175. case TarCompressZstd:
  1176. compress = cmArchiveWrite::CompressZstd;
  1177. break;
  1178. case TarCompressNone:
  1179. compress = cmArchiveWrite::CompressNone;
  1180. break;
  1181. }
  1182. cmArchiveWrite a(fout, compress, format.empty() ? "paxr" : format);
  1183. a.SetMTime(mtime);
  1184. a.SetVerbose(verbose);
  1185. bool tarCreatedSuccessfully = true;
  1186. for (auto path : files) {
  1187. if (cmSystemTools::FileIsFullPath(path)) {
  1188. // Get the relative path to the file.
  1189. path = cmSystemTools::RelativePath(cwd, path);
  1190. }
  1191. if (!a.Add(path)) {
  1192. cmSystemTools::Error(a.GetError());
  1193. tarCreatedSuccessfully = false;
  1194. }
  1195. }
  1196. return tarCreatedSuccessfully;
  1197. #else
  1198. (void)outFileName;
  1199. (void)files;
  1200. (void)verbose;
  1201. return false;
  1202. #endif
  1203. }
  1204. #if !defined(CMAKE_BOOTSTRAP)
  1205. namespace {
  1206. # define BSDTAR_FILESIZE_PRINTF "%lu"
  1207. # define BSDTAR_FILESIZE_TYPE unsigned long
  1208. void list_item_verbose(FILE* out, struct archive_entry* entry)
  1209. {
  1210. char tmp[100];
  1211. size_t w;
  1212. const char* p;
  1213. const char* fmt;
  1214. time_t tim;
  1215. static time_t now;
  1216. size_t u_width = 6;
  1217. size_t gs_width = 13;
  1218. /*
  1219. * We avoid collecting the entire list in memory at once by
  1220. * listing things as we see them. However, that also means we can't
  1221. * just pre-compute the field widths. Instead, we start with guesses
  1222. * and just widen them as necessary. These numbers are completely
  1223. * arbitrary.
  1224. */
  1225. if (!now) {
  1226. time(&now);
  1227. }
  1228. fprintf(out, "%s %d ", archive_entry_strmode(entry),
  1229. archive_entry_nlink(entry));
  1230. /* Use uname if it's present, else uid. */
  1231. p = archive_entry_uname(entry);
  1232. if ((p == nullptr) || (*p == '\0')) {
  1233. sprintf(tmp, "%lu ", static_cast<unsigned long>(archive_entry_uid(entry)));
  1234. p = tmp;
  1235. }
  1236. w = strlen(p);
  1237. if (w > u_width) {
  1238. u_width = w;
  1239. }
  1240. fprintf(out, "%-*s ", static_cast<int>(u_width), p);
  1241. /* Use gname if it's present, else gid. */
  1242. p = archive_entry_gname(entry);
  1243. if (p != nullptr && p[0] != '\0') {
  1244. fprintf(out, "%s", p);
  1245. w = strlen(p);
  1246. } else {
  1247. sprintf(tmp, "%lu", static_cast<unsigned long>(archive_entry_gid(entry)));
  1248. w = strlen(tmp);
  1249. fprintf(out, "%s", tmp);
  1250. }
  1251. /*
  1252. * Print device number or file size, right-aligned so as to make
  1253. * total width of group and devnum/filesize fields be gs_width.
  1254. * If gs_width is too small, grow it.
  1255. */
  1256. if (archive_entry_filetype(entry) == AE_IFCHR ||
  1257. archive_entry_filetype(entry) == AE_IFBLK) {
  1258. unsigned long rdevmajor = archive_entry_rdevmajor(entry);
  1259. unsigned long rdevminor = archive_entry_rdevminor(entry);
  1260. sprintf(tmp, "%lu,%lu", rdevmajor, rdevminor);
  1261. } else {
  1262. /*
  1263. * Note the use of platform-dependent macros to format
  1264. * the filesize here. We need the format string and the
  1265. * corresponding type for the cast.
  1266. */
  1267. sprintf(tmp, BSDTAR_FILESIZE_PRINTF,
  1268. static_cast<BSDTAR_FILESIZE_TYPE>(archive_entry_size(entry)));
  1269. }
  1270. if (w + strlen(tmp) >= gs_width) {
  1271. gs_width = w + strlen(tmp) + 1;
  1272. }
  1273. fprintf(out, "%*s", static_cast<int>(gs_width - w), tmp);
  1274. /* Format the time using 'ls -l' conventions. */
  1275. tim = archive_entry_mtime(entry);
  1276. # define HALF_YEAR ((time_t)365 * 86400 / 2)
  1277. # if defined(_WIN32) && !defined(__CYGWIN__)
  1278. /* Windows' strftime function does not support %e format. */
  1279. # define DAY_FMT "%d"
  1280. # else
  1281. # define DAY_FMT "%e" /* Day number without leading zeros */
  1282. # endif
  1283. if (tim < now - HALF_YEAR || tim > now + HALF_YEAR) {
  1284. fmt = DAY_FMT " %b %Y";
  1285. } else {
  1286. fmt = DAY_FMT " %b %H:%M";
  1287. }
  1288. strftime(tmp, sizeof(tmp), fmt, localtime(&tim));
  1289. fprintf(out, " %s ", tmp);
  1290. fprintf(out, "%s", cm_archive_entry_pathname(entry).c_str());
  1291. /* Extra information for links. */
  1292. if (archive_entry_hardlink(entry)) /* Hard link */
  1293. {
  1294. fprintf(out, " link to %s", archive_entry_hardlink(entry));
  1295. } else if (archive_entry_symlink(entry)) /* Symbolic link */
  1296. {
  1297. fprintf(out, " -> %s", archive_entry_symlink(entry));
  1298. }
  1299. fflush(out);
  1300. }
  1301. void ArchiveError(const char* m1, struct archive* a)
  1302. {
  1303. std::string message(m1);
  1304. const char* m2 = archive_error_string(a);
  1305. if (m2) {
  1306. message += m2;
  1307. }
  1308. cmSystemTools::Error(message);
  1309. }
  1310. bool la_diagnostic(struct archive* ar, __LA_SSIZE_T r)
  1311. {
  1312. // See archive.h definition of ARCHIVE_OK for return values.
  1313. if (r >= ARCHIVE_OK) {
  1314. return true;
  1315. }
  1316. if (r >= ARCHIVE_WARN) {
  1317. const char* warn = archive_error_string(ar);
  1318. if (!warn) {
  1319. warn = "unknown warning";
  1320. }
  1321. std::cerr << "cmake -E tar: warning: " << warn << '\n';
  1322. return true;
  1323. }
  1324. // Error.
  1325. const char* err = archive_error_string(ar);
  1326. if (!err) {
  1327. err = "unknown error";
  1328. }
  1329. std::cerr << "cmake -E tar: error: " << err << '\n';
  1330. return false;
  1331. }
  1332. // Return 'true' on success
  1333. bool copy_data(struct archive* ar, struct archive* aw)
  1334. {
  1335. long r;
  1336. const void* buff;
  1337. size_t size;
  1338. # if defined(ARCHIVE_VERSION_NUMBER) && ARCHIVE_VERSION_NUMBER >= 3000000
  1339. __LA_INT64_T offset;
  1340. # else
  1341. off_t offset;
  1342. # endif
  1343. for (;;) {
  1344. // See archive.h definition of ARCHIVE_OK for return values.
  1345. r = archive_read_data_block(ar, &buff, &size, &offset);
  1346. if (r == ARCHIVE_EOF) {
  1347. return true;
  1348. }
  1349. if (!la_diagnostic(ar, r)) {
  1350. return false;
  1351. }
  1352. // See archive.h definition of ARCHIVE_OK for return values.
  1353. __LA_SSIZE_T const w = archive_write_data_block(aw, buff, size, offset);
  1354. if (!la_diagnostic(ar, w)) {
  1355. return false;
  1356. }
  1357. }
  1358. # if !defined(__clang__) && !defined(__HP_aCC)
  1359. return false; /* this should not happen but it quiets some compilers */
  1360. # endif
  1361. }
  1362. bool extract_tar(const std::string& outFileName,
  1363. const std::vector<std::string>& files, bool verbose,
  1364. bool extract)
  1365. {
  1366. cmLocaleRAII localeRAII;
  1367. static_cast<void>(localeRAII);
  1368. struct archive* a = archive_read_new();
  1369. struct archive* ext = archive_write_disk_new();
  1370. archive_read_support_filter_all(a);
  1371. archive_read_support_format_all(a);
  1372. struct archive_entry* entry;
  1373. struct archive* matching = archive_match_new();
  1374. if (matching == nullptr) {
  1375. cmSystemTools::Error("Out of memory");
  1376. return false;
  1377. }
  1378. for (const auto& filename : files) {
  1379. if (archive_match_include_pattern(matching, filename.c_str()) !=
  1380. ARCHIVE_OK) {
  1381. cmSystemTools::Error("Failed to add to inclusion list: " + filename);
  1382. return false;
  1383. }
  1384. }
  1385. int r = cm_archive_read_open_file(a, outFileName.c_str(), 10240);
  1386. if (r) {
  1387. ArchiveError("Problem with archive_read_open_file(): ", a);
  1388. archive_write_free(ext);
  1389. archive_read_close(a);
  1390. return false;
  1391. }
  1392. for (;;) {
  1393. r = archive_read_next_header(a, &entry);
  1394. if (r == ARCHIVE_EOF) {
  1395. break;
  1396. }
  1397. if (r != ARCHIVE_OK) {
  1398. ArchiveError("Problem with archive_read_next_header(): ", a);
  1399. break;
  1400. }
  1401. if (archive_match_excluded(matching, entry)) {
  1402. continue;
  1403. }
  1404. if (verbose) {
  1405. if (extract) {
  1406. cmSystemTools::Stdout("x ");
  1407. cmSystemTools::Stdout(cm_archive_entry_pathname(entry));
  1408. } else {
  1409. list_item_verbose(stdout, entry);
  1410. }
  1411. cmSystemTools::Stdout("\n");
  1412. } else if (!extract) {
  1413. cmSystemTools::Stdout(cm_archive_entry_pathname(entry));
  1414. cmSystemTools::Stdout("\n");
  1415. }
  1416. if (extract) {
  1417. r = archive_write_disk_set_options(ext, ARCHIVE_EXTRACT_TIME);
  1418. if (r != ARCHIVE_OK) {
  1419. ArchiveError("Problem with archive_write_disk_set_options(): ", ext);
  1420. break;
  1421. }
  1422. r = archive_write_header(ext, entry);
  1423. if (r == ARCHIVE_OK) {
  1424. if (!copy_data(a, ext)) {
  1425. break;
  1426. }
  1427. r = archive_write_finish_entry(ext);
  1428. if (r != ARCHIVE_OK) {
  1429. ArchiveError("Problem with archive_write_finish_entry(): ", ext);
  1430. break;
  1431. }
  1432. }
  1433. # ifdef _WIN32
  1434. else if (const char* linktext = archive_entry_symlink(entry)) {
  1435. std::cerr << "cmake -E tar: warning: skipping symbolic link \""
  1436. << cm_archive_entry_pathname(entry) << "\" -> \"" << linktext
  1437. << "\"." << std::endl;
  1438. }
  1439. # endif
  1440. else {
  1441. ArchiveError("Problem with archive_write_header(): ", ext);
  1442. cmSystemTools::Error("Current file: " +
  1443. cm_archive_entry_pathname(entry));
  1444. break;
  1445. }
  1446. }
  1447. }
  1448. bool error_occured = false;
  1449. if (matching != nullptr) {
  1450. const char* p;
  1451. int ar;
  1452. while ((ar = archive_match_path_unmatched_inclusions_next(matching, &p)) ==
  1453. ARCHIVE_OK) {
  1454. cmSystemTools::Error("tar: " + std::string(p) +
  1455. ": Not found in archive");
  1456. error_occured = true;
  1457. }
  1458. if (error_occured) {
  1459. return false;
  1460. }
  1461. if (ar == ARCHIVE_FATAL) {
  1462. cmSystemTools::Error("tar: Out of memory");
  1463. return false;
  1464. }
  1465. }
  1466. archive_match_free(matching);
  1467. archive_write_free(ext);
  1468. archive_read_close(a);
  1469. archive_read_free(a);
  1470. return r == ARCHIVE_EOF || r == ARCHIVE_OK;
  1471. }
  1472. }
  1473. #endif
  1474. bool cmSystemTools::ExtractTar(const std::string& outFileName,
  1475. const std::vector<std::string>& files,
  1476. bool verbose)
  1477. {
  1478. #if !defined(CMAKE_BOOTSTRAP)
  1479. return extract_tar(outFileName, files, verbose, true);
  1480. #else
  1481. (void)outFileName;
  1482. (void)files;
  1483. (void)verbose;
  1484. return false;
  1485. #endif
  1486. }
  1487. bool cmSystemTools::ListTar(const std::string& outFileName,
  1488. const std::vector<std::string>& files,
  1489. bool verbose)
  1490. {
  1491. #if !defined(CMAKE_BOOTSTRAP)
  1492. return extract_tar(outFileName, files, verbose, false);
  1493. #else
  1494. (void)outFileName;
  1495. (void)files;
  1496. (void)verbose;
  1497. return false;
  1498. #endif
  1499. }
  1500. int cmSystemTools::WaitForLine(cmsysProcess* process, std::string& line,
  1501. cmDuration timeout, std::vector<char>& out,
  1502. std::vector<char>& err)
  1503. {
  1504. line.clear();
  1505. auto outiter = out.begin();
  1506. auto erriter = err.begin();
  1507. cmProcessOutput processOutput;
  1508. std::string strdata;
  1509. while (true) {
  1510. // Check for a newline in stdout.
  1511. for (; outiter != out.end(); ++outiter) {
  1512. if ((*outiter == '\r') && ((outiter + 1) == out.end())) {
  1513. break;
  1514. }
  1515. if (*outiter == '\n' || *outiter == '\0') {
  1516. std::vector<char>::size_type length = outiter - out.begin();
  1517. if (length > 1 && *(outiter - 1) == '\r') {
  1518. --length;
  1519. }
  1520. if (length > 0) {
  1521. line.append(&out[0], length);
  1522. }
  1523. out.erase(out.begin(), outiter + 1);
  1524. return cmsysProcess_Pipe_STDOUT;
  1525. }
  1526. }
  1527. // Check for a newline in stderr.
  1528. for (; erriter != err.end(); ++erriter) {
  1529. if ((*erriter == '\r') && ((erriter + 1) == err.end())) {
  1530. break;
  1531. }
  1532. if (*erriter == '\n' || *erriter == '\0') {
  1533. std::vector<char>::size_type length = erriter - err.begin();
  1534. if (length > 1 && *(erriter - 1) == '\r') {
  1535. --length;
  1536. }
  1537. if (length > 0) {
  1538. line.append(&err[0], length);
  1539. }
  1540. err.erase(err.begin(), erriter + 1);
  1541. return cmsysProcess_Pipe_STDERR;
  1542. }
  1543. }
  1544. // No newlines found. Wait for more data from the process.
  1545. int length;
  1546. char* data;
  1547. double timeoutAsDbl = timeout.count();
  1548. int pipe =
  1549. cmsysProcess_WaitForData(process, &data, &length, &timeoutAsDbl);
  1550. if (pipe == cmsysProcess_Pipe_Timeout) {
  1551. // Timeout has been exceeded.
  1552. return pipe;
  1553. }
  1554. if (pipe == cmsysProcess_Pipe_STDOUT) {
  1555. processOutput.DecodeText(data, length, strdata, 1);
  1556. // Append to the stdout buffer.
  1557. std::vector<char>::size_type size = out.size();
  1558. cmAppend(out, strdata);
  1559. outiter = out.begin() + size;
  1560. } else if (pipe == cmsysProcess_Pipe_STDERR) {
  1561. processOutput.DecodeText(data, length, strdata, 2);
  1562. // Append to the stderr buffer.
  1563. std::vector<char>::size_type size = err.size();
  1564. cmAppend(err, strdata);
  1565. erriter = err.begin() + size;
  1566. } else if (pipe == cmsysProcess_Pipe_None) {
  1567. // Both stdout and stderr pipes have broken. Return leftover data.
  1568. processOutput.DecodeText(std::string(), strdata, 1);
  1569. if (!strdata.empty()) {
  1570. std::vector<char>::size_type size = out.size();
  1571. cmAppend(out, strdata);
  1572. outiter = out.begin() + size;
  1573. }
  1574. processOutput.DecodeText(std::string(), strdata, 2);
  1575. if (!strdata.empty()) {
  1576. std::vector<char>::size_type size = err.size();
  1577. cmAppend(err, strdata);
  1578. erriter = err.begin() + size;
  1579. }
  1580. if (!out.empty()) {
  1581. line.append(&out[0], outiter - out.begin());
  1582. out.erase(out.begin(), out.end());
  1583. return cmsysProcess_Pipe_STDOUT;
  1584. }
  1585. if (!err.empty()) {
  1586. line.append(&err[0], erriter - err.begin());
  1587. err.erase(err.begin(), err.end());
  1588. return cmsysProcess_Pipe_STDERR;
  1589. }
  1590. return cmsysProcess_Pipe_None;
  1591. }
  1592. }
  1593. }
  1594. #ifdef _WIN32
  1595. static void EnsureStdPipe(DWORD fd)
  1596. {
  1597. if (GetStdHandle(fd) != INVALID_HANDLE_VALUE) {
  1598. return;
  1599. }
  1600. SECURITY_ATTRIBUTES sa;
  1601. sa.nLength = sizeof(sa);
  1602. sa.lpSecurityDescriptor = NULL;
  1603. sa.bInheritHandle = TRUE;
  1604. HANDLE h = CreateFileW(
  1605. L"NUL",
  1606. fd == STD_INPUT_HANDLE ? FILE_GENERIC_READ
  1607. : FILE_GENERIC_WRITE | FILE_READ_ATTRIBUTES,
  1608. FILE_SHARE_READ | FILE_SHARE_WRITE, &sa, OPEN_EXISTING, 0, NULL);
  1609. if (h == INVALID_HANDLE_VALUE) {
  1610. LPSTR message = NULL;
  1611. DWORD size = FormatMessageA(
  1612. FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
  1613. FORMAT_MESSAGE_IGNORE_INSERTS,
  1614. NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  1615. (LPSTR)&message, 0, NULL);
  1616. std::string msg = std::string(message, size);
  1617. LocalFree(message);
  1618. std::cerr << "failed to open NUL for missing stdio pipe: " << msg;
  1619. abort();
  1620. }
  1621. SetStdHandle(fd, h);
  1622. }
  1623. void cmSystemTools::EnsureStdPipes()
  1624. {
  1625. EnsureStdPipe(STD_INPUT_HANDLE);
  1626. EnsureStdPipe(STD_OUTPUT_HANDLE);
  1627. EnsureStdPipe(STD_ERROR_HANDLE);
  1628. }
  1629. #else
  1630. static void EnsureStdPipe(int fd)
  1631. {
  1632. if (fcntl(fd, F_GETFD) != -1 || errno != EBADF) {
  1633. return;
  1634. }
  1635. int f = open("/dev/null", fd == STDIN_FILENO ? O_RDONLY : O_WRONLY);
  1636. if (f == -1) {
  1637. perror("failed to open /dev/null for missing stdio pipe");
  1638. abort();
  1639. }
  1640. if (f != fd) {
  1641. dup2(f, fd);
  1642. close(f);
  1643. }
  1644. }
  1645. void cmSystemTools::EnsureStdPipes()
  1646. {
  1647. EnsureStdPipe(STDIN_FILENO);
  1648. EnsureStdPipe(STDOUT_FILENO);
  1649. EnsureStdPipe(STDERR_FILENO);
  1650. }
  1651. #endif
  1652. void cmSystemTools::DoNotInheritStdPipes()
  1653. {
  1654. #ifdef _WIN32
  1655. // Check to see if we are attached to a console
  1656. // if so, then do not stop the inherited pipes
  1657. // or stdout and stderr will not show up in dos
  1658. // shell windows
  1659. CONSOLE_SCREEN_BUFFER_INFO hOutInfo;
  1660. HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
  1661. if (GetConsoleScreenBufferInfo(hOut, &hOutInfo)) {
  1662. return;
  1663. }
  1664. {
  1665. HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
  1666. DuplicateHandle(GetCurrentProcess(), out, GetCurrentProcess(), &out, 0,
  1667. FALSE, DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
  1668. SetStdHandle(STD_OUTPUT_HANDLE, out);
  1669. }
  1670. {
  1671. HANDLE out = GetStdHandle(STD_ERROR_HANDLE);
  1672. DuplicateHandle(GetCurrentProcess(), out, GetCurrentProcess(), &out, 0,
  1673. FALSE, DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
  1674. SetStdHandle(STD_ERROR_HANDLE, out);
  1675. }
  1676. #endif
  1677. }
  1678. #ifdef _WIN32
  1679. # ifndef CRYPT_SILENT
  1680. # define CRYPT_SILENT 0x40 /* Not defined by VS 6 version of header. */
  1681. # endif
  1682. static int WinCryptRandom(void* data, size_t size)
  1683. {
  1684. int result = 0;
  1685. HCRYPTPROV hProvider = 0;
  1686. if (CryptAcquireContextW(&hProvider, 0, 0, PROV_RSA_FULL,
  1687. CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) {
  1688. result = CryptGenRandom(hProvider, (DWORD)size, (BYTE*)data) ? 1 : 0;
  1689. CryptReleaseContext(hProvider, 0);
  1690. }
  1691. return result;
  1692. }
  1693. #endif
  1694. unsigned int cmSystemTools::RandomSeed()
  1695. {
  1696. #if defined(_WIN32) && !defined(__CYGWIN__)
  1697. unsigned int seed = 0;
  1698. // Try using a real random source.
  1699. if (WinCryptRandom(&seed, sizeof(seed))) {
  1700. return seed;
  1701. }
  1702. // Fall back to the time and pid.
  1703. FILETIME ft;
  1704. GetSystemTimeAsFileTime(&ft);
  1705. unsigned int t1 = static_cast<unsigned int>(ft.dwHighDateTime);
  1706. unsigned int t2 = static_cast<unsigned int>(ft.dwLowDateTime);
  1707. unsigned int pid = static_cast<unsigned int>(GetCurrentProcessId());
  1708. return t1 ^ t2 ^ pid;
  1709. #else
  1710. union
  1711. {
  1712. unsigned int integer;
  1713. char bytes[sizeof(unsigned int)];
  1714. } seed;
  1715. // Try using a real random source.
  1716. cmsys::ifstream fin;
  1717. fin.rdbuf()->pubsetbuf(nullptr, 0); // Unbuffered read.
  1718. fin.open("/dev/urandom");
  1719. if (fin.good() && fin.read(seed.bytes, sizeof(seed)) &&
  1720. fin.gcount() == sizeof(seed)) {
  1721. return seed.integer;
  1722. }
  1723. // Fall back to the time and pid.
  1724. struct timeval t;
  1725. gettimeofday(&t, nullptr);
  1726. unsigned int pid = static_cast<unsigned int>(getpid());
  1727. unsigned int tv_sec = static_cast<unsigned int>(t.tv_sec);
  1728. unsigned int tv_usec = static_cast<unsigned int>(t.tv_usec);
  1729. // Since tv_usec never fills more than 11 bits we shift it to fill
  1730. // in the slow-changing high-order bits of tv_sec.
  1731. return tv_sec ^ (tv_usec << 21) ^ pid;
  1732. #endif
  1733. }
  1734. static std::string cmSystemToolsCMakeCommand;
  1735. static std::string cmSystemToolsCTestCommand;
  1736. static std::string cmSystemToolsCPackCommand;
  1737. static std::string cmSystemToolsCMakeCursesCommand;
  1738. static std::string cmSystemToolsCMakeGUICommand;
  1739. static std::string cmSystemToolsCMClDepsCommand;
  1740. static std::string cmSystemToolsCMakeRoot;
  1741. void cmSystemTools::FindCMakeResources(const char* argv0)
  1742. {
  1743. std::string exe_dir;
  1744. #if defined(_WIN32) && !defined(__CYGWIN__)
  1745. (void)argv0; // ignore this on windows
  1746. wchar_t modulepath[_MAX_PATH];
  1747. ::GetModuleFileNameW(NULL, modulepath, sizeof(modulepath));
  1748. std::string path = cmsys::Encoding::ToNarrow(modulepath);
  1749. std::string realPath =
  1750. cmSystemTools::GetRealPathResolvingWindowsSubst(path, NULL);
  1751. if (realPath.empty()) {
  1752. realPath = path;
  1753. }
  1754. exe_dir = cmSystemTools::GetFilenamePath(realPath);
  1755. #elif defined(__APPLE__)
  1756. (void)argv0; // ignore this on OS X
  1757. # define CM_EXE_PATH_LOCAL_SIZE 16384
  1758. char exe_path_local[CM_EXE_PATH_LOCAL_SIZE];
  1759. # if defined(MAC_OS_X_VERSION_10_3) && !defined(MAC_OS_X_VERSION_10_4)
  1760. unsigned long exe_path_size = CM_EXE_PATH_LOCAL_SIZE;
  1761. # else
  1762. uint32_t exe_path_size = CM_EXE_PATH_LOCAL_SIZE;
  1763. # endif
  1764. # undef CM_EXE_PATH_LOCAL_SIZE
  1765. char* exe_path = exe_path_local;
  1766. if (_NSGetExecutablePath(exe_path, &exe_path_size) < 0) {
  1767. exe_path = static_cast<char*>(malloc(exe_path_size));
  1768. _NSGetExecutablePath(exe_path, &exe_path_size);
  1769. }
  1770. exe_dir =
  1771. cmSystemTools::GetFilenamePath(cmSystemTools::GetRealPath(exe_path));
  1772. if (exe_path != exe_path_local) {
  1773. free(exe_path);
  1774. }
  1775. if (cmSystemTools::GetFilenameName(exe_dir) == "MacOS") {
  1776. // The executable is inside an application bundle.
  1777. // Look for ..<CMAKE_BIN_DIR> (install tree) and then fall back to
  1778. // ../../../bin (build tree).
  1779. exe_dir = cmSystemTools::GetFilenamePath(exe_dir);
  1780. if (cmSystemTools::FileExists(exe_dir + CMAKE_BIN_DIR "/cmake")) {
  1781. exe_dir += CMAKE_BIN_DIR;
  1782. } else {
  1783. exe_dir = cmSystemTools::GetFilenamePath(exe_dir);
  1784. exe_dir = cmSystemTools::GetFilenamePath(exe_dir);
  1785. }
  1786. }
  1787. #else
  1788. std::string errorMsg;
  1789. std::string exe;
  1790. if (cmSystemTools::FindProgramPath(argv0, exe, errorMsg)) {
  1791. // remove symlinks
  1792. exe = cmSystemTools::GetRealPath(exe);
  1793. exe_dir = cmSystemTools::GetFilenamePath(exe);
  1794. } else {
  1795. // ???
  1796. }
  1797. #endif
  1798. exe_dir = cmSystemTools::GetActualCaseForPath(exe_dir);
  1799. cmSystemToolsCMakeCommand =
  1800. cmStrCat(exe_dir, "/cmake", cmSystemTools::GetExecutableExtension());
  1801. #ifdef CMAKE_BOOTSTRAP
  1802. // The bootstrap cmake does not provide the other tools,
  1803. // so use the directory where they are about to be built.
  1804. exe_dir = CMAKE_BOOTSTRAP_BINARY_DIR "/bin";
  1805. #endif
  1806. cmSystemToolsCTestCommand =
  1807. cmStrCat(exe_dir, "/ctest", cmSystemTools::GetExecutableExtension());
  1808. cmSystemToolsCPackCommand =
  1809. cmStrCat(exe_dir, "/cpack", cmSystemTools::GetExecutableExtension());
  1810. cmSystemToolsCMakeGUICommand =
  1811. cmStrCat(exe_dir, "/cmake-gui", cmSystemTools::GetExecutableExtension());
  1812. if (!cmSystemTools::FileExists(cmSystemToolsCMakeGUICommand)) {
  1813. cmSystemToolsCMakeGUICommand.clear();
  1814. }
  1815. cmSystemToolsCMakeCursesCommand =
  1816. cmStrCat(exe_dir, "/ccmake", cmSystemTools::GetExecutableExtension());
  1817. if (!cmSystemTools::FileExists(cmSystemToolsCMakeCursesCommand)) {
  1818. cmSystemToolsCMakeCursesCommand.clear();
  1819. }
  1820. cmSystemToolsCMClDepsCommand =
  1821. cmStrCat(exe_dir, "/cmcldeps", cmSystemTools::GetExecutableExtension());
  1822. if (!cmSystemTools::FileExists(cmSystemToolsCMClDepsCommand)) {
  1823. cmSystemToolsCMClDepsCommand.clear();
  1824. }
  1825. #ifndef CMAKE_BOOTSTRAP
  1826. // Install tree has
  1827. // - "<prefix><CMAKE_BIN_DIR>/cmake"
  1828. // - "<prefix><CMAKE_DATA_DIR>"
  1829. if (cmHasSuffix(exe_dir, CMAKE_BIN_DIR)) {
  1830. std::string const prefix =
  1831. exe_dir.substr(0, exe_dir.size() - strlen(CMAKE_BIN_DIR));
  1832. cmSystemToolsCMakeRoot = prefix + CMAKE_DATA_DIR;
  1833. }
  1834. if (cmSystemToolsCMakeRoot.empty() ||
  1835. !cmSystemTools::FileExists(
  1836. (cmSystemToolsCMakeRoot + "/Modules/CMake.cmake"))) {
  1837. // Build tree has "<build>/bin[/<config>]/cmake" and
  1838. // "<build>/CMakeFiles/CMakeSourceDir.txt".
  1839. std::string dir = cmSystemTools::GetFilenamePath(exe_dir);
  1840. std::string src_dir_txt = dir + "/CMakeFiles/CMakeSourceDir.txt";
  1841. cmsys::ifstream fin(src_dir_txt.c_str());
  1842. std::string src_dir;
  1843. if (fin && cmSystemTools::GetLineFromStream(fin, src_dir) &&
  1844. cmSystemTools::FileIsDirectory(src_dir)) {
  1845. cmSystemToolsCMakeRoot = src_dir;
  1846. } else {
  1847. dir = cmSystemTools::GetFilenamePath(dir);
  1848. src_dir_txt = dir + "/CMakeFiles/CMakeSourceDir.txt";
  1849. cmsys::ifstream fin2(src_dir_txt.c_str());
  1850. if (fin2 && cmSystemTools::GetLineFromStream(fin2, src_dir) &&
  1851. cmSystemTools::FileIsDirectory(src_dir)) {
  1852. cmSystemToolsCMakeRoot = src_dir;
  1853. }
  1854. }
  1855. }
  1856. #else
  1857. // Bootstrap build knows its source.
  1858. cmSystemToolsCMakeRoot = CMAKE_BOOTSTRAP_SOURCE_DIR;
  1859. #endif
  1860. }
  1861. std::string const& cmSystemTools::GetCMakeCommand()
  1862. {
  1863. return cmSystemToolsCMakeCommand;
  1864. }
  1865. std::string const& cmSystemTools::GetCTestCommand()
  1866. {
  1867. return cmSystemToolsCTestCommand;
  1868. }
  1869. std::string const& cmSystemTools::GetCPackCommand()
  1870. {
  1871. return cmSystemToolsCPackCommand;
  1872. }
  1873. std::string const& cmSystemTools::GetCMakeCursesCommand()
  1874. {
  1875. return cmSystemToolsCMakeCursesCommand;
  1876. }
  1877. std::string const& cmSystemTools::GetCMakeGUICommand()
  1878. {
  1879. return cmSystemToolsCMakeGUICommand;
  1880. }
  1881. std::string const& cmSystemTools::GetCMClDepsCommand()
  1882. {
  1883. return cmSystemToolsCMClDepsCommand;
  1884. }
  1885. std::string const& cmSystemTools::GetCMakeRoot()
  1886. {
  1887. return cmSystemToolsCMakeRoot;
  1888. }
  1889. void cmSystemTools::MakefileColorEcho(int color, const char* message,
  1890. bool newline, bool enabled)
  1891. {
  1892. // On some platforms (an MSYS prompt) cmsysTerminal may not be able
  1893. // to determine whether the stream is displayed on a tty. In this
  1894. // case it assumes no unless we tell it otherwise. Since we want
  1895. // color messages to be displayed for users we will assume yes.
  1896. // However, we can test for some situations when the answer is most
  1897. // likely no.
  1898. int assumeTTY = cmsysTerminal_Color_AssumeTTY;
  1899. if (cmSystemTools::HasEnv("DART_TEST_FROM_DART") ||
  1900. cmSystemTools::HasEnv("DASHBOARD_TEST_FROM_CTEST") ||
  1901. cmSystemTools::HasEnv("CTEST_INTERACTIVE_DEBUG_MODE")) {
  1902. // Avoid printing color escapes during dashboard builds.
  1903. assumeTTY = 0;
  1904. }
  1905. if (enabled && color != cmsysTerminal_Color_Normal) {
  1906. // Print with color. Delay the newline until later so that
  1907. // all color restore sequences appear before it.
  1908. cmsysTerminal_cfprintf(color | assumeTTY, stdout, "%s", message);
  1909. } else {
  1910. // Color is disabled. Print without color.
  1911. fprintf(stdout, "%s", message);
  1912. }
  1913. if (newline) {
  1914. fprintf(stdout, "\n");
  1915. }
  1916. }
  1917. bool cmSystemTools::GuessLibrarySOName(std::string const& fullPath,
  1918. std::string& soname)
  1919. {
  1920. // For ELF shared libraries use a real parser to get the correct
  1921. // soname.
  1922. #if defined(CMAKE_USE_ELF_PARSER)
  1923. cmELF elf(fullPath.c_str());
  1924. if (elf) {
  1925. return elf.GetSOName(soname);
  1926. }
  1927. #endif
  1928. // If the file is not a symlink we have no guess for its soname.
  1929. if (!cmSystemTools::FileIsSymlink(fullPath)) {
  1930. return false;
  1931. }
  1932. if (!cmSystemTools::ReadSymlink(fullPath, soname)) {
  1933. return false;
  1934. }
  1935. // If the symlink has a path component we have no guess for the soname.
  1936. if (!cmSystemTools::GetFilenamePath(soname).empty()) {
  1937. return false;
  1938. }
  1939. // If the symlink points at an extended version of the same name
  1940. // assume it is the soname.
  1941. std::string name = cmSystemTools::GetFilenameName(fullPath);
  1942. return soname.length() > name.length() &&
  1943. soname.compare(0, name.length(), name) == 0;
  1944. }
  1945. bool cmSystemTools::GuessLibraryInstallName(std::string const& fullPath,
  1946. std::string& soname)
  1947. {
  1948. #if defined(CMAKE_USE_MACH_PARSER)
  1949. cmMachO macho(fullPath.c_str());
  1950. if (macho) {
  1951. return macho.GetInstallName(soname);
  1952. }
  1953. #else
  1954. (void)fullPath;
  1955. (void)soname;
  1956. #endif
  1957. return false;
  1958. }
  1959. #if defined(CMAKE_USE_ELF_PARSER)
  1960. std::string::size_type cmSystemToolsFindRPath(std::string const& have,
  1961. std::string const& want)
  1962. {
  1963. std::string::size_type pos = 0;
  1964. while (pos < have.size()) {
  1965. // Look for an occurrence of the string.
  1966. std::string::size_type const beg = have.find(want, pos);
  1967. if (beg == std::string::npos) {
  1968. return std::string::npos;
  1969. }
  1970. // Make sure it is separated from preceding entries.
  1971. if (beg > 0 && have[beg - 1] != ':') {
  1972. pos = beg + 1;
  1973. continue;
  1974. }
  1975. // Make sure it is separated from following entries.
  1976. std::string::size_type const end = beg + want.size();
  1977. if (end < have.size() && have[end] != ':') {
  1978. pos = beg + 1;
  1979. continue;
  1980. }
  1981. // Return the position of the path portion.
  1982. return beg;
  1983. }
  1984. // The desired rpath was not found.
  1985. return std::string::npos;
  1986. }
  1987. #endif
  1988. #if defined(CMAKE_USE_ELF_PARSER)
  1989. struct cmSystemToolsRPathInfo
  1990. {
  1991. unsigned long Position;
  1992. unsigned long Size;
  1993. std::string Name;
  1994. std::string Value;
  1995. };
  1996. #endif
  1997. #if defined(CMAKE_USE_ELF_PARSER)
  1998. bool cmSystemTools::ChangeRPath(std::string const& file,
  1999. std::string const& oldRPath,
  2000. std::string const& newRPath,
  2001. bool removeEnvironmentRPath, std::string* emsg,
  2002. bool* changed)
  2003. {
  2004. if (changed) {
  2005. *changed = false;
  2006. }
  2007. int rp_count = 0;
  2008. bool remove_rpath = true;
  2009. cmSystemToolsRPathInfo rp[2];
  2010. {
  2011. // Parse the ELF binary.
  2012. cmELF elf(file.c_str());
  2013. // Get the RPATH and RUNPATH entries from it.
  2014. int se_count = 0;
  2015. cmELF::StringEntry const* se[2] = { nullptr, nullptr };
  2016. const char* se_name[2] = { nullptr, nullptr };
  2017. if (cmELF::StringEntry const* se_rpath = elf.GetRPath()) {
  2018. se[se_count] = se_rpath;
  2019. se_name[se_count] = "RPATH";
  2020. ++se_count;
  2021. }
  2022. if (cmELF::StringEntry const* se_runpath = elf.GetRunPath()) {
  2023. se[se_count] = se_runpath;
  2024. se_name[se_count] = "RUNPATH";
  2025. ++se_count;
  2026. }
  2027. if (se_count == 0) {
  2028. if (newRPath.empty()) {
  2029. // The new rpath is empty and there is no rpath anyway so it is
  2030. // okay.
  2031. return true;
  2032. }
  2033. if (emsg) {
  2034. *emsg =
  2035. cmStrCat("No valid ELF RPATH or RUNPATH entry exists in the file; ",
  2036. elf.GetErrorMessage());
  2037. }
  2038. return false;
  2039. }
  2040. for (int i = 0; i < se_count; ++i) {
  2041. // If both RPATH and RUNPATH refer to the same string literal it
  2042. // needs to be changed only once.
  2043. if (rp_count && rp[0].Position == se[i]->Position) {
  2044. continue;
  2045. }
  2046. // Make sure the current rpath contains the old rpath.
  2047. std::string::size_type pos =
  2048. cmSystemToolsFindRPath(se[i]->Value, oldRPath);
  2049. if (pos == std::string::npos) {
  2050. // If it contains the new rpath instead then it is okay.
  2051. if (cmSystemToolsFindRPath(se[i]->Value, newRPath) !=
  2052. std::string::npos) {
  2053. remove_rpath = false;
  2054. continue;
  2055. }
  2056. if (emsg) {
  2057. std::ostringstream e;
  2058. /* clang-format off */
  2059. e << "The current " << se_name[i] << " is:\n"
  2060. << " " << se[i]->Value << "\n"
  2061. << "which does not contain:\n"
  2062. << " " << oldRPath << "\n"
  2063. << "as was expected.";
  2064. /* clang-format on */
  2065. *emsg = e.str();
  2066. }
  2067. return false;
  2068. }
  2069. // Store information about the entry in the file.
  2070. rp[rp_count].Position = se[i]->Position;
  2071. rp[rp_count].Size = se[i]->Size;
  2072. rp[rp_count].Name = se_name[i];
  2073. std::string::size_type prefix_len = pos;
  2074. // If oldRPath was at the end of the file's RPath, and newRPath is empty,
  2075. // we should remove the unnecessary ':' at the end.
  2076. if (newRPath.empty() && pos > 0 && se[i]->Value[pos - 1] == ':' &&
  2077. pos + oldRPath.length() == se[i]->Value.length()) {
  2078. prefix_len--;
  2079. }
  2080. // Construct the new value which preserves the part of the path
  2081. // not being changed.
  2082. if (!removeEnvironmentRPath) {
  2083. rp[rp_count].Value = se[i]->Value.substr(0, prefix_len);
  2084. }
  2085. rp[rp_count].Value += newRPath;
  2086. rp[rp_count].Value += se[i]->Value.substr(pos + oldRPath.length());
  2087. if (!rp[rp_count].Value.empty()) {
  2088. remove_rpath = false;
  2089. }
  2090. // Make sure there is enough room to store the new rpath and at
  2091. // least one null terminator.
  2092. if (rp[rp_count].Size < rp[rp_count].Value.length() + 1) {
  2093. if (emsg) {
  2094. *emsg = cmStrCat("The replacement path is too long for the ",
  2095. se_name[i], " entry.");
  2096. }
  2097. return false;
  2098. }
  2099. // This entry is ready for update.
  2100. ++rp_count;
  2101. }
  2102. }
  2103. // If no runtime path needs to be changed, we are done.
  2104. if (rp_count == 0) {
  2105. return true;
  2106. }
  2107. // If the resulting rpath is empty, just remove the entire entry instead.
  2108. if (remove_rpath) {
  2109. return cmSystemTools::RemoveRPath(file, emsg, changed);
  2110. }
  2111. {
  2112. // Open the file for update.
  2113. cmsys::ofstream f(file.c_str(),
  2114. std::ios::in | std::ios::out | std::ios::binary);
  2115. if (!f) {
  2116. if (emsg) {
  2117. *emsg = "Error opening file for update.";
  2118. }
  2119. return false;
  2120. }
  2121. // Store the new RPATH and RUNPATH strings.
  2122. for (int i = 0; i < rp_count; ++i) {
  2123. // Seek to the RPATH position.
  2124. if (!f.seekp(rp[i].Position)) {
  2125. if (emsg) {
  2126. *emsg = cmStrCat("Error seeking to ", rp[i].Name, " position.");
  2127. }
  2128. return false;
  2129. }
  2130. // Write the new rpath. Follow it with enough null terminators to
  2131. // fill the string table entry.
  2132. f << rp[i].Value;
  2133. for (unsigned long j = rp[i].Value.length(); j < rp[i].Size; ++j) {
  2134. f << '\0';
  2135. }
  2136. // Make sure it wrote correctly.
  2137. if (!f) {
  2138. if (emsg) {
  2139. *emsg = cmStrCat("Error writing the new ", rp[i].Name,
  2140. " string to the file.");
  2141. }
  2142. return false;
  2143. }
  2144. }
  2145. }
  2146. // Everything was updated successfully.
  2147. if (changed) {
  2148. *changed = true;
  2149. }
  2150. return true;
  2151. }
  2152. #else
  2153. bool cmSystemTools::ChangeRPath(std::string const& /*file*/,
  2154. std::string const& /*oldRPath*/,
  2155. std::string const& /*newRPath*/,
  2156. bool /*removeEnvironmentRPath*/,
  2157. std::string* /*emsg*/, bool* /*changed*/)
  2158. {
  2159. return false;
  2160. }
  2161. #endif
  2162. bool cmSystemTools::VersionCompare(cmSystemTools::CompareOp op,
  2163. const char* lhss, const char* rhss)
  2164. {
  2165. const char* endl = lhss;
  2166. const char* endr = rhss;
  2167. unsigned long lhs;
  2168. unsigned long rhs;
  2169. while (((*endl >= '0') && (*endl <= '9')) ||
  2170. ((*endr >= '0') && (*endr <= '9'))) {
  2171. // Do component-wise comparison.
  2172. lhs = strtoul(endl, const_cast<char**>(&endl), 10);
  2173. rhs = strtoul(endr, const_cast<char**>(&endr), 10);
  2174. if (lhs < rhs) {
  2175. // lhs < rhs, so true if operation is LESS
  2176. return (op & cmSystemTools::OP_LESS) != 0;
  2177. }
  2178. if (lhs > rhs) {
  2179. // lhs > rhs, so true if operation is GREATER
  2180. return (op & cmSystemTools::OP_GREATER) != 0;
  2181. }
  2182. if (*endr == '.') {
  2183. endr++;
  2184. }
  2185. if (*endl == '.') {
  2186. endl++;
  2187. }
  2188. }
  2189. // lhs == rhs, so true if operation is EQUAL
  2190. return (op & cmSystemTools::OP_EQUAL) != 0;
  2191. }
  2192. bool cmSystemTools::VersionCompareEqual(std::string const& lhs,
  2193. std::string const& rhs)
  2194. {
  2195. return cmSystemTools::VersionCompare(cmSystemTools::OP_EQUAL, lhs.c_str(),
  2196. rhs.c_str());
  2197. }
  2198. bool cmSystemTools::VersionCompareGreater(std::string const& lhs,
  2199. std::string const& rhs)
  2200. {
  2201. return cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER, lhs.c_str(),
  2202. rhs.c_str());
  2203. }
  2204. bool cmSystemTools::VersionCompareGreaterEq(std::string const& lhs,
  2205. std::string const& rhs)
  2206. {
  2207. return cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER_EQUAL,
  2208. lhs.c_str(), rhs.c_str());
  2209. }
  2210. static size_t cm_strverscmp_find_first_difference_or_end(const char* lhs,
  2211. const char* rhs)
  2212. {
  2213. size_t i = 0;
  2214. /* Step forward until we find a difference or both strings end together.
  2215. The difference may lie on the null-terminator of one string. */
  2216. while (lhs[i] == rhs[i] && lhs[i] != 0) {
  2217. ++i;
  2218. }
  2219. return i;
  2220. }
  2221. static size_t cm_strverscmp_find_digits_begin(const char* s, size_t i)
  2222. {
  2223. /* Step back until we are not preceded by a digit. */
  2224. while (i > 0 && isdigit(s[i - 1])) {
  2225. --i;
  2226. }
  2227. return i;
  2228. }
  2229. static size_t cm_strverscmp_find_digits_end(const char* s, size_t i)
  2230. {
  2231. /* Step forward over digits. */
  2232. while (isdigit(s[i])) {
  2233. ++i;
  2234. }
  2235. return i;
  2236. }
  2237. static size_t cm_strverscmp_count_leading_zeros(const char* s, size_t b)
  2238. {
  2239. size_t i = b;
  2240. /* Step forward over zeros that are followed by another digit. */
  2241. while (s[i] == '0' && isdigit(s[i + 1])) {
  2242. ++i;
  2243. }
  2244. return i - b;
  2245. }
  2246. static int cm_strverscmp(const char* lhs, const char* rhs)
  2247. {
  2248. size_t const i = cm_strverscmp_find_first_difference_or_end(lhs, rhs);
  2249. if (lhs[i] != rhs[i]) {
  2250. /* The strings differ starting at 'i'. Check for a digit sequence. */
  2251. size_t const b = cm_strverscmp_find_digits_begin(lhs, i);
  2252. if (b != i || (isdigit(lhs[i]) && isdigit(rhs[i]))) {
  2253. /* A digit sequence starts at 'b', preceding or at 'i'. */
  2254. /* Look for leading zeros, implying a leading decimal point. */
  2255. size_t const lhs_zeros = cm_strverscmp_count_leading_zeros(lhs, b);
  2256. size_t const rhs_zeros = cm_strverscmp_count_leading_zeros(rhs, b);
  2257. if (lhs_zeros != rhs_zeros) {
  2258. /* The side with more leading zeros orders first. */
  2259. return rhs_zeros > lhs_zeros ? 1 : -1;
  2260. }
  2261. if (lhs_zeros == 0) {
  2262. /* No leading zeros; compare digit sequence lengths. */
  2263. size_t const lhs_end = cm_strverscmp_find_digits_end(lhs, i);
  2264. size_t const rhs_end = cm_strverscmp_find_digits_end(rhs, i);
  2265. if (lhs_end != rhs_end) {
  2266. /* The side with fewer digits orders first. */
  2267. return lhs_end > rhs_end ? 1 : -1;
  2268. }
  2269. }
  2270. }
  2271. }
  2272. /* Ordering was not decided by digit sequence lengths; compare bytes. */
  2273. return lhs[i] - rhs[i];
  2274. }
  2275. int cmSystemTools::strverscmp(std::string const& lhs, std::string const& rhs)
  2276. {
  2277. return cm_strverscmp(lhs.c_str(), rhs.c_str());
  2278. }
  2279. #if defined(CMAKE_USE_ELF_PARSER)
  2280. bool cmSystemTools::RemoveRPath(std::string const& file, std::string* emsg,
  2281. bool* removed)
  2282. {
  2283. if (removed) {
  2284. *removed = false;
  2285. }
  2286. int zeroCount = 0;
  2287. unsigned long zeroPosition[2] = { 0, 0 };
  2288. unsigned long zeroSize[2] = { 0, 0 };
  2289. unsigned long bytesBegin = 0;
  2290. std::vector<char> bytes;
  2291. {
  2292. // Parse the ELF binary.
  2293. cmELF elf(file.c_str());
  2294. // Get the RPATH and RUNPATH entries from it and sort them by index
  2295. // in the dynamic section header.
  2296. int se_count = 0;
  2297. cmELF::StringEntry const* se[2] = { nullptr, nullptr };
  2298. if (cmELF::StringEntry const* se_rpath = elf.GetRPath()) {
  2299. se[se_count++] = se_rpath;
  2300. }
  2301. if (cmELF::StringEntry const* se_runpath = elf.GetRunPath()) {
  2302. se[se_count++] = se_runpath;
  2303. }
  2304. if (se_count == 0) {
  2305. // There is no RPATH or RUNPATH anyway.
  2306. return true;
  2307. }
  2308. if (se_count == 2 && se[1]->IndexInSection < se[0]->IndexInSection) {
  2309. std::swap(se[0], se[1]);
  2310. }
  2311. // Obtain a copy of the dynamic entries
  2312. cmELF::DynamicEntryList dentries = elf.GetDynamicEntries();
  2313. if (dentries.empty()) {
  2314. // This should happen only for invalid ELF files where a DT_NULL
  2315. // appears before the end of the table.
  2316. if (emsg) {
  2317. *emsg = "DYNAMIC section contains a DT_NULL before the end.";
  2318. }
  2319. return false;
  2320. }
  2321. // Save information about the string entries to be zeroed.
  2322. zeroCount = se_count;
  2323. for (int i = 0; i < se_count; ++i) {
  2324. zeroPosition[i] = se[i]->Position;
  2325. zeroSize[i] = se[i]->Size;
  2326. }
  2327. // Get size of one DYNAMIC entry
  2328. unsigned long const sizeof_dentry =
  2329. elf.GetDynamicEntryPosition(1) - elf.GetDynamicEntryPosition(0);
  2330. // Adjust the entry list as necessary to remove the run path
  2331. unsigned long entriesErased = 0;
  2332. for (auto it = dentries.begin(); it != dentries.end();) {
  2333. if (it->first == cmELF::TagRPath || it->first == cmELF::TagRunPath) {
  2334. it = dentries.erase(it);
  2335. entriesErased++;
  2336. continue;
  2337. }
  2338. if (cmELF::TagMipsRldMapRel != 0 &&
  2339. it->first == cmELF::TagMipsRldMapRel) {
  2340. // Background: debuggers need to know the "linker map" which contains
  2341. // the addresses each dynamic object is loaded at. Most arches use
  2342. // the DT_DEBUG tag which the dynamic linker writes to (directly) and
  2343. // contain the location of the linker map, however on MIPS the
  2344. // .dynamic section is always read-only so this is not possible. MIPS
  2345. // objects instead contain a DT_MIPS_RLD_MAP tag which contains the
  2346. // address where the dynamic linker will write to (an indirect
  2347. // version of DT_DEBUG). Since this doesn't work when using PIE, a
  2348. // relative equivalent was created - DT_MIPS_RLD_MAP_REL. Since this
  2349. // version contains a relative offset, moving it changes the
  2350. // calculated address. This may cause the dynamic linker to write
  2351. // into memory it should not be changing.
  2352. //
  2353. // To fix this, we adjust the value of DT_MIPS_RLD_MAP_REL here. If
  2354. // we move it up by n bytes, we add n bytes to the value of this tag.
  2355. it->second += entriesErased * sizeof_dentry;
  2356. }
  2357. it++;
  2358. }
  2359. // Encode new entries list
  2360. bytes = elf.EncodeDynamicEntries(dentries);
  2361. bytesBegin = elf.GetDynamicEntryPosition(0);
  2362. }
  2363. // Open the file for update.
  2364. cmsys::ofstream f(file.c_str(),
  2365. std::ios::in | std::ios::out | std::ios::binary);
  2366. if (!f) {
  2367. if (emsg) {
  2368. *emsg = "Error opening file for update.";
  2369. }
  2370. return false;
  2371. }
  2372. // Write the new DYNAMIC table header.
  2373. if (!f.seekp(bytesBegin)) {
  2374. if (emsg) {
  2375. *emsg = "Error seeking to DYNAMIC table header for RPATH.";
  2376. }
  2377. return false;
  2378. }
  2379. if (!f.write(&bytes[0], bytes.size())) {
  2380. if (emsg) {
  2381. *emsg = "Error replacing DYNAMIC table header.";
  2382. }
  2383. return false;
  2384. }
  2385. // Fill the RPATH and RUNPATH strings with zero bytes.
  2386. for (int i = 0; i < zeroCount; ++i) {
  2387. if (!f.seekp(zeroPosition[i])) {
  2388. if (emsg) {
  2389. *emsg = "Error seeking to RPATH position.";
  2390. }
  2391. return false;
  2392. }
  2393. for (unsigned long j = 0; j < zeroSize[i]; ++j) {
  2394. f << '\0';
  2395. }
  2396. if (!f) {
  2397. if (emsg) {
  2398. *emsg = "Error writing the empty rpath string to the file.";
  2399. }
  2400. return false;
  2401. }
  2402. }
  2403. // Everything was updated successfully.
  2404. if (removed) {
  2405. *removed = true;
  2406. }
  2407. return true;
  2408. }
  2409. #else
  2410. bool cmSystemTools::RemoveRPath(std::string const& /*file*/,
  2411. std::string* /*emsg*/, bool* /*removed*/)
  2412. {
  2413. return false;
  2414. }
  2415. #endif
  2416. bool cmSystemTools::CheckRPath(std::string const& file,
  2417. std::string const& newRPath)
  2418. {
  2419. #if defined(CMAKE_USE_ELF_PARSER)
  2420. // Parse the ELF binary.
  2421. cmELF elf(file.c_str());
  2422. // Get the RPATH or RUNPATH entry from it.
  2423. cmELF::StringEntry const* se = elf.GetRPath();
  2424. if (!se) {
  2425. se = elf.GetRunPath();
  2426. }
  2427. // Make sure the current rpath contains the new rpath.
  2428. if (newRPath.empty()) {
  2429. if (!se) {
  2430. return true;
  2431. }
  2432. } else {
  2433. if (se &&
  2434. cmSystemToolsFindRPath(se->Value, newRPath) != std::string::npos) {
  2435. return true;
  2436. }
  2437. }
  2438. return false;
  2439. #else
  2440. (void)file;
  2441. (void)newRPath;
  2442. return false;
  2443. #endif
  2444. }
  2445. bool cmSystemTools::RepeatedRemoveDirectory(const std::string& dir)
  2446. {
  2447. #ifdef _WIN32
  2448. // Windows sometimes locks files temporarily so try a few times.
  2449. WindowsFileRetry retry = cmSystemTools::GetWindowsFileRetry();
  2450. for (unsigned int i = 0; i < retry.Count; ++i) {
  2451. if (cmSystemTools::RemoveADirectory(dir)) {
  2452. return true;
  2453. }
  2454. cmSystemTools::Delay(retry.Delay);
  2455. }
  2456. return false;
  2457. #else
  2458. return cmSystemTools::RemoveADirectory(dir);
  2459. #endif
  2460. }
  2461. std::string cmSystemTools::EncodeURL(std::string const& in, bool escapeSlashes)
  2462. {
  2463. std::string out;
  2464. for (char c : in) {
  2465. char hexCh[4] = { 0, 0, 0, 0 };
  2466. hexCh[0] = c;
  2467. switch (c) {
  2468. case '+':
  2469. case '?':
  2470. case '\\':
  2471. case '&':
  2472. case ' ':
  2473. case '=':
  2474. case '%':
  2475. sprintf(hexCh, "%%%02X", static_cast<int>(c));
  2476. break;
  2477. case '/':
  2478. if (escapeSlashes) {
  2479. strcpy(hexCh, "%2F");
  2480. }
  2481. break;
  2482. default:
  2483. break;
  2484. }
  2485. out.append(hexCh);
  2486. }
  2487. return out;
  2488. }
  2489. bool cmSystemTools::CreateSymlink(const std::string& origName,
  2490. const std::string& newName,
  2491. std::string* errorMessage)
  2492. {
  2493. uv_fs_t req;
  2494. int flags = 0;
  2495. #if defined(_WIN32)
  2496. if (cmsys::SystemTools::FileIsDirectory(origName)) {
  2497. flags |= UV_FS_SYMLINK_DIR;
  2498. }
  2499. #endif
  2500. int err = uv_fs_symlink(nullptr, &req, origName.c_str(), newName.c_str(),
  2501. flags, nullptr);
  2502. if (err) {
  2503. std::string e =
  2504. "failed to create symbolic link '" + newName + "': " + uv_strerror(err);
  2505. if (errorMessage) {
  2506. *errorMessage = std::move(e);
  2507. } else {
  2508. cmSystemTools::Error(e);
  2509. }
  2510. return false;
  2511. }
  2512. return true;
  2513. }
  2514. bool cmSystemTools::CreateLink(const std::string& origName,
  2515. const std::string& newName,
  2516. std::string* errorMessage)
  2517. {
  2518. uv_fs_t req;
  2519. int err =
  2520. uv_fs_link(nullptr, &req, origName.c_str(), newName.c_str(), nullptr);
  2521. if (err) {
  2522. std::string e =
  2523. "failed to create link '" + newName + "': " + uv_strerror(err);
  2524. if (errorMessage) {
  2525. *errorMessage = std::move(e);
  2526. } else {
  2527. cmSystemTools::Error(e);
  2528. }
  2529. return false;
  2530. }
  2531. return true;
  2532. }