cmFileCommand.cxx 110 KB

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