cmFileCommand.cxx 96 KB

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