cmFileCommand.cxx 117 KB

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