cmFileCommand.cxx 118 KB

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