cmSystemTools.cxx 87 KB

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