cmFileCommand.cxx 85 KB

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