cmFileCommand.cxx 86 KB

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