cmSystemTools.cxx 81 KB

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