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