cmSystemTools.cxx 82 KB

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