cmFileCommand.cxx 112 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643
  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. };
  1149. static auto const parser = cmArgumentParser<Arguments>{}.Bind(
  1150. "BASE_DIRECTORY"_s, &Arguments::BaseDirectory);
  1151. std::vector<std::string> unparsedArguments;
  1152. std::vector<std::string> keywordsMissingValue;
  1153. std::vector<std::string> parsedKeywords;
  1154. auto arguments =
  1155. parser.Parse(cmMakeRange(args).advance(3), &unparsedArguments,
  1156. &keywordsMissingValue, &parsedKeywords);
  1157. if (!unparsedArguments.empty()) {
  1158. status.SetError("REAL_PATH called with unexpected arguments");
  1159. return false;
  1160. }
  1161. if (!keywordsMissingValue.empty()) {
  1162. status.SetError("BASE_DIRECTORY requires a value");
  1163. return false;
  1164. }
  1165. if (parsedKeywords.empty()) {
  1166. arguments.BaseDirectory = status.GetMakefile().GetCurrentSourceDirectory();
  1167. }
  1168. cmCMakePath path(args[1]);
  1169. path = path.Absolute(arguments.BaseDirectory).Normal();
  1170. auto realPath = cmSystemTools::GetRealPath(path.GenericString());
  1171. status.GetMakefile().AddDefinition(args[2], realPath);
  1172. return true;
  1173. }
  1174. bool HandleRelativePathCommand(std::vector<std::string> const& args,
  1175. cmExecutionStatus& status)
  1176. {
  1177. if (args.size() != 4) {
  1178. status.SetError("RELATIVE_PATH called with incorrect number of arguments");
  1179. return false;
  1180. }
  1181. const std::string& outVar = args[1];
  1182. const std::string& directoryName = args[2];
  1183. const std::string& fileName = args[3];
  1184. if (!cmSystemTools::FileIsFullPath(directoryName)) {
  1185. std::string errstring =
  1186. "RELATIVE_PATH must be passed a full path to the directory: " +
  1187. directoryName;
  1188. status.SetError(errstring);
  1189. return false;
  1190. }
  1191. if (!cmSystemTools::FileIsFullPath(fileName)) {
  1192. std::string errstring =
  1193. "RELATIVE_PATH must be passed a full path to the file: " + fileName;
  1194. status.SetError(errstring);
  1195. return false;
  1196. }
  1197. std::string res = cmSystemTools::RelativePath(directoryName, fileName);
  1198. status.GetMakefile().AddDefinition(outVar, res);
  1199. return true;
  1200. }
  1201. bool HandleRename(std::vector<std::string> const& args,
  1202. cmExecutionStatus& status)
  1203. {
  1204. if (args.size() < 3) {
  1205. status.SetError("RENAME must be called with at least two additional "
  1206. "arguments");
  1207. return false;
  1208. }
  1209. // Compute full path for old and new names.
  1210. std::string oldname = args[1];
  1211. if (!cmsys::SystemTools::FileIsFullPath(oldname)) {
  1212. oldname =
  1213. cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', args[1]);
  1214. }
  1215. std::string newname = args[2];
  1216. if (!cmsys::SystemTools::FileIsFullPath(newname)) {
  1217. newname =
  1218. cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', args[2]);
  1219. }
  1220. struct Arguments
  1221. {
  1222. bool NoReplace = false;
  1223. std::string Result;
  1224. };
  1225. static auto const parser = cmArgumentParser<Arguments>{}
  1226. .Bind("NO_REPLACE"_s, &Arguments::NoReplace)
  1227. .Bind("RESULT"_s, &Arguments::Result);
  1228. std::vector<std::string> unconsumedArgs;
  1229. Arguments const arguments =
  1230. parser.Parse(cmMakeRange(args).advance(3), &unconsumedArgs);
  1231. if (!unconsumedArgs.empty()) {
  1232. status.SetError("RENAME unknown argument:\n " + unconsumedArgs.front());
  1233. return false;
  1234. }
  1235. std::string err;
  1236. switch (cmSystemTools::RenameFile(oldname, newname,
  1237. arguments.NoReplace
  1238. ? cmSystemTools::Replace::No
  1239. : cmSystemTools::Replace::Yes,
  1240. &err)) {
  1241. case cmSystemTools::RenameResult::Success:
  1242. if (!arguments.Result.empty()) {
  1243. status.GetMakefile().AddDefinition(arguments.Result, "0");
  1244. }
  1245. return true;
  1246. case cmSystemTools::RenameResult::NoReplace:
  1247. if (!arguments.Result.empty()) {
  1248. err = "NO_REPLACE";
  1249. } else {
  1250. err = "path not replaced";
  1251. }
  1252. CM_FALLTHROUGH;
  1253. case cmSystemTools::RenameResult::Failure:
  1254. if (!arguments.Result.empty()) {
  1255. status.GetMakefile().AddDefinition(arguments.Result, err);
  1256. return true;
  1257. }
  1258. break;
  1259. }
  1260. status.SetError(cmStrCat("RENAME failed to rename\n ", oldname, "\nto\n ",
  1261. newname, "\nbecause: ", err, "\n"));
  1262. return false;
  1263. }
  1264. bool HandleRemoveImpl(std::vector<std::string> const& args, bool recurse,
  1265. cmExecutionStatus& status)
  1266. {
  1267. std::string message;
  1268. for (std::string const& arg :
  1269. cmMakeRange(args).advance(1)) // Get rid of subcommand
  1270. {
  1271. std::string fileName = arg;
  1272. if (fileName.empty()) {
  1273. std::string const r = recurse ? "REMOVE_RECURSE" : "REMOVE";
  1274. status.GetMakefile().IssueMessage(
  1275. MessageType::AUTHOR_WARNING, "Ignoring empty file name in " + r + ".");
  1276. continue;
  1277. }
  1278. if (!cmsys::SystemTools::FileIsFullPath(fileName)) {
  1279. fileName =
  1280. cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', arg);
  1281. }
  1282. if (cmSystemTools::FileIsDirectory(fileName) &&
  1283. !cmSystemTools::FileIsSymlink(fileName) && recurse) {
  1284. cmSystemTools::RepeatedRemoveDirectory(fileName);
  1285. } else {
  1286. cmSystemTools::RemoveFile(fileName);
  1287. }
  1288. }
  1289. return true;
  1290. }
  1291. bool HandleRemove(std::vector<std::string> const& args,
  1292. cmExecutionStatus& status)
  1293. {
  1294. return HandleRemoveImpl(args, false, status);
  1295. }
  1296. bool HandleRemoveRecurse(std::vector<std::string> const& args,
  1297. cmExecutionStatus& status)
  1298. {
  1299. return HandleRemoveImpl(args, true, status);
  1300. }
  1301. std::string ToNativePath(const std::string& path)
  1302. {
  1303. const auto& outPath = cmSystemTools::ConvertToOutputPath(path);
  1304. if (outPath.size() > 1 && outPath.front() == '\"' &&
  1305. outPath.back() == '\"') {
  1306. return outPath.substr(1, outPath.size() - 2);
  1307. }
  1308. return outPath;
  1309. }
  1310. std::string ToCMakePath(const std::string& path)
  1311. {
  1312. auto temp = path;
  1313. cmSystemTools::ConvertToUnixSlashes(temp);
  1314. return temp;
  1315. }
  1316. bool HandlePathCommand(std::vector<std::string> const& args,
  1317. std::string (*convert)(std::string const&),
  1318. cmExecutionStatus& status)
  1319. {
  1320. if (args.size() != 3) {
  1321. status.SetError("FILE([TO_CMAKE_PATH|TO_NATIVE_PATH] path result) must be "
  1322. "called with exactly three arguments.");
  1323. return false;
  1324. }
  1325. #if defined(_WIN32) && !defined(__CYGWIN__)
  1326. char pathSep = ';';
  1327. #else
  1328. char pathSep = ':';
  1329. #endif
  1330. std::vector<std::string> path = cmSystemTools::SplitString(args[1], pathSep);
  1331. std::string value = cmJoin(cmMakeRange(path).transform(convert), ";");
  1332. status.GetMakefile().AddDefinition(args[2], value);
  1333. return true;
  1334. }
  1335. bool HandleCMakePathCommand(std::vector<std::string> const& args,
  1336. cmExecutionStatus& status)
  1337. {
  1338. return HandlePathCommand(args, ToCMakePath, status);
  1339. }
  1340. bool HandleNativePathCommand(std::vector<std::string> const& args,
  1341. cmExecutionStatus& status)
  1342. {
  1343. return HandlePathCommand(args, ToNativePath, status);
  1344. }
  1345. #if !defined(CMAKE_BOOTSTRAP)
  1346. // Stuff for curl download/upload
  1347. using cmFileCommandVectorOfChar = std::vector<char>;
  1348. size_t cmWriteToFileCallback(void* ptr, size_t size, size_t nmemb, void* data)
  1349. {
  1350. int realsize = static_cast<int>(size * nmemb);
  1351. cmsys::ofstream* fout = static_cast<cmsys::ofstream*>(data);
  1352. if (fout) {
  1353. const char* chPtr = static_cast<char*>(ptr);
  1354. fout->write(chPtr, realsize);
  1355. }
  1356. return realsize;
  1357. }
  1358. size_t cmWriteToMemoryCallback(void* ptr, size_t size, size_t nmemb,
  1359. void* data)
  1360. {
  1361. int realsize = static_cast<int>(size * nmemb);
  1362. const char* chPtr = static_cast<char*>(ptr);
  1363. cm::append(*static_cast<cmFileCommandVectorOfChar*>(data), chPtr,
  1364. chPtr + realsize);
  1365. return realsize;
  1366. }
  1367. size_t cmFileCommandCurlDebugCallback(CURL*, curl_infotype type, char* chPtr,
  1368. size_t size, void* data)
  1369. {
  1370. cmFileCommandVectorOfChar& vec =
  1371. *static_cast<cmFileCommandVectorOfChar*>(data);
  1372. switch (type) {
  1373. case CURLINFO_TEXT:
  1374. case CURLINFO_HEADER_IN:
  1375. case CURLINFO_HEADER_OUT:
  1376. cm::append(vec, chPtr, chPtr + size);
  1377. break;
  1378. case CURLINFO_DATA_IN:
  1379. case CURLINFO_DATA_OUT:
  1380. case CURLINFO_SSL_DATA_IN:
  1381. case CURLINFO_SSL_DATA_OUT: {
  1382. char buf[128];
  1383. int n = sprintf(buf, "[%" KWIML_INT_PRIu64 " bytes data]\n",
  1384. static_cast<KWIML_INT_uint64_t>(size));
  1385. if (n > 0) {
  1386. cm::append(vec, buf, buf + n);
  1387. }
  1388. } break;
  1389. default:
  1390. break;
  1391. }
  1392. return 0;
  1393. }
  1394. class cURLProgressHelper
  1395. {
  1396. public:
  1397. cURLProgressHelper(cmMakefile* mf, const char* text)
  1398. : Makefile(mf)
  1399. , Text(text)
  1400. {
  1401. }
  1402. bool UpdatePercentage(double value, double total, std::string& status)
  1403. {
  1404. long OldPercentage = this->CurrentPercentage;
  1405. if (total > 0.0) {
  1406. this->CurrentPercentage = std::lround(value / total * 100.0);
  1407. if (this->CurrentPercentage > 100) {
  1408. // Avoid extra progress reports for unexpected data beyond total.
  1409. this->CurrentPercentage = 100;
  1410. }
  1411. }
  1412. bool updated = (OldPercentage != this->CurrentPercentage);
  1413. if (updated) {
  1414. status =
  1415. cmStrCat("[", this->Text, " ", this->CurrentPercentage, "% complete]");
  1416. }
  1417. return updated;
  1418. }
  1419. cmMakefile* GetMakefile() { return this->Makefile; }
  1420. private:
  1421. long CurrentPercentage = -1;
  1422. cmMakefile* Makefile;
  1423. std::string Text;
  1424. };
  1425. int cmFileDownloadProgressCallback(void* clientp, double dltotal, double dlnow,
  1426. double ultotal, double ulnow)
  1427. {
  1428. cURLProgressHelper* helper = reinterpret_cast<cURLProgressHelper*>(clientp);
  1429. static_cast<void>(ultotal);
  1430. static_cast<void>(ulnow);
  1431. std::string status;
  1432. if (helper->UpdatePercentage(dlnow, dltotal, status)) {
  1433. cmMakefile* mf = helper->GetMakefile();
  1434. mf->DisplayStatus(status, -1);
  1435. }
  1436. return 0;
  1437. }
  1438. int cmFileUploadProgressCallback(void* clientp, double dltotal, double dlnow,
  1439. double ultotal, double ulnow)
  1440. {
  1441. cURLProgressHelper* helper = reinterpret_cast<cURLProgressHelper*>(clientp);
  1442. static_cast<void>(dltotal);
  1443. static_cast<void>(dlnow);
  1444. std::string status;
  1445. if (helper->UpdatePercentage(ulnow, ultotal, status)) {
  1446. cmMakefile* mf = helper->GetMakefile();
  1447. mf->DisplayStatus(status, -1);
  1448. }
  1449. return 0;
  1450. }
  1451. class cURLEasyGuard
  1452. {
  1453. public:
  1454. cURLEasyGuard(CURL* easy)
  1455. : Easy(easy)
  1456. {
  1457. }
  1458. ~cURLEasyGuard()
  1459. {
  1460. if (this->Easy) {
  1461. ::curl_easy_cleanup(this->Easy);
  1462. }
  1463. }
  1464. cURLEasyGuard(const cURLEasyGuard&) = delete;
  1465. cURLEasyGuard& operator=(const cURLEasyGuard&) = delete;
  1466. void release() { this->Easy = nullptr; }
  1467. private:
  1468. ::CURL* Easy;
  1469. };
  1470. #endif
  1471. #define check_curl_result(result, errstr) \
  1472. do { \
  1473. if (result != CURLE_OK) { \
  1474. std::string e(errstr); \
  1475. e += ::curl_easy_strerror(result); \
  1476. status.SetError(e); \
  1477. return false; \
  1478. } \
  1479. } while (false)
  1480. bool HandleDownloadCommand(std::vector<std::string> const& args,
  1481. cmExecutionStatus& status)
  1482. {
  1483. #if !defined(CMAKE_BOOTSTRAP)
  1484. auto i = args.begin();
  1485. if (args.size() < 2) {
  1486. status.SetError("DOWNLOAD must be called with at least two arguments.");
  1487. return false;
  1488. }
  1489. ++i; // Get rid of subcommand
  1490. std::string url = *i;
  1491. ++i;
  1492. std::string file;
  1493. long timeout = 0;
  1494. long inactivity_timeout = 0;
  1495. std::string logVar;
  1496. std::string statusVar;
  1497. bool tls_verify = status.GetMakefile().IsOn("CMAKE_TLS_VERIFY");
  1498. cmProp cainfo = status.GetMakefile().GetDefinition("CMAKE_TLS_CAINFO");
  1499. std::string netrc_level =
  1500. status.GetMakefile().GetSafeDefinition("CMAKE_NETRC");
  1501. std::string netrc_file =
  1502. status.GetMakefile().GetSafeDefinition("CMAKE_NETRC_FILE");
  1503. std::string expectedHash;
  1504. std::string hashMatchMSG;
  1505. std::unique_ptr<cmCryptoHash> hash;
  1506. bool showProgress = false;
  1507. std::string userpwd;
  1508. std::vector<std::string> curl_headers;
  1509. while (i != args.end()) {
  1510. if (*i == "TIMEOUT") {
  1511. ++i;
  1512. if (i != args.end()) {
  1513. timeout = atol(i->c_str());
  1514. } else {
  1515. status.SetError("DOWNLOAD missing time for TIMEOUT.");
  1516. return false;
  1517. }
  1518. } else if (*i == "INACTIVITY_TIMEOUT") {
  1519. ++i;
  1520. if (i != args.end()) {
  1521. inactivity_timeout = atol(i->c_str());
  1522. } else {
  1523. status.SetError("DOWNLOAD missing time for INACTIVITY_TIMEOUT.");
  1524. return false;
  1525. }
  1526. } else if (*i == "LOG") {
  1527. ++i;
  1528. if (i == args.end()) {
  1529. status.SetError("DOWNLOAD missing VAR for LOG.");
  1530. return false;
  1531. }
  1532. logVar = *i;
  1533. } else if (*i == "STATUS") {
  1534. ++i;
  1535. if (i == args.end()) {
  1536. status.SetError("DOWNLOAD missing VAR for STATUS.");
  1537. return false;
  1538. }
  1539. statusVar = *i;
  1540. } else if (*i == "TLS_VERIFY") {
  1541. ++i;
  1542. if (i != args.end()) {
  1543. tls_verify = cmIsOn(*i);
  1544. } else {
  1545. status.SetError("DOWNLOAD missing bool value for TLS_VERIFY.");
  1546. return false;
  1547. }
  1548. } else if (*i == "TLS_CAINFO") {
  1549. ++i;
  1550. if (i != args.end()) {
  1551. cainfo = &(*i);
  1552. } else {
  1553. status.SetError("DOWNLOAD missing file value for TLS_CAINFO.");
  1554. return false;
  1555. }
  1556. } else if (*i == "NETRC_FILE") {
  1557. ++i;
  1558. if (i != args.end()) {
  1559. netrc_file = *i;
  1560. } else {
  1561. status.SetError("DOWNLOAD missing file value for NETRC_FILE.");
  1562. return false;
  1563. }
  1564. } else if (*i == "NETRC") {
  1565. ++i;
  1566. if (i != args.end()) {
  1567. netrc_level = *i;
  1568. } else {
  1569. status.SetError("DOWNLOAD missing level value for NETRC.");
  1570. return false;
  1571. }
  1572. } else if (*i == "EXPECTED_MD5") {
  1573. ++i;
  1574. if (i == args.end()) {
  1575. status.SetError("DOWNLOAD missing sum value for EXPECTED_MD5.");
  1576. return false;
  1577. }
  1578. hash = cm::make_unique<cmCryptoHash>(cmCryptoHash::AlgoMD5);
  1579. hashMatchMSG = "MD5 sum";
  1580. expectedHash = cmSystemTools::LowerCase(*i);
  1581. } else if (*i == "SHOW_PROGRESS") {
  1582. showProgress = true;
  1583. } else if (*i == "EXPECTED_HASH") {
  1584. ++i;
  1585. if (i == args.end()) {
  1586. status.SetError("DOWNLOAD missing ALGO=value for EXPECTED_HASH.");
  1587. return false;
  1588. }
  1589. std::string::size_type pos = i->find("=");
  1590. if (pos == std::string::npos) {
  1591. std::string err =
  1592. cmStrCat("DOWNLOAD EXPECTED_HASH expects ALGO=value but got: ", *i);
  1593. status.SetError(err);
  1594. return false;
  1595. }
  1596. std::string algo = i->substr(0, pos);
  1597. expectedHash = cmSystemTools::LowerCase(i->substr(pos + 1));
  1598. hash = std::unique_ptr<cmCryptoHash>(cmCryptoHash::New(algo));
  1599. if (!hash) {
  1600. std::string err =
  1601. cmStrCat("DOWNLOAD EXPECTED_HASH given unknown ALGO: ", algo);
  1602. status.SetError(err);
  1603. return false;
  1604. }
  1605. hashMatchMSG = algo + " hash";
  1606. } else if (*i == "USERPWD") {
  1607. ++i;
  1608. if (i == args.end()) {
  1609. status.SetError("DOWNLOAD missing string for USERPWD.");
  1610. return false;
  1611. }
  1612. userpwd = *i;
  1613. } else if (*i == "HTTPHEADER") {
  1614. ++i;
  1615. if (i == args.end()) {
  1616. status.SetError("DOWNLOAD missing string for HTTPHEADER.");
  1617. return false;
  1618. }
  1619. curl_headers.push_back(*i);
  1620. } else if (file.empty()) {
  1621. file = *i;
  1622. } else {
  1623. // Do not return error for compatibility reason.
  1624. std::string err = cmStrCat("Unexpected argument: ", *i);
  1625. status.GetMakefile().IssueMessage(MessageType::AUTHOR_WARNING, err);
  1626. }
  1627. ++i;
  1628. }
  1629. // Can't calculate hash if we don't save the file.
  1630. // TODO Incrementally calculate hash in the write callback as the file is
  1631. // being downloaded so this check can be relaxed.
  1632. if (file.empty() && hash) {
  1633. status.SetError("DOWNLOAD cannot calculate hash if file is not saved.");
  1634. return false;
  1635. }
  1636. // If file exists already, and caller specified an expected md5 or sha,
  1637. // and the existing file already has the expected hash, then simply
  1638. // return.
  1639. //
  1640. if (!file.empty() && cmSystemTools::FileExists(file) && hash.get()) {
  1641. std::string msg;
  1642. std::string actualHash = hash->HashFile(file);
  1643. if (actualHash == expectedHash) {
  1644. msg = cmStrCat("returning early; file already exists with expected ",
  1645. hashMatchMSG, '"');
  1646. if (!statusVar.empty()) {
  1647. status.GetMakefile().AddDefinition(statusVar, cmStrCat(0, ";\"", msg));
  1648. }
  1649. return true;
  1650. }
  1651. }
  1652. // Make sure parent directory exists so we can write to the file
  1653. // as we receive downloaded bits from curl...
  1654. //
  1655. if (!file.empty()) {
  1656. std::string dir = cmSystemTools::GetFilenamePath(file);
  1657. if (!dir.empty() && !cmSystemTools::FileExists(dir) &&
  1658. !cmSystemTools::MakeDirectory(dir)) {
  1659. std::string errstring = "DOWNLOAD error: cannot create directory '" +
  1660. dir +
  1661. "' - Specify file by full path name and verify that you "
  1662. "have directory creation and file write privileges.";
  1663. status.SetError(errstring);
  1664. return false;
  1665. }
  1666. }
  1667. cmsys::ofstream fout;
  1668. if (!file.empty()) {
  1669. fout.open(file.c_str(), std::ios::binary);
  1670. if (!fout) {
  1671. status.SetError("DOWNLOAD cannot open file for write.");
  1672. return false;
  1673. }
  1674. }
  1675. # if defined(_WIN32)
  1676. url = fix_file_url_windows(url);
  1677. # endif
  1678. ::CURL* curl;
  1679. ::curl_global_init(CURL_GLOBAL_DEFAULT);
  1680. curl = ::curl_easy_init();
  1681. if (!curl) {
  1682. status.SetError("DOWNLOAD error initializing curl.");
  1683. return false;
  1684. }
  1685. cURLEasyGuard g_curl(curl);
  1686. ::CURLcode res = ::curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  1687. check_curl_result(res, "DOWNLOAD cannot set url: ");
  1688. // enable HTTP ERROR parsing
  1689. res = ::curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  1690. check_curl_result(res, "DOWNLOAD cannot set http failure option: ");
  1691. res = ::curl_easy_setopt(curl, CURLOPT_USERAGENT, "curl/" LIBCURL_VERSION);
  1692. check_curl_result(res, "DOWNLOAD cannot set user agent option: ");
  1693. res = ::curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cmWriteToFileCallback);
  1694. check_curl_result(res, "DOWNLOAD cannot set write function: ");
  1695. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION,
  1696. cmFileCommandCurlDebugCallback);
  1697. check_curl_result(res, "DOWNLOAD cannot set debug function: ");
  1698. // check to see if TLS verification is requested
  1699. if (tls_verify) {
  1700. res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1);
  1701. check_curl_result(res, "DOWNLOAD cannot set TLS/SSL Verify on: ");
  1702. } else {
  1703. res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
  1704. check_curl_result(res, "DOWNLOAD cannot set TLS/SSL Verify off: ");
  1705. }
  1706. // check to see if a CAINFO file has been specified
  1707. // command arg comes first
  1708. std::string const& cainfo_err = cmCurlSetCAInfo(curl, cmToCStr(cainfo));
  1709. if (!cainfo_err.empty()) {
  1710. status.SetError(cainfo_err);
  1711. return false;
  1712. }
  1713. // check to see if netrc parameters have been specified
  1714. // local command args takes precedence over CMAKE_NETRC*
  1715. netrc_level = cmSystemTools::UpperCase(netrc_level);
  1716. std::string const& netrc_option_err =
  1717. cmCurlSetNETRCOption(curl, netrc_level, netrc_file);
  1718. if (!netrc_option_err.empty()) {
  1719. status.SetError(netrc_option_err);
  1720. return false;
  1721. }
  1722. cmFileCommandVectorOfChar chunkDebug;
  1723. res = ::curl_easy_setopt(curl, CURLOPT_WRITEDATA,
  1724. file.empty() ? nullptr : &fout);
  1725. check_curl_result(res, "DOWNLOAD cannot set write data: ");
  1726. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, &chunkDebug);
  1727. check_curl_result(res, "DOWNLOAD cannot set debug data: ");
  1728. res = ::curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  1729. check_curl_result(res, "DOWNLOAD cannot set follow-redirect option: ");
  1730. if (!logVar.empty()) {
  1731. res = ::curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  1732. check_curl_result(res, "DOWNLOAD cannot set verbose: ");
  1733. }
  1734. if (timeout > 0) {
  1735. res = ::curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  1736. check_curl_result(res, "DOWNLOAD cannot set timeout: ");
  1737. }
  1738. if (inactivity_timeout > 0) {
  1739. // Give up if there is no progress for a long time.
  1740. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1);
  1741. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, inactivity_timeout);
  1742. }
  1743. // Need the progress helper's scope to last through the duration of
  1744. // the curl_easy_perform call... so this object is declared at function
  1745. // scope intentionally, rather than inside the "if(showProgress)"
  1746. // block...
  1747. //
  1748. cURLProgressHelper helper(&status.GetMakefile(), "download");
  1749. if (showProgress) {
  1750. res = ::curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
  1751. check_curl_result(res, "DOWNLOAD cannot set noprogress value: ");
  1752. res = ::curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION,
  1753. cmFileDownloadProgressCallback);
  1754. check_curl_result(res, "DOWNLOAD cannot set progress function: ");
  1755. res = ::curl_easy_setopt(curl, CURLOPT_PROGRESSDATA,
  1756. reinterpret_cast<void*>(&helper));
  1757. check_curl_result(res, "DOWNLOAD cannot set progress data: ");
  1758. }
  1759. if (!userpwd.empty()) {
  1760. res = ::curl_easy_setopt(curl, CURLOPT_USERPWD, userpwd.c_str());
  1761. check_curl_result(res, "DOWNLOAD cannot set user password: ");
  1762. }
  1763. struct curl_slist* headers = nullptr;
  1764. for (std::string const& h : curl_headers) {
  1765. headers = ::curl_slist_append(headers, h.c_str());
  1766. }
  1767. ::curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  1768. res = ::curl_easy_perform(curl);
  1769. ::curl_slist_free_all(headers);
  1770. /* always cleanup */
  1771. g_curl.release();
  1772. ::curl_easy_cleanup(curl);
  1773. if (!statusVar.empty()) {
  1774. status.GetMakefile().AddDefinition(
  1775. statusVar,
  1776. cmStrCat(static_cast<int>(res), ";\"", ::curl_easy_strerror(res), "\""));
  1777. }
  1778. ::curl_global_cleanup();
  1779. // Explicitly flush/close so we can measure the md5 accurately.
  1780. //
  1781. if (!file.empty()) {
  1782. fout.flush();
  1783. fout.close();
  1784. }
  1785. // Verify MD5 sum if requested:
  1786. //
  1787. if (hash) {
  1788. std::string actualHash = hash->HashFile(file);
  1789. if (actualHash.empty()) {
  1790. status.SetError("DOWNLOAD cannot compute hash on downloaded file");
  1791. return false;
  1792. }
  1793. if (expectedHash != actualHash) {
  1794. if (!statusVar.empty() && res == 0) {
  1795. status.GetMakefile().AddDefinition(statusVar,
  1796. "1;HASH mismatch: "
  1797. "expected: " +
  1798. expectedHash +
  1799. " actual: " + actualHash);
  1800. }
  1801. status.SetError(cmStrCat("DOWNLOAD HASH mismatch\n"
  1802. " for file: [",
  1803. file,
  1804. "]\n"
  1805. " expected hash: [",
  1806. expectedHash,
  1807. "]\n"
  1808. " actual hash: [",
  1809. actualHash,
  1810. "]\n"
  1811. " status: [",
  1812. static_cast<int>(res), ";\"",
  1813. ::curl_easy_strerror(res), "\"]\n"));
  1814. return false;
  1815. }
  1816. }
  1817. if (!logVar.empty()) {
  1818. chunkDebug.push_back(0);
  1819. status.GetMakefile().AddDefinition(logVar, chunkDebug.data());
  1820. }
  1821. return true;
  1822. #else
  1823. status.SetError("DOWNLOAD not supported by bootstrap cmake.");
  1824. return false;
  1825. #endif
  1826. }
  1827. bool HandleUploadCommand(std::vector<std::string> const& args,
  1828. cmExecutionStatus& status)
  1829. {
  1830. #if !defined(CMAKE_BOOTSTRAP)
  1831. if (args.size() < 3) {
  1832. status.SetError("UPLOAD must be called with at least three arguments.");
  1833. return false;
  1834. }
  1835. auto i = args.begin();
  1836. ++i;
  1837. std::string filename = *i;
  1838. ++i;
  1839. std::string url = *i;
  1840. ++i;
  1841. long timeout = 0;
  1842. long inactivity_timeout = 0;
  1843. std::string logVar;
  1844. std::string statusVar;
  1845. bool showProgress = false;
  1846. bool tls_verify = status.GetMakefile().IsOn("CMAKE_TLS_VERIFY");
  1847. cmProp cainfo = status.GetMakefile().GetDefinition("CMAKE_TLS_CAINFO");
  1848. std::string userpwd;
  1849. std::string netrc_level =
  1850. status.GetMakefile().GetSafeDefinition("CMAKE_NETRC");
  1851. std::string netrc_file =
  1852. status.GetMakefile().GetSafeDefinition("CMAKE_NETRC_FILE");
  1853. std::vector<std::string> curl_headers;
  1854. while (i != args.end()) {
  1855. if (*i == "TIMEOUT") {
  1856. ++i;
  1857. if (i != args.end()) {
  1858. timeout = atol(i->c_str());
  1859. } else {
  1860. status.SetError("UPLOAD missing time for TIMEOUT.");
  1861. return false;
  1862. }
  1863. } else if (*i == "INACTIVITY_TIMEOUT") {
  1864. ++i;
  1865. if (i != args.end()) {
  1866. inactivity_timeout = atol(i->c_str());
  1867. } else {
  1868. status.SetError("UPLOAD missing time for INACTIVITY_TIMEOUT.");
  1869. return false;
  1870. }
  1871. } else if (*i == "LOG") {
  1872. ++i;
  1873. if (i == args.end()) {
  1874. status.SetError("UPLOAD missing VAR for LOG.");
  1875. return false;
  1876. }
  1877. logVar = *i;
  1878. } else if (*i == "STATUS") {
  1879. ++i;
  1880. if (i == args.end()) {
  1881. status.SetError("UPLOAD missing VAR for STATUS.");
  1882. return false;
  1883. }
  1884. statusVar = *i;
  1885. } else if (*i == "SHOW_PROGRESS") {
  1886. showProgress = true;
  1887. } else if (*i == "TLS_VERIFY") {
  1888. ++i;
  1889. if (i != args.end()) {
  1890. tls_verify = cmIsOn(*i);
  1891. } else {
  1892. status.SetError("UPLOAD missing bool value for TLS_VERIFY.");
  1893. return false;
  1894. }
  1895. } else if (*i == "TLS_CAINFO") {
  1896. ++i;
  1897. if (i != args.end()) {
  1898. cainfo = &(*i);
  1899. } else {
  1900. status.SetError("UPLOAD missing file value for TLS_CAINFO.");
  1901. return false;
  1902. }
  1903. } else if (*i == "NETRC_FILE") {
  1904. ++i;
  1905. if (i != args.end()) {
  1906. netrc_file = *i;
  1907. } else {
  1908. status.SetError("UPLOAD missing file value for NETRC_FILE.");
  1909. return false;
  1910. }
  1911. } else if (*i == "NETRC") {
  1912. ++i;
  1913. if (i != args.end()) {
  1914. netrc_level = *i;
  1915. } else {
  1916. status.SetError("UPLOAD missing level value for NETRC.");
  1917. return false;
  1918. }
  1919. } else if (*i == "USERPWD") {
  1920. ++i;
  1921. if (i == args.end()) {
  1922. status.SetError("UPLOAD missing string for USERPWD.");
  1923. return false;
  1924. }
  1925. userpwd = *i;
  1926. } else if (*i == "HTTPHEADER") {
  1927. ++i;
  1928. if (i == args.end()) {
  1929. status.SetError("UPLOAD missing string for HTTPHEADER.");
  1930. return false;
  1931. }
  1932. curl_headers.push_back(*i);
  1933. } else {
  1934. // Do not return error for compatibility reason.
  1935. std::string err = cmStrCat("Unexpected argument: ", *i);
  1936. status.GetMakefile().IssueMessage(MessageType::AUTHOR_WARNING, err);
  1937. }
  1938. ++i;
  1939. }
  1940. // Open file for reading:
  1941. //
  1942. FILE* fin = cmsys::SystemTools::Fopen(filename, "rb");
  1943. if (!fin) {
  1944. std::string errStr =
  1945. cmStrCat("UPLOAD cannot open file '", filename, "' for reading.");
  1946. status.SetError(errStr);
  1947. return false;
  1948. }
  1949. unsigned long file_size = cmsys::SystemTools::FileLength(filename);
  1950. # if defined(_WIN32)
  1951. url = fix_file_url_windows(url);
  1952. # endif
  1953. ::CURL* curl;
  1954. ::curl_global_init(CURL_GLOBAL_DEFAULT);
  1955. curl = ::curl_easy_init();
  1956. if (!curl) {
  1957. status.SetError("UPLOAD error initializing curl.");
  1958. fclose(fin);
  1959. return false;
  1960. }
  1961. cURLEasyGuard g_curl(curl);
  1962. // enable HTTP ERROR parsing
  1963. ::CURLcode res = ::curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  1964. check_curl_result(res, "UPLOAD cannot set fail on error flag: ");
  1965. // enable uploading
  1966. res = ::curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
  1967. check_curl_result(res, "UPLOAD cannot set upload flag: ");
  1968. res = ::curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  1969. check_curl_result(res, "UPLOAD cannot set url: ");
  1970. res =
  1971. ::curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cmWriteToMemoryCallback);
  1972. check_curl_result(res, "UPLOAD cannot set write function: ");
  1973. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION,
  1974. cmFileCommandCurlDebugCallback);
  1975. check_curl_result(res, "UPLOAD cannot set debug function: ");
  1976. // check to see if TLS verification is requested
  1977. if (tls_verify) {
  1978. res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1);
  1979. check_curl_result(res, "UPLOAD cannot set TLS/SSL Verify on: ");
  1980. } else {
  1981. res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
  1982. check_curl_result(res, "UPLOAD cannot set TLS/SSL Verify off: ");
  1983. }
  1984. // check to see if a CAINFO file has been specified
  1985. // command arg comes first
  1986. std::string const& cainfo_err = cmCurlSetCAInfo(curl, cmToCStr(cainfo));
  1987. if (!cainfo_err.empty()) {
  1988. status.SetError(cainfo_err);
  1989. return false;
  1990. }
  1991. cmFileCommandVectorOfChar chunkResponse;
  1992. cmFileCommandVectorOfChar chunkDebug;
  1993. res = ::curl_easy_setopt(curl, CURLOPT_WRITEDATA, &chunkResponse);
  1994. check_curl_result(res, "UPLOAD cannot set write data: ");
  1995. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, &chunkDebug);
  1996. check_curl_result(res, "UPLOAD cannot set debug data: ");
  1997. res = ::curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  1998. check_curl_result(res, "UPLOAD cannot set follow-redirect option: ");
  1999. if (!logVar.empty()) {
  2000. res = ::curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  2001. check_curl_result(res, "UPLOAD cannot set verbose: ");
  2002. }
  2003. if (timeout > 0) {
  2004. res = ::curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  2005. check_curl_result(res, "UPLOAD cannot set timeout: ");
  2006. }
  2007. if (inactivity_timeout > 0) {
  2008. // Give up if there is no progress for a long time.
  2009. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1);
  2010. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, inactivity_timeout);
  2011. }
  2012. // Need the progress helper's scope to last through the duration of
  2013. // the curl_easy_perform call... so this object is declared at function
  2014. // scope intentionally, rather than inside the "if(showProgress)"
  2015. // block...
  2016. //
  2017. cURLProgressHelper helper(&status.GetMakefile(), "upload");
  2018. if (showProgress) {
  2019. res = ::curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
  2020. check_curl_result(res, "UPLOAD cannot set noprogress value: ");
  2021. res = ::curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION,
  2022. cmFileUploadProgressCallback);
  2023. check_curl_result(res, "UPLOAD cannot set progress function: ");
  2024. res = ::curl_easy_setopt(curl, CURLOPT_PROGRESSDATA,
  2025. reinterpret_cast<void*>(&helper));
  2026. check_curl_result(res, "UPLOAD cannot set progress data: ");
  2027. }
  2028. // now specify which file to upload
  2029. res = ::curl_easy_setopt(curl, CURLOPT_INFILE, fin);
  2030. check_curl_result(res, "UPLOAD cannot set input file: ");
  2031. // and give the size of the upload (optional)
  2032. res =
  2033. ::curl_easy_setopt(curl, CURLOPT_INFILESIZE, static_cast<long>(file_size));
  2034. check_curl_result(res, "UPLOAD cannot set input file size: ");
  2035. if (!userpwd.empty()) {
  2036. res = ::curl_easy_setopt(curl, CURLOPT_USERPWD, userpwd.c_str());
  2037. check_curl_result(res, "UPLOAD cannot set user password: ");
  2038. }
  2039. // check to see if netrc parameters have been specified
  2040. // local command args takes precedence over CMAKE_NETRC*
  2041. netrc_level = cmSystemTools::UpperCase(netrc_level);
  2042. std::string const& netrc_option_err =
  2043. cmCurlSetNETRCOption(curl, netrc_level, netrc_file);
  2044. if (!netrc_option_err.empty()) {
  2045. status.SetError(netrc_option_err);
  2046. return false;
  2047. }
  2048. struct curl_slist* headers = nullptr;
  2049. for (std::string const& h : curl_headers) {
  2050. headers = ::curl_slist_append(headers, h.c_str());
  2051. }
  2052. ::curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  2053. res = ::curl_easy_perform(curl);
  2054. ::curl_slist_free_all(headers);
  2055. /* always cleanup */
  2056. g_curl.release();
  2057. ::curl_easy_cleanup(curl);
  2058. if (!statusVar.empty()) {
  2059. status.GetMakefile().AddDefinition(
  2060. statusVar,
  2061. cmStrCat(static_cast<int>(res), ";\"", ::curl_easy_strerror(res), "\""));
  2062. }
  2063. ::curl_global_cleanup();
  2064. fclose(fin);
  2065. fin = nullptr;
  2066. if (!logVar.empty()) {
  2067. std::string log;
  2068. if (!chunkResponse.empty()) {
  2069. chunkResponse.push_back(0);
  2070. log += "Response:\n";
  2071. log += chunkResponse.data();
  2072. log += "\n";
  2073. }
  2074. if (!chunkDebug.empty()) {
  2075. chunkDebug.push_back(0);
  2076. log += "Debug:\n";
  2077. log += chunkDebug.data();
  2078. log += "\n";
  2079. }
  2080. status.GetMakefile().AddDefinition(logVar, log);
  2081. }
  2082. return true;
  2083. #else
  2084. status.SetError("UPLOAD not supported by bootstrap cmake.");
  2085. return false;
  2086. #endif
  2087. }
  2088. void AddEvaluationFile(const std::string& inputName,
  2089. const std::string& targetName,
  2090. const std::string& outputExpr,
  2091. const std::string& condition, bool inputIsContent,
  2092. const std::string& newLineCharacter, mode_t permissions,
  2093. cmExecutionStatus& status)
  2094. {
  2095. cmListFileBacktrace lfbt = status.GetMakefile().GetBacktrace();
  2096. cmGeneratorExpression outputGe(lfbt);
  2097. std::unique_ptr<cmCompiledGeneratorExpression> outputCge =
  2098. outputGe.Parse(outputExpr);
  2099. cmGeneratorExpression conditionGe(lfbt);
  2100. std::unique_ptr<cmCompiledGeneratorExpression> conditionCge =
  2101. conditionGe.Parse(condition);
  2102. status.GetMakefile().AddEvaluationFile(
  2103. inputName, targetName, std::move(outputCge), std::move(conditionCge),
  2104. newLineCharacter, permissions, inputIsContent);
  2105. }
  2106. bool HandleGenerateCommand(std::vector<std::string> const& args,
  2107. cmExecutionStatus& status)
  2108. {
  2109. if (args.size() < 5) {
  2110. status.SetError("Incorrect arguments to GENERATE subcommand.");
  2111. return false;
  2112. }
  2113. struct Arguments
  2114. {
  2115. std::string Output;
  2116. std::string Input;
  2117. std::string Content;
  2118. std::string Condition;
  2119. std::string Target;
  2120. std::string NewLineStyle;
  2121. bool NoSourcePermissions = false;
  2122. bool UseSourcePermissions = false;
  2123. std::vector<std::string> FilePermissions;
  2124. };
  2125. static auto const parser =
  2126. cmArgumentParser<Arguments>{}
  2127. .Bind("OUTPUT"_s, &Arguments::Output)
  2128. .Bind("INPUT"_s, &Arguments::Input)
  2129. .Bind("CONTENT"_s, &Arguments::Content)
  2130. .Bind("CONDITION"_s, &Arguments::Condition)
  2131. .Bind("TARGET"_s, &Arguments::Target)
  2132. .Bind("NO_SOURCE_PERMISSIONS"_s, &Arguments::NoSourcePermissions)
  2133. .Bind("USE_SOURCE_PERMISSIONS"_s, &Arguments::UseSourcePermissions)
  2134. .Bind("FILE_PERMISSIONS"_s, &Arguments::FilePermissions)
  2135. .Bind("NEWLINE_STYLE"_s, &Arguments::NewLineStyle);
  2136. std::vector<std::string> unparsedArguments;
  2137. std::vector<std::string> keywordsMissingValues;
  2138. std::vector<std::string> parsedKeywords;
  2139. Arguments const arguments =
  2140. parser.Parse(cmMakeRange(args).advance(1), &unparsedArguments,
  2141. &keywordsMissingValues, &parsedKeywords);
  2142. if (!keywordsMissingValues.empty()) {
  2143. status.SetError("Incorrect arguments to GENERATE subcommand.");
  2144. return false;
  2145. }
  2146. if (!unparsedArguments.empty()) {
  2147. status.SetError("Unknown argument to GENERATE subcommand.");
  2148. return false;
  2149. }
  2150. bool mandatoryOptionsSpecified = false;
  2151. if (parsedKeywords.size() > 1) {
  2152. const bool outputOprionSpecified = parsedKeywords[0] == "OUTPUT"_s;
  2153. const bool inputOrContentSpecified =
  2154. parsedKeywords[1] == "INPUT"_s || parsedKeywords[1] == "CONTENT"_s;
  2155. if (outputOprionSpecified && inputOrContentSpecified) {
  2156. mandatoryOptionsSpecified = true;
  2157. }
  2158. }
  2159. if (!mandatoryOptionsSpecified) {
  2160. status.SetError("Incorrect arguments to GENERATE subcommand.");
  2161. return false;
  2162. }
  2163. const bool conditionOptionSpecified =
  2164. std::find(parsedKeywords.begin(), parsedKeywords.end(), "CONDITION"_s) !=
  2165. parsedKeywords.end();
  2166. if (conditionOptionSpecified && arguments.Condition.empty()) {
  2167. status.SetError("CONDITION of sub-command GENERATE must not be empty "
  2168. "if specified.");
  2169. return false;
  2170. }
  2171. const bool targetOptionSpecified =
  2172. std::find(parsedKeywords.begin(), parsedKeywords.end(), "TARGET"_s) !=
  2173. parsedKeywords.end();
  2174. if (targetOptionSpecified && arguments.Target.empty()) {
  2175. status.SetError("TARGET of sub-command GENERATE must not be empty "
  2176. "if specified.");
  2177. return false;
  2178. }
  2179. const bool outputOptionSpecified =
  2180. std::find(parsedKeywords.begin(), parsedKeywords.end(), "OUTPUT"_s) !=
  2181. parsedKeywords.end();
  2182. if (outputOptionSpecified && parsedKeywords[0] != "OUTPUT"_s) {
  2183. status.SetError("Incorrect arguments to GENERATE subcommand.");
  2184. return false;
  2185. }
  2186. const bool inputIsContent = parsedKeywords[1] != "INPUT"_s;
  2187. if (inputIsContent && parsedKeywords[1] != "CONTENT") {
  2188. status.SetError("Unknown argument to GENERATE subcommand.");
  2189. }
  2190. const bool newLineStyleSpecified =
  2191. std::find(parsedKeywords.begin(), parsedKeywords.end(),
  2192. "NEWLINE_STYLE"_s) != parsedKeywords.end();
  2193. cmNewLineStyle newLineStyle;
  2194. if (newLineStyleSpecified) {
  2195. std::string errorMessage;
  2196. if (!newLineStyle.ReadFromArguments(args, errorMessage)) {
  2197. status.SetError(cmStrCat("GENERATE ", errorMessage));
  2198. return false;
  2199. }
  2200. }
  2201. std::string input = arguments.Input;
  2202. if (inputIsContent) {
  2203. input = arguments.Content;
  2204. }
  2205. if (arguments.NoSourcePermissions && arguments.UseSourcePermissions) {
  2206. status.SetError("given both NO_SOURCE_PERMISSIONS and "
  2207. "USE_SOURCE_PERMISSIONS. Only one option allowed.");
  2208. return false;
  2209. }
  2210. if (!arguments.FilePermissions.empty()) {
  2211. if (arguments.NoSourcePermissions) {
  2212. status.SetError("given both NO_SOURCE_PERMISSIONS and "
  2213. "FILE_PERMISSIONS. Only one option allowed.");
  2214. return false;
  2215. }
  2216. if (arguments.UseSourcePermissions) {
  2217. status.SetError("given both USE_SOURCE_PERMISSIONS and "
  2218. "FILE_PERMISSIONS. Only one option allowed.");
  2219. return false;
  2220. }
  2221. }
  2222. if (arguments.UseSourcePermissions) {
  2223. if (inputIsContent) {
  2224. status.SetError("given USE_SOURCE_PERMISSIONS without a file INPUT.");
  2225. return false;
  2226. }
  2227. }
  2228. mode_t permisiions = 0;
  2229. if (arguments.NoSourcePermissions) {
  2230. permisiions |= cmFSPermissions::mode_owner_read;
  2231. permisiions |= cmFSPermissions::mode_owner_write;
  2232. permisiions |= cmFSPermissions::mode_group_read;
  2233. permisiions |= cmFSPermissions::mode_world_read;
  2234. }
  2235. if (!arguments.FilePermissions.empty()) {
  2236. std::vector<std::string> invalidOptions;
  2237. for (auto const& e : arguments.FilePermissions) {
  2238. if (!cmFSPermissions::stringToModeT(e, permisiions)) {
  2239. invalidOptions.push_back(e);
  2240. }
  2241. }
  2242. if (!invalidOptions.empty()) {
  2243. std::ostringstream oss;
  2244. oss << "given invalid permission ";
  2245. for (auto i = 0u; i < invalidOptions.size(); i++) {
  2246. if (i == 0u) {
  2247. oss << "\"" << invalidOptions[i] << "\"";
  2248. } else {
  2249. oss << ",\"" << invalidOptions[i] << "\"";
  2250. }
  2251. }
  2252. oss << ".";
  2253. status.SetError(oss.str());
  2254. return false;
  2255. }
  2256. }
  2257. AddEvaluationFile(input, arguments.Target, arguments.Output,
  2258. arguments.Condition, inputIsContent,
  2259. newLineStyle.GetCharacters(), permisiions, status);
  2260. return true;
  2261. }
  2262. bool HandleLockCommand(std::vector<std::string> const& args,
  2263. cmExecutionStatus& status)
  2264. {
  2265. #if !defined(CMAKE_BOOTSTRAP)
  2266. // Default values
  2267. bool directory = false;
  2268. bool release = false;
  2269. enum Guard
  2270. {
  2271. GUARD_FUNCTION,
  2272. GUARD_FILE,
  2273. GUARD_PROCESS
  2274. };
  2275. Guard guard = GUARD_PROCESS;
  2276. std::string resultVariable;
  2277. unsigned long timeout = static_cast<unsigned long>(-1);
  2278. // Parse arguments
  2279. if (args.size() < 2) {
  2280. status.GetMakefile().IssueMessage(
  2281. MessageType::FATAL_ERROR,
  2282. "sub-command LOCK requires at least two arguments.");
  2283. return false;
  2284. }
  2285. std::string path = args[1];
  2286. for (unsigned i = 2; i < args.size(); ++i) {
  2287. if (args[i] == "DIRECTORY") {
  2288. directory = true;
  2289. } else if (args[i] == "RELEASE") {
  2290. release = true;
  2291. } else if (args[i] == "GUARD") {
  2292. ++i;
  2293. const char* merr = "expected FUNCTION, FILE or PROCESS after GUARD";
  2294. if (i >= args.size()) {
  2295. status.GetMakefile().IssueMessage(MessageType::FATAL_ERROR, merr);
  2296. return false;
  2297. }
  2298. if (args[i] == "FUNCTION") {
  2299. guard = GUARD_FUNCTION;
  2300. } else if (args[i] == "FILE") {
  2301. guard = GUARD_FILE;
  2302. } else if (args[i] == "PROCESS") {
  2303. guard = GUARD_PROCESS;
  2304. } else {
  2305. status.GetMakefile().IssueMessage(
  2306. MessageType::FATAL_ERROR,
  2307. cmStrCat(merr, ", but got:\n \"", args[i], "\"."));
  2308. return false;
  2309. }
  2310. } else if (args[i] == "RESULT_VARIABLE") {
  2311. ++i;
  2312. if (i >= args.size()) {
  2313. status.GetMakefile().IssueMessage(
  2314. MessageType::FATAL_ERROR,
  2315. "expected variable name after RESULT_VARIABLE");
  2316. return false;
  2317. }
  2318. resultVariable = args[i];
  2319. } else if (args[i] == "TIMEOUT") {
  2320. ++i;
  2321. if (i >= args.size()) {
  2322. status.GetMakefile().IssueMessage(
  2323. MessageType::FATAL_ERROR, "expected timeout value after TIMEOUT");
  2324. return false;
  2325. }
  2326. long scanned;
  2327. if (!cmStrToLong(args[i], &scanned) || scanned < 0) {
  2328. status.GetMakefile().IssueMessage(
  2329. MessageType::FATAL_ERROR,
  2330. cmStrCat("TIMEOUT value \"", args[i],
  2331. "\" is not an unsigned integer."));
  2332. return false;
  2333. }
  2334. timeout = static_cast<unsigned long>(scanned);
  2335. } else {
  2336. status.GetMakefile().IssueMessage(
  2337. MessageType::FATAL_ERROR,
  2338. cmStrCat("expected DIRECTORY, RELEASE, GUARD, RESULT_VARIABLE or ",
  2339. "TIMEOUT\nbut got: \"", args[i], "\"."));
  2340. return false;
  2341. }
  2342. }
  2343. if (directory) {
  2344. path += "/cmake.lock";
  2345. }
  2346. // Unify path (remove '//', '/../', ...)
  2347. path = cmSystemTools::CollapseFullPath(
  2348. path, status.GetMakefile().GetCurrentSourceDirectory());
  2349. // Create file and directories if needed
  2350. std::string parentDir = cmSystemTools::GetParentDirectory(path);
  2351. if (!cmSystemTools::MakeDirectory(parentDir)) {
  2352. status.GetMakefile().IssueMessage(
  2353. MessageType::FATAL_ERROR,
  2354. cmStrCat("directory\n \"", parentDir,
  2355. "\"\ncreation failed (check permissions)."));
  2356. cmSystemTools::SetFatalErrorOccured();
  2357. return false;
  2358. }
  2359. FILE* file = cmsys::SystemTools::Fopen(path, "w");
  2360. if (!file) {
  2361. status.GetMakefile().IssueMessage(
  2362. MessageType::FATAL_ERROR,
  2363. cmStrCat("file\n \"", path,
  2364. "\"\ncreation failed (check permissions)."));
  2365. cmSystemTools::SetFatalErrorOccured();
  2366. return false;
  2367. }
  2368. fclose(file);
  2369. // Actual lock/unlock
  2370. cmFileLockPool& lockPool =
  2371. status.GetMakefile().GetGlobalGenerator()->GetFileLockPool();
  2372. cmFileLockResult fileLockResult(cmFileLockResult::MakeOk());
  2373. if (release) {
  2374. fileLockResult = lockPool.Release(path);
  2375. } else {
  2376. switch (guard) {
  2377. case GUARD_FUNCTION:
  2378. fileLockResult = lockPool.LockFunctionScope(path, timeout);
  2379. break;
  2380. case GUARD_FILE:
  2381. fileLockResult = lockPool.LockFileScope(path, timeout);
  2382. break;
  2383. case GUARD_PROCESS:
  2384. fileLockResult = lockPool.LockProcessScope(path, timeout);
  2385. break;
  2386. default:
  2387. cmSystemTools::SetFatalErrorOccured();
  2388. return false;
  2389. }
  2390. }
  2391. const std::string result = fileLockResult.GetOutputMessage();
  2392. if (resultVariable.empty() && !fileLockResult.IsOk()) {
  2393. status.GetMakefile().IssueMessage(
  2394. MessageType::FATAL_ERROR,
  2395. cmStrCat("error locking file\n \"", path, "\"\n", result, "."));
  2396. cmSystemTools::SetFatalErrorOccured();
  2397. return false;
  2398. }
  2399. if (!resultVariable.empty()) {
  2400. status.GetMakefile().AddDefinition(resultVariable, result);
  2401. }
  2402. return true;
  2403. #else
  2404. static_cast<void>(args);
  2405. status.SetError("sub-command LOCK not implemented in bootstrap cmake");
  2406. return false;
  2407. #endif
  2408. }
  2409. bool HandleTimestampCommand(std::vector<std::string> const& args,
  2410. cmExecutionStatus& status)
  2411. {
  2412. if (args.size() < 3) {
  2413. status.SetError("sub-command TIMESTAMP requires at least two arguments.");
  2414. return false;
  2415. }
  2416. if (args.size() > 5) {
  2417. status.SetError("sub-command TIMESTAMP takes at most four arguments.");
  2418. return false;
  2419. }
  2420. unsigned int argsIndex = 1;
  2421. const std::string& filename = args[argsIndex++];
  2422. const std::string& outputVariable = args[argsIndex++];
  2423. std::string formatString;
  2424. if (args.size() > argsIndex && args[argsIndex] != "UTC") {
  2425. formatString = args[argsIndex++];
  2426. }
  2427. bool utcFlag = false;
  2428. if (args.size() > argsIndex) {
  2429. if (args[argsIndex] == "UTC") {
  2430. utcFlag = true;
  2431. } else {
  2432. std::string e = " TIMESTAMP sub-command does not recognize option " +
  2433. args[argsIndex] + ".";
  2434. status.SetError(e);
  2435. return false;
  2436. }
  2437. }
  2438. cmTimestamp timestamp;
  2439. std::string result =
  2440. timestamp.FileModificationTime(filename.c_str(), formatString, utcFlag);
  2441. status.GetMakefile().AddDefinition(outputVariable, result);
  2442. return true;
  2443. }
  2444. bool HandleSizeCommand(std::vector<std::string> const& args,
  2445. cmExecutionStatus& status)
  2446. {
  2447. if (args.size() != 3) {
  2448. status.SetError(
  2449. cmStrCat(args[0], " requires a file name and output variable"));
  2450. return false;
  2451. }
  2452. unsigned int argsIndex = 1;
  2453. const std::string& filename = args[argsIndex++];
  2454. const std::string& outputVariable = args[argsIndex++];
  2455. if (!cmSystemTools::FileExists(filename, true)) {
  2456. status.SetError(
  2457. cmStrCat("SIZE requested of path that is not readable:\n ", filename));
  2458. return false;
  2459. }
  2460. status.GetMakefile().AddDefinition(
  2461. outputVariable, std::to_string(cmSystemTools::FileLength(filename)));
  2462. return true;
  2463. }
  2464. bool HandleReadSymlinkCommand(std::vector<std::string> const& args,
  2465. cmExecutionStatus& status)
  2466. {
  2467. if (args.size() != 3) {
  2468. status.SetError(
  2469. cmStrCat(args[0], " requires a file name and output variable"));
  2470. return false;
  2471. }
  2472. const std::string& filename = args[1];
  2473. const std::string& outputVariable = args[2];
  2474. std::string result;
  2475. if (!cmSystemTools::ReadSymlink(filename, result)) {
  2476. status.SetError(cmStrCat(
  2477. "READ_SYMLINK requested of path that is not a symlink:\n ", filename));
  2478. return false;
  2479. }
  2480. status.GetMakefile().AddDefinition(outputVariable, result);
  2481. return true;
  2482. }
  2483. bool HandleCreateLinkCommand(std::vector<std::string> const& args,
  2484. cmExecutionStatus& status)
  2485. {
  2486. if (args.size() < 3) {
  2487. status.SetError("CREATE_LINK must be called with at least two additional "
  2488. "arguments");
  2489. return false;
  2490. }
  2491. std::string const& fileName = args[1];
  2492. std::string const& newFileName = args[2];
  2493. struct Arguments
  2494. {
  2495. std::string Result;
  2496. bool CopyOnError = false;
  2497. bool Symbolic = false;
  2498. };
  2499. static auto const parser =
  2500. cmArgumentParser<Arguments>{}
  2501. .Bind("RESULT"_s, &Arguments::Result)
  2502. .Bind("COPY_ON_ERROR"_s, &Arguments::CopyOnError)
  2503. .Bind("SYMBOLIC"_s, &Arguments::Symbolic);
  2504. std::vector<std::string> unconsumedArgs;
  2505. Arguments const arguments =
  2506. parser.Parse(cmMakeRange(args).advance(3), &unconsumedArgs);
  2507. if (!unconsumedArgs.empty()) {
  2508. status.SetError("unknown argument: \"" + unconsumedArgs.front() + '\"');
  2509. return false;
  2510. }
  2511. // The system error message generated in the operation.
  2512. std::string result;
  2513. // Check if the paths are distinct.
  2514. if (fileName == newFileName) {
  2515. result = "CREATE_LINK cannot use same file and newfile";
  2516. if (!arguments.Result.empty()) {
  2517. status.GetMakefile().AddDefinition(arguments.Result, result);
  2518. return true;
  2519. }
  2520. status.SetError(result);
  2521. return false;
  2522. }
  2523. // Hard link requires original file to exist.
  2524. if (!arguments.Symbolic && !cmSystemTools::FileExists(fileName)) {
  2525. result = "Cannot hard link \'" + fileName + "\' as it does not exist.";
  2526. if (!arguments.Result.empty()) {
  2527. status.GetMakefile().AddDefinition(arguments.Result, result);
  2528. return true;
  2529. }
  2530. status.SetError(result);
  2531. return false;
  2532. }
  2533. // Check if the new file already exists and remove it.
  2534. if ((cmSystemTools::FileExists(newFileName) ||
  2535. cmSystemTools::FileIsSymlink(newFileName)) &&
  2536. !cmSystemTools::RemoveFile(newFileName)) {
  2537. std::ostringstream e;
  2538. e << "Failed to create link '" << newFileName
  2539. << "' because existing path cannot be removed: "
  2540. << cmSystemTools::GetLastSystemError() << "\n";
  2541. if (!arguments.Result.empty()) {
  2542. status.GetMakefile().AddDefinition(arguments.Result, e.str());
  2543. return true;
  2544. }
  2545. status.SetError(e.str());
  2546. return false;
  2547. }
  2548. // Whether the operation completed successfully.
  2549. bool completed = false;
  2550. // Check if the command requires a symbolic link.
  2551. if (arguments.Symbolic) {
  2552. completed = cmSystemTools::CreateSymlink(fileName, newFileName, &result);
  2553. } else {
  2554. completed = cmSystemTools::CreateLink(fileName, newFileName, &result);
  2555. }
  2556. // Check if copy-on-error is enabled in the arguments.
  2557. if (!completed && arguments.CopyOnError) {
  2558. completed = cmsys::SystemTools::CopyFileAlways(fileName, newFileName);
  2559. if (!completed) {
  2560. result = "Copy failed: " + cmSystemTools::GetLastSystemError();
  2561. }
  2562. }
  2563. // Check if the operation was successful.
  2564. if (completed) {
  2565. result = "0";
  2566. } else if (arguments.Result.empty()) {
  2567. // The operation failed and the result is not reported in a variable.
  2568. status.SetError(result);
  2569. return false;
  2570. }
  2571. if (!arguments.Result.empty()) {
  2572. status.GetMakefile().AddDefinition(arguments.Result, result);
  2573. }
  2574. return true;
  2575. }
  2576. bool HandleGetRuntimeDependenciesCommand(std::vector<std::string> const& args,
  2577. cmExecutionStatus& status)
  2578. {
  2579. static const std::set<std::string> supportedPlatforms = { "Windows", "Linux",
  2580. "Darwin" };
  2581. std::string platform =
  2582. status.GetMakefile().GetSafeDefinition("CMAKE_HOST_SYSTEM_NAME");
  2583. if (!supportedPlatforms.count(platform)) {
  2584. status.SetError(
  2585. cmStrCat("GET_RUNTIME_DEPENDENCIES is not supported on system \"",
  2586. platform, "\""));
  2587. cmSystemTools::SetFatalErrorOccured();
  2588. return false;
  2589. }
  2590. if (status.GetMakefile().GetState()->GetMode() == cmState::Project) {
  2591. status.GetMakefile().IssueMessage(
  2592. MessageType::AUTHOR_WARNING,
  2593. "You have used file(GET_RUNTIME_DEPENDENCIES)"
  2594. " in project mode. This is probably not what "
  2595. "you intended to do. Instead, please consider"
  2596. " using it in an install(CODE) or "
  2597. "install(SCRIPT) command. For example:"
  2598. "\n install(CODE [["
  2599. "\n file(GET_RUNTIME_DEPENDENCIES"
  2600. "\n # ..."
  2601. "\n )"
  2602. "\n ]])");
  2603. }
  2604. struct Arguments
  2605. {
  2606. std::string ResolvedDependenciesVar;
  2607. std::string UnresolvedDependenciesVar;
  2608. std::string ConflictingDependenciesPrefix;
  2609. std::string BundleExecutable;
  2610. std::vector<std::string> Executables;
  2611. std::vector<std::string> Libraries;
  2612. std::vector<std::string> Directories;
  2613. std::vector<std::string> Modules;
  2614. std::vector<std::string> PreIncludeRegexes;
  2615. std::vector<std::string> PreExcludeRegexes;
  2616. std::vector<std::string> PostIncludeRegexes;
  2617. std::vector<std::string> PostExcludeRegexes;
  2618. };
  2619. static auto const parser =
  2620. cmArgumentParser<Arguments>{}
  2621. .Bind("RESOLVED_DEPENDENCIES_VAR"_s, &Arguments::ResolvedDependenciesVar)
  2622. .Bind("UNRESOLVED_DEPENDENCIES_VAR"_s,
  2623. &Arguments::UnresolvedDependenciesVar)
  2624. .Bind("CONFLICTING_DEPENDENCIES_PREFIX"_s,
  2625. &Arguments::ConflictingDependenciesPrefix)
  2626. .Bind("BUNDLE_EXECUTABLE"_s, &Arguments::BundleExecutable)
  2627. .Bind("EXECUTABLES"_s, &Arguments::Executables)
  2628. .Bind("LIBRARIES"_s, &Arguments::Libraries)
  2629. .Bind("MODULES"_s, &Arguments::Modules)
  2630. .Bind("DIRECTORIES"_s, &Arguments::Directories)
  2631. .Bind("PRE_INCLUDE_REGEXES"_s, &Arguments::PreIncludeRegexes)
  2632. .Bind("PRE_EXCLUDE_REGEXES"_s, &Arguments::PreExcludeRegexes)
  2633. .Bind("POST_INCLUDE_REGEXES"_s, &Arguments::PostIncludeRegexes)
  2634. .Bind("POST_EXCLUDE_REGEXES"_s, &Arguments::PostExcludeRegexes);
  2635. std::vector<std::string> unrecognizedArguments;
  2636. std::vector<std::string> keywordsMissingValues;
  2637. auto parsedArgs =
  2638. parser.Parse(cmMakeRange(args).advance(1), &unrecognizedArguments,
  2639. &keywordsMissingValues);
  2640. auto argIt = unrecognizedArguments.begin();
  2641. if (argIt != unrecognizedArguments.end()) {
  2642. status.SetError(cmStrCat("Unrecognized argument: \"", *argIt, "\""));
  2643. cmSystemTools::SetFatalErrorOccured();
  2644. return false;
  2645. }
  2646. const std::vector<std::string> LIST_ARGS = { "DIRECTORIES",
  2647. "EXECUTABLES",
  2648. "LIBRARIES",
  2649. "MODULES",
  2650. "POST_EXCLUDE_REGEXES",
  2651. "POST_INCLUDE_REGEXES",
  2652. "PRE_EXCLUDE_REGEXES",
  2653. "PRE_INCLUDE_REGEXES" };
  2654. auto kwbegin = keywordsMissingValues.cbegin();
  2655. auto kwend = cmRemoveMatching(keywordsMissingValues, LIST_ARGS);
  2656. if (kwend != kwbegin) {
  2657. status.SetError(cmStrCat("Keywords missing values:\n ",
  2658. cmJoin(cmMakeRange(kwbegin, kwend), "\n ")));
  2659. cmSystemTools::SetFatalErrorOccured();
  2660. return false;
  2661. }
  2662. cmRuntimeDependencyArchive archive(
  2663. status, parsedArgs.Directories, parsedArgs.BundleExecutable,
  2664. parsedArgs.PreIncludeRegexes, parsedArgs.PreExcludeRegexes,
  2665. parsedArgs.PostIncludeRegexes, parsedArgs.PostExcludeRegexes);
  2666. if (!archive.Prepare()) {
  2667. cmSystemTools::SetFatalErrorOccured();
  2668. return false;
  2669. }
  2670. if (!archive.GetRuntimeDependencies(
  2671. parsedArgs.Executables, parsedArgs.Libraries, parsedArgs.Modules)) {
  2672. cmSystemTools::SetFatalErrorOccured();
  2673. return false;
  2674. }
  2675. std::vector<std::string> deps;
  2676. std::vector<std::string> unresolvedDeps;
  2677. std::vector<std::string> conflictingDeps;
  2678. for (auto const& val : archive.GetResolvedPaths()) {
  2679. bool unique = true;
  2680. auto it = val.second.begin();
  2681. assert(it != val.second.end());
  2682. auto const& firstPath = *it;
  2683. while (++it != val.second.end()) {
  2684. if (!cmSystemTools::SameFile(firstPath, *it)) {
  2685. unique = false;
  2686. break;
  2687. }
  2688. }
  2689. if (unique) {
  2690. deps.push_back(firstPath);
  2691. } else if (!parsedArgs.ConflictingDependenciesPrefix.empty()) {
  2692. conflictingDeps.push_back(val.first);
  2693. std::vector<std::string> paths;
  2694. paths.insert(paths.begin(), val.second.begin(), val.second.end());
  2695. std::string varName =
  2696. parsedArgs.ConflictingDependenciesPrefix + "_" + val.first;
  2697. std::string pathsStr = cmJoin(paths, ";");
  2698. status.GetMakefile().AddDefinition(varName, pathsStr);
  2699. } else {
  2700. std::ostringstream e;
  2701. e << "Multiple conflicting paths found for " << val.first << ":";
  2702. for (auto const& path : val.second) {
  2703. e << "\n " << path;
  2704. }
  2705. status.SetError(e.str());
  2706. cmSystemTools::SetFatalErrorOccured();
  2707. return false;
  2708. }
  2709. }
  2710. if (!archive.GetUnresolvedPaths().empty()) {
  2711. if (!parsedArgs.UnresolvedDependenciesVar.empty()) {
  2712. unresolvedDeps.insert(unresolvedDeps.begin(),
  2713. archive.GetUnresolvedPaths().begin(),
  2714. archive.GetUnresolvedPaths().end());
  2715. } else {
  2716. auto it = archive.GetUnresolvedPaths().begin();
  2717. assert(it != archive.GetUnresolvedPaths().end());
  2718. status.SetError(cmStrCat("Could not resolve file ", *it));
  2719. cmSystemTools::SetFatalErrorOccured();
  2720. return false;
  2721. }
  2722. }
  2723. if (!parsedArgs.ResolvedDependenciesVar.empty()) {
  2724. std::string val = cmJoin(deps, ";");
  2725. status.GetMakefile().AddDefinition(parsedArgs.ResolvedDependenciesVar,
  2726. val);
  2727. }
  2728. if (!parsedArgs.UnresolvedDependenciesVar.empty()) {
  2729. std::string val = cmJoin(unresolvedDeps, ";");
  2730. status.GetMakefile().AddDefinition(parsedArgs.UnresolvedDependenciesVar,
  2731. val);
  2732. }
  2733. if (!parsedArgs.ConflictingDependenciesPrefix.empty()) {
  2734. std::string val = cmJoin(conflictingDeps, ";");
  2735. status.GetMakefile().AddDefinition(
  2736. parsedArgs.ConflictingDependenciesPrefix + "_FILENAMES", val);
  2737. }
  2738. return true;
  2739. }
  2740. bool HandleConfigureCommand(std::vector<std::string> const& args,
  2741. cmExecutionStatus& status)
  2742. {
  2743. struct Arguments
  2744. {
  2745. std::string Output;
  2746. std::string Content;
  2747. bool EscapeQuotes = false;
  2748. bool AtOnly = false;
  2749. std::string NewlineStyle;
  2750. };
  2751. static auto const parser =
  2752. cmArgumentParser<Arguments>{}
  2753. .Bind("OUTPUT"_s, &Arguments::Output)
  2754. .Bind("CONTENT"_s, &Arguments::Content)
  2755. .Bind("ESCAPE_QUOTES"_s, &Arguments::EscapeQuotes)
  2756. .Bind("@ONLY"_s, &Arguments::AtOnly)
  2757. .Bind("NEWLINE_STYLE"_s, &Arguments::NewlineStyle);
  2758. std::vector<std::string> unrecognizedArguments;
  2759. std::vector<std::string> keywordsMissingArguments;
  2760. std::vector<std::string> parsedKeywords;
  2761. auto parsedArgs =
  2762. parser.Parse(cmMakeRange(args).advance(1), &unrecognizedArguments,
  2763. &keywordsMissingArguments, &parsedKeywords);
  2764. auto argIt = unrecognizedArguments.begin();
  2765. if (argIt != unrecognizedArguments.end()) {
  2766. status.SetError(
  2767. cmStrCat("CONFIGURE Unrecognized argument: \"", *argIt, "\""));
  2768. cmSystemTools::SetFatalErrorOccured();
  2769. return false;
  2770. }
  2771. std::vector<std::string> mandatoryOptions{ "OUTPUT", "CONTENT" };
  2772. for (auto const& e : mandatoryOptions) {
  2773. const bool optionHasNoValue =
  2774. std::find(keywordsMissingArguments.begin(),
  2775. keywordsMissingArguments.end(),
  2776. e) != keywordsMissingArguments.end();
  2777. if (optionHasNoValue) {
  2778. status.SetError(cmStrCat("CONFIGURE ", e, " option needs a value."));
  2779. cmSystemTools::SetFatalErrorOccured();
  2780. return false;
  2781. }
  2782. }
  2783. for (auto const& e : mandatoryOptions) {
  2784. const bool optionGiven =
  2785. std::find(parsedKeywords.begin(), parsedKeywords.end(), e) !=
  2786. parsedKeywords.end();
  2787. if (!optionGiven) {
  2788. status.SetError(cmStrCat("CONFIGURE ", e, " option is mandatory."));
  2789. cmSystemTools::SetFatalErrorOccured();
  2790. return false;
  2791. }
  2792. }
  2793. std::string errorMessage;
  2794. cmNewLineStyle newLineStyle;
  2795. if (!newLineStyle.ReadFromArguments(args, errorMessage)) {
  2796. status.SetError(cmStrCat("CONFIGURE ", errorMessage));
  2797. return false;
  2798. }
  2799. // Check for generator expressions
  2800. std::string outputFile = cmSystemTools::CollapseFullPath(
  2801. parsedArgs.Output, status.GetMakefile().GetCurrentBinaryDirectory());
  2802. std::string::size_type pos = outputFile.find_first_of("<>");
  2803. if (pos != std::string::npos) {
  2804. status.SetError(cmStrCat("CONFIGURE called with OUTPUT containing a \"",
  2805. outputFile[pos],
  2806. "\". This character is not allowed."));
  2807. return false;
  2808. }
  2809. cmMakefile& makeFile = status.GetMakefile();
  2810. if (!makeFile.CanIWriteThisFile(outputFile)) {
  2811. cmSystemTools::Error("Attempt to write file: " + outputFile +
  2812. " into a source directory.");
  2813. return false;
  2814. }
  2815. cmSystemTools::ConvertToUnixSlashes(outputFile);
  2816. // Re-generate if non-temporary outputs are missing.
  2817. // when we finalize the configuration we will remove all
  2818. // output files that now don't exist.
  2819. makeFile.AddCMakeOutputFile(outputFile);
  2820. // Create output directory
  2821. const std::string::size_type slashPos = outputFile.rfind('/');
  2822. if (slashPos != std::string::npos) {
  2823. const std::string path = outputFile.substr(0, slashPos);
  2824. cmSystemTools::MakeDirectory(path);
  2825. }
  2826. std::string newLineCharacters = "\n";
  2827. bool open_with_binary_flag = false;
  2828. if (newLineStyle.IsValid()) {
  2829. newLineCharacters = newLineStyle.GetCharacters();
  2830. open_with_binary_flag = true;
  2831. }
  2832. cmGeneratedFileStream fout;
  2833. fout.Open(outputFile, false, open_with_binary_flag);
  2834. if (!fout) {
  2835. cmSystemTools::Error("Could not open file for write in copy operation " +
  2836. outputFile);
  2837. cmSystemTools::ReportLastSystemError("");
  2838. return false;
  2839. }
  2840. fout.SetCopyIfDifferent(true);
  2841. // copy input to output and expand variables from input at the same time
  2842. std::stringstream sin(parsedArgs.Content, std::ios::in);
  2843. std::string inLine;
  2844. std::string outLine;
  2845. bool hasNewLine = false;
  2846. while (cmSystemTools::GetLineFromStream(sin, inLine, &hasNewLine)) {
  2847. outLine.clear();
  2848. makeFile.ConfigureString(inLine, outLine, parsedArgs.AtOnly,
  2849. parsedArgs.EscapeQuotes);
  2850. fout << outLine;
  2851. if (hasNewLine || newLineStyle.IsValid()) {
  2852. fout << newLineCharacters;
  2853. }
  2854. }
  2855. // close file before attempting to copy
  2856. fout.close();
  2857. return true;
  2858. }
  2859. bool HandleArchiveCreateCommand(std::vector<std::string> const& args,
  2860. cmExecutionStatus& status)
  2861. {
  2862. struct Arguments
  2863. {
  2864. std::string Output;
  2865. std::string Format;
  2866. std::string Compression;
  2867. std::string CompressionLevel;
  2868. std::string MTime;
  2869. bool Verbose = false;
  2870. std::vector<std::string> Paths;
  2871. };
  2872. static auto const parser =
  2873. cmArgumentParser<Arguments>{}
  2874. .Bind("OUTPUT"_s, &Arguments::Output)
  2875. .Bind("FORMAT"_s, &Arguments::Format)
  2876. .Bind("COMPRESSION"_s, &Arguments::Compression)
  2877. .Bind("COMPRESSION_LEVEL"_s, &Arguments::CompressionLevel)
  2878. .Bind("MTIME"_s, &Arguments::MTime)
  2879. .Bind("VERBOSE"_s, &Arguments::Verbose)
  2880. .Bind("PATHS"_s, &Arguments::Paths);
  2881. std::vector<std::string> unrecognizedArguments;
  2882. std::vector<std::string> keywordsMissingValues;
  2883. auto parsedArgs =
  2884. parser.Parse(cmMakeRange(args).advance(1), &unrecognizedArguments,
  2885. &keywordsMissingValues);
  2886. auto argIt = unrecognizedArguments.begin();
  2887. if (argIt != unrecognizedArguments.end()) {
  2888. status.SetError(cmStrCat("Unrecognized argument: \"", *argIt, "\""));
  2889. cmSystemTools::SetFatalErrorOccured();
  2890. return false;
  2891. }
  2892. const std::vector<std::string> LIST_ARGS = {
  2893. "OUTPUT", "FORMAT", "COMPRESSION", "COMPRESSION_LEVEL", "MTIME", "PATHS"
  2894. };
  2895. auto kwbegin = keywordsMissingValues.cbegin();
  2896. auto kwend = cmRemoveMatching(keywordsMissingValues, LIST_ARGS);
  2897. if (kwend != kwbegin) {
  2898. status.SetError(cmStrCat("Keywords missing values:\n ",
  2899. cmJoin(cmMakeRange(kwbegin, kwend), "\n ")));
  2900. cmSystemTools::SetFatalErrorOccured();
  2901. return false;
  2902. }
  2903. const char* knownFormats[] = {
  2904. "7zip", "gnutar", "pax", "paxr", "raw", "zip"
  2905. };
  2906. if (!parsedArgs.Format.empty() &&
  2907. !cm::contains(knownFormats, parsedArgs.Format)) {
  2908. status.SetError(
  2909. cmStrCat("archive format ", parsedArgs.Format, " not supported"));
  2910. cmSystemTools::SetFatalErrorOccured();
  2911. return false;
  2912. }
  2913. const char* zipFileFormats[] = { "7zip", "zip" };
  2914. if (!parsedArgs.Compression.empty() &&
  2915. cm::contains(zipFileFormats, parsedArgs.Format)) {
  2916. status.SetError(cmStrCat("archive format ", parsedArgs.Format,
  2917. " does not support COMPRESSION arguments"));
  2918. cmSystemTools::SetFatalErrorOccured();
  2919. return false;
  2920. }
  2921. static std::map<std::string, cmSystemTools::cmTarCompression>
  2922. compressionTypeMap = { { "None", cmSystemTools::TarCompressNone },
  2923. { "BZip2", cmSystemTools::TarCompressBZip2 },
  2924. { "GZip", cmSystemTools::TarCompressGZip },
  2925. { "XZ", cmSystemTools::TarCompressXZ },
  2926. { "Zstd", cmSystemTools::TarCompressZstd } };
  2927. cmSystemTools::cmTarCompression compress = cmSystemTools::TarCompressNone;
  2928. auto typeIt = compressionTypeMap.find(parsedArgs.Compression);
  2929. if (typeIt != compressionTypeMap.end()) {
  2930. compress = typeIt->second;
  2931. } else if (!parsedArgs.Compression.empty()) {
  2932. status.SetError(cmStrCat("compression type ", parsedArgs.Compression,
  2933. " is not supported"));
  2934. cmSystemTools::SetFatalErrorOccured();
  2935. return false;
  2936. }
  2937. int compressionLevel = 0;
  2938. if (!parsedArgs.CompressionLevel.empty()) {
  2939. if (parsedArgs.CompressionLevel.size() != 1 &&
  2940. !std::isdigit(parsedArgs.CompressionLevel[0])) {
  2941. status.SetError(cmStrCat("compression level ",
  2942. parsedArgs.CompressionLevel,
  2943. " should be in range 0 to 9"));
  2944. cmSystemTools::SetFatalErrorOccured();
  2945. return false;
  2946. }
  2947. compressionLevel = std::stoi(parsedArgs.CompressionLevel);
  2948. if (compressionLevel < 0 || compressionLevel > 9) {
  2949. status.SetError(cmStrCat("compression level ",
  2950. parsedArgs.CompressionLevel,
  2951. " should be in range 0 to 9"));
  2952. cmSystemTools::SetFatalErrorOccured();
  2953. return false;
  2954. }
  2955. if (compress == cmSystemTools::TarCompressNone) {
  2956. status.SetError(cmStrCat("compression level is not supported for "
  2957. "compression \"None\"",
  2958. parsedArgs.Compression));
  2959. cmSystemTools::SetFatalErrorOccured();
  2960. return false;
  2961. }
  2962. }
  2963. if (parsedArgs.Paths.empty()) {
  2964. status.SetError("ARCHIVE_CREATE requires a non-empty list of PATHS");
  2965. cmSystemTools::SetFatalErrorOccured();
  2966. return false;
  2967. }
  2968. if (!cmSystemTools::CreateTar(parsedArgs.Output, parsedArgs.Paths, compress,
  2969. parsedArgs.Verbose, parsedArgs.MTime,
  2970. parsedArgs.Format, compressionLevel)) {
  2971. status.SetError(cmStrCat("failed to compress: ", parsedArgs.Output));
  2972. cmSystemTools::SetFatalErrorOccured();
  2973. return false;
  2974. }
  2975. return true;
  2976. }
  2977. bool HandleArchiveExtractCommand(std::vector<std::string> const& args,
  2978. cmExecutionStatus& status)
  2979. {
  2980. struct Arguments
  2981. {
  2982. std::string Input;
  2983. bool Verbose = false;
  2984. bool ListOnly = false;
  2985. std::string Destination;
  2986. std::vector<std::string> Patterns;
  2987. };
  2988. static auto const parser = cmArgumentParser<Arguments>{}
  2989. .Bind("INPUT"_s, &Arguments::Input)
  2990. .Bind("VERBOSE"_s, &Arguments::Verbose)
  2991. .Bind("LIST_ONLY"_s, &Arguments::ListOnly)
  2992. .Bind("DESTINATION"_s, &Arguments::Destination)
  2993. .Bind("PATTERNS"_s, &Arguments::Patterns);
  2994. std::vector<std::string> unrecognizedArguments;
  2995. std::vector<std::string> keywordsMissingValues;
  2996. auto parsedArgs =
  2997. parser.Parse(cmMakeRange(args).advance(1), &unrecognizedArguments,
  2998. &keywordsMissingValues);
  2999. auto argIt = unrecognizedArguments.begin();
  3000. if (argIt != unrecognizedArguments.end()) {
  3001. status.SetError(cmStrCat("Unrecognized argument: \"", *argIt, "\""));
  3002. cmSystemTools::SetFatalErrorOccured();
  3003. return false;
  3004. }
  3005. const std::vector<std::string> LIST_ARGS = { "INPUT", "DESTINATION",
  3006. "PATTERNS" };
  3007. auto kwbegin = keywordsMissingValues.cbegin();
  3008. auto kwend = cmRemoveMatching(keywordsMissingValues, LIST_ARGS);
  3009. if (kwend != kwbegin) {
  3010. status.SetError(cmStrCat("Keywords missing values:\n ",
  3011. cmJoin(cmMakeRange(kwbegin, kwend), "\n ")));
  3012. cmSystemTools::SetFatalErrorOccured();
  3013. return false;
  3014. }
  3015. std::string inFile = parsedArgs.Input;
  3016. if (parsedArgs.ListOnly) {
  3017. if (!cmSystemTools::ListTar(inFile, parsedArgs.Patterns,
  3018. parsedArgs.Verbose)) {
  3019. status.SetError(cmStrCat("failed to list: ", inFile));
  3020. cmSystemTools::SetFatalErrorOccured();
  3021. return false;
  3022. }
  3023. } else {
  3024. std::string destDir = status.GetMakefile().GetCurrentBinaryDirectory();
  3025. if (!parsedArgs.Destination.empty()) {
  3026. if (cmSystemTools::FileIsFullPath(parsedArgs.Destination)) {
  3027. destDir = parsedArgs.Destination;
  3028. } else {
  3029. destDir = cmStrCat(destDir, "/", parsedArgs.Destination);
  3030. }
  3031. if (!cmSystemTools::MakeDirectory(destDir)) {
  3032. status.SetError(cmStrCat("failed to create directory: ", destDir));
  3033. cmSystemTools::SetFatalErrorOccured();
  3034. return false;
  3035. }
  3036. if (!cmSystemTools::FileIsFullPath(inFile)) {
  3037. inFile =
  3038. cmStrCat(cmSystemTools::GetCurrentWorkingDirectory(), "/", inFile);
  3039. }
  3040. }
  3041. cmWorkingDirectory workdir(destDir);
  3042. if (workdir.Failed()) {
  3043. status.SetError(
  3044. cmStrCat("failed to change working directory to: ", destDir));
  3045. cmSystemTools::SetFatalErrorOccured();
  3046. return false;
  3047. }
  3048. if (!cmSystemTools::ExtractTar(inFile, parsedArgs.Patterns,
  3049. parsedArgs.Verbose)) {
  3050. status.SetError(cmStrCat("failed to extract: ", inFile));
  3051. cmSystemTools::SetFatalErrorOccured();
  3052. return false;
  3053. }
  3054. }
  3055. return true;
  3056. }
  3057. bool ValidateAndConvertPermissions(const std::vector<std::string>& permissions,
  3058. mode_t& perms, cmExecutionStatus& status)
  3059. {
  3060. for (const auto& i : permissions) {
  3061. if (!cmFSPermissions::stringToModeT(i, perms)) {
  3062. status.SetError(i + " is an invalid permission specifier");
  3063. cmSystemTools::SetFatalErrorOccured();
  3064. return false;
  3065. }
  3066. }
  3067. return true;
  3068. }
  3069. bool SetPermissions(const std::string& filename, const mode_t& perms,
  3070. cmExecutionStatus& status)
  3071. {
  3072. if (!cmSystemTools::SetPermissions(filename, perms)) {
  3073. status.SetError("Failed to set permissions for " + filename);
  3074. cmSystemTools::SetFatalErrorOccured();
  3075. return false;
  3076. }
  3077. return true;
  3078. }
  3079. bool HandleChmodCommandImpl(std::vector<std::string> const& args, bool recurse,
  3080. cmExecutionStatus& status)
  3081. {
  3082. mode_t perms = 0;
  3083. mode_t fperms = 0;
  3084. mode_t dperms = 0;
  3085. cmsys::Glob globber;
  3086. globber.SetRecurse(recurse);
  3087. globber.SetRecurseListDirs(recurse);
  3088. struct Arguments
  3089. {
  3090. std::vector<std::string> Permissions;
  3091. std::vector<std::string> FilePermissions;
  3092. std::vector<std::string> DirectoryPermissions;
  3093. };
  3094. static auto const parser =
  3095. cmArgumentParser<Arguments>{}
  3096. .Bind("PERMISSIONS"_s, &Arguments::Permissions)
  3097. .Bind("FILE_PERMISSIONS"_s, &Arguments::FilePermissions)
  3098. .Bind("DIRECTORY_PERMISSIONS"_s, &Arguments::DirectoryPermissions);
  3099. std::vector<std::string> pathEntries;
  3100. std::vector<std::string> keywordsMissingValues;
  3101. Arguments parsedArgs = parser.Parse(cmMakeRange(args).advance(1),
  3102. &pathEntries, &keywordsMissingValues);
  3103. // check validity of arguments
  3104. if (parsedArgs.Permissions.empty() && parsedArgs.FilePermissions.empty() &&
  3105. parsedArgs.DirectoryPermissions.empty()) // no permissions given
  3106. {
  3107. status.SetError("No permissions given");
  3108. cmSystemTools::SetFatalErrorOccured();
  3109. return false;
  3110. }
  3111. if (!parsedArgs.Permissions.empty() && !parsedArgs.FilePermissions.empty() &&
  3112. !parsedArgs.DirectoryPermissions.empty()) // all keywords are used
  3113. {
  3114. status.SetError("Remove either PERMISSIONS or FILE_PERMISSIONS or "
  3115. "DIRECTORY_PERMISSIONS from the invocation");
  3116. cmSystemTools::SetFatalErrorOccured();
  3117. return false;
  3118. }
  3119. if (!keywordsMissingValues.empty()) {
  3120. for (const auto& i : keywordsMissingValues) {
  3121. status.SetError(i + " is not given any arguments");
  3122. cmSystemTools::SetFatalErrorOccured();
  3123. }
  3124. return false;
  3125. }
  3126. // validate permissions
  3127. bool validatePermissions =
  3128. ValidateAndConvertPermissions(parsedArgs.Permissions, perms, status) &&
  3129. ValidateAndConvertPermissions(parsedArgs.FilePermissions, fperms,
  3130. status) &&
  3131. ValidateAndConvertPermissions(parsedArgs.DirectoryPermissions, dperms,
  3132. status);
  3133. if (!validatePermissions) {
  3134. return false;
  3135. }
  3136. std::vector<std::string> allPathEntries;
  3137. if (recurse) {
  3138. std::vector<std::string> tempPathEntries;
  3139. for (const auto& i : pathEntries) {
  3140. if (cmSystemTools::FileIsDirectory(i)) {
  3141. globber.FindFiles(i + "/*");
  3142. tempPathEntries = globber.GetFiles();
  3143. allPathEntries.insert(allPathEntries.end(), tempPathEntries.begin(),
  3144. tempPathEntries.end());
  3145. allPathEntries.emplace_back(i);
  3146. } else {
  3147. allPathEntries.emplace_back(i); // We validate path entries below
  3148. }
  3149. }
  3150. } else {
  3151. allPathEntries = std::move(pathEntries);
  3152. }
  3153. // chmod
  3154. for (const auto& i : allPathEntries) {
  3155. if (!(cmSystemTools::FileExists(i) || cmSystemTools::FileIsDirectory(i))) {
  3156. status.SetError(cmStrCat("does not exist:\n ", i));
  3157. cmSystemTools::SetFatalErrorOccured();
  3158. return false;
  3159. }
  3160. if (cmSystemTools::FileExists(i, true)) {
  3161. bool success = true;
  3162. const mode_t& filePermissions =
  3163. parsedArgs.FilePermissions.empty() ? perms : fperms;
  3164. if (filePermissions) {
  3165. success = SetPermissions(i, filePermissions, status);
  3166. }
  3167. if (!success) {
  3168. return false;
  3169. }
  3170. }
  3171. else if (cmSystemTools::FileIsDirectory(i)) {
  3172. bool success = true;
  3173. const mode_t& directoryPermissions =
  3174. parsedArgs.DirectoryPermissions.empty() ? perms : dperms;
  3175. if (directoryPermissions) {
  3176. success = SetPermissions(i, directoryPermissions, status);
  3177. }
  3178. if (!success) {
  3179. return false;
  3180. }
  3181. }
  3182. }
  3183. return true;
  3184. }
  3185. bool HandleChmodCommand(std::vector<std::string> const& args,
  3186. cmExecutionStatus& status)
  3187. {
  3188. return HandleChmodCommandImpl(args, false, status);
  3189. }
  3190. bool HandleChmodRecurseCommand(std::vector<std::string> const& args,
  3191. cmExecutionStatus& status)
  3192. {
  3193. return HandleChmodCommandImpl(args, true, status);
  3194. }
  3195. } // namespace
  3196. bool cmFileCommand(std::vector<std::string> const& args,
  3197. cmExecutionStatus& status)
  3198. {
  3199. if (args.size() < 2) {
  3200. status.SetError("must be called with at least two arguments.");
  3201. return false;
  3202. }
  3203. static cmSubcommandTable const subcommand{
  3204. { "WRITE"_s, HandleWriteCommand },
  3205. { "APPEND"_s, HandleAppendCommand },
  3206. { "DOWNLOAD"_s, HandleDownloadCommand },
  3207. { "UPLOAD"_s, HandleUploadCommand },
  3208. { "READ"_s, HandleReadCommand },
  3209. { "MD5"_s, HandleHashCommand },
  3210. { "SHA1"_s, HandleHashCommand },
  3211. { "SHA224"_s, HandleHashCommand },
  3212. { "SHA256"_s, HandleHashCommand },
  3213. { "SHA384"_s, HandleHashCommand },
  3214. { "SHA512"_s, HandleHashCommand },
  3215. { "SHA3_224"_s, HandleHashCommand },
  3216. { "SHA3_256"_s, HandleHashCommand },
  3217. { "SHA3_384"_s, HandleHashCommand },
  3218. { "SHA3_512"_s, HandleHashCommand },
  3219. { "STRINGS"_s, HandleStringsCommand },
  3220. { "GLOB"_s, HandleGlobCommand },
  3221. { "GLOB_RECURSE"_s, HandleGlobRecurseCommand },
  3222. { "MAKE_DIRECTORY"_s, HandleMakeDirectoryCommand },
  3223. { "RENAME"_s, HandleRename },
  3224. { "REMOVE"_s, HandleRemove },
  3225. { "REMOVE_RECURSE"_s, HandleRemoveRecurse },
  3226. { "COPY"_s, HandleCopyCommand },
  3227. { "INSTALL"_s, HandleInstallCommand },
  3228. { "DIFFERENT"_s, HandleDifferentCommand },
  3229. { "RPATH_CHANGE"_s, HandleRPathChangeCommand },
  3230. { "CHRPATH"_s, HandleRPathChangeCommand },
  3231. { "RPATH_CHECK"_s, HandleRPathCheckCommand },
  3232. { "RPATH_REMOVE"_s, HandleRPathRemoveCommand },
  3233. { "READ_ELF"_s, HandleReadElfCommand },
  3234. { "REAL_PATH"_s, HandleRealPathCommand },
  3235. { "RELATIVE_PATH"_s, HandleRelativePathCommand },
  3236. { "TO_CMAKE_PATH"_s, HandleCMakePathCommand },
  3237. { "TO_NATIVE_PATH"_s, HandleNativePathCommand },
  3238. { "TOUCH"_s, HandleTouchCommand },
  3239. { "TOUCH_NOCREATE"_s, HandleTouchNocreateCommand },
  3240. { "TIMESTAMP"_s, HandleTimestampCommand },
  3241. { "GENERATE"_s, HandleGenerateCommand },
  3242. { "LOCK"_s, HandleLockCommand },
  3243. { "SIZE"_s, HandleSizeCommand },
  3244. { "READ_SYMLINK"_s, HandleReadSymlinkCommand },
  3245. { "CREATE_LINK"_s, HandleCreateLinkCommand },
  3246. { "GET_RUNTIME_DEPENDENCIES"_s, HandleGetRuntimeDependenciesCommand },
  3247. { "CONFIGURE"_s, HandleConfigureCommand },
  3248. { "ARCHIVE_CREATE"_s, HandleArchiveCreateCommand },
  3249. { "ARCHIVE_EXTRACT"_s, HandleArchiveExtractCommand },
  3250. { "CHMOD"_s, HandleChmodCommand },
  3251. { "CHMOD_RECURSE"_s, HandleChmodRecurseCommand },
  3252. };
  3253. return subcommand(args[0], args, status);
  3254. }