cmFileCommand.cxx 103 KB

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