cmSystemTools.cxx 94 KB

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