cmFileCommand.cxx 118 KB

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