cmFileCommand.cxx 85 KB

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