cmFileCommand.cxx 117 KB

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