cmSystemTools.cxx 87 KB

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