cmFileCommand.cxx 84 KB

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