cmFileCommand.cxx 105 KB

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