cmSystemTools.cxx 85 KB

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