cmFileCommand.cxx 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953
  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 "cmFileCommand.h"
  4. #include <algorithm>
  5. #include <cassert>
  6. #include <cctype>
  7. #include <cmath>
  8. #include <cstdio>
  9. #include <cstdlib>
  10. #include <map>
  11. #include <set>
  12. #include <sstream>
  13. #include <utility>
  14. #include <vector>
  15. #include <cm/memory>
  16. #include <cmext/algorithm>
  17. #include "cmsys/FStream.hxx"
  18. #include "cmsys/Glob.hxx"
  19. #include "cmsys/RegularExpression.hxx"
  20. #include "cm_kwiml.h"
  21. #include "cm_static_string_view.hxx"
  22. #include "cm_sys_stat.h"
  23. #include "cmAlgorithms.h"
  24. #include "cmArgumentParser.h"
  25. #include "cmCryptoHash.h"
  26. #include "cmExecutionStatus.h"
  27. #include "cmFileCopier.h"
  28. #include "cmFileInstaller.h"
  29. #include "cmFileLockPool.h"
  30. #include "cmFileTimes.h"
  31. #include "cmGeneratedFileStream.h"
  32. #include "cmGeneratorExpression.h"
  33. #include "cmGlobalGenerator.h"
  34. #include "cmHexFileConverter.h"
  35. #include "cmListFileCache.h"
  36. #include "cmMakefile.h"
  37. #include "cmMessageType.h"
  38. #include "cmNewLineStyle.h"
  39. #include "cmPolicies.h"
  40. #include "cmRange.h"
  41. #include "cmRuntimeDependencyArchive.h"
  42. #include "cmState.h"
  43. #include "cmStringAlgorithms.h"
  44. #include "cmSubcommandTable.h"
  45. #include "cmSystemTools.h"
  46. #include "cmTimestamp.h"
  47. #include "cmake.h"
  48. #if !defined(CMAKE_BOOTSTRAP)
  49. # include "cm_curl.h"
  50. # include "cmCurl.h"
  51. # include "cmFileLockResult.h"
  52. #endif
  53. #if defined(CMAKE_USE_ELF_PARSER)
  54. # include "cmELF.h"
  55. #endif
  56. #if defined(_WIN32)
  57. # include <windows.h>
  58. #endif
  59. namespace {
  60. #if defined(_WIN32)
  61. // libcurl doesn't support file:// urls for unicode filenames on Windows.
  62. // Convert string from UTF-8 to ACP if this is a file:// URL.
  63. std::string fix_file_url_windows(const std::string& url)
  64. {
  65. std::string ret = url;
  66. if (strncmp(url.c_str(), "file://", 7) == 0) {
  67. std::wstring wurl = cmsys::Encoding::ToWide(url);
  68. if (!wurl.empty()) {
  69. int mblen =
  70. WideCharToMultiByte(CP_ACP, 0, wurl.c_str(), -1, NULL, 0, NULL, NULL);
  71. if (mblen > 0) {
  72. std::vector<char> chars(mblen);
  73. mblen = WideCharToMultiByte(CP_ACP, 0, wurl.c_str(), -1, &chars[0],
  74. mblen, NULL, NULL);
  75. if (mblen > 0) {
  76. ret = &chars[0];
  77. }
  78. }
  79. }
  80. }
  81. return ret;
  82. }
  83. #endif
  84. bool HandleWriteImpl(std::vector<std::string> const& args, bool append,
  85. cmExecutionStatus& status)
  86. {
  87. auto i = args.begin();
  88. i++; // Get rid of subcommand
  89. std::string fileName = *i;
  90. if (!cmsys::SystemTools::FileIsFullPath(*i)) {
  91. fileName =
  92. cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', *i);
  93. }
  94. i++;
  95. if (!status.GetMakefile().CanIWriteThisFile(fileName)) {
  96. std::string e =
  97. "attempted to write a file: " + fileName + " into a source directory.";
  98. status.SetError(e);
  99. cmSystemTools::SetFatalErrorOccured();
  100. return false;
  101. }
  102. std::string dir = cmSystemTools::GetFilenamePath(fileName);
  103. cmSystemTools::MakeDirectory(dir);
  104. mode_t mode = 0;
  105. bool writable = false;
  106. // Set permissions to writable
  107. if (cmSystemTools::GetPermissions(fileName, mode)) {
  108. #if defined(_MSC_VER) || defined(__MINGW32__)
  109. writable = (mode & S_IWRITE) != 0;
  110. mode_t newMode = mode | S_IWRITE;
  111. #else
  112. writable = mode & S_IWUSR;
  113. mode_t newMode = mode | S_IWUSR | S_IWGRP;
  114. #endif
  115. if (!writable) {
  116. cmSystemTools::SetPermissions(fileName, newMode);
  117. }
  118. }
  119. // If GetPermissions fails, pretend like it is ok. File open will fail if
  120. // the file is not writable
  121. cmsys::ofstream file(fileName.c_str(),
  122. append ? std::ios::app : std::ios::out);
  123. if (!file) {
  124. std::string error =
  125. cmStrCat("failed to open for writing (",
  126. cmSystemTools::GetLastSystemError(), "):\n ", fileName);
  127. status.SetError(error);
  128. return false;
  129. }
  130. std::string message = cmJoin(cmMakeRange(i, args.end()), std::string());
  131. file << message;
  132. if (!file) {
  133. std::string error =
  134. cmStrCat("write failed (", cmSystemTools::GetLastSystemError(), "):\n ",
  135. fileName);
  136. status.SetError(error);
  137. return false;
  138. }
  139. file.close();
  140. if (mode && !writable) {
  141. cmSystemTools::SetPermissions(fileName, mode);
  142. }
  143. return true;
  144. }
  145. bool HandleWriteCommand(std::vector<std::string> const& args,
  146. cmExecutionStatus& status)
  147. {
  148. return HandleWriteImpl(args, false, status);
  149. }
  150. bool HandleAppendCommand(std::vector<std::string> const& args,
  151. cmExecutionStatus& status)
  152. {
  153. return HandleWriteImpl(args, true, status);
  154. }
  155. bool HandleReadCommand(std::vector<std::string> const& args,
  156. cmExecutionStatus& status)
  157. {
  158. if (args.size() < 3) {
  159. status.SetError("READ must be called with at least two additional "
  160. "arguments");
  161. return false;
  162. }
  163. std::string const& fileNameArg = args[1];
  164. std::string const& variable = args[2];
  165. struct Arguments
  166. {
  167. std::string Offset;
  168. std::string Limit;
  169. bool Hex = false;
  170. };
  171. static auto const parser = cmArgumentParser<Arguments>{}
  172. .Bind("OFFSET"_s, &Arguments::Offset)
  173. .Bind("LIMIT"_s, &Arguments::Limit)
  174. .Bind("HEX"_s, &Arguments::Hex);
  175. Arguments const arguments = parser.Parse(cmMakeRange(args).advance(3));
  176. std::string fileName = fileNameArg;
  177. if (!cmsys::SystemTools::FileIsFullPath(fileName)) {
  178. fileName = cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/',
  179. fileNameArg);
  180. }
  181. // Open the specified file.
  182. #if defined(_WIN32) || defined(__CYGWIN__)
  183. cmsys::ifstream file(fileName.c_str(),
  184. arguments.Hex ? (std::ios::binary | std::ios::in)
  185. : std::ios::in);
  186. #else
  187. cmsys::ifstream file(fileName.c_str());
  188. #endif
  189. if (!file) {
  190. std::string error =
  191. cmStrCat("failed to open for reading (",
  192. cmSystemTools::GetLastSystemError(), "):\n ", fileName);
  193. status.SetError(error);
  194. return false;
  195. }
  196. // is there a limit?
  197. long sizeLimit = -1;
  198. if (!arguments.Limit.empty()) {
  199. sizeLimit = atoi(arguments.Limit.c_str());
  200. }
  201. // is there an offset?
  202. long offset = 0;
  203. if (!arguments.Offset.empty()) {
  204. offset = atoi(arguments.Offset.c_str());
  205. }
  206. file.seekg(offset, std::ios::beg); // explicit ios::beg for IBM VisualAge 6
  207. std::string output;
  208. if (arguments.Hex) {
  209. // Convert part of the file into hex code
  210. char c;
  211. while ((sizeLimit != 0) && (file.get(c))) {
  212. char hex[4];
  213. sprintf(hex, "%.2x", c & 0xff);
  214. output += hex;
  215. if (sizeLimit > 0) {
  216. sizeLimit--;
  217. }
  218. }
  219. } else {
  220. std::string line;
  221. bool has_newline = false;
  222. while (
  223. sizeLimit != 0 &&
  224. cmSystemTools::GetLineFromStream(file, line, &has_newline, sizeLimit)) {
  225. if (sizeLimit > 0) {
  226. sizeLimit = sizeLimit - static_cast<long>(line.size());
  227. if (has_newline) {
  228. sizeLimit--;
  229. }
  230. if (sizeLimit < 0) {
  231. sizeLimit = 0;
  232. }
  233. }
  234. output += line;
  235. if (has_newline) {
  236. output += "\n";
  237. }
  238. }
  239. }
  240. status.GetMakefile().AddDefinition(variable, output);
  241. return true;
  242. }
  243. bool HandleHashCommand(std::vector<std::string> const& args,
  244. cmExecutionStatus& status)
  245. {
  246. #if !defined(CMAKE_BOOTSTRAP)
  247. if (args.size() != 3) {
  248. status.SetError(
  249. cmStrCat(args[0], " requires a file name and output variable"));
  250. return false;
  251. }
  252. std::unique_ptr<cmCryptoHash> hash(cmCryptoHash::New(args[0]));
  253. if (hash) {
  254. std::string out = hash->HashFile(args[1]);
  255. if (!out.empty()) {
  256. status.GetMakefile().AddDefinition(args[2], out);
  257. return true;
  258. }
  259. status.SetError(cmStrCat(args[0], " failed to read file \"", args[1],
  260. "\": ", cmSystemTools::GetLastSystemError()));
  261. }
  262. return false;
  263. #else
  264. status.SetError(cmStrCat(args[0], " not available during bootstrap"));
  265. return false;
  266. #endif
  267. }
  268. bool HandleStringsCommand(std::vector<std::string> const& args,
  269. cmExecutionStatus& status)
  270. {
  271. if (args.size() < 3) {
  272. status.SetError("STRINGS requires a file name and output variable");
  273. return false;
  274. }
  275. // Get the file to read.
  276. std::string fileName = args[1];
  277. if (!cmsys::SystemTools::FileIsFullPath(fileName)) {
  278. fileName =
  279. cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', args[1]);
  280. }
  281. // Get the variable in which to store the results.
  282. std::string outVar = args[2];
  283. // Parse the options.
  284. enum
  285. {
  286. arg_none,
  287. arg_limit_input,
  288. arg_limit_output,
  289. arg_limit_count,
  290. arg_length_minimum,
  291. arg_length_maximum,
  292. arg__maximum,
  293. arg_regex,
  294. arg_encoding
  295. };
  296. unsigned int minlen = 0;
  297. unsigned int maxlen = 0;
  298. int limit_input = -1;
  299. int limit_output = -1;
  300. unsigned int limit_count = 0;
  301. cmsys::RegularExpression regex;
  302. bool have_regex = false;
  303. bool newline_consume = false;
  304. bool hex_conversion_enabled = true;
  305. enum
  306. {
  307. encoding_none = cmsys::FStream::BOM_None,
  308. encoding_utf8 = cmsys::FStream::BOM_UTF8,
  309. encoding_utf16le = cmsys::FStream::BOM_UTF16LE,
  310. encoding_utf16be = cmsys::FStream::BOM_UTF16BE,
  311. encoding_utf32le = cmsys::FStream::BOM_UTF32LE,
  312. encoding_utf32be = cmsys::FStream::BOM_UTF32BE
  313. };
  314. int encoding = encoding_none;
  315. int arg_mode = arg_none;
  316. for (unsigned int i = 3; i < args.size(); ++i) {
  317. if (args[i] == "LIMIT_INPUT") {
  318. arg_mode = arg_limit_input;
  319. } else if (args[i] == "LIMIT_OUTPUT") {
  320. arg_mode = arg_limit_output;
  321. } else if (args[i] == "LIMIT_COUNT") {
  322. arg_mode = arg_limit_count;
  323. } else if (args[i] == "LENGTH_MINIMUM") {
  324. arg_mode = arg_length_minimum;
  325. } else if (args[i] == "LENGTH_MAXIMUM") {
  326. arg_mode = arg_length_maximum;
  327. } else if (args[i] == "REGEX") {
  328. arg_mode = arg_regex;
  329. } else if (args[i] == "NEWLINE_CONSUME") {
  330. newline_consume = true;
  331. arg_mode = arg_none;
  332. } else if (args[i] == "NO_HEX_CONVERSION") {
  333. hex_conversion_enabled = false;
  334. arg_mode = arg_none;
  335. } else if (args[i] == "ENCODING") {
  336. arg_mode = arg_encoding;
  337. } else if (arg_mode == arg_limit_input) {
  338. if (sscanf(args[i].c_str(), "%d", &limit_input) != 1 ||
  339. limit_input < 0) {
  340. status.SetError(cmStrCat("STRINGS option LIMIT_INPUT value \"",
  341. args[i], "\" is not an unsigned integer."));
  342. return false;
  343. }
  344. arg_mode = arg_none;
  345. } else if (arg_mode == arg_limit_output) {
  346. if (sscanf(args[i].c_str(), "%d", &limit_output) != 1 ||
  347. limit_output < 0) {
  348. status.SetError(cmStrCat("STRINGS option LIMIT_OUTPUT value \"",
  349. args[i], "\" is not an unsigned integer."));
  350. return false;
  351. }
  352. arg_mode = arg_none;
  353. } else if (arg_mode == arg_limit_count) {
  354. int count;
  355. if (sscanf(args[i].c_str(), "%d", &count) != 1 || count < 0) {
  356. status.SetError(cmStrCat("STRINGS option LIMIT_COUNT value \"",
  357. args[i], "\" is not an unsigned integer."));
  358. return false;
  359. }
  360. limit_count = count;
  361. arg_mode = arg_none;
  362. } else if (arg_mode == arg_length_minimum) {
  363. int len;
  364. if (sscanf(args[i].c_str(), "%d", &len) != 1 || len < 0) {
  365. status.SetError(cmStrCat("STRINGS option LENGTH_MINIMUM value \"",
  366. args[i], "\" is not an unsigned integer."));
  367. return false;
  368. }
  369. minlen = len;
  370. arg_mode = arg_none;
  371. } else if (arg_mode == arg_length_maximum) {
  372. int len;
  373. if (sscanf(args[i].c_str(), "%d", &len) != 1 || len < 0) {
  374. status.SetError(cmStrCat("STRINGS option LENGTH_MAXIMUM value \"",
  375. args[i], "\" is not an unsigned integer."));
  376. return false;
  377. }
  378. maxlen = len;
  379. arg_mode = arg_none;
  380. } else if (arg_mode == arg_regex) {
  381. if (!regex.compile(args[i])) {
  382. status.SetError(cmStrCat("STRINGS option REGEX value \"", args[i],
  383. "\" could not be compiled."));
  384. return false;
  385. }
  386. have_regex = true;
  387. arg_mode = arg_none;
  388. } else if (arg_mode == arg_encoding) {
  389. if (args[i] == "UTF-8") {
  390. encoding = encoding_utf8;
  391. } else if (args[i] == "UTF-16LE") {
  392. encoding = encoding_utf16le;
  393. } else if (args[i] == "UTF-16BE") {
  394. encoding = encoding_utf16be;
  395. } else if (args[i] == "UTF-32LE") {
  396. encoding = encoding_utf32le;
  397. } else if (args[i] == "UTF-32BE") {
  398. encoding = encoding_utf32be;
  399. } else {
  400. status.SetError(cmStrCat("STRINGS option ENCODING \"", args[i],
  401. "\" not recognized."));
  402. return false;
  403. }
  404. arg_mode = arg_none;
  405. } else {
  406. status.SetError(
  407. cmStrCat("STRINGS given unknown argument \"", args[i], "\""));
  408. return false;
  409. }
  410. }
  411. if (hex_conversion_enabled) {
  412. // TODO: should work without temp file, but just on a memory buffer
  413. std::string binaryFileName =
  414. cmStrCat(status.GetMakefile().GetCurrentBinaryDirectory(),
  415. "/CMakeFiles/FileCommandStringsBinaryFile");
  416. if (cmHexFileConverter::TryConvert(fileName, binaryFileName)) {
  417. fileName = binaryFileName;
  418. }
  419. }
  420. // Open the specified file.
  421. #if defined(_WIN32) || defined(__CYGWIN__)
  422. cmsys::ifstream fin(fileName.c_str(), std::ios::in | std::ios::binary);
  423. #else
  424. cmsys::ifstream fin(fileName.c_str());
  425. #endif
  426. if (!fin) {
  427. status.SetError(
  428. cmStrCat("STRINGS file \"", fileName, "\" cannot be read."));
  429. return false;
  430. }
  431. // If BOM is found and encoding was not specified, use the BOM
  432. int bom_found = cmsys::FStream::ReadBOM(fin);
  433. if (encoding == encoding_none && bom_found != cmsys::FStream::BOM_None) {
  434. encoding = bom_found;
  435. }
  436. unsigned int bytes_rem = 0;
  437. if (encoding == encoding_utf16le || encoding == encoding_utf16be) {
  438. bytes_rem = 1;
  439. }
  440. if (encoding == encoding_utf32le || encoding == encoding_utf32be) {
  441. bytes_rem = 3;
  442. }
  443. // Parse strings out of the file.
  444. int output_size = 0;
  445. std::vector<std::string> strings;
  446. std::string s;
  447. while ((!limit_count || strings.size() < limit_count) &&
  448. (limit_input < 0 || static_cast<int>(fin.tellg()) < limit_input) &&
  449. fin) {
  450. std::string current_str;
  451. int c = fin.get();
  452. for (unsigned int i = 0; i < bytes_rem; ++i) {
  453. int c1 = fin.get();
  454. if (!fin) {
  455. fin.putback(static_cast<char>(c1));
  456. break;
  457. }
  458. c = (c << 8) | c1;
  459. }
  460. if (encoding == encoding_utf16le) {
  461. c = ((c & 0xFF) << 8) | ((c & 0xFF00) >> 8);
  462. } else if (encoding == encoding_utf32le) {
  463. c = (((c & 0xFF) << 24) | ((c & 0xFF00) << 8) | ((c & 0xFF0000) >> 8) |
  464. ((c & 0xFF000000) >> 24));
  465. }
  466. if (c == '\r') {
  467. // Ignore CR character to make output always have UNIX newlines.
  468. continue;
  469. }
  470. if (c >= 0 && c <= 0xFF &&
  471. (isprint(c) || c == '\t' || (c == '\n' && newline_consume))) {
  472. // This is an ASCII character that may be part of a string.
  473. // Cast added to avoid compiler warning. Cast is ok because
  474. // c is guaranteed to fit in char by the above if...
  475. current_str += static_cast<char>(c);
  476. } else if (encoding == encoding_utf8) {
  477. // Check for UTF-8 encoded string (up to 4 octets)
  478. static const unsigned char utf8_check_table[3][2] = {
  479. { 0xE0, 0xC0 },
  480. { 0xF0, 0xE0 },
  481. { 0xF8, 0xF0 },
  482. };
  483. // how many octets are there?
  484. unsigned int num_utf8_bytes = 0;
  485. for (unsigned int j = 0; num_utf8_bytes == 0 && j < 3; j++) {
  486. if ((c & utf8_check_table[j][0]) == utf8_check_table[j][1]) {
  487. num_utf8_bytes = j + 2;
  488. }
  489. }
  490. // get subsequent octets and check that they are valid
  491. for (unsigned int j = 0; j < num_utf8_bytes; j++) {
  492. if (j != 0) {
  493. c = fin.get();
  494. if (!fin || (c & 0xC0) != 0x80) {
  495. fin.putback(static_cast<char>(c));
  496. break;
  497. }
  498. }
  499. current_str += static_cast<char>(c);
  500. }
  501. // if this was an invalid utf8 sequence, discard the data, and put
  502. // back subsequent characters
  503. if ((current_str.length() != num_utf8_bytes)) {
  504. for (unsigned int j = 0; j < current_str.size() - 1; j++) {
  505. c = current_str[current_str.size() - 1 - j];
  506. fin.putback(static_cast<char>(c));
  507. }
  508. current_str.clear();
  509. }
  510. }
  511. if (c == '\n' && !newline_consume) {
  512. // The current line has been terminated. Check if the current
  513. // string matches the requirements. The length may now be as
  514. // low as zero since blank lines are allowed.
  515. if (s.length() >= minlen && (!have_regex || regex.find(s))) {
  516. output_size += static_cast<int>(s.size()) + 1;
  517. if (limit_output >= 0 && output_size >= limit_output) {
  518. s.clear();
  519. break;
  520. }
  521. strings.push_back(s);
  522. }
  523. // Reset the string to empty.
  524. s.clear();
  525. } else if (current_str.empty()) {
  526. // A non-string character has been found. Check if the current
  527. // string matches the requirements. We require that the length
  528. // be at least one no matter what the user specified.
  529. if (s.length() >= minlen && !s.empty() &&
  530. (!have_regex || regex.find(s))) {
  531. output_size += static_cast<int>(s.size()) + 1;
  532. if (limit_output >= 0 && output_size >= limit_output) {
  533. s.clear();
  534. break;
  535. }
  536. strings.push_back(s);
  537. }
  538. // Reset the string to empty.
  539. s.clear();
  540. } else {
  541. s += current_str;
  542. }
  543. if (maxlen > 0 && s.size() == maxlen) {
  544. // Terminate a string if the maximum length is reached.
  545. if (s.length() >= minlen && (!have_regex || regex.find(s))) {
  546. output_size += static_cast<int>(s.size()) + 1;
  547. if (limit_output >= 0 && output_size >= limit_output) {
  548. s.clear();
  549. break;
  550. }
  551. strings.push_back(s);
  552. }
  553. s.clear();
  554. }
  555. }
  556. // If there is a non-empty current string we have hit the end of the
  557. // input file or the input size limit. Check if the current string
  558. // matches the requirements.
  559. if ((!limit_count || strings.size() < limit_count) && !s.empty() &&
  560. s.length() >= minlen && (!have_regex || regex.find(s))) {
  561. output_size += static_cast<int>(s.size()) + 1;
  562. if (limit_output < 0 || output_size < limit_output) {
  563. strings.push_back(s);
  564. }
  565. }
  566. // Encode the result in a CMake list.
  567. const char* sep = "";
  568. std::string output;
  569. for (std::string const& sr : strings) {
  570. // Separate the strings in the output to make it a list.
  571. output += sep;
  572. sep = ";";
  573. // Store the string in the output, but escape semicolons to
  574. // make sure it is a list.
  575. for (char i : sr) {
  576. if (i == ';') {
  577. output += '\\';
  578. }
  579. output += i;
  580. }
  581. }
  582. // Save the output in a makefile variable.
  583. status.GetMakefile().AddDefinition(outVar, output);
  584. return true;
  585. }
  586. bool HandleGlobImpl(std::vector<std::string> const& args, bool recurse,
  587. cmExecutionStatus& status)
  588. {
  589. // File commands has at least one argument
  590. assert(args.size() > 1);
  591. auto i = args.begin();
  592. i++; // Get rid of subcommand
  593. std::string variable = *i;
  594. i++;
  595. cmsys::Glob g;
  596. g.SetRecurse(recurse);
  597. bool explicitFollowSymlinks = false;
  598. cmPolicies::PolicyStatus policyStatus =
  599. status.GetMakefile().GetPolicyStatus(cmPolicies::CMP0009);
  600. if (recurse) {
  601. switch (policyStatus) {
  602. case cmPolicies::REQUIRED_IF_USED:
  603. case cmPolicies::REQUIRED_ALWAYS:
  604. case cmPolicies::NEW:
  605. g.RecurseThroughSymlinksOff();
  606. break;
  607. case cmPolicies::OLD:
  608. case cmPolicies::WARN:
  609. g.RecurseThroughSymlinksOn();
  610. break;
  611. }
  612. }
  613. std::vector<std::string> files;
  614. bool configureDepends = false;
  615. bool warnConfigureLate = false;
  616. bool warnFollowedSymlinks = false;
  617. const cmake::WorkingMode workingMode =
  618. status.GetMakefile().GetCMakeInstance()->GetWorkingMode();
  619. while (i != args.end()) {
  620. if (*i == "LIST_DIRECTORIES") {
  621. ++i; // skip LIST_DIRECTORIES
  622. if (i != args.end()) {
  623. if (cmIsOn(*i)) {
  624. g.SetListDirs(true);
  625. g.SetRecurseListDirs(true);
  626. } else if (cmIsOff(*i)) {
  627. g.SetListDirs(false);
  628. g.SetRecurseListDirs(false);
  629. } else {
  630. status.SetError("LIST_DIRECTORIES missing bool value.");
  631. return false;
  632. }
  633. ++i;
  634. } else {
  635. status.SetError("LIST_DIRECTORIES missing bool value.");
  636. return false;
  637. }
  638. } else if (*i == "FOLLOW_SYMLINKS") {
  639. ++i; // skip FOLLOW_SYMLINKS
  640. if (recurse) {
  641. explicitFollowSymlinks = true;
  642. g.RecurseThroughSymlinksOn();
  643. if (i == args.end()) {
  644. status.SetError(
  645. "GLOB_RECURSE requires a glob expression after FOLLOW_SYMLINKS.");
  646. return false;
  647. }
  648. }
  649. } else if (*i == "RELATIVE") {
  650. ++i; // skip RELATIVE
  651. if (i == args.end()) {
  652. status.SetError("GLOB requires a directory after the RELATIVE tag.");
  653. return false;
  654. }
  655. g.SetRelative(i->c_str());
  656. ++i;
  657. if (i == args.end()) {
  658. status.SetError(
  659. "GLOB requires a glob expression after the directory.");
  660. return false;
  661. }
  662. } else if (*i == "CONFIGURE_DEPENDS") {
  663. // Generated build system depends on glob results
  664. if (!configureDepends && warnConfigureLate) {
  665. status.GetMakefile().IssueMessage(
  666. MessageType::AUTHOR_WARNING,
  667. "CONFIGURE_DEPENDS flag was given after a glob expression was "
  668. "already evaluated.");
  669. }
  670. if (workingMode != cmake::NORMAL_MODE) {
  671. status.GetMakefile().IssueMessage(
  672. MessageType::FATAL_ERROR,
  673. "CONFIGURE_DEPENDS is invalid for script and find package modes.");
  674. return false;
  675. }
  676. configureDepends = true;
  677. ++i;
  678. if (i == args.end()) {
  679. status.SetError(
  680. "GLOB requires a glob expression after CONFIGURE_DEPENDS.");
  681. return false;
  682. }
  683. } else {
  684. std::string expr = *i;
  685. if (!cmsys::SystemTools::FileIsFullPath(*i)) {
  686. expr = status.GetMakefile().GetCurrentSourceDirectory();
  687. // Handle script mode
  688. if (!expr.empty()) {
  689. expr += "/" + *i;
  690. } else {
  691. expr = *i;
  692. }
  693. }
  694. cmsys::Glob::GlobMessages globMessages;
  695. g.FindFiles(expr, &globMessages);
  696. if (!globMessages.empty()) {
  697. bool shouldExit = false;
  698. for (cmsys::Glob::Message const& globMessage : globMessages) {
  699. if (globMessage.type == cmsys::Glob::cyclicRecursion) {
  700. status.GetMakefile().IssueMessage(
  701. MessageType::AUTHOR_WARNING,
  702. "Cyclic recursion detected while globbing for '" + *i + "':\n" +
  703. globMessage.content);
  704. } else {
  705. status.GetMakefile().IssueMessage(
  706. MessageType::FATAL_ERROR,
  707. "Error has occurred while globbing for '" + *i + "' - " +
  708. globMessage.content);
  709. shouldExit = true;
  710. }
  711. }
  712. if (shouldExit) {
  713. return false;
  714. }
  715. }
  716. if (recurse && !explicitFollowSymlinks &&
  717. g.GetFollowedSymlinkCount() != 0) {
  718. warnFollowedSymlinks = true;
  719. }
  720. std::vector<std::string>& foundFiles = g.GetFiles();
  721. cm::append(files, foundFiles);
  722. if (configureDepends) {
  723. std::sort(foundFiles.begin(), foundFiles.end());
  724. foundFiles.erase(std::unique(foundFiles.begin(), foundFiles.end()),
  725. foundFiles.end());
  726. status.GetMakefile().GetCMakeInstance()->AddGlobCacheEntry(
  727. recurse, (recurse ? g.GetRecurseListDirs() : g.GetListDirs()),
  728. (recurse ? g.GetRecurseThroughSymlinks() : false),
  729. (g.GetRelative() ? g.GetRelative() : ""), expr, foundFiles, variable,
  730. status.GetMakefile().GetBacktrace());
  731. } else {
  732. warnConfigureLate = true;
  733. }
  734. ++i;
  735. }
  736. }
  737. switch (policyStatus) {
  738. case cmPolicies::REQUIRED_IF_USED:
  739. case cmPolicies::REQUIRED_ALWAYS:
  740. case cmPolicies::NEW:
  741. // Correct behavior, yay!
  742. break;
  743. case cmPolicies::OLD:
  744. // Probably not really the expected behavior, but the author explicitly
  745. // asked for the old behavior... no warning.
  746. case cmPolicies::WARN:
  747. // Possibly unexpected old behavior *and* we actually traversed
  748. // symlinks without being explicitly asked to: warn the author.
  749. if (warnFollowedSymlinks) {
  750. status.GetMakefile().IssueMessage(
  751. MessageType::AUTHOR_WARNING,
  752. cmPolicies::GetPolicyWarning(cmPolicies::CMP0009));
  753. }
  754. break;
  755. }
  756. std::sort(files.begin(), files.end());
  757. files.erase(std::unique(files.begin(), files.end()), files.end());
  758. status.GetMakefile().AddDefinition(variable, cmJoin(files, ";"));
  759. return true;
  760. }
  761. bool HandleGlobCommand(std::vector<std::string> const& args,
  762. cmExecutionStatus& status)
  763. {
  764. return HandleGlobImpl(args, false, status);
  765. }
  766. bool HandleGlobRecurseCommand(std::vector<std::string> const& args,
  767. cmExecutionStatus& status)
  768. {
  769. return HandleGlobImpl(args, true, status);
  770. }
  771. bool HandleMakeDirectoryCommand(std::vector<std::string> const& args,
  772. cmExecutionStatus& status)
  773. {
  774. // File command has at least one argument
  775. assert(args.size() > 1);
  776. std::string expr;
  777. for (std::string const& arg :
  778. cmMakeRange(args).advance(1)) // Get rid of subcommand
  779. {
  780. const std::string* cdir = &arg;
  781. if (!cmsys::SystemTools::FileIsFullPath(arg)) {
  782. expr =
  783. cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', arg);
  784. cdir = &expr;
  785. }
  786. if (!status.GetMakefile().CanIWriteThisFile(*cdir)) {
  787. std::string e = "attempted to create a directory: " + *cdir +
  788. " into a source directory.";
  789. status.SetError(e);
  790. cmSystemTools::SetFatalErrorOccured();
  791. return false;
  792. }
  793. if (!cmSystemTools::MakeDirectory(*cdir)) {
  794. std::string error = "problem creating directory: " + *cdir;
  795. status.SetError(error);
  796. return false;
  797. }
  798. }
  799. return true;
  800. }
  801. bool HandleTouchImpl(std::vector<std::string> const& args, bool create,
  802. cmExecutionStatus& status)
  803. {
  804. // File command has at least one argument
  805. assert(args.size() > 1);
  806. for (std::string const& arg :
  807. cmMakeRange(args).advance(1)) // Get rid of subcommand
  808. {
  809. std::string tfile = arg;
  810. if (!cmsys::SystemTools::FileIsFullPath(tfile)) {
  811. tfile =
  812. cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', arg);
  813. }
  814. if (!status.GetMakefile().CanIWriteThisFile(tfile)) {
  815. std::string e =
  816. "attempted to touch a file: " + tfile + " in a source directory.";
  817. status.SetError(e);
  818. cmSystemTools::SetFatalErrorOccured();
  819. return false;
  820. }
  821. if (!cmSystemTools::Touch(tfile, create)) {
  822. std::string error = "problem touching file: " + tfile;
  823. status.SetError(error);
  824. return false;
  825. }
  826. }
  827. return true;
  828. }
  829. bool HandleTouchCommand(std::vector<std::string> const& args,
  830. cmExecutionStatus& status)
  831. {
  832. return HandleTouchImpl(args, true, status);
  833. }
  834. bool HandleTouchNocreateCommand(std::vector<std::string> const& args,
  835. cmExecutionStatus& status)
  836. {
  837. return HandleTouchImpl(args, false, status);
  838. }
  839. bool HandleDifferentCommand(std::vector<std::string> const& args,
  840. cmExecutionStatus& status)
  841. {
  842. /*
  843. FILE(DIFFERENT <variable> FILES <lhs> <rhs>)
  844. */
  845. // Evaluate arguments.
  846. const char* file_lhs = nullptr;
  847. const char* file_rhs = nullptr;
  848. const char* var = nullptr;
  849. enum Doing
  850. {
  851. DoingNone,
  852. DoingVar,
  853. DoingFileLHS,
  854. DoingFileRHS
  855. };
  856. Doing doing = DoingVar;
  857. for (unsigned int i = 1; i < args.size(); ++i) {
  858. if (args[i] == "FILES") {
  859. doing = DoingFileLHS;
  860. } else if (doing == DoingVar) {
  861. var = args[i].c_str();
  862. doing = DoingNone;
  863. } else if (doing == DoingFileLHS) {
  864. file_lhs = args[i].c_str();
  865. doing = DoingFileRHS;
  866. } else if (doing == DoingFileRHS) {
  867. file_rhs = args[i].c_str();
  868. doing = DoingNone;
  869. } else {
  870. status.SetError(cmStrCat("DIFFERENT given unknown argument ", args[i]));
  871. return false;
  872. }
  873. }
  874. if (!var) {
  875. status.SetError("DIFFERENT not given result variable name.");
  876. return false;
  877. }
  878. if (!file_lhs || !file_rhs) {
  879. status.SetError("DIFFERENT not given FILES option with two file names.");
  880. return false;
  881. }
  882. // Compare the files.
  883. const char* result =
  884. cmSystemTools::FilesDiffer(file_lhs, file_rhs) ? "1" : "0";
  885. status.GetMakefile().AddDefinition(var, result);
  886. return true;
  887. }
  888. bool HandleCopyCommand(std::vector<std::string> const& args,
  889. cmExecutionStatus& status)
  890. {
  891. cmFileCopier copier(status);
  892. return copier.Run(args);
  893. }
  894. bool HandleRPathChangeCommand(std::vector<std::string> const& args,
  895. cmExecutionStatus& status)
  896. {
  897. // Evaluate arguments.
  898. std::string file;
  899. const char* oldRPath = nullptr;
  900. const char* newRPath = nullptr;
  901. bool removeEnvironmentRPath = false;
  902. enum Doing
  903. {
  904. DoingNone,
  905. DoingFile,
  906. DoingOld,
  907. DoingNew
  908. };
  909. Doing doing = DoingNone;
  910. for (unsigned int i = 1; i < args.size(); ++i) {
  911. if (args[i] == "OLD_RPATH") {
  912. doing = DoingOld;
  913. } else if (args[i] == "NEW_RPATH") {
  914. doing = DoingNew;
  915. } else if (args[i] == "FILE") {
  916. doing = DoingFile;
  917. } else if (args[i] == "INSTALL_REMOVE_ENVIRONMENT_RPATH") {
  918. removeEnvironmentRPath = true;
  919. } else if (doing == DoingFile) {
  920. file = args[i];
  921. doing = DoingNone;
  922. } else if (doing == DoingOld) {
  923. oldRPath = args[i].c_str();
  924. doing = DoingNone;
  925. } else if (doing == DoingNew) {
  926. newRPath = args[i].c_str();
  927. doing = DoingNone;
  928. } else {
  929. status.SetError(
  930. cmStrCat("RPATH_CHANGE given unknown argument ", args[i]));
  931. return false;
  932. }
  933. }
  934. if (file.empty()) {
  935. status.SetError("RPATH_CHANGE not given FILE option.");
  936. return false;
  937. }
  938. if (!oldRPath) {
  939. status.SetError("RPATH_CHANGE not given OLD_RPATH option.");
  940. return false;
  941. }
  942. if (!newRPath) {
  943. status.SetError("RPATH_CHANGE not given NEW_RPATH option.");
  944. return false;
  945. }
  946. if (!cmSystemTools::FileExists(file, true)) {
  947. status.SetError(
  948. cmStrCat("RPATH_CHANGE given FILE \"", file, "\" that does not exist."));
  949. return false;
  950. }
  951. bool success = true;
  952. cmFileTimes const ft(file);
  953. std::string emsg;
  954. bool changed;
  955. if (!cmSystemTools::ChangeRPath(file, oldRPath, newRPath,
  956. removeEnvironmentRPath, &emsg, &changed)) {
  957. status.SetError(cmStrCat("RPATH_CHANGE could not write new RPATH:\n ",
  958. newRPath, "\nto the file:\n ", file, "\n",
  959. emsg));
  960. success = false;
  961. }
  962. if (success) {
  963. if (changed) {
  964. std::string message =
  965. cmStrCat("Set runtime path of \"", file, "\" to \"", newRPath, '"');
  966. status.GetMakefile().DisplayStatus(message, -1);
  967. }
  968. ft.Store(file);
  969. }
  970. return success;
  971. }
  972. bool HandleRPathRemoveCommand(std::vector<std::string> const& args,
  973. cmExecutionStatus& status)
  974. {
  975. // Evaluate arguments.
  976. std::string file;
  977. enum Doing
  978. {
  979. DoingNone,
  980. DoingFile
  981. };
  982. Doing doing = DoingNone;
  983. for (unsigned int i = 1; i < args.size(); ++i) {
  984. if (args[i] == "FILE") {
  985. doing = DoingFile;
  986. } else if (doing == DoingFile) {
  987. file = args[i];
  988. doing = DoingNone;
  989. } else {
  990. status.SetError(
  991. cmStrCat("RPATH_REMOVE given unknown argument ", args[i]));
  992. return false;
  993. }
  994. }
  995. if (file.empty()) {
  996. status.SetError("RPATH_REMOVE not given FILE option.");
  997. return false;
  998. }
  999. if (!cmSystemTools::FileExists(file, true)) {
  1000. status.SetError(
  1001. cmStrCat("RPATH_REMOVE given FILE \"", file, "\" that does not exist."));
  1002. return false;
  1003. }
  1004. bool success = true;
  1005. cmFileTimes const ft(file);
  1006. std::string emsg;
  1007. bool removed;
  1008. if (!cmSystemTools::RemoveRPath(file, &emsg, &removed)) {
  1009. status.SetError(
  1010. cmStrCat("RPATH_REMOVE could not remove RPATH from file: \n ", file,
  1011. "\n", emsg));
  1012. success = false;
  1013. }
  1014. if (success) {
  1015. if (removed) {
  1016. std::string message =
  1017. cmStrCat("Removed runtime path from \"", file, '"');
  1018. status.GetMakefile().DisplayStatus(message, -1);
  1019. }
  1020. ft.Store(file);
  1021. }
  1022. return success;
  1023. }
  1024. bool HandleRPathCheckCommand(std::vector<std::string> const& args,
  1025. cmExecutionStatus& status)
  1026. {
  1027. // Evaluate arguments.
  1028. std::string file;
  1029. const char* rpath = nullptr;
  1030. enum Doing
  1031. {
  1032. DoingNone,
  1033. DoingFile,
  1034. DoingRPath
  1035. };
  1036. Doing doing = DoingNone;
  1037. for (unsigned int i = 1; i < args.size(); ++i) {
  1038. if (args[i] == "RPATH") {
  1039. doing = DoingRPath;
  1040. } else if (args[i] == "FILE") {
  1041. doing = DoingFile;
  1042. } else if (doing == DoingFile) {
  1043. file = args[i];
  1044. doing = DoingNone;
  1045. } else if (doing == DoingRPath) {
  1046. rpath = args[i].c_str();
  1047. doing = DoingNone;
  1048. } else {
  1049. status.SetError(
  1050. cmStrCat("RPATH_CHECK given unknown argument ", args[i]));
  1051. return false;
  1052. }
  1053. }
  1054. if (file.empty()) {
  1055. status.SetError("RPATH_CHECK not given FILE option.");
  1056. return false;
  1057. }
  1058. if (!rpath) {
  1059. status.SetError("RPATH_CHECK not given RPATH option.");
  1060. return false;
  1061. }
  1062. // If the file exists but does not have the desired RPath then
  1063. // delete it. This is used during installation to re-install a file
  1064. // if its RPath will change.
  1065. if (cmSystemTools::FileExists(file, true) &&
  1066. !cmSystemTools::CheckRPath(file, rpath)) {
  1067. cmSystemTools::RemoveFile(file);
  1068. }
  1069. return true;
  1070. }
  1071. bool HandleReadElfCommand(std::vector<std::string> const& args,
  1072. cmExecutionStatus& status)
  1073. {
  1074. if (args.size() < 4) {
  1075. status.SetError("READ_ELF must be called with at least three additional "
  1076. "arguments.");
  1077. return false;
  1078. }
  1079. std::string const& fileNameArg = args[1];
  1080. struct Arguments
  1081. {
  1082. std::string RPath;
  1083. std::string RunPath;
  1084. std::string Error;
  1085. };
  1086. static auto const parser = cmArgumentParser<Arguments>{}
  1087. .Bind("RPATH"_s, &Arguments::RPath)
  1088. .Bind("RUNPATH"_s, &Arguments::RunPath)
  1089. .Bind("CAPTURE_ERROR"_s, &Arguments::Error);
  1090. Arguments const arguments = parser.Parse(cmMakeRange(args).advance(2));
  1091. if (!cmSystemTools::FileExists(fileNameArg, true)) {
  1092. status.SetError(cmStrCat("READ_ELF given FILE \"", fileNameArg,
  1093. "\" that does not exist."));
  1094. return false;
  1095. }
  1096. #if defined(CMAKE_USE_ELF_PARSER)
  1097. cmELF elf(fileNameArg.c_str());
  1098. if (!arguments.RPath.empty()) {
  1099. if (cmELF::StringEntry const* se_rpath = elf.GetRPath()) {
  1100. std::string rpath(se_rpath->Value);
  1101. std::replace(rpath.begin(), rpath.end(), ':', ';');
  1102. status.GetMakefile().AddDefinition(arguments.RPath, rpath);
  1103. }
  1104. }
  1105. if (!arguments.RunPath.empty()) {
  1106. if (cmELF::StringEntry const* se_runpath = elf.GetRunPath()) {
  1107. std::string runpath(se_runpath->Value);
  1108. std::replace(runpath.begin(), runpath.end(), ':', ';');
  1109. status.GetMakefile().AddDefinition(arguments.RunPath, runpath);
  1110. }
  1111. }
  1112. return true;
  1113. #else
  1114. std::string error = "ELF parser not available on this platform.";
  1115. if (arguments.Error.empty()) {
  1116. status.SetError(error);
  1117. return false;
  1118. }
  1119. status.GetMakefile().AddDefinition(arguments.Error, error);
  1120. return true;
  1121. #endif
  1122. }
  1123. bool HandleInstallCommand(std::vector<std::string> const& args,
  1124. cmExecutionStatus& status)
  1125. {
  1126. cmFileInstaller installer(status);
  1127. return installer.Run(args);
  1128. }
  1129. bool HandleRelativePathCommand(std::vector<std::string> const& args,
  1130. cmExecutionStatus& status)
  1131. {
  1132. if (args.size() != 4) {
  1133. status.SetError("RELATIVE_PATH called with incorrect number of arguments");
  1134. return false;
  1135. }
  1136. const std::string& outVar = args[1];
  1137. const std::string& directoryName = args[2];
  1138. const std::string& fileName = args[3];
  1139. if (!cmSystemTools::FileIsFullPath(directoryName)) {
  1140. std::string errstring =
  1141. "RELATIVE_PATH must be passed a full path to the directory: " +
  1142. directoryName;
  1143. status.SetError(errstring);
  1144. return false;
  1145. }
  1146. if (!cmSystemTools::FileIsFullPath(fileName)) {
  1147. std::string errstring =
  1148. "RELATIVE_PATH must be passed a full path to the file: " + fileName;
  1149. status.SetError(errstring);
  1150. return false;
  1151. }
  1152. std::string res = cmSystemTools::RelativePath(directoryName, fileName);
  1153. status.GetMakefile().AddDefinition(outVar, res);
  1154. return true;
  1155. }
  1156. bool HandleRename(std::vector<std::string> const& args,
  1157. cmExecutionStatus& status)
  1158. {
  1159. if (args.size() != 3) {
  1160. status.SetError("RENAME given incorrect number of arguments.");
  1161. return false;
  1162. }
  1163. // Compute full path for old and new names.
  1164. std::string oldname = args[1];
  1165. if (!cmsys::SystemTools::FileIsFullPath(oldname)) {
  1166. oldname =
  1167. cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', args[1]);
  1168. }
  1169. std::string newname = args[2];
  1170. if (!cmsys::SystemTools::FileIsFullPath(newname)) {
  1171. newname =
  1172. cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', args[2]);
  1173. }
  1174. if (!cmSystemTools::RenameFile(oldname, newname)) {
  1175. std::string err = cmSystemTools::GetLastSystemError();
  1176. status.SetError(cmStrCat("RENAME failed to rename\n ", oldname,
  1177. "\nto\n ", newname, "\nbecause: ", err, "\n"));
  1178. return false;
  1179. }
  1180. return true;
  1181. }
  1182. bool HandleRemoveImpl(std::vector<std::string> const& args, bool recurse,
  1183. cmExecutionStatus& status)
  1184. {
  1185. std::string message;
  1186. for (std::string const& arg :
  1187. cmMakeRange(args).advance(1)) // Get rid of subcommand
  1188. {
  1189. std::string fileName = arg;
  1190. if (fileName.empty()) {
  1191. std::string const r = recurse ? "REMOVE_RECURSE" : "REMOVE";
  1192. status.GetMakefile().IssueMessage(
  1193. MessageType::AUTHOR_WARNING, "Ignoring empty file name in " + r + ".");
  1194. continue;
  1195. }
  1196. if (!cmsys::SystemTools::FileIsFullPath(fileName)) {
  1197. fileName =
  1198. cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', arg);
  1199. }
  1200. if (cmSystemTools::FileIsDirectory(fileName) &&
  1201. !cmSystemTools::FileIsSymlink(fileName) && recurse) {
  1202. cmSystemTools::RepeatedRemoveDirectory(fileName);
  1203. } else {
  1204. cmSystemTools::RemoveFile(fileName);
  1205. }
  1206. }
  1207. return true;
  1208. }
  1209. bool HandleRemove(std::vector<std::string> const& args,
  1210. cmExecutionStatus& status)
  1211. {
  1212. return HandleRemoveImpl(args, false, status);
  1213. }
  1214. bool HandleRemoveRecurse(std::vector<std::string> const& args,
  1215. cmExecutionStatus& status)
  1216. {
  1217. return HandleRemoveImpl(args, true, status);
  1218. }
  1219. std::string ToNativePath(const std::string& path)
  1220. {
  1221. const auto& outPath = cmSystemTools::ConvertToOutputPath(path);
  1222. if (outPath.size() > 1 && outPath.front() == '\"' &&
  1223. outPath.back() == '\"') {
  1224. return outPath.substr(1, outPath.size() - 2);
  1225. }
  1226. return outPath;
  1227. }
  1228. std::string ToCMakePath(const std::string& path)
  1229. {
  1230. auto temp = path;
  1231. cmSystemTools::ConvertToUnixSlashes(temp);
  1232. return temp;
  1233. }
  1234. bool HandlePathCommand(std::vector<std::string> const& args,
  1235. std::string (*convert)(std::string const&),
  1236. cmExecutionStatus& status)
  1237. {
  1238. if (args.size() != 3) {
  1239. status.SetError("FILE([TO_CMAKE_PATH|TO_NATIVE_PATH] path result) must be "
  1240. "called with exactly three arguments.");
  1241. return false;
  1242. }
  1243. #if defined(_WIN32) && !defined(__CYGWIN__)
  1244. char pathSep = ';';
  1245. #else
  1246. char pathSep = ':';
  1247. #endif
  1248. std::vector<std::string> path = cmSystemTools::SplitString(args[1], pathSep);
  1249. std::string value = cmJoin(cmMakeRange(path).transform(convert), ";");
  1250. status.GetMakefile().AddDefinition(args[2], value);
  1251. return true;
  1252. }
  1253. bool HandleCMakePathCommand(std::vector<std::string> const& args,
  1254. cmExecutionStatus& status)
  1255. {
  1256. return HandlePathCommand(args, ToCMakePath, status);
  1257. }
  1258. bool HandleNativePathCommand(std::vector<std::string> const& args,
  1259. cmExecutionStatus& status)
  1260. {
  1261. return HandlePathCommand(args, ToNativePath, status);
  1262. }
  1263. #if !defined(CMAKE_BOOTSTRAP)
  1264. // Stuff for curl download/upload
  1265. using cmFileCommandVectorOfChar = std::vector<char>;
  1266. size_t cmWriteToFileCallback(void* ptr, size_t size, size_t nmemb, void* data)
  1267. {
  1268. int realsize = static_cast<int>(size * nmemb);
  1269. cmsys::ofstream* fout = static_cast<cmsys::ofstream*>(data);
  1270. const char* chPtr = static_cast<char*>(ptr);
  1271. fout->write(chPtr, realsize);
  1272. return realsize;
  1273. }
  1274. size_t cmWriteToMemoryCallback(void* ptr, size_t size, size_t nmemb,
  1275. void* data)
  1276. {
  1277. int realsize = static_cast<int>(size * nmemb);
  1278. const char* chPtr = static_cast<char*>(ptr);
  1279. cm::append(*static_cast<cmFileCommandVectorOfChar*>(data), chPtr,
  1280. chPtr + realsize);
  1281. return realsize;
  1282. }
  1283. size_t cmFileCommandCurlDebugCallback(CURL*, curl_infotype type, char* chPtr,
  1284. size_t size, void* data)
  1285. {
  1286. cmFileCommandVectorOfChar& vec =
  1287. *static_cast<cmFileCommandVectorOfChar*>(data);
  1288. switch (type) {
  1289. case CURLINFO_TEXT:
  1290. case CURLINFO_HEADER_IN:
  1291. case CURLINFO_HEADER_OUT:
  1292. cm::append(vec, chPtr, chPtr + size);
  1293. break;
  1294. case CURLINFO_DATA_IN:
  1295. case CURLINFO_DATA_OUT:
  1296. case CURLINFO_SSL_DATA_IN:
  1297. case CURLINFO_SSL_DATA_OUT: {
  1298. char buf[128];
  1299. int n = sprintf(buf, "[%" KWIML_INT_PRIu64 " bytes data]\n",
  1300. static_cast<KWIML_INT_uint64_t>(size));
  1301. if (n > 0) {
  1302. cm::append(vec, buf, buf + n);
  1303. }
  1304. } break;
  1305. default:
  1306. break;
  1307. }
  1308. return 0;
  1309. }
  1310. class cURLProgressHelper
  1311. {
  1312. public:
  1313. cURLProgressHelper(cmMakefile* mf, const char* text)
  1314. : Makefile(mf)
  1315. , Text(text)
  1316. {
  1317. }
  1318. bool UpdatePercentage(double value, double total, std::string& status)
  1319. {
  1320. long OldPercentage = this->CurrentPercentage;
  1321. if (total > 0.0) {
  1322. this->CurrentPercentage = std::lround(value / total * 100.0);
  1323. if (this->CurrentPercentage > 100) {
  1324. // Avoid extra progress reports for unexpected data beyond total.
  1325. this->CurrentPercentage = 100;
  1326. }
  1327. }
  1328. bool updated = (OldPercentage != this->CurrentPercentage);
  1329. if (updated) {
  1330. status =
  1331. cmStrCat("[", this->Text, " ", this->CurrentPercentage, "% complete]");
  1332. }
  1333. return updated;
  1334. }
  1335. cmMakefile* GetMakefile() { return this->Makefile; }
  1336. private:
  1337. long CurrentPercentage = -1;
  1338. cmMakefile* Makefile;
  1339. std::string Text;
  1340. };
  1341. int cmFileDownloadProgressCallback(void* clientp, double dltotal, double dlnow,
  1342. double ultotal, double ulnow)
  1343. {
  1344. cURLProgressHelper* helper = reinterpret_cast<cURLProgressHelper*>(clientp);
  1345. static_cast<void>(ultotal);
  1346. static_cast<void>(ulnow);
  1347. std::string status;
  1348. if (helper->UpdatePercentage(dlnow, dltotal, status)) {
  1349. cmMakefile* mf = helper->GetMakefile();
  1350. mf->DisplayStatus(status, -1);
  1351. }
  1352. return 0;
  1353. }
  1354. int cmFileUploadProgressCallback(void* clientp, double dltotal, double dlnow,
  1355. double ultotal, double ulnow)
  1356. {
  1357. cURLProgressHelper* helper = reinterpret_cast<cURLProgressHelper*>(clientp);
  1358. static_cast<void>(dltotal);
  1359. static_cast<void>(dlnow);
  1360. std::string status;
  1361. if (helper->UpdatePercentage(ulnow, ultotal, status)) {
  1362. cmMakefile* mf = helper->GetMakefile();
  1363. mf->DisplayStatus(status, -1);
  1364. }
  1365. return 0;
  1366. }
  1367. class cURLEasyGuard
  1368. {
  1369. public:
  1370. cURLEasyGuard(CURL* easy)
  1371. : Easy(easy)
  1372. {
  1373. }
  1374. ~cURLEasyGuard()
  1375. {
  1376. if (this->Easy) {
  1377. ::curl_easy_cleanup(this->Easy);
  1378. }
  1379. }
  1380. cURLEasyGuard(const cURLEasyGuard&) = delete;
  1381. cURLEasyGuard& operator=(const cURLEasyGuard&) = delete;
  1382. void release() { this->Easy = nullptr; }
  1383. private:
  1384. ::CURL* Easy;
  1385. };
  1386. #endif
  1387. #define check_curl_result(result, errstr) \
  1388. do { \
  1389. if (result != CURLE_OK) { \
  1390. std::string e(errstr); \
  1391. e += ::curl_easy_strerror(result); \
  1392. status.SetError(e); \
  1393. return false; \
  1394. } \
  1395. } while (false)
  1396. bool HandleDownloadCommand(std::vector<std::string> const& args,
  1397. cmExecutionStatus& status)
  1398. {
  1399. #if !defined(CMAKE_BOOTSTRAP)
  1400. auto i = args.begin();
  1401. if (args.size() < 3) {
  1402. status.SetError("DOWNLOAD must be called with at least three arguments.");
  1403. return false;
  1404. }
  1405. ++i; // Get rid of subcommand
  1406. std::string url = *i;
  1407. ++i;
  1408. std::string file = *i;
  1409. ++i;
  1410. long timeout = 0;
  1411. long inactivity_timeout = 0;
  1412. std::string logVar;
  1413. std::string statusVar;
  1414. bool tls_verify = status.GetMakefile().IsOn("CMAKE_TLS_VERIFY");
  1415. const char* cainfo = status.GetMakefile().GetDefinition("CMAKE_TLS_CAINFO");
  1416. std::string netrc_level =
  1417. status.GetMakefile().GetSafeDefinition("CMAKE_NETRC");
  1418. std::string netrc_file =
  1419. status.GetMakefile().GetSafeDefinition("CMAKE_NETRC_FILE");
  1420. std::string expectedHash;
  1421. std::string hashMatchMSG;
  1422. std::unique_ptr<cmCryptoHash> hash;
  1423. bool showProgress = false;
  1424. std::string userpwd;
  1425. std::vector<std::string> curl_headers;
  1426. while (i != args.end()) {
  1427. if (*i == "TIMEOUT") {
  1428. ++i;
  1429. if (i != args.end()) {
  1430. timeout = atol(i->c_str());
  1431. } else {
  1432. status.SetError("DOWNLOAD missing time for TIMEOUT.");
  1433. return false;
  1434. }
  1435. } else if (*i == "INACTIVITY_TIMEOUT") {
  1436. ++i;
  1437. if (i != args.end()) {
  1438. inactivity_timeout = atol(i->c_str());
  1439. } else {
  1440. status.SetError("DOWNLOAD missing time for INACTIVITY_TIMEOUT.");
  1441. return false;
  1442. }
  1443. } else if (*i == "LOG") {
  1444. ++i;
  1445. if (i == args.end()) {
  1446. status.SetError("DOWNLOAD missing VAR for LOG.");
  1447. return false;
  1448. }
  1449. logVar = *i;
  1450. } else if (*i == "STATUS") {
  1451. ++i;
  1452. if (i == args.end()) {
  1453. status.SetError("DOWNLOAD missing VAR for STATUS.");
  1454. return false;
  1455. }
  1456. statusVar = *i;
  1457. } else if (*i == "TLS_VERIFY") {
  1458. ++i;
  1459. if (i != args.end()) {
  1460. tls_verify = cmIsOn(*i);
  1461. } else {
  1462. status.SetError("TLS_VERIFY missing bool value.");
  1463. return false;
  1464. }
  1465. } else if (*i == "TLS_CAINFO") {
  1466. ++i;
  1467. if (i != args.end()) {
  1468. cainfo = i->c_str();
  1469. } else {
  1470. status.SetError("TLS_CAFILE missing file value.");
  1471. return false;
  1472. }
  1473. } else if (*i == "NETRC_FILE") {
  1474. ++i;
  1475. if (i != args.end()) {
  1476. netrc_file = *i;
  1477. } else {
  1478. status.SetError("DOWNLOAD missing file value for NETRC_FILE.");
  1479. return false;
  1480. }
  1481. } else if (*i == "NETRC") {
  1482. ++i;
  1483. if (i != args.end()) {
  1484. netrc_level = *i;
  1485. } else {
  1486. status.SetError("DOWNLOAD missing level value for NETRC.");
  1487. return false;
  1488. }
  1489. } else if (*i == "EXPECTED_MD5") {
  1490. ++i;
  1491. if (i == args.end()) {
  1492. status.SetError("DOWNLOAD missing sum value for EXPECTED_MD5.");
  1493. return false;
  1494. }
  1495. hash = cm::make_unique<cmCryptoHash>(cmCryptoHash::AlgoMD5);
  1496. hashMatchMSG = "MD5 sum";
  1497. expectedHash = cmSystemTools::LowerCase(*i);
  1498. } else if (*i == "SHOW_PROGRESS") {
  1499. showProgress = true;
  1500. } else if (*i == "EXPECTED_HASH") {
  1501. ++i;
  1502. if (i == args.end()) {
  1503. status.SetError("DOWNLOAD missing ALGO=value for EXPECTED_HASH.");
  1504. return false;
  1505. }
  1506. std::string::size_type pos = i->find("=");
  1507. if (pos == std::string::npos) {
  1508. std::string err =
  1509. cmStrCat("DOWNLOAD EXPECTED_HASH expects ALGO=value but got: ", *i);
  1510. status.SetError(err);
  1511. return false;
  1512. }
  1513. std::string algo = i->substr(0, pos);
  1514. expectedHash = cmSystemTools::LowerCase(i->substr(pos + 1));
  1515. hash = std::unique_ptr<cmCryptoHash>(cmCryptoHash::New(algo));
  1516. if (!hash) {
  1517. std::string err =
  1518. cmStrCat("DOWNLOAD EXPECTED_HASH given unknown ALGO: ", algo);
  1519. status.SetError(err);
  1520. return false;
  1521. }
  1522. hashMatchMSG = algo + " hash";
  1523. } else if (*i == "USERPWD") {
  1524. ++i;
  1525. if (i == args.end()) {
  1526. status.SetError("DOWNLOAD missing string for USERPWD.");
  1527. return false;
  1528. }
  1529. userpwd = *i;
  1530. } else if (*i == "HTTPHEADER") {
  1531. ++i;
  1532. if (i == args.end()) {
  1533. status.SetError("DOWNLOAD missing string for HTTPHEADER.");
  1534. return false;
  1535. }
  1536. curl_headers.push_back(*i);
  1537. } else {
  1538. // Do not return error for compatibility reason.
  1539. std::string err = cmStrCat("Unexpected argument: ", *i);
  1540. status.GetMakefile().IssueMessage(MessageType::AUTHOR_WARNING, err);
  1541. }
  1542. ++i;
  1543. }
  1544. // If file exists already, and caller specified an expected md5 or sha,
  1545. // and the existing file already has the expected hash, then simply
  1546. // return.
  1547. //
  1548. if (cmSystemTools::FileExists(file) && hash.get()) {
  1549. std::string msg;
  1550. std::string actualHash = hash->HashFile(file);
  1551. if (actualHash == expectedHash) {
  1552. msg = cmStrCat("returning early; file already exists with expected ",
  1553. hashMatchMSG, '"');
  1554. if (!statusVar.empty()) {
  1555. status.GetMakefile().AddDefinition(statusVar, cmStrCat(0, ";\"", msg));
  1556. }
  1557. return true;
  1558. }
  1559. }
  1560. // Make sure parent directory exists so we can write to the file
  1561. // as we receive downloaded bits from curl...
  1562. //
  1563. std::string dir = cmSystemTools::GetFilenamePath(file);
  1564. if (!dir.empty() && !cmSystemTools::FileExists(dir) &&
  1565. !cmSystemTools::MakeDirectory(dir)) {
  1566. std::string errstring = "DOWNLOAD error: cannot create directory '" + dir +
  1567. "' - Specify file by full path name and verify that you "
  1568. "have directory creation and file write privileges.";
  1569. status.SetError(errstring);
  1570. return false;
  1571. }
  1572. cmsys::ofstream fout(file.c_str(), std::ios::binary);
  1573. if (!fout) {
  1574. status.SetError("DOWNLOAD cannot open file for write.");
  1575. return false;
  1576. }
  1577. # if defined(_WIN32)
  1578. url = fix_file_url_windows(url);
  1579. # endif
  1580. ::CURL* curl;
  1581. ::curl_global_init(CURL_GLOBAL_DEFAULT);
  1582. curl = ::curl_easy_init();
  1583. if (!curl) {
  1584. status.SetError("DOWNLOAD error initializing curl.");
  1585. return false;
  1586. }
  1587. cURLEasyGuard g_curl(curl);
  1588. ::CURLcode res = ::curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  1589. check_curl_result(res, "DOWNLOAD cannot set url: ");
  1590. // enable HTTP ERROR parsing
  1591. res = ::curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  1592. check_curl_result(res, "DOWNLOAD cannot set http failure option: ");
  1593. res = ::curl_easy_setopt(curl, CURLOPT_USERAGENT, "curl/" LIBCURL_VERSION);
  1594. check_curl_result(res, "DOWNLOAD cannot set user agent option: ");
  1595. res = ::curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cmWriteToFileCallback);
  1596. check_curl_result(res, "DOWNLOAD cannot set write function: ");
  1597. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION,
  1598. cmFileCommandCurlDebugCallback);
  1599. check_curl_result(res, "DOWNLOAD cannot set debug function: ");
  1600. // check to see if TLS verification is requested
  1601. if (tls_verify) {
  1602. res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1);
  1603. check_curl_result(res, "Unable to set TLS/SSL Verify on: ");
  1604. } else {
  1605. res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
  1606. check_curl_result(res, "Unable to set TLS/SSL Verify off: ");
  1607. }
  1608. // check to see if a CAINFO file has been specified
  1609. // command arg comes first
  1610. std::string const& cainfo_err = cmCurlSetCAInfo(curl, cainfo);
  1611. if (!cainfo_err.empty()) {
  1612. status.SetError(cainfo_err);
  1613. return false;
  1614. }
  1615. // check to see if netrc parameters have been specified
  1616. // local command args takes precedence over CMAKE_NETRC*
  1617. netrc_level = cmSystemTools::UpperCase(netrc_level);
  1618. std::string const& netrc_option_err =
  1619. cmCurlSetNETRCOption(curl, netrc_level, netrc_file);
  1620. if (!netrc_option_err.empty()) {
  1621. status.SetError(netrc_option_err);
  1622. return false;
  1623. }
  1624. cmFileCommandVectorOfChar chunkDebug;
  1625. res = ::curl_easy_setopt(curl, CURLOPT_WRITEDATA, &fout);
  1626. check_curl_result(res, "DOWNLOAD cannot set write data: ");
  1627. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, &chunkDebug);
  1628. check_curl_result(res, "DOWNLOAD cannot set debug data: ");
  1629. res = ::curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  1630. check_curl_result(res, "DOWNLOAD cannot set follow-redirect option: ");
  1631. if (!logVar.empty()) {
  1632. res = ::curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  1633. check_curl_result(res, "DOWNLOAD cannot set verbose: ");
  1634. }
  1635. if (timeout > 0) {
  1636. res = ::curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  1637. check_curl_result(res, "DOWNLOAD cannot set timeout: ");
  1638. }
  1639. if (inactivity_timeout > 0) {
  1640. // Give up if there is no progress for a long time.
  1641. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1);
  1642. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, inactivity_timeout);
  1643. }
  1644. // Need the progress helper's scope to last through the duration of
  1645. // the curl_easy_perform call... so this object is declared at function
  1646. // scope intentionally, rather than inside the "if(showProgress)"
  1647. // block...
  1648. //
  1649. cURLProgressHelper helper(&status.GetMakefile(), "download");
  1650. if (showProgress) {
  1651. res = ::curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
  1652. check_curl_result(res, "DOWNLOAD cannot set noprogress value: ");
  1653. res = ::curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION,
  1654. cmFileDownloadProgressCallback);
  1655. check_curl_result(res, "DOWNLOAD cannot set progress function: ");
  1656. res = ::curl_easy_setopt(curl, CURLOPT_PROGRESSDATA,
  1657. reinterpret_cast<void*>(&helper));
  1658. check_curl_result(res, "DOWNLOAD cannot set progress data: ");
  1659. }
  1660. if (!userpwd.empty()) {
  1661. res = ::curl_easy_setopt(curl, CURLOPT_USERPWD, userpwd.c_str());
  1662. check_curl_result(res, "DOWNLOAD cannot set user password: ");
  1663. }
  1664. struct curl_slist* headers = nullptr;
  1665. for (std::string const& h : curl_headers) {
  1666. headers = ::curl_slist_append(headers, h.c_str());
  1667. }
  1668. ::curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  1669. res = ::curl_easy_perform(curl);
  1670. ::curl_slist_free_all(headers);
  1671. /* always cleanup */
  1672. g_curl.release();
  1673. ::curl_easy_cleanup(curl);
  1674. if (!statusVar.empty()) {
  1675. status.GetMakefile().AddDefinition(
  1676. statusVar,
  1677. cmStrCat(static_cast<int>(res), ";\"", ::curl_easy_strerror(res), "\""));
  1678. }
  1679. ::curl_global_cleanup();
  1680. // Explicitly flush/close so we can measure the md5 accurately.
  1681. //
  1682. fout.flush();
  1683. fout.close();
  1684. // Verify MD5 sum if requested:
  1685. //
  1686. if (hash) {
  1687. std::string actualHash = hash->HashFile(file);
  1688. if (actualHash.empty()) {
  1689. status.SetError("DOWNLOAD cannot compute hash on downloaded file");
  1690. return false;
  1691. }
  1692. if (expectedHash != actualHash) {
  1693. if (!statusVar.empty() && res == 0) {
  1694. status.GetMakefile().AddDefinition(statusVar,
  1695. "1;HASH mismatch: "
  1696. "expected: " +
  1697. expectedHash +
  1698. " actual: " + actualHash);
  1699. }
  1700. status.SetError(cmStrCat("DOWNLOAD HASH mismatch\n"
  1701. " for file: [",
  1702. file,
  1703. "]\n"
  1704. " expected hash: [",
  1705. expectedHash,
  1706. "]\n"
  1707. " actual hash: [",
  1708. actualHash,
  1709. "]\n"
  1710. " status: [",
  1711. static_cast<int>(res), ";\"",
  1712. ::curl_easy_strerror(res), "\"]\n"));
  1713. return false;
  1714. }
  1715. }
  1716. if (!logVar.empty()) {
  1717. chunkDebug.push_back(0);
  1718. status.GetMakefile().AddDefinition(logVar, chunkDebug.data());
  1719. }
  1720. return true;
  1721. #else
  1722. status.SetError("DOWNLOAD not supported by bootstrap cmake.");
  1723. return false;
  1724. #endif
  1725. }
  1726. bool HandleUploadCommand(std::vector<std::string> const& args,
  1727. cmExecutionStatus& status)
  1728. {
  1729. #if !defined(CMAKE_BOOTSTRAP)
  1730. if (args.size() < 3) {
  1731. status.SetError("UPLOAD must be called with at least three arguments.");
  1732. return false;
  1733. }
  1734. auto i = args.begin();
  1735. ++i;
  1736. std::string filename = *i;
  1737. ++i;
  1738. std::string url = *i;
  1739. ++i;
  1740. long timeout = 0;
  1741. long inactivity_timeout = 0;
  1742. std::string logVar;
  1743. std::string statusVar;
  1744. bool showProgress = false;
  1745. std::string userpwd;
  1746. std::string netrc_level =
  1747. status.GetMakefile().GetSafeDefinition("CMAKE_NETRC");
  1748. std::string netrc_file =
  1749. status.GetMakefile().GetSafeDefinition("CMAKE_NETRC_FILE");
  1750. std::vector<std::string> curl_headers;
  1751. while (i != args.end()) {
  1752. if (*i == "TIMEOUT") {
  1753. ++i;
  1754. if (i != args.end()) {
  1755. timeout = atol(i->c_str());
  1756. } else {
  1757. status.SetError("UPLOAD missing time for TIMEOUT.");
  1758. return false;
  1759. }
  1760. } else if (*i == "INACTIVITY_TIMEOUT") {
  1761. ++i;
  1762. if (i != args.end()) {
  1763. inactivity_timeout = atol(i->c_str());
  1764. } else {
  1765. status.SetError("UPLOAD missing time for INACTIVITY_TIMEOUT.");
  1766. return false;
  1767. }
  1768. } else if (*i == "LOG") {
  1769. ++i;
  1770. if (i == args.end()) {
  1771. status.SetError("UPLOAD missing VAR for LOG.");
  1772. return false;
  1773. }
  1774. logVar = *i;
  1775. } else if (*i == "STATUS") {
  1776. ++i;
  1777. if (i == args.end()) {
  1778. status.SetError("UPLOAD missing VAR for STATUS.");
  1779. return false;
  1780. }
  1781. statusVar = *i;
  1782. } else if (*i == "SHOW_PROGRESS") {
  1783. showProgress = true;
  1784. } else if (*i == "NETRC_FILE") {
  1785. ++i;
  1786. if (i != args.end()) {
  1787. netrc_file = *i;
  1788. } else {
  1789. status.SetError("UPLOAD missing file value for NETRC_FILE.");
  1790. return false;
  1791. }
  1792. } else if (*i == "NETRC") {
  1793. ++i;
  1794. if (i != args.end()) {
  1795. netrc_level = *i;
  1796. } else {
  1797. status.SetError("UPLOAD missing level value for NETRC.");
  1798. return false;
  1799. }
  1800. } else if (*i == "USERPWD") {
  1801. ++i;
  1802. if (i == args.end()) {
  1803. status.SetError("UPLOAD missing string for USERPWD.");
  1804. return false;
  1805. }
  1806. userpwd = *i;
  1807. } else if (*i == "HTTPHEADER") {
  1808. ++i;
  1809. if (i == args.end()) {
  1810. status.SetError("UPLOAD missing string for HTTPHEADER.");
  1811. return false;
  1812. }
  1813. curl_headers.push_back(*i);
  1814. } else {
  1815. // Do not return error for compatibility reason.
  1816. std::string err = cmStrCat("Unexpected argument: ", *i);
  1817. status.GetMakefile().IssueMessage(MessageType::AUTHOR_WARNING, err);
  1818. }
  1819. ++i;
  1820. }
  1821. // Open file for reading:
  1822. //
  1823. FILE* fin = cmsys::SystemTools::Fopen(filename, "rb");
  1824. if (!fin) {
  1825. std::string errStr =
  1826. cmStrCat("UPLOAD cannot open file '", filename, "' for reading.");
  1827. status.SetError(errStr);
  1828. return false;
  1829. }
  1830. unsigned long file_size = cmsys::SystemTools::FileLength(filename);
  1831. # if defined(_WIN32)
  1832. url = fix_file_url_windows(url);
  1833. # endif
  1834. ::CURL* curl;
  1835. ::curl_global_init(CURL_GLOBAL_DEFAULT);
  1836. curl = ::curl_easy_init();
  1837. if (!curl) {
  1838. status.SetError("UPLOAD error initializing curl.");
  1839. fclose(fin);
  1840. return false;
  1841. }
  1842. cURLEasyGuard g_curl(curl);
  1843. // enable HTTP ERROR parsing
  1844. ::CURLcode res = ::curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  1845. check_curl_result(res, "UPLOAD cannot set fail on error flag: ");
  1846. // enable uploading
  1847. res = ::curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
  1848. check_curl_result(res, "UPLOAD cannot set upload flag: ");
  1849. res = ::curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  1850. check_curl_result(res, "UPLOAD cannot set url: ");
  1851. res =
  1852. ::curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cmWriteToMemoryCallback);
  1853. check_curl_result(res, "UPLOAD cannot set write function: ");
  1854. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION,
  1855. cmFileCommandCurlDebugCallback);
  1856. check_curl_result(res, "UPLOAD cannot set debug function: ");
  1857. cmFileCommandVectorOfChar chunkResponse;
  1858. cmFileCommandVectorOfChar chunkDebug;
  1859. res = ::curl_easy_setopt(curl, CURLOPT_WRITEDATA, &chunkResponse);
  1860. check_curl_result(res, "UPLOAD cannot set write data: ");
  1861. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, &chunkDebug);
  1862. check_curl_result(res, "UPLOAD cannot set debug data: ");
  1863. res = ::curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  1864. check_curl_result(res, "UPLOAD cannot set follow-redirect option: ");
  1865. if (!logVar.empty()) {
  1866. res = ::curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  1867. check_curl_result(res, "UPLOAD cannot set verbose: ");
  1868. }
  1869. if (timeout > 0) {
  1870. res = ::curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  1871. check_curl_result(res, "UPLOAD cannot set timeout: ");
  1872. }
  1873. if (inactivity_timeout > 0) {
  1874. // Give up if there is no progress for a long time.
  1875. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1);
  1876. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, inactivity_timeout);
  1877. }
  1878. // Need the progress helper's scope to last through the duration of
  1879. // the curl_easy_perform call... so this object is declared at function
  1880. // scope intentionally, rather than inside the "if(showProgress)"
  1881. // block...
  1882. //
  1883. cURLProgressHelper helper(&status.GetMakefile(), "upload");
  1884. if (showProgress) {
  1885. res = ::curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
  1886. check_curl_result(res, "UPLOAD cannot set noprogress value: ");
  1887. res = ::curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION,
  1888. cmFileUploadProgressCallback);
  1889. check_curl_result(res, "UPLOAD cannot set progress function: ");
  1890. res = ::curl_easy_setopt(curl, CURLOPT_PROGRESSDATA,
  1891. reinterpret_cast<void*>(&helper));
  1892. check_curl_result(res, "UPLOAD cannot set progress data: ");
  1893. }
  1894. // now specify which file to upload
  1895. res = ::curl_easy_setopt(curl, CURLOPT_INFILE, fin);
  1896. check_curl_result(res, "UPLOAD cannot set input file: ");
  1897. // and give the size of the upload (optional)
  1898. res =
  1899. ::curl_easy_setopt(curl, CURLOPT_INFILESIZE, static_cast<long>(file_size));
  1900. check_curl_result(res, "UPLOAD cannot set input file size: ");
  1901. if (!userpwd.empty()) {
  1902. res = ::curl_easy_setopt(curl, CURLOPT_USERPWD, userpwd.c_str());
  1903. check_curl_result(res, "UPLOAD cannot set user password: ");
  1904. }
  1905. // check to see if netrc parameters have been specified
  1906. // local command args takes precedence over CMAKE_NETRC*
  1907. netrc_level = cmSystemTools::UpperCase(netrc_level);
  1908. std::string const& netrc_option_err =
  1909. cmCurlSetNETRCOption(curl, netrc_level, netrc_file);
  1910. if (!netrc_option_err.empty()) {
  1911. status.SetError(netrc_option_err);
  1912. return false;
  1913. }
  1914. struct curl_slist* headers = nullptr;
  1915. for (std::string const& h : curl_headers) {
  1916. headers = ::curl_slist_append(headers, h.c_str());
  1917. }
  1918. ::curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  1919. res = ::curl_easy_perform(curl);
  1920. ::curl_slist_free_all(headers);
  1921. /* always cleanup */
  1922. g_curl.release();
  1923. ::curl_easy_cleanup(curl);
  1924. if (!statusVar.empty()) {
  1925. status.GetMakefile().AddDefinition(
  1926. statusVar,
  1927. cmStrCat(static_cast<int>(res), ";\"", ::curl_easy_strerror(res), "\""));
  1928. }
  1929. ::curl_global_cleanup();
  1930. fclose(fin);
  1931. fin = nullptr;
  1932. if (!logVar.empty()) {
  1933. std::string log;
  1934. if (!chunkResponse.empty()) {
  1935. chunkResponse.push_back(0);
  1936. log += "Response:\n";
  1937. log += chunkResponse.data();
  1938. log += "\n";
  1939. }
  1940. if (!chunkDebug.empty()) {
  1941. chunkDebug.push_back(0);
  1942. log += "Debug:\n";
  1943. log += chunkDebug.data();
  1944. log += "\n";
  1945. }
  1946. status.GetMakefile().AddDefinition(logVar, log);
  1947. }
  1948. return true;
  1949. #else
  1950. status.SetError("UPLOAD not supported by bootstrap cmake.");
  1951. return false;
  1952. #endif
  1953. }
  1954. void AddEvaluationFile(const std::string& inputName,
  1955. const std::string& outputExpr,
  1956. const std::string& condition, bool inputIsContent,
  1957. cmExecutionStatus& status)
  1958. {
  1959. cmListFileBacktrace lfbt = status.GetMakefile().GetBacktrace();
  1960. cmGeneratorExpression outputGe(lfbt);
  1961. std::unique_ptr<cmCompiledGeneratorExpression> outputCge =
  1962. outputGe.Parse(outputExpr);
  1963. cmGeneratorExpression conditionGe(lfbt);
  1964. std::unique_ptr<cmCompiledGeneratorExpression> conditionCge =
  1965. conditionGe.Parse(condition);
  1966. status.GetMakefile().AddEvaluationFile(
  1967. inputName, std::move(outputCge), std::move(conditionCge), inputIsContent);
  1968. }
  1969. bool HandleGenerateCommand(std::vector<std::string> const& args,
  1970. cmExecutionStatus& status)
  1971. {
  1972. if (args.size() < 5) {
  1973. status.SetError("Incorrect arguments to GENERATE subcommand.");
  1974. return false;
  1975. }
  1976. if (args[1] != "OUTPUT") {
  1977. status.SetError("Incorrect arguments to GENERATE subcommand.");
  1978. return false;
  1979. }
  1980. std::string condition;
  1981. if (args.size() > 5) {
  1982. if (args[5] != "CONDITION") {
  1983. status.SetError("Incorrect arguments to GENERATE subcommand.");
  1984. return false;
  1985. }
  1986. if (args.size() != 7) {
  1987. status.SetError("Incorrect arguments to GENERATE subcommand.");
  1988. return false;
  1989. }
  1990. condition = args[6];
  1991. if (condition.empty()) {
  1992. status.SetError("CONDITION of sub-command GENERATE must not be empty if "
  1993. "specified.");
  1994. return false;
  1995. }
  1996. }
  1997. std::string output = args[2];
  1998. const bool inputIsContent = args[3] != "INPUT";
  1999. if (inputIsContent && args[3] != "CONTENT") {
  2000. status.SetError("Incorrect arguments to GENERATE subcommand.");
  2001. return false;
  2002. }
  2003. std::string input = args[4];
  2004. AddEvaluationFile(input, output, condition, inputIsContent, status);
  2005. return true;
  2006. }
  2007. bool HandleLockCommand(std::vector<std::string> const& args,
  2008. cmExecutionStatus& status)
  2009. {
  2010. #if !defined(CMAKE_BOOTSTRAP)
  2011. // Default values
  2012. bool directory = false;
  2013. bool release = false;
  2014. enum Guard
  2015. {
  2016. GUARD_FUNCTION,
  2017. GUARD_FILE,
  2018. GUARD_PROCESS
  2019. };
  2020. Guard guard = GUARD_PROCESS;
  2021. std::string resultVariable;
  2022. unsigned long timeout = static_cast<unsigned long>(-1);
  2023. // Parse arguments
  2024. if (args.size() < 2) {
  2025. status.GetMakefile().IssueMessage(
  2026. MessageType::FATAL_ERROR,
  2027. "sub-command LOCK requires at least two arguments.");
  2028. return false;
  2029. }
  2030. std::string path = args[1];
  2031. for (unsigned i = 2; i < args.size(); ++i) {
  2032. if (args[i] == "DIRECTORY") {
  2033. directory = true;
  2034. } else if (args[i] == "RELEASE") {
  2035. release = true;
  2036. } else if (args[i] == "GUARD") {
  2037. ++i;
  2038. const char* merr = "expected FUNCTION, FILE or PROCESS after GUARD";
  2039. if (i >= args.size()) {
  2040. status.GetMakefile().IssueMessage(MessageType::FATAL_ERROR, merr);
  2041. return false;
  2042. }
  2043. if (args[i] == "FUNCTION") {
  2044. guard = GUARD_FUNCTION;
  2045. } else if (args[i] == "FILE") {
  2046. guard = GUARD_FILE;
  2047. } else if (args[i] == "PROCESS") {
  2048. guard = GUARD_PROCESS;
  2049. } else {
  2050. status.GetMakefile().IssueMessage(
  2051. MessageType::FATAL_ERROR,
  2052. cmStrCat(merr, ", but got:\n \"", args[i], "\"."));
  2053. return false;
  2054. }
  2055. } else if (args[i] == "RESULT_VARIABLE") {
  2056. ++i;
  2057. if (i >= args.size()) {
  2058. status.GetMakefile().IssueMessage(
  2059. MessageType::FATAL_ERROR,
  2060. "expected variable name after RESULT_VARIABLE");
  2061. return false;
  2062. }
  2063. resultVariable = args[i];
  2064. } else if (args[i] == "TIMEOUT") {
  2065. ++i;
  2066. if (i >= args.size()) {
  2067. status.GetMakefile().IssueMessage(
  2068. MessageType::FATAL_ERROR, "expected timeout value after TIMEOUT");
  2069. return false;
  2070. }
  2071. long scanned;
  2072. if (!cmStrToLong(args[i], &scanned) || scanned < 0) {
  2073. status.GetMakefile().IssueMessage(
  2074. MessageType::FATAL_ERROR,
  2075. cmStrCat("TIMEOUT value \"", args[i],
  2076. "\" is not an unsigned integer."));
  2077. return false;
  2078. }
  2079. timeout = static_cast<unsigned long>(scanned);
  2080. } else {
  2081. status.GetMakefile().IssueMessage(
  2082. MessageType::FATAL_ERROR,
  2083. cmStrCat("expected DIRECTORY, RELEASE, GUARD, RESULT_VARIABLE or ",
  2084. "TIMEOUT\nbut got: \"", args[i], "\"."));
  2085. return false;
  2086. }
  2087. }
  2088. if (directory) {
  2089. path += "/cmake.lock";
  2090. }
  2091. if (!cmsys::SystemTools::FileIsFullPath(path)) {
  2092. path = status.GetMakefile().GetCurrentSourceDirectory() + "/" + path;
  2093. }
  2094. // Unify path (remove '//', '/../', ...)
  2095. path = cmSystemTools::CollapseFullPath(path);
  2096. // Create file and directories if needed
  2097. std::string parentDir = cmSystemTools::GetParentDirectory(path);
  2098. if (!cmSystemTools::MakeDirectory(parentDir)) {
  2099. status.GetMakefile().IssueMessage(
  2100. MessageType::FATAL_ERROR,
  2101. cmStrCat("directory\n \"", parentDir,
  2102. "\"\ncreation failed (check permissions)."));
  2103. cmSystemTools::SetFatalErrorOccured();
  2104. return false;
  2105. }
  2106. FILE* file = cmsys::SystemTools::Fopen(path, "w");
  2107. if (!file) {
  2108. status.GetMakefile().IssueMessage(
  2109. MessageType::FATAL_ERROR,
  2110. cmStrCat("file\n \"", path,
  2111. "\"\ncreation failed (check permissions)."));
  2112. cmSystemTools::SetFatalErrorOccured();
  2113. return false;
  2114. }
  2115. fclose(file);
  2116. // Actual lock/unlock
  2117. cmFileLockPool& lockPool =
  2118. status.GetMakefile().GetGlobalGenerator()->GetFileLockPool();
  2119. cmFileLockResult fileLockResult(cmFileLockResult::MakeOk());
  2120. if (release) {
  2121. fileLockResult = lockPool.Release(path);
  2122. } else {
  2123. switch (guard) {
  2124. case GUARD_FUNCTION:
  2125. fileLockResult = lockPool.LockFunctionScope(path, timeout);
  2126. break;
  2127. case GUARD_FILE:
  2128. fileLockResult = lockPool.LockFileScope(path, timeout);
  2129. break;
  2130. case GUARD_PROCESS:
  2131. fileLockResult = lockPool.LockProcessScope(path, timeout);
  2132. break;
  2133. default:
  2134. cmSystemTools::SetFatalErrorOccured();
  2135. return false;
  2136. }
  2137. }
  2138. const std::string result = fileLockResult.GetOutputMessage();
  2139. if (resultVariable.empty() && !fileLockResult.IsOk()) {
  2140. status.GetMakefile().IssueMessage(
  2141. MessageType::FATAL_ERROR,
  2142. cmStrCat("error locking file\n \"", path, "\"\n", result, "."));
  2143. cmSystemTools::SetFatalErrorOccured();
  2144. return false;
  2145. }
  2146. if (!resultVariable.empty()) {
  2147. status.GetMakefile().AddDefinition(resultVariable, result);
  2148. }
  2149. return true;
  2150. #else
  2151. static_cast<void>(args);
  2152. status.SetError("sub-command LOCK not implemented in bootstrap cmake");
  2153. return false;
  2154. #endif
  2155. }
  2156. bool HandleTimestampCommand(std::vector<std::string> const& args,
  2157. cmExecutionStatus& status)
  2158. {
  2159. if (args.size() < 3) {
  2160. status.SetError("sub-command TIMESTAMP requires at least two arguments.");
  2161. return false;
  2162. }
  2163. if (args.size() > 5) {
  2164. status.SetError("sub-command TIMESTAMP takes at most four arguments.");
  2165. return false;
  2166. }
  2167. unsigned int argsIndex = 1;
  2168. const std::string& filename = args[argsIndex++];
  2169. const std::string& outputVariable = args[argsIndex++];
  2170. std::string formatString;
  2171. if (args.size() > argsIndex && args[argsIndex] != "UTC") {
  2172. formatString = args[argsIndex++];
  2173. }
  2174. bool utcFlag = false;
  2175. if (args.size() > argsIndex) {
  2176. if (args[argsIndex] == "UTC") {
  2177. utcFlag = true;
  2178. } else {
  2179. std::string e = " TIMESTAMP sub-command does not recognize option " +
  2180. args[argsIndex] + ".";
  2181. status.SetError(e);
  2182. return false;
  2183. }
  2184. }
  2185. cmTimestamp timestamp;
  2186. std::string result =
  2187. timestamp.FileModificationTime(filename.c_str(), formatString, utcFlag);
  2188. status.GetMakefile().AddDefinition(outputVariable, result);
  2189. return true;
  2190. }
  2191. bool HandleSizeCommand(std::vector<std::string> const& args,
  2192. cmExecutionStatus& status)
  2193. {
  2194. if (args.size() != 3) {
  2195. status.SetError(
  2196. cmStrCat(args[0], " requires a file name and output variable"));
  2197. return false;
  2198. }
  2199. unsigned int argsIndex = 1;
  2200. const std::string& filename = args[argsIndex++];
  2201. const std::string& outputVariable = args[argsIndex++];
  2202. if (!cmSystemTools::FileExists(filename, true)) {
  2203. status.SetError(
  2204. cmStrCat("SIZE requested of path that is not readable:\n ", filename));
  2205. return false;
  2206. }
  2207. status.GetMakefile().AddDefinition(
  2208. outputVariable, std::to_string(cmSystemTools::FileLength(filename)));
  2209. return true;
  2210. }
  2211. bool HandleReadSymlinkCommand(std::vector<std::string> const& args,
  2212. cmExecutionStatus& status)
  2213. {
  2214. if (args.size() != 3) {
  2215. status.SetError(
  2216. cmStrCat(args[0], " requires a file name and output variable"));
  2217. return false;
  2218. }
  2219. const std::string& filename = args[1];
  2220. const std::string& outputVariable = args[2];
  2221. std::string result;
  2222. if (!cmSystemTools::ReadSymlink(filename, result)) {
  2223. status.SetError(cmStrCat(
  2224. "READ_SYMLINK requested of path that is not a symlink:\n ", filename));
  2225. return false;
  2226. }
  2227. status.GetMakefile().AddDefinition(outputVariable, result);
  2228. return true;
  2229. }
  2230. bool HandleCreateLinkCommand(std::vector<std::string> const& args,
  2231. cmExecutionStatus& status)
  2232. {
  2233. if (args.size() < 3) {
  2234. status.SetError("CREATE_LINK must be called with at least two additional "
  2235. "arguments");
  2236. return false;
  2237. }
  2238. std::string const& fileName = args[1];
  2239. std::string const& newFileName = args[2];
  2240. struct Arguments
  2241. {
  2242. std::string Result;
  2243. bool CopyOnError = false;
  2244. bool Symbolic = false;
  2245. };
  2246. static auto const parser =
  2247. cmArgumentParser<Arguments>{}
  2248. .Bind("RESULT"_s, &Arguments::Result)
  2249. .Bind("COPY_ON_ERROR"_s, &Arguments::CopyOnError)
  2250. .Bind("SYMBOLIC"_s, &Arguments::Symbolic);
  2251. std::vector<std::string> unconsumedArgs;
  2252. Arguments const arguments =
  2253. parser.Parse(cmMakeRange(args).advance(3), &unconsumedArgs);
  2254. if (!unconsumedArgs.empty()) {
  2255. status.SetError("unknown argument: \"" + unconsumedArgs.front() + '\"');
  2256. return false;
  2257. }
  2258. // The system error message generated in the operation.
  2259. std::string result;
  2260. // Check if the paths are distinct.
  2261. if (fileName == newFileName) {
  2262. result = "CREATE_LINK cannot use same file and newfile";
  2263. if (!arguments.Result.empty()) {
  2264. status.GetMakefile().AddDefinition(arguments.Result, result);
  2265. return true;
  2266. }
  2267. status.SetError(result);
  2268. return false;
  2269. }
  2270. // Hard link requires original file to exist.
  2271. if (!arguments.Symbolic && !cmSystemTools::FileExists(fileName)) {
  2272. result = "Cannot hard link \'" + fileName + "\' as it does not exist.";
  2273. if (!arguments.Result.empty()) {
  2274. status.GetMakefile().AddDefinition(arguments.Result, result);
  2275. return true;
  2276. }
  2277. status.SetError(result);
  2278. return false;
  2279. }
  2280. // Check if the new file already exists and remove it.
  2281. if ((cmSystemTools::FileExists(newFileName) ||
  2282. cmSystemTools::FileIsSymlink(newFileName)) &&
  2283. !cmSystemTools::RemoveFile(newFileName)) {
  2284. std::ostringstream e;
  2285. e << "Failed to create link '" << newFileName
  2286. << "' because existing path cannot be removed: "
  2287. << cmSystemTools::GetLastSystemError() << "\n";
  2288. if (!arguments.Result.empty()) {
  2289. status.GetMakefile().AddDefinition(arguments.Result, e.str());
  2290. return true;
  2291. }
  2292. status.SetError(e.str());
  2293. return false;
  2294. }
  2295. // Whether the operation completed successfully.
  2296. bool completed = false;
  2297. // Check if the command requires a symbolic link.
  2298. if (arguments.Symbolic) {
  2299. completed = cmSystemTools::CreateSymlink(fileName, newFileName, &result);
  2300. } else {
  2301. completed = cmSystemTools::CreateLink(fileName, newFileName, &result);
  2302. }
  2303. // Check if copy-on-error is enabled in the arguments.
  2304. if (!completed && arguments.CopyOnError) {
  2305. completed = cmsys::SystemTools::CopyFileAlways(fileName, newFileName);
  2306. if (!completed) {
  2307. result = "Copy failed: " + cmSystemTools::GetLastSystemError();
  2308. }
  2309. }
  2310. // Check if the operation was successful.
  2311. if (completed) {
  2312. result = "0";
  2313. } else if (arguments.Result.empty()) {
  2314. // The operation failed and the result is not reported in a variable.
  2315. status.SetError(result);
  2316. return false;
  2317. }
  2318. if (!arguments.Result.empty()) {
  2319. status.GetMakefile().AddDefinition(arguments.Result, result);
  2320. }
  2321. return true;
  2322. }
  2323. bool HandleGetRuntimeDependenciesCommand(std::vector<std::string> const& args,
  2324. cmExecutionStatus& status)
  2325. {
  2326. static const std::set<std::string> supportedPlatforms = { "Windows", "Linux",
  2327. "Darwin" };
  2328. std::string platform =
  2329. status.GetMakefile().GetSafeDefinition("CMAKE_HOST_SYSTEM_NAME");
  2330. if (!supportedPlatforms.count(platform)) {
  2331. status.SetError(
  2332. cmStrCat("GET_RUNTIME_DEPENDENCIES is not supported on system \"",
  2333. platform, "\""));
  2334. cmSystemTools::SetFatalErrorOccured();
  2335. return false;
  2336. }
  2337. if (status.GetMakefile().GetState()->GetMode() == cmState::Project) {
  2338. status.GetMakefile().IssueMessage(
  2339. MessageType::AUTHOR_WARNING,
  2340. "You have used file(GET_RUNTIME_DEPENDENCIES)"
  2341. " in project mode. This is probably not what "
  2342. "you intended to do. Instead, please consider"
  2343. " using it in an install(CODE) or "
  2344. "install(SCRIPT) command. For example:"
  2345. "\n install(CODE [["
  2346. "\n file(GET_RUNTIME_DEPENDENCIES"
  2347. "\n # ..."
  2348. "\n )"
  2349. "\n ]])");
  2350. }
  2351. struct Arguments
  2352. {
  2353. std::string ResolvedDependenciesVar;
  2354. std::string UnresolvedDependenciesVar;
  2355. std::string ConflictingDependenciesPrefix;
  2356. std::string BundleExecutable;
  2357. std::vector<std::string> Executables;
  2358. std::vector<std::string> Libraries;
  2359. std::vector<std::string> Directories;
  2360. std::vector<std::string> Modules;
  2361. std::vector<std::string> PreIncludeRegexes;
  2362. std::vector<std::string> PreExcludeRegexes;
  2363. std::vector<std::string> PostIncludeRegexes;
  2364. std::vector<std::string> PostExcludeRegexes;
  2365. };
  2366. static auto const parser =
  2367. cmArgumentParser<Arguments>{}
  2368. .Bind("RESOLVED_DEPENDENCIES_VAR"_s, &Arguments::ResolvedDependenciesVar)
  2369. .Bind("UNRESOLVED_DEPENDENCIES_VAR"_s,
  2370. &Arguments::UnresolvedDependenciesVar)
  2371. .Bind("CONFLICTING_DEPENDENCIES_PREFIX"_s,
  2372. &Arguments::ConflictingDependenciesPrefix)
  2373. .Bind("BUNDLE_EXECUTABLE"_s, &Arguments::BundleExecutable)
  2374. .Bind("EXECUTABLES"_s, &Arguments::Executables)
  2375. .Bind("LIBRARIES"_s, &Arguments::Libraries)
  2376. .Bind("MODULES"_s, &Arguments::Modules)
  2377. .Bind("DIRECTORIES"_s, &Arguments::Directories)
  2378. .Bind("PRE_INCLUDE_REGEXES"_s, &Arguments::PreIncludeRegexes)
  2379. .Bind("PRE_EXCLUDE_REGEXES"_s, &Arguments::PreExcludeRegexes)
  2380. .Bind("POST_INCLUDE_REGEXES"_s, &Arguments::PostIncludeRegexes)
  2381. .Bind("POST_EXCLUDE_REGEXES"_s, &Arguments::PostExcludeRegexes);
  2382. std::vector<std::string> unrecognizedArguments;
  2383. std::vector<std::string> keywordsMissingValues;
  2384. auto parsedArgs =
  2385. parser.Parse(cmMakeRange(args).advance(1), &unrecognizedArguments,
  2386. &keywordsMissingValues);
  2387. auto argIt = unrecognizedArguments.begin();
  2388. if (argIt != unrecognizedArguments.end()) {
  2389. status.SetError(cmStrCat("Unrecognized argument: \"", *argIt, "\""));
  2390. cmSystemTools::SetFatalErrorOccured();
  2391. return false;
  2392. }
  2393. const std::vector<std::string> LIST_ARGS = { "DIRECTORIES",
  2394. "EXECUTABLES",
  2395. "LIBRARIES",
  2396. "MODULES",
  2397. "POST_EXCLUDE_REGEXES",
  2398. "POST_INCLUDE_REGEXES",
  2399. "PRE_EXCLUDE_REGEXES",
  2400. "PRE_INCLUDE_REGEXES" };
  2401. auto kwbegin = keywordsMissingValues.cbegin();
  2402. auto kwend = cmRemoveMatching(keywordsMissingValues, LIST_ARGS);
  2403. if (kwend != kwbegin) {
  2404. status.SetError(cmStrCat("Keywords missing values:\n ",
  2405. cmJoin(cmMakeRange(kwbegin, kwend), "\n ")));
  2406. cmSystemTools::SetFatalErrorOccured();
  2407. return false;
  2408. }
  2409. cmRuntimeDependencyArchive archive(
  2410. status, parsedArgs.Directories, parsedArgs.BundleExecutable,
  2411. parsedArgs.PreIncludeRegexes, parsedArgs.PreExcludeRegexes,
  2412. parsedArgs.PostIncludeRegexes, parsedArgs.PostExcludeRegexes);
  2413. if (!archive.Prepare()) {
  2414. cmSystemTools::SetFatalErrorOccured();
  2415. return false;
  2416. }
  2417. if (!archive.GetRuntimeDependencies(
  2418. parsedArgs.Executables, parsedArgs.Libraries, parsedArgs.Modules)) {
  2419. cmSystemTools::SetFatalErrorOccured();
  2420. return false;
  2421. }
  2422. std::vector<std::string> deps;
  2423. std::vector<std::string> unresolvedDeps;
  2424. std::vector<std::string> conflictingDeps;
  2425. for (auto const& val : archive.GetResolvedPaths()) {
  2426. bool unique = true;
  2427. auto it = val.second.begin();
  2428. assert(it != val.second.end());
  2429. auto const& firstPath = *it;
  2430. while (++it != val.second.end()) {
  2431. if (!cmSystemTools::SameFile(firstPath, *it)) {
  2432. unique = false;
  2433. break;
  2434. }
  2435. }
  2436. if (unique) {
  2437. deps.push_back(firstPath);
  2438. } else if (!parsedArgs.ConflictingDependenciesPrefix.empty()) {
  2439. conflictingDeps.push_back(val.first);
  2440. std::vector<std::string> paths;
  2441. paths.insert(paths.begin(), val.second.begin(), val.second.end());
  2442. std::string varName =
  2443. parsedArgs.ConflictingDependenciesPrefix + "_" + val.first;
  2444. std::string pathsStr = cmJoin(paths, ";");
  2445. status.GetMakefile().AddDefinition(varName, pathsStr);
  2446. } else {
  2447. std::ostringstream e;
  2448. e << "Multiple conflicting paths found for " << val.first << ":";
  2449. for (auto const& path : val.second) {
  2450. e << "\n " << path;
  2451. }
  2452. status.SetError(e.str());
  2453. cmSystemTools::SetFatalErrorOccured();
  2454. return false;
  2455. }
  2456. }
  2457. if (!archive.GetUnresolvedPaths().empty()) {
  2458. if (!parsedArgs.UnresolvedDependenciesVar.empty()) {
  2459. unresolvedDeps.insert(unresolvedDeps.begin(),
  2460. archive.GetUnresolvedPaths().begin(),
  2461. archive.GetUnresolvedPaths().end());
  2462. } else {
  2463. auto it = archive.GetUnresolvedPaths().begin();
  2464. assert(it != archive.GetUnresolvedPaths().end());
  2465. status.SetError(cmStrCat("Could not resolve file ", *it));
  2466. cmSystemTools::SetFatalErrorOccured();
  2467. return false;
  2468. }
  2469. }
  2470. if (!parsedArgs.ResolvedDependenciesVar.empty()) {
  2471. std::string val = cmJoin(deps, ";");
  2472. status.GetMakefile().AddDefinition(parsedArgs.ResolvedDependenciesVar,
  2473. val);
  2474. }
  2475. if (!parsedArgs.UnresolvedDependenciesVar.empty()) {
  2476. std::string val = cmJoin(unresolvedDeps, ";");
  2477. status.GetMakefile().AddDefinition(parsedArgs.UnresolvedDependenciesVar,
  2478. val);
  2479. }
  2480. if (!parsedArgs.ConflictingDependenciesPrefix.empty()) {
  2481. std::string val = cmJoin(conflictingDeps, ";");
  2482. status.GetMakefile().AddDefinition(
  2483. parsedArgs.ConflictingDependenciesPrefix + "_FILENAMES", val);
  2484. }
  2485. return true;
  2486. }
  2487. bool HandleConfigureCommand(std::vector<std::string> const& args,
  2488. cmExecutionStatus& status)
  2489. {
  2490. if (args.size() < 5) {
  2491. status.SetError("Incorrect arguments to CONFIGURE subcommand.");
  2492. return false;
  2493. }
  2494. if (args[1] != "OUTPUT") {
  2495. status.SetError("Incorrect arguments to CONFIGURE subcommand.");
  2496. return false;
  2497. }
  2498. if (args[3] != "CONTENT") {
  2499. status.SetError("Incorrect arguments to CONFIGURE subcommand.");
  2500. return false;
  2501. }
  2502. std::string errorMessage;
  2503. cmNewLineStyle newLineStyle;
  2504. if (!newLineStyle.ReadFromArguments(args, errorMessage)) {
  2505. status.SetError(cmStrCat("CONFIGURE ", errorMessage));
  2506. return false;
  2507. }
  2508. bool escapeQuotes = false;
  2509. bool atOnly = false;
  2510. for (unsigned int i = 5; i < args.size(); ++i) {
  2511. if (args[i] == "@ONLY") {
  2512. atOnly = true;
  2513. } else if (args[i] == "ESCAPE_QUOTES") {
  2514. escapeQuotes = true;
  2515. } else if (args[i] == "NEWLINE_STYLE" || args[i] == "LF" ||
  2516. args[i] == "UNIX" || args[i] == "CRLF" || args[i] == "WIN32" ||
  2517. args[i] == "DOS") {
  2518. /* Options handled by NewLineStyle member above. */
  2519. } else {
  2520. status.SetError(
  2521. cmStrCat("CONFIGURE Unrecognized argument \"", args[i], "\""));
  2522. return false;
  2523. }
  2524. }
  2525. // Check for generator expressions
  2526. const std::string input = args[4];
  2527. std::string outputFile = args[2];
  2528. std::string::size_type pos = input.find_first_of("<>");
  2529. if (pos != std::string::npos) {
  2530. status.SetError(cmStrCat("CONFIGURE called with CONTENT containing a \"",
  2531. input[pos],
  2532. "\". This character is not allowed."));
  2533. return false;
  2534. }
  2535. pos = outputFile.find_first_of("<>");
  2536. if (pos != std::string::npos) {
  2537. status.SetError(cmStrCat("CONFIGURE called with OUTPUT containing a \"",
  2538. outputFile[pos],
  2539. "\". This character is not allowed."));
  2540. return false;
  2541. }
  2542. cmMakefile& makeFile = status.GetMakefile();
  2543. if (!makeFile.CanIWriteThisFile(outputFile)) {
  2544. cmSystemTools::Error("Attempt to write file: " + outputFile +
  2545. " into a source directory.");
  2546. return false;
  2547. }
  2548. cmSystemTools::ConvertToUnixSlashes(outputFile);
  2549. // Re-generate if non-temporary outputs are missing.
  2550. // when we finalize the configuration we will remove all
  2551. // output files that now don't exist.
  2552. makeFile.AddCMakeOutputFile(outputFile);
  2553. // Create output directory
  2554. const std::string::size_type slashPos = outputFile.rfind('/');
  2555. if (slashPos != std::string::npos) {
  2556. const std::string path = outputFile.substr(0, slashPos);
  2557. cmSystemTools::MakeDirectory(path);
  2558. }
  2559. std::string newLineCharacters;
  2560. bool open_with_binary_flag = false;
  2561. if (newLineStyle.IsValid()) {
  2562. open_with_binary_flag = true;
  2563. newLineCharacters = newLineStyle.GetCharacters();
  2564. }
  2565. cmGeneratedFileStream fout;
  2566. fout.Open(outputFile, false, open_with_binary_flag);
  2567. if (!fout) {
  2568. cmSystemTools::Error("Could not open file for write in copy operation " +
  2569. outputFile);
  2570. cmSystemTools::ReportLastSystemError("");
  2571. return false;
  2572. }
  2573. fout.SetCopyIfDifferent(true);
  2574. // copy intput to output and expand variables from input at the same time
  2575. std::stringstream sin(input, std::ios::in);
  2576. std::string inLine;
  2577. std::string outLine;
  2578. while (cmSystemTools::GetLineFromStream(sin, inLine)) {
  2579. outLine.clear();
  2580. makeFile.ConfigureString(inLine, outLine, atOnly, escapeQuotes);
  2581. fout << outLine << newLineCharacters;
  2582. }
  2583. // close file before attempting to copy
  2584. fout.close();
  2585. return true;
  2586. }
  2587. } // namespace
  2588. bool cmFileCommand(std::vector<std::string> const& args,
  2589. cmExecutionStatus& status)
  2590. {
  2591. if (args.size() < 2) {
  2592. status.SetError("must be called with at least two arguments.");
  2593. return false;
  2594. }
  2595. static cmSubcommandTable const subcommand{
  2596. { "WRITE"_s, HandleWriteCommand },
  2597. { "APPEND"_s, HandleAppendCommand },
  2598. { "DOWNLOAD"_s, HandleDownloadCommand },
  2599. { "UPLOAD"_s, HandleUploadCommand },
  2600. { "READ"_s, HandleReadCommand },
  2601. { "MD5"_s, HandleHashCommand },
  2602. { "SHA1"_s, HandleHashCommand },
  2603. { "SHA224"_s, HandleHashCommand },
  2604. { "SHA256"_s, HandleHashCommand },
  2605. { "SHA384"_s, HandleHashCommand },
  2606. { "SHA512"_s, HandleHashCommand },
  2607. { "SHA3_224"_s, HandleHashCommand },
  2608. { "SHA3_256"_s, HandleHashCommand },
  2609. { "SHA3_384"_s, HandleHashCommand },
  2610. { "SHA3_512"_s, HandleHashCommand },
  2611. { "STRINGS"_s, HandleStringsCommand },
  2612. { "GLOB"_s, HandleGlobCommand },
  2613. { "GLOB_RECURSE"_s, HandleGlobRecurseCommand },
  2614. { "MAKE_DIRECTORY"_s, HandleMakeDirectoryCommand },
  2615. { "RENAME"_s, HandleRename },
  2616. { "REMOVE"_s, HandleRemove },
  2617. { "REMOVE_RECURSE"_s, HandleRemoveRecurse },
  2618. { "COPY"_s, HandleCopyCommand },
  2619. { "INSTALL"_s, HandleInstallCommand },
  2620. { "DIFFERENT"_s, HandleDifferentCommand },
  2621. { "RPATH_CHANGE"_s, HandleRPathChangeCommand },
  2622. { "CHRPATH"_s, HandleRPathChangeCommand },
  2623. { "RPATH_CHECK"_s, HandleRPathCheckCommand },
  2624. { "RPATH_REMOVE"_s, HandleRPathRemoveCommand },
  2625. { "READ_ELF"_s, HandleReadElfCommand },
  2626. { "RELATIVE_PATH"_s, HandleRelativePathCommand },
  2627. { "TO_CMAKE_PATH"_s, HandleCMakePathCommand },
  2628. { "TO_NATIVE_PATH"_s, HandleNativePathCommand },
  2629. { "TOUCH"_s, HandleTouchCommand },
  2630. { "TOUCH_NOCREATE"_s, HandleTouchNocreateCommand },
  2631. { "TIMESTAMP"_s, HandleTimestampCommand },
  2632. { "GENERATE"_s, HandleGenerateCommand },
  2633. { "LOCK"_s, HandleLockCommand },
  2634. { "SIZE"_s, HandleSizeCommand },
  2635. { "READ_SYMLINK"_s, HandleReadSymlinkCommand },
  2636. { "CREATE_LINK"_s, HandleCreateLinkCommand },
  2637. { "GET_RUNTIME_DEPENDENCIES"_s, HandleGetRuntimeDependenciesCommand },
  2638. { "CONFIGURE"_s, HandleConfigureCommand },
  2639. };
  2640. return subcommand(args[0], args, status);
  2641. }