cmFileCommand.cxx 78 KB

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