cmFileCommand.cxx 116 KB

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