cmFileCommand.cxx 84 KB

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