cmFileCommand.cxx 115 KB

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