cmFileCommand.cxx 117 KB

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