cmFileCommand.cxx 116 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737
  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. parser.Bind("FILE"_s, file)
  881. .Bind("OLD_RPATH"_s, oldRPath)
  882. .Bind("NEW_RPATH"_s, newRPath)
  883. .Bind("INSTALL_REMOVE_ENVIRONMENT_RPATH"_s, removeEnvironmentRPath);
  884. ArgumentParser::ParseResult parseResult =
  885. parser.Parse(cmMakeRange(args).advance(1), &unknownArgs);
  886. if (!unknownArgs.empty()) {
  887. status.SetError(
  888. cmStrCat("RPATH_CHANGE given unknown argument ", unknownArgs.front()));
  889. return false;
  890. }
  891. if (parseResult.MaybeReportError(status.GetMakefile())) {
  892. return true;
  893. }
  894. if (file.empty()) {
  895. status.SetError("RPATH_CHANGE not given FILE option.");
  896. return false;
  897. }
  898. if (!oldRPath) {
  899. status.SetError("RPATH_CHANGE not given OLD_RPATH option.");
  900. return false;
  901. }
  902. if (!newRPath) {
  903. status.SetError("RPATH_CHANGE not given NEW_RPATH option.");
  904. return false;
  905. }
  906. if (!cmSystemTools::FileExists(file, true)) {
  907. status.SetError(
  908. cmStrCat("RPATH_CHANGE given FILE \"", file, "\" that does not exist."));
  909. return false;
  910. }
  911. bool success = true;
  912. cmFileTimes const ft(file);
  913. std::string emsg;
  914. bool changed;
  915. if (!cmSystemTools::ChangeRPath(file, *oldRPath, *newRPath,
  916. removeEnvironmentRPath, &emsg, &changed)) {
  917. status.SetError(cmStrCat("RPATH_CHANGE could not write new RPATH:\n ",
  918. *newRPath, "\nto the file:\n ", file, "\n",
  919. emsg));
  920. success = false;
  921. }
  922. if (success) {
  923. if (changed) {
  924. std::string message =
  925. cmStrCat("Set runtime path of \"", file, "\" to \"", *newRPath, '"');
  926. status.GetMakefile().DisplayStatus(message, -1);
  927. }
  928. ft.Store(file);
  929. }
  930. return success;
  931. }
  932. bool HandleRPathSetCommand(std::vector<std::string> const& args,
  933. cmExecutionStatus& status)
  934. {
  935. // Evaluate arguments.
  936. std::string file;
  937. cm::optional<std::string> newRPath;
  938. cmArgumentParser<void> parser;
  939. std::vector<std::string> unknownArgs;
  940. parser.Bind("FILE"_s, file).Bind("NEW_RPATH"_s, newRPath);
  941. ArgumentParser::ParseResult parseResult =
  942. parser.Parse(cmMakeRange(args).advance(1), &unknownArgs);
  943. if (!unknownArgs.empty()) {
  944. status.SetError(cmStrCat("RPATH_SET given unrecognized argument \"",
  945. unknownArgs.front(), "\"."));
  946. return false;
  947. }
  948. if (parseResult.MaybeReportError(status.GetMakefile())) {
  949. return true;
  950. }
  951. if (file.empty()) {
  952. status.SetError("RPATH_SET not given FILE option.");
  953. return false;
  954. }
  955. if (!newRPath) {
  956. status.SetError("RPATH_SET not given NEW_RPATH option.");
  957. return false;
  958. }
  959. if (!cmSystemTools::FileExists(file, true)) {
  960. status.SetError(
  961. cmStrCat("RPATH_SET given FILE \"", file, "\" that does not exist."));
  962. return false;
  963. }
  964. bool success = true;
  965. cmFileTimes const ft(file);
  966. std::string emsg;
  967. bool changed;
  968. if (!cmSystemTools::SetRPath(file, *newRPath, &emsg, &changed)) {
  969. status.SetError(cmStrCat("RPATH_SET could not write new RPATH:\n ",
  970. *newRPath, "\nto the file:\n ", file, "\n",
  971. emsg));
  972. success = false;
  973. }
  974. if (success) {
  975. if (changed) {
  976. std::string message =
  977. cmStrCat("Set runtime path of \"", file, "\" to \"", *newRPath, '"');
  978. status.GetMakefile().DisplayStatus(message, -1);
  979. }
  980. ft.Store(file);
  981. }
  982. return success;
  983. }
  984. bool HandleRPathRemoveCommand(std::vector<std::string> const& args,
  985. cmExecutionStatus& status)
  986. {
  987. // Evaluate arguments.
  988. std::string file;
  989. cmArgumentParser<void> parser;
  990. std::vector<std::string> unknownArgs;
  991. parser.Bind("FILE"_s, file);
  992. ArgumentParser::ParseResult parseResult =
  993. parser.Parse(cmMakeRange(args).advance(1), &unknownArgs);
  994. if (!unknownArgs.empty()) {
  995. status.SetError(
  996. cmStrCat("RPATH_REMOVE given unknown argument ", unknownArgs.front()));
  997. return false;
  998. }
  999. if (parseResult.MaybeReportError(status.GetMakefile())) {
  1000. return true;
  1001. }
  1002. if (file.empty()) {
  1003. status.SetError("RPATH_REMOVE not given FILE option.");
  1004. return false;
  1005. }
  1006. if (!cmSystemTools::FileExists(file, true)) {
  1007. status.SetError(
  1008. cmStrCat("RPATH_REMOVE given FILE \"", file, "\" that does not exist."));
  1009. return false;
  1010. }
  1011. bool success = true;
  1012. cmFileTimes const ft(file);
  1013. std::string emsg;
  1014. bool removed;
  1015. if (!cmSystemTools::RemoveRPath(file, &emsg, &removed)) {
  1016. status.SetError(
  1017. cmStrCat("RPATH_REMOVE could not remove RPATH from file: \n ", file,
  1018. "\n", emsg));
  1019. success = false;
  1020. }
  1021. if (success) {
  1022. if (removed) {
  1023. std::string message =
  1024. cmStrCat("Removed runtime path from \"", file, '"');
  1025. status.GetMakefile().DisplayStatus(message, -1);
  1026. }
  1027. ft.Store(file);
  1028. }
  1029. return success;
  1030. }
  1031. bool HandleRPathCheckCommand(std::vector<std::string> const& args,
  1032. cmExecutionStatus& status)
  1033. {
  1034. // Evaluate arguments.
  1035. std::string file;
  1036. cm::optional<std::string> rpath;
  1037. cmArgumentParser<void> parser;
  1038. std::vector<std::string> unknownArgs;
  1039. parser.Bind("FILE"_s, file).Bind("RPATH"_s, rpath);
  1040. ArgumentParser::ParseResult parseResult =
  1041. parser.Parse(cmMakeRange(args).advance(1), &unknownArgs);
  1042. if (!unknownArgs.empty()) {
  1043. status.SetError(
  1044. cmStrCat("RPATH_CHECK given unknown argument ", unknownArgs.front()));
  1045. return false;
  1046. }
  1047. if (parseResult.MaybeReportError(status.GetMakefile())) {
  1048. return true;
  1049. }
  1050. if (file.empty()) {
  1051. status.SetError("RPATH_CHECK not given FILE option.");
  1052. return false;
  1053. }
  1054. if (!rpath) {
  1055. status.SetError("RPATH_CHECK not given RPATH option.");
  1056. return false;
  1057. }
  1058. // If the file exists but does not have the desired RPath then
  1059. // delete it. This is used during installation to re-install a file
  1060. // if its RPath will change.
  1061. if (cmSystemTools::FileExists(file, true) &&
  1062. !cmSystemTools::CheckRPath(file, *rpath)) {
  1063. cmSystemTools::RemoveFile(file);
  1064. }
  1065. return true;
  1066. }
  1067. bool HandleReadElfCommand(std::vector<std::string> const& args,
  1068. cmExecutionStatus& status)
  1069. {
  1070. if (args.size() < 4) {
  1071. status.SetError("READ_ELF must be called with at least three additional "
  1072. "arguments.");
  1073. return false;
  1074. }
  1075. std::string const& fileNameArg = args[1];
  1076. struct Arguments
  1077. {
  1078. std::string RPath;
  1079. std::string RunPath;
  1080. std::string Error;
  1081. };
  1082. static auto const parser = cmArgumentParser<Arguments>{}
  1083. .Bind("RPATH"_s, &Arguments::RPath)
  1084. .Bind("RUNPATH"_s, &Arguments::RunPath)
  1085. .Bind("CAPTURE_ERROR"_s, &Arguments::Error);
  1086. Arguments const arguments = parser.Parse(cmMakeRange(args).advance(2),
  1087. /*unparsedArguments=*/nullptr);
  1088. if (!cmSystemTools::FileExists(fileNameArg, true)) {
  1089. status.SetError(cmStrCat("READ_ELF given FILE \"", fileNameArg,
  1090. "\" that does not exist."));
  1091. return false;
  1092. }
  1093. cmELF elf(fileNameArg.c_str());
  1094. if (!elf) {
  1095. if (arguments.Error.empty()) {
  1096. status.SetError(cmStrCat("READ_ELF given FILE:\n ", fileNameArg,
  1097. "\nthat is not a valid ELF file."));
  1098. return false;
  1099. }
  1100. status.GetMakefile().AddDefinition(arguments.Error,
  1101. "not a valid ELF file");
  1102. return true;
  1103. }
  1104. if (!arguments.RPath.empty()) {
  1105. if (cmELF::StringEntry const* se_rpath = elf.GetRPath()) {
  1106. std::string rpath(se_rpath->Value);
  1107. std::replace(rpath.begin(), rpath.end(), ':', ';');
  1108. status.GetMakefile().AddDefinition(arguments.RPath, rpath);
  1109. }
  1110. }
  1111. if (!arguments.RunPath.empty()) {
  1112. if (cmELF::StringEntry const* se_runpath = elf.GetRunPath()) {
  1113. std::string runpath(se_runpath->Value);
  1114. std::replace(runpath.begin(), runpath.end(), ':', ';');
  1115. status.GetMakefile().AddDefinition(arguments.RunPath, runpath);
  1116. }
  1117. }
  1118. return true;
  1119. }
  1120. bool HandleInstallCommand(std::vector<std::string> const& args,
  1121. cmExecutionStatus& status)
  1122. {
  1123. cmFileInstaller installer(status);
  1124. return installer.Run(args);
  1125. }
  1126. bool HandleRealPathCommand(std::vector<std::string> const& args,
  1127. cmExecutionStatus& status)
  1128. {
  1129. if (args.size() < 3) {
  1130. status.SetError("REAL_PATH requires a path and an output variable");
  1131. return false;
  1132. }
  1133. struct Arguments : public ArgumentParser::ParseResult
  1134. {
  1135. cm::optional<std::string> BaseDirectory;
  1136. bool ExpandTilde = false;
  1137. };
  1138. static auto const parser =
  1139. cmArgumentParser<Arguments>{}
  1140. .Bind("BASE_DIRECTORY"_s, &Arguments::BaseDirectory)
  1141. .Bind("EXPAND_TILDE"_s, &Arguments::ExpandTilde);
  1142. std::vector<std::string> unparsedArguments;
  1143. auto arguments =
  1144. parser.Parse(cmMakeRange(args).advance(3), &unparsedArguments);
  1145. if (!unparsedArguments.empty()) {
  1146. status.SetError("REAL_PATH called with unexpected arguments");
  1147. return false;
  1148. }
  1149. if (arguments.MaybeReportError(status.GetMakefile())) {
  1150. return true;
  1151. }
  1152. if (!arguments.BaseDirectory) {
  1153. arguments.BaseDirectory = status.GetMakefile().GetCurrentSourceDirectory();
  1154. }
  1155. auto input = args[1];
  1156. if (arguments.ExpandTilde && !input.empty()) {
  1157. if (input[0] == '~' && (input.length() == 1 || input[1] == '/')) {
  1158. std::string home;
  1159. if (
  1160. #if defined(_WIN32) && !defined(__CYGWIN__)
  1161. cmSystemTools::GetEnv("USERPROFILE", home) ||
  1162. #endif
  1163. cmSystemTools::GetEnv("HOME", home)) {
  1164. input.replace(0, 1, home);
  1165. }
  1166. }
  1167. }
  1168. cmCMakePath path(input, cmCMakePath::auto_format);
  1169. path = path.Absolute(*arguments.BaseDirectory).Normal();
  1170. auto realPath = cmSystemTools::GetRealPath(path.GenericString());
  1171. status.GetMakefile().AddDefinition(args[2], realPath);
  1172. return true;
  1173. }
  1174. bool HandleRelativePathCommand(std::vector<std::string> const& args,
  1175. cmExecutionStatus& status)
  1176. {
  1177. if (args.size() != 4) {
  1178. status.SetError("RELATIVE_PATH called with incorrect number of arguments");
  1179. return false;
  1180. }
  1181. const std::string& outVar = args[1];
  1182. const std::string& directoryName = args[2];
  1183. const std::string& fileName = args[3];
  1184. if (!cmSystemTools::FileIsFullPath(directoryName)) {
  1185. std::string errstring =
  1186. "RELATIVE_PATH must be passed a full path to the directory: " +
  1187. directoryName;
  1188. status.SetError(errstring);
  1189. return false;
  1190. }
  1191. if (!cmSystemTools::FileIsFullPath(fileName)) {
  1192. std::string errstring =
  1193. "RELATIVE_PATH must be passed a full path to the file: " + fileName;
  1194. status.SetError(errstring);
  1195. return false;
  1196. }
  1197. std::string res = cmSystemTools::RelativePath(directoryName, fileName);
  1198. status.GetMakefile().AddDefinition(outVar, res);
  1199. return true;
  1200. }
  1201. bool HandleRename(std::vector<std::string> const& args,
  1202. cmExecutionStatus& status)
  1203. {
  1204. if (args.size() < 3) {
  1205. status.SetError("RENAME must be called with at least two additional "
  1206. "arguments");
  1207. return false;
  1208. }
  1209. // Compute full path for old and new names.
  1210. std::string oldname = args[1];
  1211. if (!cmsys::SystemTools::FileIsFullPath(oldname)) {
  1212. oldname =
  1213. cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', args[1]);
  1214. }
  1215. std::string newname = args[2];
  1216. if (!cmsys::SystemTools::FileIsFullPath(newname)) {
  1217. newname =
  1218. cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', args[2]);
  1219. }
  1220. struct Arguments
  1221. {
  1222. bool NoReplace = false;
  1223. std::string Result;
  1224. };
  1225. static auto const parser = cmArgumentParser<Arguments>{}
  1226. .Bind("NO_REPLACE"_s, &Arguments::NoReplace)
  1227. .Bind("RESULT"_s, &Arguments::Result);
  1228. std::vector<std::string> unconsumedArgs;
  1229. Arguments const arguments =
  1230. parser.Parse(cmMakeRange(args).advance(3), &unconsumedArgs);
  1231. if (!unconsumedArgs.empty()) {
  1232. status.SetError("RENAME unknown argument:\n " + unconsumedArgs.front());
  1233. return false;
  1234. }
  1235. std::string err;
  1236. switch (cmSystemTools::RenameFile(oldname, newname,
  1237. arguments.NoReplace
  1238. ? cmSystemTools::Replace::No
  1239. : cmSystemTools::Replace::Yes,
  1240. &err)) {
  1241. case cmSystemTools::RenameResult::Success:
  1242. if (!arguments.Result.empty()) {
  1243. status.GetMakefile().AddDefinition(arguments.Result, "0");
  1244. }
  1245. return true;
  1246. case cmSystemTools::RenameResult::NoReplace:
  1247. if (!arguments.Result.empty()) {
  1248. err = "NO_REPLACE";
  1249. } else {
  1250. err = "path not replaced";
  1251. }
  1252. CM_FALLTHROUGH;
  1253. case cmSystemTools::RenameResult::Failure:
  1254. if (!arguments.Result.empty()) {
  1255. status.GetMakefile().AddDefinition(arguments.Result, err);
  1256. return true;
  1257. }
  1258. break;
  1259. }
  1260. status.SetError(cmStrCat("RENAME failed to rename\n ", oldname, "\nto\n ",
  1261. newname, "\nbecause: ", err, "\n"));
  1262. return false;
  1263. }
  1264. bool HandleCopyFile(std::vector<std::string> const& args,
  1265. cmExecutionStatus& status)
  1266. {
  1267. if (args.size() < 3) {
  1268. status.SetError("COPY_FILE must be called with at least two additional "
  1269. "arguments");
  1270. return false;
  1271. }
  1272. // Compute full path for old and new names.
  1273. std::string oldname = args[1];
  1274. if (!cmsys::SystemTools::FileIsFullPath(oldname)) {
  1275. oldname =
  1276. cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', args[1]);
  1277. }
  1278. std::string newname = args[2];
  1279. if (!cmsys::SystemTools::FileIsFullPath(newname)) {
  1280. newname =
  1281. cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', args[2]);
  1282. }
  1283. struct Arguments
  1284. {
  1285. bool OnlyIfDifferent = false;
  1286. std::string Result;
  1287. };
  1288. static auto const parser =
  1289. cmArgumentParser<Arguments>{}
  1290. .Bind("ONLY_IF_DIFFERENT"_s, &Arguments::OnlyIfDifferent)
  1291. .Bind("RESULT"_s, &Arguments::Result);
  1292. std::vector<std::string> unconsumedArgs;
  1293. Arguments const arguments =
  1294. parser.Parse(cmMakeRange(args).advance(3), &unconsumedArgs);
  1295. if (!unconsumedArgs.empty()) {
  1296. status.SetError("COPY_FILE unknown argument:\n " +
  1297. unconsumedArgs.front());
  1298. return false;
  1299. }
  1300. bool result = true;
  1301. if (cmsys::SystemTools::FileIsDirectory(oldname)) {
  1302. if (!arguments.Result.empty()) {
  1303. status.GetMakefile().AddDefinition(arguments.Result,
  1304. "cannot copy a directory");
  1305. } else {
  1306. status.SetError(
  1307. cmStrCat("COPY_FILE cannot copy a directory\n ", oldname));
  1308. result = false;
  1309. }
  1310. return result;
  1311. }
  1312. if (cmsys::SystemTools::FileIsDirectory(newname)) {
  1313. if (!arguments.Result.empty()) {
  1314. status.GetMakefile().AddDefinition(arguments.Result,
  1315. "cannot copy to a directory");
  1316. } else {
  1317. status.SetError(
  1318. cmStrCat("COPY_FILE cannot copy to a directory\n ", newname));
  1319. result = false;
  1320. }
  1321. return result;
  1322. }
  1323. cmSystemTools::CopyWhen when;
  1324. if (arguments.OnlyIfDifferent) {
  1325. when = cmSystemTools::CopyWhen::OnlyIfDifferent;
  1326. } else {
  1327. when = cmSystemTools::CopyWhen::Always;
  1328. }
  1329. std::string err;
  1330. if (cmSystemTools::CopySingleFile(oldname, newname, when, &err) ==
  1331. cmSystemTools::CopyResult::Success) {
  1332. if (!arguments.Result.empty()) {
  1333. status.GetMakefile().AddDefinition(arguments.Result, "0");
  1334. }
  1335. } else {
  1336. if (!arguments.Result.empty()) {
  1337. status.GetMakefile().AddDefinition(arguments.Result, err);
  1338. } else {
  1339. status.SetError(cmStrCat("COPY_FILE failed to copy\n ", oldname,
  1340. "\nto\n ", newname, "\nbecause: ", err, "\n"));
  1341. result = false;
  1342. }
  1343. }
  1344. return result;
  1345. }
  1346. bool HandleRemoveImpl(std::vector<std::string> const& args, bool recurse,
  1347. cmExecutionStatus& status)
  1348. {
  1349. for (std::string const& arg :
  1350. cmMakeRange(args).advance(1)) // Get rid of subcommand
  1351. {
  1352. std::string fileName = arg;
  1353. if (fileName.empty()) {
  1354. std::string const r = recurse ? "REMOVE_RECURSE" : "REMOVE";
  1355. status.GetMakefile().IssueMessage(
  1356. MessageType::AUTHOR_WARNING, "Ignoring empty file name in " + r + ".");
  1357. continue;
  1358. }
  1359. if (!cmsys::SystemTools::FileIsFullPath(fileName)) {
  1360. fileName =
  1361. cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', arg);
  1362. }
  1363. if (cmSystemTools::FileIsDirectory(fileName) &&
  1364. !cmSystemTools::FileIsSymlink(fileName) && recurse) {
  1365. cmSystemTools::RepeatedRemoveDirectory(fileName);
  1366. } else {
  1367. cmSystemTools::RemoveFile(fileName);
  1368. }
  1369. }
  1370. return true;
  1371. }
  1372. bool HandleRemove(std::vector<std::string> const& args,
  1373. cmExecutionStatus& status)
  1374. {
  1375. return HandleRemoveImpl(args, false, status);
  1376. }
  1377. bool HandleRemoveRecurse(std::vector<std::string> const& args,
  1378. cmExecutionStatus& status)
  1379. {
  1380. return HandleRemoveImpl(args, true, status);
  1381. }
  1382. std::string ToNativePath(const std::string& path)
  1383. {
  1384. const auto& outPath = cmSystemTools::ConvertToOutputPath(path);
  1385. if (outPath.size() > 1 && outPath.front() == '\"' &&
  1386. outPath.back() == '\"') {
  1387. return outPath.substr(1, outPath.size() - 2);
  1388. }
  1389. return outPath;
  1390. }
  1391. std::string ToCMakePath(const std::string& path)
  1392. {
  1393. auto temp = path;
  1394. cmSystemTools::ConvertToUnixSlashes(temp);
  1395. return temp;
  1396. }
  1397. bool HandlePathCommand(std::vector<std::string> const& args,
  1398. std::string (*convert)(std::string const&),
  1399. cmExecutionStatus& status)
  1400. {
  1401. if (args.size() != 3) {
  1402. status.SetError("FILE([TO_CMAKE_PATH|TO_NATIVE_PATH] path result) must be "
  1403. "called with exactly three arguments.");
  1404. return false;
  1405. }
  1406. #if defined(_WIN32) && !defined(__CYGWIN__)
  1407. char pathSep = ';';
  1408. #else
  1409. char pathSep = ':';
  1410. #endif
  1411. std::vector<std::string> path = cmSystemTools::SplitString(args[1], pathSep);
  1412. std::string value = cmJoin(cmMakeRange(path).transform(convert), ";");
  1413. status.GetMakefile().AddDefinition(args[2], value);
  1414. return true;
  1415. }
  1416. bool HandleCMakePathCommand(std::vector<std::string> const& args,
  1417. cmExecutionStatus& status)
  1418. {
  1419. return HandlePathCommand(args, ToCMakePath, status);
  1420. }
  1421. bool HandleNativePathCommand(std::vector<std::string> const& args,
  1422. cmExecutionStatus& status)
  1423. {
  1424. return HandlePathCommand(args, ToNativePath, status);
  1425. }
  1426. #if !defined(CMAKE_BOOTSTRAP)
  1427. // Stuff for curl download/upload
  1428. using cmFileCommandVectorOfChar = std::vector<char>;
  1429. size_t cmWriteToFileCallback(void* ptr, size_t size, size_t nmemb, void* data)
  1430. {
  1431. int realsize = static_cast<int>(size * nmemb);
  1432. cmsys::ofstream* fout = static_cast<cmsys::ofstream*>(data);
  1433. if (fout) {
  1434. const char* chPtr = static_cast<char*>(ptr);
  1435. fout->write(chPtr, realsize);
  1436. }
  1437. return realsize;
  1438. }
  1439. size_t cmWriteToMemoryCallback(void* ptr, size_t size, size_t nmemb,
  1440. void* data)
  1441. {
  1442. int realsize = static_cast<int>(size * nmemb);
  1443. const char* chPtr = static_cast<char*>(ptr);
  1444. cm::append(*static_cast<cmFileCommandVectorOfChar*>(data), chPtr,
  1445. chPtr + realsize);
  1446. return realsize;
  1447. }
  1448. int cmFileCommandCurlDebugCallback(CURL*, curl_infotype type, char* chPtr,
  1449. size_t size, void* data)
  1450. {
  1451. cmFileCommandVectorOfChar& vec =
  1452. *static_cast<cmFileCommandVectorOfChar*>(data);
  1453. switch (type) {
  1454. case CURLINFO_TEXT:
  1455. case CURLINFO_HEADER_IN:
  1456. case CURLINFO_HEADER_OUT:
  1457. cm::append(vec, chPtr, chPtr + size);
  1458. break;
  1459. case CURLINFO_DATA_IN:
  1460. case CURLINFO_DATA_OUT:
  1461. case CURLINFO_SSL_DATA_IN:
  1462. case CURLINFO_SSL_DATA_OUT: {
  1463. char buf[128];
  1464. int n =
  1465. snprintf(buf, sizeof(buf), "[%" KWIML_INT_PRIu64 " bytes data]\n",
  1466. static_cast<KWIML_INT_uint64_t>(size));
  1467. if (n > 0) {
  1468. cm::append(vec, buf, buf + n);
  1469. }
  1470. } break;
  1471. default:
  1472. break;
  1473. }
  1474. return 0;
  1475. }
  1476. class cURLProgressHelper
  1477. {
  1478. public:
  1479. cURLProgressHelper(cmMakefile* mf, const char* text)
  1480. : Makefile(mf)
  1481. , Text(text)
  1482. {
  1483. }
  1484. bool UpdatePercentage(double value, double total, std::string& status)
  1485. {
  1486. long OldPercentage = this->CurrentPercentage;
  1487. if (total > 0.0) {
  1488. this->CurrentPercentage = std::lround(value / total * 100.0);
  1489. if (this->CurrentPercentage > 100) {
  1490. // Avoid extra progress reports for unexpected data beyond total.
  1491. this->CurrentPercentage = 100;
  1492. }
  1493. }
  1494. bool updated = (OldPercentage != this->CurrentPercentage);
  1495. if (updated) {
  1496. status =
  1497. cmStrCat("[", this->Text, " ", this->CurrentPercentage, "% complete]");
  1498. }
  1499. return updated;
  1500. }
  1501. cmMakefile* GetMakefile() { return this->Makefile; }
  1502. private:
  1503. long CurrentPercentage = -1;
  1504. cmMakefile* Makefile;
  1505. std::string Text;
  1506. };
  1507. int cmFileDownloadProgressCallback(void* clientp, double dltotal, double dlnow,
  1508. double ultotal, double ulnow)
  1509. {
  1510. cURLProgressHelper* helper = reinterpret_cast<cURLProgressHelper*>(clientp);
  1511. static_cast<void>(ultotal);
  1512. static_cast<void>(ulnow);
  1513. std::string status;
  1514. if (helper->UpdatePercentage(dlnow, dltotal, status)) {
  1515. cmMakefile* mf = helper->GetMakefile();
  1516. mf->DisplayStatus(status, -1);
  1517. }
  1518. return 0;
  1519. }
  1520. int cmFileUploadProgressCallback(void* clientp, double dltotal, double dlnow,
  1521. double ultotal, double ulnow)
  1522. {
  1523. cURLProgressHelper* helper = reinterpret_cast<cURLProgressHelper*>(clientp);
  1524. static_cast<void>(dltotal);
  1525. static_cast<void>(dlnow);
  1526. std::string status;
  1527. if (helper->UpdatePercentage(ulnow, ultotal, status)) {
  1528. cmMakefile* mf = helper->GetMakefile();
  1529. mf->DisplayStatus(status, -1);
  1530. }
  1531. return 0;
  1532. }
  1533. class cURLEasyGuard
  1534. {
  1535. public:
  1536. cURLEasyGuard(CURL* easy)
  1537. : Easy(easy)
  1538. {
  1539. }
  1540. ~cURLEasyGuard()
  1541. {
  1542. if (this->Easy) {
  1543. ::curl_easy_cleanup(this->Easy);
  1544. }
  1545. }
  1546. cURLEasyGuard(const cURLEasyGuard&) = delete;
  1547. cURLEasyGuard& operator=(const cURLEasyGuard&) = delete;
  1548. void release() { this->Easy = nullptr; }
  1549. private:
  1550. ::CURL* Easy;
  1551. };
  1552. #endif
  1553. #define check_curl_result(result, errstr) \
  1554. do { \
  1555. if (result != CURLE_OK) { \
  1556. std::string e(errstr); \
  1557. e += ::curl_easy_strerror(result); \
  1558. status.SetError(e); \
  1559. return false; \
  1560. } \
  1561. } while (false)
  1562. bool HandleDownloadCommand(std::vector<std::string> const& args,
  1563. cmExecutionStatus& status)
  1564. {
  1565. #if !defined(CMAKE_BOOTSTRAP)
  1566. auto i = args.begin();
  1567. if (args.size() < 2) {
  1568. status.SetError("DOWNLOAD must be called with at least two arguments.");
  1569. return false;
  1570. }
  1571. ++i; // Get rid of subcommand
  1572. std::string url = *i;
  1573. ++i;
  1574. std::string file;
  1575. long timeout = 0;
  1576. long inactivity_timeout = 0;
  1577. std::string logVar;
  1578. std::string statusVar;
  1579. bool tls_verify = status.GetMakefile().IsOn("CMAKE_TLS_VERIFY");
  1580. cmValue cainfo = status.GetMakefile().GetDefinition("CMAKE_TLS_CAINFO");
  1581. std::string netrc_level =
  1582. status.GetMakefile().GetSafeDefinition("CMAKE_NETRC");
  1583. std::string netrc_file =
  1584. status.GetMakefile().GetSafeDefinition("CMAKE_NETRC_FILE");
  1585. std::string expectedHash;
  1586. std::string hashMatchMSG;
  1587. std::unique_ptr<cmCryptoHash> hash;
  1588. bool showProgress = false;
  1589. std::string userpwd;
  1590. std::vector<std::string> curl_headers;
  1591. std::vector<std::pair<std::string, cm::optional<std::string>>> curl_ranges;
  1592. while (i != args.end()) {
  1593. if (*i == "TIMEOUT") {
  1594. ++i;
  1595. if (i != args.end()) {
  1596. timeout = atol(i->c_str());
  1597. } else {
  1598. status.SetError("DOWNLOAD missing time for TIMEOUT.");
  1599. return false;
  1600. }
  1601. } else if (*i == "INACTIVITY_TIMEOUT") {
  1602. ++i;
  1603. if (i != args.end()) {
  1604. inactivity_timeout = atol(i->c_str());
  1605. } else {
  1606. status.SetError("DOWNLOAD missing time for INACTIVITY_TIMEOUT.");
  1607. return false;
  1608. }
  1609. } else if (*i == "LOG") {
  1610. ++i;
  1611. if (i == args.end()) {
  1612. status.SetError("DOWNLOAD missing VAR for LOG.");
  1613. return false;
  1614. }
  1615. logVar = *i;
  1616. } else if (*i == "STATUS") {
  1617. ++i;
  1618. if (i == args.end()) {
  1619. status.SetError("DOWNLOAD missing VAR for STATUS.");
  1620. return false;
  1621. }
  1622. statusVar = *i;
  1623. } else if (*i == "TLS_VERIFY") {
  1624. ++i;
  1625. if (i != args.end()) {
  1626. tls_verify = cmIsOn(*i);
  1627. } else {
  1628. status.SetError("DOWNLOAD missing bool value for TLS_VERIFY.");
  1629. return false;
  1630. }
  1631. } else if (*i == "TLS_CAINFO") {
  1632. ++i;
  1633. if (i != args.end()) {
  1634. cainfo = cmValue(*i);
  1635. } else {
  1636. status.SetError("DOWNLOAD missing file value for TLS_CAINFO.");
  1637. return false;
  1638. }
  1639. } else if (*i == "NETRC_FILE") {
  1640. ++i;
  1641. if (i != args.end()) {
  1642. netrc_file = *i;
  1643. } else {
  1644. status.SetError("DOWNLOAD missing file value for NETRC_FILE.");
  1645. return false;
  1646. }
  1647. } else if (*i == "NETRC") {
  1648. ++i;
  1649. if (i != args.end()) {
  1650. netrc_level = *i;
  1651. } else {
  1652. status.SetError("DOWNLOAD missing level value for NETRC.");
  1653. return false;
  1654. }
  1655. } else if (*i == "EXPECTED_MD5") {
  1656. ++i;
  1657. if (i == args.end()) {
  1658. status.SetError("DOWNLOAD missing sum value for EXPECTED_MD5.");
  1659. return false;
  1660. }
  1661. hash = cm::make_unique<cmCryptoHash>(cmCryptoHash::AlgoMD5);
  1662. hashMatchMSG = "MD5 sum";
  1663. expectedHash = cmSystemTools::LowerCase(*i);
  1664. } else if (*i == "SHOW_PROGRESS") {
  1665. showProgress = true;
  1666. } else if (*i == "EXPECTED_HASH") {
  1667. ++i;
  1668. if (i == args.end()) {
  1669. status.SetError("DOWNLOAD missing ALGO=value for EXPECTED_HASH.");
  1670. return false;
  1671. }
  1672. std::string::size_type pos = i->find("=");
  1673. if (pos == std::string::npos) {
  1674. std::string err =
  1675. cmStrCat("DOWNLOAD EXPECTED_HASH expects ALGO=value but got: ", *i);
  1676. status.SetError(err);
  1677. return false;
  1678. }
  1679. std::string algo = i->substr(0, pos);
  1680. expectedHash = cmSystemTools::LowerCase(i->substr(pos + 1));
  1681. hash = cmCryptoHash::New(algo);
  1682. if (!hash) {
  1683. std::string err =
  1684. cmStrCat("DOWNLOAD EXPECTED_HASH given unknown ALGO: ", algo);
  1685. status.SetError(err);
  1686. return false;
  1687. }
  1688. hashMatchMSG = algo + " hash";
  1689. } else if (*i == "USERPWD") {
  1690. ++i;
  1691. if (i == args.end()) {
  1692. status.SetError("DOWNLOAD missing string for USERPWD.");
  1693. return false;
  1694. }
  1695. userpwd = *i;
  1696. } else if (*i == "HTTPHEADER") {
  1697. ++i;
  1698. if (i == args.end()) {
  1699. status.SetError("DOWNLOAD missing string for HTTPHEADER.");
  1700. return false;
  1701. }
  1702. curl_headers.push_back(*i);
  1703. } else if (*i == "RANGE_START") {
  1704. ++i;
  1705. if (i == args.end()) {
  1706. status.SetError("DOWNLOAD missing value for RANGE_START.");
  1707. return false;
  1708. }
  1709. curl_ranges.emplace_back(*i, cm::nullopt);
  1710. } else if (*i == "RANGE_END") {
  1711. ++i;
  1712. if (curl_ranges.empty()) {
  1713. curl_ranges.emplace_back("0", *i);
  1714. } else {
  1715. auto& last_range = curl_ranges.back();
  1716. if (!last_range.second.has_value()) {
  1717. last_range.second = *i;
  1718. } else {
  1719. status.SetError("Multiple RANGE_END values is provided without "
  1720. "the corresponding RANGE_START.");
  1721. return false;
  1722. }
  1723. }
  1724. } else if (file.empty()) {
  1725. file = *i;
  1726. } else {
  1727. // Do not return error for compatibility reason.
  1728. std::string err = cmStrCat("Unexpected argument: ", *i);
  1729. status.GetMakefile().IssueMessage(MessageType::AUTHOR_WARNING, err);
  1730. }
  1731. ++i;
  1732. }
  1733. // Can't calculate hash if we don't save the file.
  1734. // TODO Incrementally calculate hash in the write callback as the file is
  1735. // being downloaded so this check can be relaxed.
  1736. if (file.empty() && hash) {
  1737. status.SetError("DOWNLOAD cannot calculate hash if file is not saved.");
  1738. return false;
  1739. }
  1740. // If file exists already, and caller specified an expected md5 or sha,
  1741. // and the existing file already has the expected hash, then simply
  1742. // return.
  1743. //
  1744. if (!file.empty() && cmSystemTools::FileExists(file) && hash.get()) {
  1745. std::string msg;
  1746. std::string actualHash = hash->HashFile(file);
  1747. if (actualHash == expectedHash) {
  1748. msg = cmStrCat("returning early; file already exists with expected ",
  1749. hashMatchMSG, '"');
  1750. if (!statusVar.empty()) {
  1751. status.GetMakefile().AddDefinition(statusVar, cmStrCat(0, ";\"", msg));
  1752. }
  1753. return true;
  1754. }
  1755. }
  1756. // Make sure parent directory exists so we can write to the file
  1757. // as we receive downloaded bits from curl...
  1758. //
  1759. if (!file.empty()) {
  1760. std::string dir = cmSystemTools::GetFilenamePath(file);
  1761. if (!dir.empty() && !cmSystemTools::FileExists(dir) &&
  1762. !cmSystemTools::MakeDirectory(dir)) {
  1763. std::string errstring = "DOWNLOAD error: cannot create directory '" +
  1764. dir +
  1765. "' - Specify file by full path name and verify that you "
  1766. "have directory creation and file write privileges.";
  1767. status.SetError(errstring);
  1768. return false;
  1769. }
  1770. }
  1771. cmsys::ofstream fout;
  1772. if (!file.empty()) {
  1773. fout.open(file.c_str(), std::ios::binary);
  1774. if (!fout) {
  1775. status.SetError("DOWNLOAD cannot open file for write.");
  1776. return false;
  1777. }
  1778. }
  1779. url = cmCurlFixFileURL(url);
  1780. ::CURL* curl;
  1781. ::curl_global_init(CURL_GLOBAL_DEFAULT);
  1782. curl = ::curl_easy_init();
  1783. if (!curl) {
  1784. status.SetError("DOWNLOAD error initializing curl.");
  1785. return false;
  1786. }
  1787. cURLEasyGuard g_curl(curl);
  1788. ::CURLcode res = ::curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  1789. check_curl_result(res, "DOWNLOAD cannot set url: ");
  1790. // enable HTTP ERROR parsing
  1791. res = ::curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  1792. check_curl_result(res, "DOWNLOAD cannot set http failure option: ");
  1793. res = ::curl_easy_setopt(curl, CURLOPT_USERAGENT, "curl/" LIBCURL_VERSION);
  1794. check_curl_result(res, "DOWNLOAD cannot set user agent option: ");
  1795. res = ::curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cmWriteToFileCallback);
  1796. check_curl_result(res, "DOWNLOAD cannot set write function: ");
  1797. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION,
  1798. cmFileCommandCurlDebugCallback);
  1799. check_curl_result(res, "DOWNLOAD cannot set debug function: ");
  1800. // check to see if TLS verification is requested
  1801. if (tls_verify) {
  1802. res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1);
  1803. check_curl_result(res, "DOWNLOAD cannot set TLS/SSL Verify on: ");
  1804. } else {
  1805. res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
  1806. check_curl_result(res, "DOWNLOAD cannot set TLS/SSL Verify off: ");
  1807. }
  1808. for (const auto& range : curl_ranges) {
  1809. std::string curl_range = range.first + '-' +
  1810. (range.second.has_value() ? range.second.value() : "");
  1811. res = ::curl_easy_setopt(curl, CURLOPT_RANGE, curl_range.c_str());
  1812. check_curl_result(res, "DOWNLOAD cannot set range: ");
  1813. }
  1814. // check to see if a CAINFO file has been specified
  1815. // command arg comes first
  1816. std::string const& cainfo_err = cmCurlSetCAInfo(curl, cainfo);
  1817. if (!cainfo_err.empty()) {
  1818. status.SetError(cainfo_err);
  1819. return false;
  1820. }
  1821. // check to see if netrc parameters have been specified
  1822. // local command args takes precedence over CMAKE_NETRC*
  1823. netrc_level = cmSystemTools::UpperCase(netrc_level);
  1824. std::string const& netrc_option_err =
  1825. cmCurlSetNETRCOption(curl, netrc_level, netrc_file);
  1826. if (!netrc_option_err.empty()) {
  1827. status.SetError(netrc_option_err);
  1828. return false;
  1829. }
  1830. cmFileCommandVectorOfChar chunkDebug;
  1831. res = ::curl_easy_setopt(curl, CURLOPT_WRITEDATA,
  1832. file.empty() ? nullptr : &fout);
  1833. check_curl_result(res, "DOWNLOAD cannot set write data: ");
  1834. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, &chunkDebug);
  1835. check_curl_result(res, "DOWNLOAD cannot set debug data: ");
  1836. res = ::curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  1837. check_curl_result(res, "DOWNLOAD cannot set follow-redirect option: ");
  1838. if (!logVar.empty()) {
  1839. res = ::curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  1840. check_curl_result(res, "DOWNLOAD cannot set verbose: ");
  1841. }
  1842. if (timeout > 0) {
  1843. res = ::curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  1844. check_curl_result(res, "DOWNLOAD cannot set timeout: ");
  1845. }
  1846. if (inactivity_timeout > 0) {
  1847. // Give up if there is no progress for a long time.
  1848. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1);
  1849. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, inactivity_timeout);
  1850. }
  1851. // Need the progress helper's scope to last through the duration of
  1852. // the curl_easy_perform call... so this object is declared at function
  1853. // scope intentionally, rather than inside the "if(showProgress)"
  1854. // block...
  1855. //
  1856. cURLProgressHelper helper(&status.GetMakefile(), "download");
  1857. if (showProgress) {
  1858. res = ::curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
  1859. check_curl_result(res, "DOWNLOAD cannot set noprogress value: ");
  1860. res = ::curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION,
  1861. cmFileDownloadProgressCallback);
  1862. check_curl_result(res, "DOWNLOAD cannot set progress function: ");
  1863. res = ::curl_easy_setopt(curl, CURLOPT_PROGRESSDATA,
  1864. reinterpret_cast<void*>(&helper));
  1865. check_curl_result(res, "DOWNLOAD cannot set progress data: ");
  1866. }
  1867. if (!userpwd.empty()) {
  1868. res = ::curl_easy_setopt(curl, CURLOPT_USERPWD, userpwd.c_str());
  1869. check_curl_result(res, "DOWNLOAD cannot set user password: ");
  1870. }
  1871. struct curl_slist* headers = nullptr;
  1872. for (std::string const& h : curl_headers) {
  1873. headers = ::curl_slist_append(headers, h.c_str());
  1874. }
  1875. ::curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  1876. res = ::curl_easy_perform(curl);
  1877. ::curl_slist_free_all(headers);
  1878. /* always cleanup */
  1879. g_curl.release();
  1880. ::curl_easy_cleanup(curl);
  1881. if (!statusVar.empty()) {
  1882. status.GetMakefile().AddDefinition(
  1883. statusVar,
  1884. cmStrCat(static_cast<int>(res), ";\"", ::curl_easy_strerror(res), "\""));
  1885. }
  1886. ::curl_global_cleanup();
  1887. // Explicitly flush/close so we can measure the md5 accurately.
  1888. //
  1889. if (!file.empty()) {
  1890. fout.flush();
  1891. fout.close();
  1892. }
  1893. // Verify MD5 sum if requested:
  1894. //
  1895. if (hash) {
  1896. std::string actualHash = hash->HashFile(file);
  1897. if (actualHash.empty()) {
  1898. status.SetError("DOWNLOAD cannot compute hash on downloaded file");
  1899. return false;
  1900. }
  1901. if (expectedHash != actualHash) {
  1902. if (!statusVar.empty() && res == 0) {
  1903. status.GetMakefile().AddDefinition(statusVar,
  1904. "1;HASH mismatch: "
  1905. "expected: " +
  1906. expectedHash +
  1907. " actual: " + actualHash);
  1908. }
  1909. status.SetError(cmStrCat("DOWNLOAD HASH mismatch\n"
  1910. " for file: [",
  1911. file,
  1912. "]\n"
  1913. " expected hash: [",
  1914. expectedHash,
  1915. "]\n"
  1916. " actual hash: [",
  1917. actualHash,
  1918. "]\n"
  1919. " status: [",
  1920. static_cast<int>(res), ";\"",
  1921. ::curl_easy_strerror(res), "\"]\n"));
  1922. return false;
  1923. }
  1924. }
  1925. if (!logVar.empty()) {
  1926. chunkDebug.push_back(0);
  1927. status.GetMakefile().AddDefinition(logVar, chunkDebug.data());
  1928. }
  1929. return true;
  1930. #else
  1931. status.SetError("DOWNLOAD not supported by bootstrap cmake.");
  1932. return false;
  1933. #endif
  1934. }
  1935. bool HandleUploadCommand(std::vector<std::string> const& args,
  1936. cmExecutionStatus& status)
  1937. {
  1938. #if !defined(CMAKE_BOOTSTRAP)
  1939. if (args.size() < 3) {
  1940. status.SetError("UPLOAD must be called with at least three arguments.");
  1941. return false;
  1942. }
  1943. auto i = args.begin();
  1944. ++i;
  1945. std::string filename = *i;
  1946. ++i;
  1947. std::string url = *i;
  1948. ++i;
  1949. long timeout = 0;
  1950. long inactivity_timeout = 0;
  1951. std::string logVar;
  1952. std::string statusVar;
  1953. bool showProgress = false;
  1954. bool tls_verify = status.GetMakefile().IsOn("CMAKE_TLS_VERIFY");
  1955. cmValue cainfo = status.GetMakefile().GetDefinition("CMAKE_TLS_CAINFO");
  1956. std::string userpwd;
  1957. std::string netrc_level =
  1958. status.GetMakefile().GetSafeDefinition("CMAKE_NETRC");
  1959. std::string netrc_file =
  1960. status.GetMakefile().GetSafeDefinition("CMAKE_NETRC_FILE");
  1961. std::vector<std::string> curl_headers;
  1962. while (i != args.end()) {
  1963. if (*i == "TIMEOUT") {
  1964. ++i;
  1965. if (i != args.end()) {
  1966. timeout = atol(i->c_str());
  1967. } else {
  1968. status.SetError("UPLOAD missing time for TIMEOUT.");
  1969. return false;
  1970. }
  1971. } else if (*i == "INACTIVITY_TIMEOUT") {
  1972. ++i;
  1973. if (i != args.end()) {
  1974. inactivity_timeout = atol(i->c_str());
  1975. } else {
  1976. status.SetError("UPLOAD missing time for INACTIVITY_TIMEOUT.");
  1977. return false;
  1978. }
  1979. } else if (*i == "LOG") {
  1980. ++i;
  1981. if (i == args.end()) {
  1982. status.SetError("UPLOAD missing VAR for LOG.");
  1983. return false;
  1984. }
  1985. logVar = *i;
  1986. } else if (*i == "STATUS") {
  1987. ++i;
  1988. if (i == args.end()) {
  1989. status.SetError("UPLOAD missing VAR for STATUS.");
  1990. return false;
  1991. }
  1992. statusVar = *i;
  1993. } else if (*i == "SHOW_PROGRESS") {
  1994. showProgress = true;
  1995. } else if (*i == "TLS_VERIFY") {
  1996. ++i;
  1997. if (i != args.end()) {
  1998. tls_verify = cmIsOn(*i);
  1999. } else {
  2000. status.SetError("UPLOAD missing bool value for TLS_VERIFY.");
  2001. return false;
  2002. }
  2003. } else if (*i == "TLS_CAINFO") {
  2004. ++i;
  2005. if (i != args.end()) {
  2006. cainfo = cmValue(*i);
  2007. } else {
  2008. status.SetError("UPLOAD missing file value for TLS_CAINFO.");
  2009. return false;
  2010. }
  2011. } else if (*i == "NETRC_FILE") {
  2012. ++i;
  2013. if (i != args.end()) {
  2014. netrc_file = *i;
  2015. } else {
  2016. status.SetError("UPLOAD missing file value for NETRC_FILE.");
  2017. return false;
  2018. }
  2019. } else if (*i == "NETRC") {
  2020. ++i;
  2021. if (i != args.end()) {
  2022. netrc_level = *i;
  2023. } else {
  2024. status.SetError("UPLOAD missing level value for NETRC.");
  2025. return false;
  2026. }
  2027. } else if (*i == "USERPWD") {
  2028. ++i;
  2029. if (i == args.end()) {
  2030. status.SetError("UPLOAD missing string for USERPWD.");
  2031. return false;
  2032. }
  2033. userpwd = *i;
  2034. } else if (*i == "HTTPHEADER") {
  2035. ++i;
  2036. if (i == args.end()) {
  2037. status.SetError("UPLOAD missing string for HTTPHEADER.");
  2038. return false;
  2039. }
  2040. curl_headers.push_back(*i);
  2041. } else {
  2042. // Do not return error for compatibility reason.
  2043. std::string err = cmStrCat("Unexpected argument: ", *i);
  2044. status.GetMakefile().IssueMessage(MessageType::AUTHOR_WARNING, err);
  2045. }
  2046. ++i;
  2047. }
  2048. // Open file for reading:
  2049. //
  2050. FILE* fin = cmsys::SystemTools::Fopen(filename, "rb");
  2051. if (!fin) {
  2052. std::string errStr =
  2053. cmStrCat("UPLOAD cannot open file '", filename, "' for reading.");
  2054. status.SetError(errStr);
  2055. return false;
  2056. }
  2057. unsigned long file_size = cmsys::SystemTools::FileLength(filename);
  2058. url = cmCurlFixFileURL(url);
  2059. ::CURL* curl;
  2060. ::curl_global_init(CURL_GLOBAL_DEFAULT);
  2061. curl = ::curl_easy_init();
  2062. if (!curl) {
  2063. status.SetError("UPLOAD error initializing curl.");
  2064. fclose(fin);
  2065. return false;
  2066. }
  2067. cURLEasyGuard g_curl(curl);
  2068. // enable HTTP ERROR parsing
  2069. ::CURLcode res = ::curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  2070. check_curl_result(res, "UPLOAD cannot set fail on error flag: ");
  2071. // enable uploading
  2072. res = ::curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
  2073. check_curl_result(res, "UPLOAD cannot set upload flag: ");
  2074. res = ::curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  2075. check_curl_result(res, "UPLOAD cannot set url: ");
  2076. res =
  2077. ::curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cmWriteToMemoryCallback);
  2078. check_curl_result(res, "UPLOAD cannot set write function: ");
  2079. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION,
  2080. cmFileCommandCurlDebugCallback);
  2081. check_curl_result(res, "UPLOAD cannot set debug function: ");
  2082. // check to see if TLS verification is requested
  2083. if (tls_verify) {
  2084. res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1);
  2085. check_curl_result(res, "UPLOAD cannot set TLS/SSL Verify on: ");
  2086. } else {
  2087. res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
  2088. check_curl_result(res, "UPLOAD cannot set TLS/SSL Verify off: ");
  2089. }
  2090. // check to see if a CAINFO file has been specified
  2091. // command arg comes first
  2092. std::string const& cainfo_err = cmCurlSetCAInfo(curl, cainfo);
  2093. if (!cainfo_err.empty()) {
  2094. status.SetError(cainfo_err);
  2095. return false;
  2096. }
  2097. cmFileCommandVectorOfChar chunkResponse;
  2098. cmFileCommandVectorOfChar chunkDebug;
  2099. res = ::curl_easy_setopt(curl, CURLOPT_WRITEDATA, &chunkResponse);
  2100. check_curl_result(res, "UPLOAD cannot set write data: ");
  2101. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, &chunkDebug);
  2102. check_curl_result(res, "UPLOAD cannot set debug data: ");
  2103. res = ::curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  2104. check_curl_result(res, "UPLOAD cannot set follow-redirect option: ");
  2105. if (!logVar.empty()) {
  2106. res = ::curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  2107. check_curl_result(res, "UPLOAD cannot set verbose: ");
  2108. }
  2109. if (timeout > 0) {
  2110. res = ::curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  2111. check_curl_result(res, "UPLOAD cannot set timeout: ");
  2112. }
  2113. if (inactivity_timeout > 0) {
  2114. // Give up if there is no progress for a long time.
  2115. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1);
  2116. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, inactivity_timeout);
  2117. }
  2118. // Need the progress helper's scope to last through the duration of
  2119. // the curl_easy_perform call... so this object is declared at function
  2120. // scope intentionally, rather than inside the "if(showProgress)"
  2121. // block...
  2122. //
  2123. cURLProgressHelper helper(&status.GetMakefile(), "upload");
  2124. if (showProgress) {
  2125. res = ::curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
  2126. check_curl_result(res, "UPLOAD cannot set noprogress value: ");
  2127. res = ::curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION,
  2128. cmFileUploadProgressCallback);
  2129. check_curl_result(res, "UPLOAD cannot set progress function: ");
  2130. res = ::curl_easy_setopt(curl, CURLOPT_PROGRESSDATA,
  2131. reinterpret_cast<void*>(&helper));
  2132. check_curl_result(res, "UPLOAD cannot set progress data: ");
  2133. }
  2134. // now specify which file to upload
  2135. res = ::curl_easy_setopt(curl, CURLOPT_INFILE, fin);
  2136. check_curl_result(res, "UPLOAD cannot set input file: ");
  2137. // and give the size of the upload (optional)
  2138. res =
  2139. ::curl_easy_setopt(curl, CURLOPT_INFILESIZE, static_cast<long>(file_size));
  2140. check_curl_result(res, "UPLOAD cannot set input file size: ");
  2141. if (!userpwd.empty()) {
  2142. res = ::curl_easy_setopt(curl, CURLOPT_USERPWD, userpwd.c_str());
  2143. check_curl_result(res, "UPLOAD cannot set user password: ");
  2144. }
  2145. // check to see if netrc parameters have been specified
  2146. // local command args takes precedence over CMAKE_NETRC*
  2147. netrc_level = cmSystemTools::UpperCase(netrc_level);
  2148. std::string const& netrc_option_err =
  2149. cmCurlSetNETRCOption(curl, netrc_level, netrc_file);
  2150. if (!netrc_option_err.empty()) {
  2151. status.SetError(netrc_option_err);
  2152. return false;
  2153. }
  2154. struct curl_slist* headers = nullptr;
  2155. for (std::string const& h : curl_headers) {
  2156. headers = ::curl_slist_append(headers, h.c_str());
  2157. }
  2158. ::curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  2159. res = ::curl_easy_perform(curl);
  2160. ::curl_slist_free_all(headers);
  2161. /* always cleanup */
  2162. g_curl.release();
  2163. ::curl_easy_cleanup(curl);
  2164. if (!statusVar.empty()) {
  2165. status.GetMakefile().AddDefinition(
  2166. statusVar,
  2167. cmStrCat(static_cast<int>(res), ";\"", ::curl_easy_strerror(res), "\""));
  2168. }
  2169. ::curl_global_cleanup();
  2170. fclose(fin);
  2171. fin = nullptr;
  2172. if (!logVar.empty()) {
  2173. std::string log;
  2174. if (!chunkResponse.empty()) {
  2175. chunkResponse.push_back(0);
  2176. log += "Response:\n";
  2177. log += chunkResponse.data();
  2178. log += "\n";
  2179. }
  2180. if (!chunkDebug.empty()) {
  2181. chunkDebug.push_back(0);
  2182. log += "Debug:\n";
  2183. log += chunkDebug.data();
  2184. log += "\n";
  2185. }
  2186. status.GetMakefile().AddDefinition(logVar, log);
  2187. }
  2188. return true;
  2189. #else
  2190. status.SetError("UPLOAD not supported by bootstrap cmake.");
  2191. return false;
  2192. #endif
  2193. }
  2194. void AddEvaluationFile(const std::string& inputName,
  2195. const std::string& targetName,
  2196. const std::string& outputExpr,
  2197. const std::string& condition, bool inputIsContent,
  2198. const std::string& newLineCharacter, mode_t permissions,
  2199. cmExecutionStatus& status)
  2200. {
  2201. cmListFileBacktrace lfbt = status.GetMakefile().GetBacktrace();
  2202. cmGeneratorExpression outputGe(lfbt);
  2203. std::unique_ptr<cmCompiledGeneratorExpression> outputCge =
  2204. outputGe.Parse(outputExpr);
  2205. cmGeneratorExpression conditionGe(lfbt);
  2206. std::unique_ptr<cmCompiledGeneratorExpression> conditionCge =
  2207. conditionGe.Parse(condition);
  2208. status.GetMakefile().AddEvaluationFile(
  2209. inputName, targetName, std::move(outputCge), std::move(conditionCge),
  2210. newLineCharacter, permissions, inputIsContent);
  2211. }
  2212. bool HandleGenerateCommand(std::vector<std::string> const& args,
  2213. cmExecutionStatus& status)
  2214. {
  2215. if (args.size() < 5) {
  2216. status.SetError("Incorrect arguments to GENERATE subcommand.");
  2217. return false;
  2218. }
  2219. struct Arguments : public ArgumentParser::ParseResult
  2220. {
  2221. cm::optional<std::string> Output;
  2222. cm::optional<std::string> Input;
  2223. cm::optional<std::string> Content;
  2224. cm::optional<std::string> Condition;
  2225. cm::optional<std::string> Target;
  2226. cm::optional<std::string> NewLineStyle;
  2227. bool NoSourcePermissions = false;
  2228. bool UseSourcePermissions = false;
  2229. ArgumentParser::NonEmpty<std::vector<std::string>> FilePermissions;
  2230. };
  2231. static auto const parser =
  2232. cmArgumentParser<Arguments>{}
  2233. .Bind("OUTPUT"_s, &Arguments::Output)
  2234. .Bind("INPUT"_s, &Arguments::Input)
  2235. .Bind("CONTENT"_s, &Arguments::Content)
  2236. .Bind("CONDITION"_s, &Arguments::Condition)
  2237. .Bind("TARGET"_s, &Arguments::Target)
  2238. .Bind("NO_SOURCE_PERMISSIONS"_s, &Arguments::NoSourcePermissions)
  2239. .Bind("USE_SOURCE_PERMISSIONS"_s, &Arguments::UseSourcePermissions)
  2240. .Bind("FILE_PERMISSIONS"_s, &Arguments::FilePermissions)
  2241. .Bind("NEWLINE_STYLE"_s, &Arguments::NewLineStyle);
  2242. std::vector<std::string> unparsedArguments;
  2243. std::vector<cm::string_view> parsedKeywords;
  2244. Arguments const arguments =
  2245. parser.Parse(cmMakeRange(args).advance(1), &unparsedArguments,
  2246. /*keywordsMissingValue=*/nullptr, &parsedKeywords);
  2247. if (arguments.MaybeReportError(status.GetMakefile())) {
  2248. return true;
  2249. }
  2250. if (!unparsedArguments.empty()) {
  2251. status.SetError("Unknown argument to GENERATE subcommand.");
  2252. return false;
  2253. }
  2254. if (!arguments.Output || parsedKeywords[0] != "OUTPUT"_s) {
  2255. status.SetError("GENERATE requires OUTPUT as first option.");
  2256. return false;
  2257. }
  2258. std::string const& output = *arguments.Output;
  2259. if (!arguments.Input && !arguments.Content) {
  2260. status.SetError("GENERATE requires INPUT or CONTENT option.");
  2261. return false;
  2262. }
  2263. const bool inputIsContent = parsedKeywords[1] == "CONTENT"_s;
  2264. if (!inputIsContent && parsedKeywords[1] == "INPUT") {
  2265. status.SetError("Unknown argument to GENERATE subcommand.");
  2266. }
  2267. std::string const& input =
  2268. inputIsContent ? *arguments.Content : *arguments.Input;
  2269. if (arguments.Condition && arguments.Condition->empty()) {
  2270. status.SetError("CONDITION of sub-command GENERATE must not be empty "
  2271. "if specified.");
  2272. return false;
  2273. }
  2274. std::string const& condition =
  2275. arguments.Condition ? *arguments.Condition : std::string();
  2276. if (arguments.Target && arguments.Target->empty()) {
  2277. status.SetError("TARGET of sub-command GENERATE must not be empty "
  2278. "if specified.");
  2279. return false;
  2280. }
  2281. std::string const& target =
  2282. arguments.Target ? *arguments.Target : std::string();
  2283. cmNewLineStyle newLineStyle;
  2284. if (arguments.NewLineStyle) {
  2285. std::string errorMessage;
  2286. if (!newLineStyle.ReadFromArguments(args, errorMessage)) {
  2287. status.SetError(cmStrCat("GENERATE ", errorMessage));
  2288. return false;
  2289. }
  2290. }
  2291. if (arguments.NoSourcePermissions && arguments.UseSourcePermissions) {
  2292. status.SetError("given both NO_SOURCE_PERMISSIONS and "
  2293. "USE_SOURCE_PERMISSIONS. Only one option allowed.");
  2294. return false;
  2295. }
  2296. if (!arguments.FilePermissions.empty()) {
  2297. if (arguments.NoSourcePermissions) {
  2298. status.SetError("given both NO_SOURCE_PERMISSIONS and "
  2299. "FILE_PERMISSIONS. Only one option allowed.");
  2300. return false;
  2301. }
  2302. if (arguments.UseSourcePermissions) {
  2303. status.SetError("given both USE_SOURCE_PERMISSIONS and "
  2304. "FILE_PERMISSIONS. Only one option allowed.");
  2305. return false;
  2306. }
  2307. }
  2308. if (arguments.UseSourcePermissions) {
  2309. if (inputIsContent) {
  2310. status.SetError("given USE_SOURCE_PERMISSIONS without a file INPUT.");
  2311. return false;
  2312. }
  2313. }
  2314. mode_t permissions = 0;
  2315. if (arguments.NoSourcePermissions) {
  2316. permissions |= cmFSPermissions::mode_owner_read;
  2317. permissions |= cmFSPermissions::mode_owner_write;
  2318. permissions |= cmFSPermissions::mode_group_read;
  2319. permissions |= cmFSPermissions::mode_world_read;
  2320. }
  2321. if (!arguments.FilePermissions.empty()) {
  2322. std::vector<std::string> invalidOptions;
  2323. for (auto const& e : arguments.FilePermissions) {
  2324. if (!cmFSPermissions::stringToModeT(e, permissions)) {
  2325. invalidOptions.push_back(e);
  2326. }
  2327. }
  2328. if (!invalidOptions.empty()) {
  2329. std::ostringstream oss;
  2330. oss << "given invalid permission ";
  2331. for (auto i = 0u; i < invalidOptions.size(); i++) {
  2332. if (i == 0u) {
  2333. oss << "\"" << invalidOptions[i] << "\"";
  2334. } else {
  2335. oss << ",\"" << invalidOptions[i] << "\"";
  2336. }
  2337. }
  2338. oss << ".";
  2339. status.SetError(oss.str());
  2340. return false;
  2341. }
  2342. }
  2343. AddEvaluationFile(input, target, output, condition, inputIsContent,
  2344. newLineStyle.GetCharacters(), permissions, status);
  2345. return true;
  2346. }
  2347. bool HandleLockCommand(std::vector<std::string> const& args,
  2348. cmExecutionStatus& status)
  2349. {
  2350. #if !defined(CMAKE_BOOTSTRAP)
  2351. // Default values
  2352. bool directory = false;
  2353. bool release = false;
  2354. enum Guard
  2355. {
  2356. GUARD_FUNCTION,
  2357. GUARD_FILE,
  2358. GUARD_PROCESS
  2359. };
  2360. Guard guard = GUARD_PROCESS;
  2361. std::string resultVariable;
  2362. unsigned long timeout = static_cast<unsigned long>(-1);
  2363. // Parse arguments
  2364. if (args.size() < 2) {
  2365. status.GetMakefile().IssueMessage(
  2366. MessageType::FATAL_ERROR,
  2367. "sub-command LOCK requires at least two arguments.");
  2368. return false;
  2369. }
  2370. std::string path = args[1];
  2371. for (unsigned i = 2; i < args.size(); ++i) {
  2372. if (args[i] == "DIRECTORY") {
  2373. directory = true;
  2374. } else if (args[i] == "RELEASE") {
  2375. release = true;
  2376. } else if (args[i] == "GUARD") {
  2377. ++i;
  2378. const char* merr = "expected FUNCTION, FILE or PROCESS after GUARD";
  2379. if (i >= args.size()) {
  2380. status.GetMakefile().IssueMessage(MessageType::FATAL_ERROR, merr);
  2381. return false;
  2382. }
  2383. if (args[i] == "FUNCTION") {
  2384. guard = GUARD_FUNCTION;
  2385. } else if (args[i] == "FILE") {
  2386. guard = GUARD_FILE;
  2387. } else if (args[i] == "PROCESS") {
  2388. guard = GUARD_PROCESS;
  2389. } else {
  2390. status.GetMakefile().IssueMessage(
  2391. MessageType::FATAL_ERROR,
  2392. cmStrCat(merr, ", but got:\n \"", args[i], "\"."));
  2393. return false;
  2394. }
  2395. } else if (args[i] == "RESULT_VARIABLE") {
  2396. ++i;
  2397. if (i >= args.size()) {
  2398. status.GetMakefile().IssueMessage(
  2399. MessageType::FATAL_ERROR,
  2400. "expected variable name after RESULT_VARIABLE");
  2401. return false;
  2402. }
  2403. resultVariable = args[i];
  2404. } else if (args[i] == "TIMEOUT") {
  2405. ++i;
  2406. if (i >= args.size()) {
  2407. status.GetMakefile().IssueMessage(
  2408. MessageType::FATAL_ERROR, "expected timeout value after TIMEOUT");
  2409. return false;
  2410. }
  2411. long scanned;
  2412. if (!cmStrToLong(args[i], &scanned) || scanned < 0) {
  2413. status.GetMakefile().IssueMessage(
  2414. MessageType::FATAL_ERROR,
  2415. cmStrCat("TIMEOUT value \"", args[i],
  2416. "\" is not an unsigned integer."));
  2417. return false;
  2418. }
  2419. timeout = static_cast<unsigned long>(scanned);
  2420. } else {
  2421. status.GetMakefile().IssueMessage(
  2422. MessageType::FATAL_ERROR,
  2423. cmStrCat("expected DIRECTORY, RELEASE, GUARD, RESULT_VARIABLE or ",
  2424. "TIMEOUT\nbut got: \"", args[i], "\"."));
  2425. return false;
  2426. }
  2427. }
  2428. if (directory) {
  2429. path += "/cmake.lock";
  2430. }
  2431. // Unify path (remove '//', '/../', ...)
  2432. path = cmSystemTools::CollapseFullPath(
  2433. path, status.GetMakefile().GetCurrentSourceDirectory());
  2434. // Create file and directories if needed
  2435. std::string parentDir = cmSystemTools::GetParentDirectory(path);
  2436. if (!cmSystemTools::MakeDirectory(parentDir)) {
  2437. status.GetMakefile().IssueMessage(
  2438. MessageType::FATAL_ERROR,
  2439. cmStrCat("directory\n \"", parentDir,
  2440. "\"\ncreation failed (check permissions)."));
  2441. cmSystemTools::SetFatalErrorOccurred();
  2442. return false;
  2443. }
  2444. FILE* file = cmsys::SystemTools::Fopen(path, "w");
  2445. if (!file) {
  2446. status.GetMakefile().IssueMessage(
  2447. MessageType::FATAL_ERROR,
  2448. cmStrCat("file\n \"", path,
  2449. "\"\ncreation failed (check permissions)."));
  2450. cmSystemTools::SetFatalErrorOccurred();
  2451. return false;
  2452. }
  2453. fclose(file);
  2454. // Actual lock/unlock
  2455. cmFileLockPool& lockPool =
  2456. status.GetMakefile().GetGlobalGenerator()->GetFileLockPool();
  2457. cmFileLockResult fileLockResult(cmFileLockResult::MakeOk());
  2458. if (release) {
  2459. fileLockResult = lockPool.Release(path);
  2460. } else {
  2461. switch (guard) {
  2462. case GUARD_FUNCTION:
  2463. fileLockResult = lockPool.LockFunctionScope(path, timeout);
  2464. break;
  2465. case GUARD_FILE:
  2466. fileLockResult = lockPool.LockFileScope(path, timeout);
  2467. break;
  2468. case GUARD_PROCESS:
  2469. fileLockResult = lockPool.LockProcessScope(path, timeout);
  2470. break;
  2471. default:
  2472. cmSystemTools::SetFatalErrorOccurred();
  2473. return false;
  2474. }
  2475. }
  2476. const std::string result = fileLockResult.GetOutputMessage();
  2477. if (resultVariable.empty() && !fileLockResult.IsOk()) {
  2478. status.GetMakefile().IssueMessage(
  2479. MessageType::FATAL_ERROR,
  2480. cmStrCat("error locking file\n \"", path, "\"\n", result, "."));
  2481. cmSystemTools::SetFatalErrorOccurred();
  2482. return false;
  2483. }
  2484. if (!resultVariable.empty()) {
  2485. status.GetMakefile().AddDefinition(resultVariable, result);
  2486. }
  2487. return true;
  2488. #else
  2489. static_cast<void>(args);
  2490. status.SetError("sub-command LOCK not implemented in bootstrap cmake");
  2491. return false;
  2492. #endif
  2493. }
  2494. bool HandleTimestampCommand(std::vector<std::string> const& args,
  2495. cmExecutionStatus& status)
  2496. {
  2497. if (args.size() < 3) {
  2498. status.SetError("sub-command TIMESTAMP requires at least two arguments.");
  2499. return false;
  2500. }
  2501. if (args.size() > 5) {
  2502. status.SetError("sub-command TIMESTAMP takes at most four arguments.");
  2503. return false;
  2504. }
  2505. unsigned int argsIndex = 1;
  2506. std::string filename = args[argsIndex++];
  2507. if (!cmsys::SystemTools::FileIsFullPath(filename)) {
  2508. filename = cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/',
  2509. filename);
  2510. }
  2511. const std::string& outputVariable = args[argsIndex++];
  2512. std::string formatString;
  2513. if (args.size() > argsIndex && args[argsIndex] != "UTC") {
  2514. formatString = args[argsIndex++];
  2515. }
  2516. bool utcFlag = false;
  2517. if (args.size() > argsIndex) {
  2518. if (args[argsIndex] == "UTC") {
  2519. utcFlag = true;
  2520. } else {
  2521. std::string e = " TIMESTAMP sub-command does not recognize option " +
  2522. args[argsIndex] + ".";
  2523. status.SetError(e);
  2524. return false;
  2525. }
  2526. }
  2527. cmTimestamp timestamp;
  2528. std::string result =
  2529. timestamp.FileModificationTime(filename.c_str(), formatString, utcFlag);
  2530. status.GetMakefile().AddDefinition(outputVariable, result);
  2531. return true;
  2532. }
  2533. bool HandleSizeCommand(std::vector<std::string> const& args,
  2534. cmExecutionStatus& status)
  2535. {
  2536. if (args.size() != 3) {
  2537. status.SetError(
  2538. cmStrCat(args[0], " requires a file name and output variable"));
  2539. return false;
  2540. }
  2541. unsigned int argsIndex = 1;
  2542. const std::string& filename = args[argsIndex++];
  2543. const std::string& outputVariable = args[argsIndex++];
  2544. if (!cmSystemTools::FileExists(filename, true)) {
  2545. status.SetError(
  2546. cmStrCat("SIZE requested of path that is not readable:\n ", filename));
  2547. return false;
  2548. }
  2549. status.GetMakefile().AddDefinition(
  2550. outputVariable, std::to_string(cmSystemTools::FileLength(filename)));
  2551. return true;
  2552. }
  2553. bool HandleReadSymlinkCommand(std::vector<std::string> const& args,
  2554. cmExecutionStatus& status)
  2555. {
  2556. if (args.size() != 3) {
  2557. status.SetError(
  2558. cmStrCat(args[0], " requires a file name and output variable"));
  2559. return false;
  2560. }
  2561. const std::string& filename = args[1];
  2562. const std::string& outputVariable = args[2];
  2563. std::string result;
  2564. if (!cmSystemTools::ReadSymlink(filename, result)) {
  2565. status.SetError(cmStrCat(
  2566. "READ_SYMLINK requested of path that is not a symlink:\n ", filename));
  2567. return false;
  2568. }
  2569. status.GetMakefile().AddDefinition(outputVariable, result);
  2570. return true;
  2571. }
  2572. bool HandleCreateLinkCommand(std::vector<std::string> const& args,
  2573. cmExecutionStatus& status)
  2574. {
  2575. if (args.size() < 3) {
  2576. status.SetError("CREATE_LINK must be called with at least two additional "
  2577. "arguments");
  2578. return false;
  2579. }
  2580. std::string const& fileName = args[1];
  2581. std::string const& newFileName = args[2];
  2582. struct Arguments
  2583. {
  2584. std::string Result;
  2585. bool CopyOnError = false;
  2586. bool Symbolic = false;
  2587. };
  2588. static auto const parser =
  2589. cmArgumentParser<Arguments>{}
  2590. .Bind("RESULT"_s, &Arguments::Result)
  2591. .Bind("COPY_ON_ERROR"_s, &Arguments::CopyOnError)
  2592. .Bind("SYMBOLIC"_s, &Arguments::Symbolic);
  2593. std::vector<std::string> unconsumedArgs;
  2594. Arguments const arguments =
  2595. parser.Parse(cmMakeRange(args).advance(3), &unconsumedArgs);
  2596. if (!unconsumedArgs.empty()) {
  2597. status.SetError("unknown argument: \"" + unconsumedArgs.front() + '\"');
  2598. return false;
  2599. }
  2600. // The system error message generated in the operation.
  2601. std::string result;
  2602. // Check if the paths are distinct.
  2603. if (fileName == newFileName) {
  2604. result = "CREATE_LINK cannot use same file and newfile";
  2605. if (!arguments.Result.empty()) {
  2606. status.GetMakefile().AddDefinition(arguments.Result, result);
  2607. return true;
  2608. }
  2609. status.SetError(result);
  2610. return false;
  2611. }
  2612. // Hard link requires original file to exist.
  2613. if (!arguments.Symbolic && !cmSystemTools::FileExists(fileName)) {
  2614. result = "Cannot hard link \'" + fileName + "\' as it does not exist.";
  2615. if (!arguments.Result.empty()) {
  2616. status.GetMakefile().AddDefinition(arguments.Result, result);
  2617. return true;
  2618. }
  2619. status.SetError(result);
  2620. return false;
  2621. }
  2622. // Check if the new file already exists and remove it.
  2623. if ((cmSystemTools::FileExists(newFileName) ||
  2624. cmSystemTools::FileIsSymlink(newFileName)) &&
  2625. !cmSystemTools::RemoveFile(newFileName)) {
  2626. std::ostringstream e;
  2627. e << "Failed to create link '" << newFileName
  2628. << "' because existing path cannot be removed: "
  2629. << cmSystemTools::GetLastSystemError() << "\n";
  2630. if (!arguments.Result.empty()) {
  2631. status.GetMakefile().AddDefinition(arguments.Result, e.str());
  2632. return true;
  2633. }
  2634. status.SetError(e.str());
  2635. return false;
  2636. }
  2637. // Whether the operation completed successfully.
  2638. bool completed = false;
  2639. // Check if the command requires a symbolic link.
  2640. if (arguments.Symbolic) {
  2641. completed = static_cast<bool>(
  2642. cmSystemTools::CreateSymlink(fileName, newFileName, &result));
  2643. } else {
  2644. completed = static_cast<bool>(
  2645. cmSystemTools::CreateLink(fileName, newFileName, &result));
  2646. }
  2647. // Check if copy-on-error is enabled in the arguments.
  2648. if (!completed && arguments.CopyOnError) {
  2649. cmsys::Status copied =
  2650. cmsys::SystemTools::CopyFileAlways(fileName, newFileName);
  2651. if (copied) {
  2652. completed = true;
  2653. } else {
  2654. result = "Copy failed: " + copied.GetString();
  2655. }
  2656. }
  2657. // Check if the operation was successful.
  2658. if (completed) {
  2659. result = "0";
  2660. } else if (arguments.Result.empty()) {
  2661. // The operation failed and the result is not reported in a variable.
  2662. status.SetError(result);
  2663. return false;
  2664. }
  2665. if (!arguments.Result.empty()) {
  2666. status.GetMakefile().AddDefinition(arguments.Result, result);
  2667. }
  2668. return true;
  2669. }
  2670. bool HandleGetRuntimeDependenciesCommand(std::vector<std::string> const& args,
  2671. cmExecutionStatus& status)
  2672. {
  2673. std::string platform =
  2674. status.GetMakefile().GetSafeDefinition("CMAKE_HOST_SYSTEM_NAME");
  2675. if (!cmRuntimeDependencyArchive::PlatformSupportsRuntimeDependencies(
  2676. platform)) {
  2677. status.SetError(
  2678. cmStrCat("GET_RUNTIME_DEPENDENCIES is not supported on system \"",
  2679. platform, "\""));
  2680. cmSystemTools::SetFatalErrorOccurred();
  2681. return false;
  2682. }
  2683. if (status.GetMakefile().GetState()->GetMode() == cmState::Project) {
  2684. status.GetMakefile().IssueMessage(
  2685. MessageType::AUTHOR_WARNING,
  2686. "You have used file(GET_RUNTIME_DEPENDENCIES)"
  2687. " in project mode. This is probably not what "
  2688. "you intended to do. Instead, please consider"
  2689. " using it in an install(CODE) or "
  2690. "install(SCRIPT) command. For example:"
  2691. "\n install(CODE [["
  2692. "\n file(GET_RUNTIME_DEPENDENCIES"
  2693. "\n # ..."
  2694. "\n )"
  2695. "\n ]])");
  2696. }
  2697. struct Arguments : public ArgumentParser::ParseResult
  2698. {
  2699. std::string ResolvedDependenciesVar;
  2700. std::string UnresolvedDependenciesVar;
  2701. std::string ConflictingDependenciesPrefix;
  2702. std::string RPathPrefix;
  2703. std::string BundleExecutable;
  2704. ArgumentParser::MaybeEmpty<std::vector<std::string>> Executables;
  2705. ArgumentParser::MaybeEmpty<std::vector<std::string>> Libraries;
  2706. ArgumentParser::MaybeEmpty<std::vector<std::string>> Directories;
  2707. ArgumentParser::MaybeEmpty<std::vector<std::string>> Modules;
  2708. ArgumentParser::MaybeEmpty<std::vector<std::string>> PreIncludeRegexes;
  2709. ArgumentParser::MaybeEmpty<std::vector<std::string>> PreExcludeRegexes;
  2710. ArgumentParser::MaybeEmpty<std::vector<std::string>> PostIncludeRegexes;
  2711. ArgumentParser::MaybeEmpty<std::vector<std::string>> PostExcludeRegexes;
  2712. ArgumentParser::MaybeEmpty<std::vector<std::string>> PostIncludeFiles;
  2713. ArgumentParser::MaybeEmpty<std::vector<std::string>> PostExcludeFiles;
  2714. ArgumentParser::MaybeEmpty<std::vector<std::string>>
  2715. PostExcludeFilesStrict;
  2716. };
  2717. static auto const parser =
  2718. cmArgumentParser<Arguments>{}
  2719. .Bind("RESOLVED_DEPENDENCIES_VAR"_s, &Arguments::ResolvedDependenciesVar)
  2720. .Bind("UNRESOLVED_DEPENDENCIES_VAR"_s,
  2721. &Arguments::UnresolvedDependenciesVar)
  2722. .Bind("CONFLICTING_DEPENDENCIES_PREFIX"_s,
  2723. &Arguments::ConflictingDependenciesPrefix)
  2724. .Bind("RPATH_PREFIX"_s, &Arguments::RPathPrefix)
  2725. .Bind("BUNDLE_EXECUTABLE"_s, &Arguments::BundleExecutable)
  2726. .Bind("EXECUTABLES"_s, &Arguments::Executables)
  2727. .Bind("LIBRARIES"_s, &Arguments::Libraries)
  2728. .Bind("MODULES"_s, &Arguments::Modules)
  2729. .Bind("DIRECTORIES"_s, &Arguments::Directories)
  2730. .Bind("PRE_INCLUDE_REGEXES"_s, &Arguments::PreIncludeRegexes)
  2731. .Bind("PRE_EXCLUDE_REGEXES"_s, &Arguments::PreExcludeRegexes)
  2732. .Bind("POST_INCLUDE_REGEXES"_s, &Arguments::PostIncludeRegexes)
  2733. .Bind("POST_EXCLUDE_REGEXES"_s, &Arguments::PostExcludeRegexes)
  2734. .Bind("POST_INCLUDE_FILES"_s, &Arguments::PostIncludeFiles)
  2735. .Bind("POST_EXCLUDE_FILES"_s, &Arguments::PostExcludeFiles)
  2736. .Bind("POST_EXCLUDE_FILES_STRICT"_s, &Arguments::PostExcludeFilesStrict);
  2737. std::vector<std::string> unrecognizedArguments;
  2738. auto parsedArgs =
  2739. parser.Parse(cmMakeRange(args).advance(1), &unrecognizedArguments);
  2740. auto argIt = unrecognizedArguments.begin();
  2741. if (argIt != unrecognizedArguments.end()) {
  2742. status.SetError(cmStrCat("Unrecognized argument: \"", *argIt, "\""));
  2743. cmSystemTools::SetFatalErrorOccurred();
  2744. return false;
  2745. }
  2746. if (parsedArgs.MaybeReportError(status.GetMakefile())) {
  2747. cmSystemTools::SetFatalErrorOccurred();
  2748. return true;
  2749. }
  2750. cmRuntimeDependencyArchive archive(
  2751. status, parsedArgs.Directories, parsedArgs.BundleExecutable,
  2752. parsedArgs.PreIncludeRegexes, parsedArgs.PreExcludeRegexes,
  2753. parsedArgs.PostIncludeRegexes, parsedArgs.PostExcludeRegexes,
  2754. std::move(parsedArgs.PostIncludeFiles),
  2755. std::move(parsedArgs.PostExcludeFiles),
  2756. std::move(parsedArgs.PostExcludeFilesStrict));
  2757. if (!archive.Prepare()) {
  2758. cmSystemTools::SetFatalErrorOccurred();
  2759. return false;
  2760. }
  2761. if (!archive.GetRuntimeDependencies(
  2762. parsedArgs.Executables, parsedArgs.Libraries, parsedArgs.Modules)) {
  2763. cmSystemTools::SetFatalErrorOccurred();
  2764. return false;
  2765. }
  2766. std::vector<std::string> deps;
  2767. std::vector<std::string> unresolvedDeps;
  2768. std::vector<std::string> conflictingDeps;
  2769. for (auto const& val : archive.GetResolvedPaths()) {
  2770. bool unique = true;
  2771. auto it = val.second.begin();
  2772. assert(it != val.second.end());
  2773. auto const& firstPath = *it;
  2774. while (++it != val.second.end()) {
  2775. if (!cmSystemTools::SameFile(firstPath, *it)) {
  2776. unique = false;
  2777. break;
  2778. }
  2779. }
  2780. if (unique) {
  2781. deps.push_back(firstPath);
  2782. if (!parsedArgs.RPathPrefix.empty()) {
  2783. status.GetMakefile().AddDefinition(
  2784. parsedArgs.RPathPrefix + "_" + firstPath,
  2785. cmJoin(archive.GetRPaths().at(firstPath), ";"));
  2786. }
  2787. } else if (!parsedArgs.ConflictingDependenciesPrefix.empty()) {
  2788. conflictingDeps.push_back(val.first);
  2789. std::vector<std::string> paths;
  2790. paths.insert(paths.begin(), val.second.begin(), val.second.end());
  2791. std::string varName =
  2792. parsedArgs.ConflictingDependenciesPrefix + "_" + val.first;
  2793. std::string pathsStr = cmJoin(paths, ";");
  2794. status.GetMakefile().AddDefinition(varName, pathsStr);
  2795. } else {
  2796. std::ostringstream e;
  2797. e << "Multiple conflicting paths found for " << val.first << ":";
  2798. for (auto const& path : val.second) {
  2799. e << "\n " << path;
  2800. }
  2801. status.SetError(e.str());
  2802. cmSystemTools::SetFatalErrorOccurred();
  2803. return false;
  2804. }
  2805. }
  2806. if (!archive.GetUnresolvedPaths().empty()) {
  2807. if (!parsedArgs.UnresolvedDependenciesVar.empty()) {
  2808. unresolvedDeps.insert(unresolvedDeps.begin(),
  2809. archive.GetUnresolvedPaths().begin(),
  2810. archive.GetUnresolvedPaths().end());
  2811. } else {
  2812. std::ostringstream e;
  2813. e << "Could not resolve runtime dependencies:";
  2814. for (auto const& path : archive.GetUnresolvedPaths()) {
  2815. e << "\n " << path;
  2816. }
  2817. status.SetError(e.str());
  2818. cmSystemTools::SetFatalErrorOccurred();
  2819. return false;
  2820. }
  2821. }
  2822. if (!parsedArgs.ResolvedDependenciesVar.empty()) {
  2823. std::string val = cmJoin(deps, ";");
  2824. status.GetMakefile().AddDefinition(parsedArgs.ResolvedDependenciesVar,
  2825. val);
  2826. }
  2827. if (!parsedArgs.UnresolvedDependenciesVar.empty()) {
  2828. std::string val = cmJoin(unresolvedDeps, ";");
  2829. status.GetMakefile().AddDefinition(parsedArgs.UnresolvedDependenciesVar,
  2830. val);
  2831. }
  2832. if (!parsedArgs.ConflictingDependenciesPrefix.empty()) {
  2833. std::string val = cmJoin(conflictingDeps, ";");
  2834. status.GetMakefile().AddDefinition(
  2835. parsedArgs.ConflictingDependenciesPrefix + "_FILENAMES", val);
  2836. }
  2837. return true;
  2838. }
  2839. bool HandleConfigureCommand(std::vector<std::string> const& args,
  2840. cmExecutionStatus& status)
  2841. {
  2842. struct Arguments : public ArgumentParser::ParseResult
  2843. {
  2844. cm::optional<std::string> Output;
  2845. cm::optional<std::string> Content;
  2846. bool EscapeQuotes = false;
  2847. bool AtOnly = false;
  2848. // "NEWLINE_STYLE" requires one value, but we use a custom check below.
  2849. ArgumentParser::Maybe<std::string> NewlineStyle;
  2850. };
  2851. static auto const parser =
  2852. cmArgumentParser<Arguments>{}
  2853. .Bind("OUTPUT"_s, &Arguments::Output)
  2854. .Bind("CONTENT"_s, &Arguments::Content)
  2855. .Bind("ESCAPE_QUOTES"_s, &Arguments::EscapeQuotes)
  2856. .Bind("@ONLY"_s, &Arguments::AtOnly)
  2857. .Bind("NEWLINE_STYLE"_s, &Arguments::NewlineStyle);
  2858. std::vector<std::string> unrecognizedArguments;
  2859. auto parsedArgs =
  2860. parser.Parse(cmMakeRange(args).advance(1), &unrecognizedArguments);
  2861. auto argIt = unrecognizedArguments.begin();
  2862. if (argIt != unrecognizedArguments.end()) {
  2863. status.SetError(
  2864. cmStrCat("CONFIGURE Unrecognized argument: \"", *argIt, "\""));
  2865. cmSystemTools::SetFatalErrorOccurred();
  2866. return false;
  2867. }
  2868. if (parsedArgs.MaybeReportError(status.GetMakefile())) {
  2869. cmSystemTools::SetFatalErrorOccurred();
  2870. return true;
  2871. }
  2872. if (!parsedArgs.Output) {
  2873. status.SetError("CONFIGURE OUTPUT option is mandatory.");
  2874. cmSystemTools::SetFatalErrorOccurred();
  2875. return false;
  2876. }
  2877. if (!parsedArgs.Content) {
  2878. status.SetError("CONFIGURE CONTENT option is mandatory.");
  2879. cmSystemTools::SetFatalErrorOccurred();
  2880. return false;
  2881. }
  2882. std::string errorMessage;
  2883. cmNewLineStyle newLineStyle;
  2884. if (!newLineStyle.ReadFromArguments(args, errorMessage)) {
  2885. status.SetError(cmStrCat("CONFIGURE ", errorMessage));
  2886. return false;
  2887. }
  2888. // Check for generator expressions
  2889. std::string outputFile = cmSystemTools::CollapseFullPath(
  2890. *parsedArgs.Output, status.GetMakefile().GetCurrentBinaryDirectory());
  2891. std::string::size_type pos = outputFile.find_first_of("<>");
  2892. if (pos != std::string::npos) {
  2893. status.SetError(cmStrCat("CONFIGURE called with OUTPUT containing a \"",
  2894. outputFile[pos],
  2895. "\". This character is not allowed."));
  2896. return false;
  2897. }
  2898. cmMakefile& makeFile = status.GetMakefile();
  2899. if (!makeFile.CanIWriteThisFile(outputFile)) {
  2900. cmSystemTools::Error("Attempt to write file: " + outputFile +
  2901. " into a source directory.");
  2902. return false;
  2903. }
  2904. cmSystemTools::ConvertToUnixSlashes(outputFile);
  2905. // Re-generate if non-temporary outputs are missing.
  2906. // when we finalize the configuration we will remove all
  2907. // output files that now don't exist.
  2908. makeFile.AddCMakeOutputFile(outputFile);
  2909. // Create output directory
  2910. const std::string::size_type slashPos = outputFile.rfind('/');
  2911. if (slashPos != std::string::npos) {
  2912. const std::string path = outputFile.substr(0, slashPos);
  2913. cmSystemTools::MakeDirectory(path);
  2914. }
  2915. std::string newLineCharacters = "\n";
  2916. bool open_with_binary_flag = false;
  2917. if (newLineStyle.IsValid()) {
  2918. newLineCharacters = newLineStyle.GetCharacters();
  2919. open_with_binary_flag = true;
  2920. }
  2921. cmGeneratedFileStream fout;
  2922. fout.Open(outputFile, false, open_with_binary_flag);
  2923. if (!fout) {
  2924. cmSystemTools::Error("Could not open file for write in copy operation " +
  2925. outputFile);
  2926. cmSystemTools::ReportLastSystemError("");
  2927. return false;
  2928. }
  2929. fout.SetCopyIfDifferent(true);
  2930. // copy input to output and expand variables from input at the same time
  2931. std::stringstream sin(*parsedArgs.Content, std::ios::in);
  2932. std::string inLine;
  2933. std::string outLine;
  2934. bool hasNewLine = false;
  2935. while (cmSystemTools::GetLineFromStream(sin, inLine, &hasNewLine)) {
  2936. outLine.clear();
  2937. makeFile.ConfigureString(inLine, outLine, parsedArgs.AtOnly,
  2938. parsedArgs.EscapeQuotes);
  2939. fout << outLine;
  2940. if (hasNewLine || newLineStyle.IsValid()) {
  2941. fout << newLineCharacters;
  2942. }
  2943. }
  2944. // close file before attempting to copy
  2945. fout.close();
  2946. return true;
  2947. }
  2948. bool HandleArchiveCreateCommand(std::vector<std::string> const& args,
  2949. cmExecutionStatus& status)
  2950. {
  2951. struct Arguments : public ArgumentParser::ParseResult
  2952. {
  2953. std::string Output;
  2954. std::string Format;
  2955. std::string Compression;
  2956. std::string CompressionLevel;
  2957. // "MTIME" should require one value, but it has long been accidentally
  2958. // accepted without one and treated as if an empty value were given.
  2959. // Fixing this would require a policy.
  2960. ArgumentParser::Maybe<std::string> MTime;
  2961. bool Verbose = false;
  2962. // "PATHS" requires at least one value, but use a custom check below.
  2963. ArgumentParser::MaybeEmpty<std::vector<std::string>> Paths;
  2964. };
  2965. static auto const parser =
  2966. cmArgumentParser<Arguments>{}
  2967. .Bind("OUTPUT"_s, &Arguments::Output)
  2968. .Bind("FORMAT"_s, &Arguments::Format)
  2969. .Bind("COMPRESSION"_s, &Arguments::Compression)
  2970. .Bind("COMPRESSION_LEVEL"_s, &Arguments::CompressionLevel)
  2971. .Bind("MTIME"_s, &Arguments::MTime)
  2972. .Bind("VERBOSE"_s, &Arguments::Verbose)
  2973. .Bind("PATHS"_s, &Arguments::Paths);
  2974. std::vector<std::string> unrecognizedArguments;
  2975. auto parsedArgs =
  2976. parser.Parse(cmMakeRange(args).advance(1), &unrecognizedArguments);
  2977. auto argIt = unrecognizedArguments.begin();
  2978. if (argIt != unrecognizedArguments.end()) {
  2979. status.SetError(cmStrCat("Unrecognized argument: \"", *argIt, "\""));
  2980. cmSystemTools::SetFatalErrorOccurred();
  2981. return false;
  2982. }
  2983. if (parsedArgs.MaybeReportError(status.GetMakefile())) {
  2984. cmSystemTools::SetFatalErrorOccurred();
  2985. return true;
  2986. }
  2987. const char* knownFormats[] = {
  2988. "7zip", "gnutar", "pax", "paxr", "raw", "zip"
  2989. };
  2990. if (!parsedArgs.Format.empty() &&
  2991. !cm::contains(knownFormats, parsedArgs.Format)) {
  2992. status.SetError(
  2993. cmStrCat("archive format ", parsedArgs.Format, " not supported"));
  2994. cmSystemTools::SetFatalErrorOccurred();
  2995. return false;
  2996. }
  2997. const char* zipFileFormats[] = { "7zip", "zip" };
  2998. if (!parsedArgs.Compression.empty() &&
  2999. cm::contains(zipFileFormats, parsedArgs.Format)) {
  3000. status.SetError(cmStrCat("archive format ", parsedArgs.Format,
  3001. " does not support COMPRESSION arguments"));
  3002. cmSystemTools::SetFatalErrorOccurred();
  3003. return false;
  3004. }
  3005. static std::map<std::string, cmSystemTools::cmTarCompression>
  3006. compressionTypeMap = { { "None", cmSystemTools::TarCompressNone },
  3007. { "BZip2", cmSystemTools::TarCompressBZip2 },
  3008. { "GZip", cmSystemTools::TarCompressGZip },
  3009. { "XZ", cmSystemTools::TarCompressXZ },
  3010. { "Zstd", cmSystemTools::TarCompressZstd } };
  3011. cmSystemTools::cmTarCompression compress = cmSystemTools::TarCompressNone;
  3012. auto typeIt = compressionTypeMap.find(parsedArgs.Compression);
  3013. if (typeIt != compressionTypeMap.end()) {
  3014. compress = typeIt->second;
  3015. } else if (!parsedArgs.Compression.empty()) {
  3016. status.SetError(cmStrCat("compression type ", parsedArgs.Compression,
  3017. " is not supported"));
  3018. cmSystemTools::SetFatalErrorOccurred();
  3019. return false;
  3020. }
  3021. int compressionLevel = 0;
  3022. if (!parsedArgs.CompressionLevel.empty()) {
  3023. if (parsedArgs.CompressionLevel.size() != 1 &&
  3024. !std::isdigit(parsedArgs.CompressionLevel[0])) {
  3025. status.SetError(cmStrCat("compression level ",
  3026. parsedArgs.CompressionLevel,
  3027. " should be in range 0 to 9"));
  3028. cmSystemTools::SetFatalErrorOccurred();
  3029. return false;
  3030. }
  3031. compressionLevel = std::stoi(parsedArgs.CompressionLevel);
  3032. if (compressionLevel < 0 || compressionLevel > 9) {
  3033. status.SetError(cmStrCat("compression level ",
  3034. parsedArgs.CompressionLevel,
  3035. " should be in range 0 to 9"));
  3036. cmSystemTools::SetFatalErrorOccurred();
  3037. return false;
  3038. }
  3039. if (compress == cmSystemTools::TarCompressNone) {
  3040. status.SetError(cmStrCat("compression level is not supported for "
  3041. "compression \"None\"",
  3042. parsedArgs.Compression));
  3043. cmSystemTools::SetFatalErrorOccurred();
  3044. return false;
  3045. }
  3046. }
  3047. if (parsedArgs.Paths.empty()) {
  3048. status.SetError("ARCHIVE_CREATE requires a non-empty list of PATHS");
  3049. cmSystemTools::SetFatalErrorOccurred();
  3050. return false;
  3051. }
  3052. if (!cmSystemTools::CreateTar(parsedArgs.Output, parsedArgs.Paths, compress,
  3053. parsedArgs.Verbose, parsedArgs.MTime,
  3054. parsedArgs.Format, compressionLevel)) {
  3055. status.SetError(cmStrCat("failed to compress: ", parsedArgs.Output));
  3056. cmSystemTools::SetFatalErrorOccurred();
  3057. return false;
  3058. }
  3059. return true;
  3060. }
  3061. bool HandleArchiveExtractCommand(std::vector<std::string> const& args,
  3062. cmExecutionStatus& status)
  3063. {
  3064. struct Arguments : public ArgumentParser::ParseResult
  3065. {
  3066. std::string Input;
  3067. bool Verbose = false;
  3068. bool ListOnly = false;
  3069. std::string Destination;
  3070. ArgumentParser::MaybeEmpty<std::vector<std::string>> Patterns;
  3071. bool Touch = false;
  3072. };
  3073. static auto const parser = cmArgumentParser<Arguments>{}
  3074. .Bind("INPUT"_s, &Arguments::Input)
  3075. .Bind("VERBOSE"_s, &Arguments::Verbose)
  3076. .Bind("LIST_ONLY"_s, &Arguments::ListOnly)
  3077. .Bind("DESTINATION"_s, &Arguments::Destination)
  3078. .Bind("PATTERNS"_s, &Arguments::Patterns)
  3079. .Bind("TOUCH"_s, &Arguments::Touch);
  3080. std::vector<std::string> unrecognizedArguments;
  3081. auto parsedArgs =
  3082. parser.Parse(cmMakeRange(args).advance(1), &unrecognizedArguments);
  3083. auto argIt = unrecognizedArguments.begin();
  3084. if (argIt != unrecognizedArguments.end()) {
  3085. status.SetError(cmStrCat("Unrecognized argument: \"", *argIt, "\""));
  3086. cmSystemTools::SetFatalErrorOccurred();
  3087. return false;
  3088. }
  3089. if (parsedArgs.MaybeReportError(status.GetMakefile())) {
  3090. cmSystemTools::SetFatalErrorOccurred();
  3091. return true;
  3092. }
  3093. std::string inFile = parsedArgs.Input;
  3094. if (parsedArgs.ListOnly) {
  3095. if (!cmSystemTools::ListTar(inFile, parsedArgs.Patterns,
  3096. parsedArgs.Verbose)) {
  3097. status.SetError(cmStrCat("failed to list: ", inFile));
  3098. cmSystemTools::SetFatalErrorOccurred();
  3099. return false;
  3100. }
  3101. } else {
  3102. std::string destDir = status.GetMakefile().GetCurrentBinaryDirectory();
  3103. if (!parsedArgs.Destination.empty()) {
  3104. if (cmSystemTools::FileIsFullPath(parsedArgs.Destination)) {
  3105. destDir = parsedArgs.Destination;
  3106. } else {
  3107. destDir = cmStrCat(destDir, "/", parsedArgs.Destination);
  3108. }
  3109. if (!cmSystemTools::MakeDirectory(destDir)) {
  3110. status.SetError(cmStrCat("failed to create directory: ", destDir));
  3111. cmSystemTools::SetFatalErrorOccurred();
  3112. return false;
  3113. }
  3114. if (!cmSystemTools::FileIsFullPath(inFile)) {
  3115. inFile =
  3116. cmStrCat(cmSystemTools::GetCurrentWorkingDirectory(), "/", inFile);
  3117. }
  3118. }
  3119. cmWorkingDirectory workdir(destDir);
  3120. if (workdir.Failed()) {
  3121. status.SetError(
  3122. cmStrCat("failed to change working directory to: ", destDir));
  3123. cmSystemTools::SetFatalErrorOccurred();
  3124. return false;
  3125. }
  3126. if (!cmSystemTools::ExtractTar(
  3127. inFile, parsedArgs.Patterns,
  3128. parsedArgs.Touch ? cmSystemTools::cmTarExtractTimestamps::No
  3129. : cmSystemTools::cmTarExtractTimestamps::Yes,
  3130. parsedArgs.Verbose)) {
  3131. status.SetError(cmStrCat("failed to extract: ", inFile));
  3132. cmSystemTools::SetFatalErrorOccurred();
  3133. return false;
  3134. }
  3135. }
  3136. return true;
  3137. }
  3138. bool ValidateAndConvertPermissions(
  3139. cm::optional<ArgumentParser::NonEmpty<std::vector<std::string>>> const&
  3140. permissions,
  3141. mode_t& perms, cmExecutionStatus& status)
  3142. {
  3143. if (!permissions) {
  3144. return true;
  3145. }
  3146. for (const auto& i : *permissions) {
  3147. if (!cmFSPermissions::stringToModeT(i, perms)) {
  3148. status.SetError(i + " is an invalid permission specifier");
  3149. cmSystemTools::SetFatalErrorOccurred();
  3150. return false;
  3151. }
  3152. }
  3153. return true;
  3154. }
  3155. bool SetPermissions(const std::string& filename, const mode_t& perms,
  3156. cmExecutionStatus& status)
  3157. {
  3158. if (!cmSystemTools::SetPermissions(filename, perms)) {
  3159. status.SetError("Failed to set permissions for " + filename);
  3160. cmSystemTools::SetFatalErrorOccurred();
  3161. return false;
  3162. }
  3163. return true;
  3164. }
  3165. bool HandleChmodCommandImpl(std::vector<std::string> const& args, bool recurse,
  3166. cmExecutionStatus& status)
  3167. {
  3168. mode_t perms = 0;
  3169. mode_t fperms = 0;
  3170. mode_t dperms = 0;
  3171. cmsys::Glob globber;
  3172. globber.SetRecurse(recurse);
  3173. globber.SetRecurseListDirs(recurse);
  3174. struct Arguments : public ArgumentParser::ParseResult
  3175. {
  3176. cm::optional<ArgumentParser::NonEmpty<std::vector<std::string>>>
  3177. Permissions;
  3178. cm::optional<ArgumentParser::NonEmpty<std::vector<std::string>>>
  3179. FilePermissions;
  3180. cm::optional<ArgumentParser::NonEmpty<std::vector<std::string>>>
  3181. DirectoryPermissions;
  3182. };
  3183. static auto const parser =
  3184. cmArgumentParser<Arguments>{}
  3185. .Bind("PERMISSIONS"_s, &Arguments::Permissions)
  3186. .Bind("FILE_PERMISSIONS"_s, &Arguments::FilePermissions)
  3187. .Bind("DIRECTORY_PERMISSIONS"_s, &Arguments::DirectoryPermissions);
  3188. std::vector<std::string> pathEntries;
  3189. Arguments parsedArgs =
  3190. parser.Parse(cmMakeRange(args).advance(1), &pathEntries);
  3191. // check validity of arguments
  3192. if (!parsedArgs.Permissions && !parsedArgs.FilePermissions &&
  3193. !parsedArgs.DirectoryPermissions) // no permissions given
  3194. {
  3195. status.SetError("No permissions given");
  3196. cmSystemTools::SetFatalErrorOccurred();
  3197. return false;
  3198. }
  3199. if (parsedArgs.Permissions && parsedArgs.FilePermissions &&
  3200. parsedArgs.DirectoryPermissions) // all keywords are used
  3201. {
  3202. status.SetError("Remove either PERMISSIONS or FILE_PERMISSIONS or "
  3203. "DIRECTORY_PERMISSIONS from the invocation");
  3204. cmSystemTools::SetFatalErrorOccurred();
  3205. return false;
  3206. }
  3207. if (parsedArgs.MaybeReportError(status.GetMakefile())) {
  3208. cmSystemTools::SetFatalErrorOccurred();
  3209. return true;
  3210. }
  3211. // validate permissions
  3212. bool validatePermissions =
  3213. ValidateAndConvertPermissions(parsedArgs.Permissions, perms, status) &&
  3214. ValidateAndConvertPermissions(parsedArgs.FilePermissions, fperms,
  3215. status) &&
  3216. ValidateAndConvertPermissions(parsedArgs.DirectoryPermissions, dperms,
  3217. status);
  3218. if (!validatePermissions) {
  3219. return false;
  3220. }
  3221. std::vector<std::string> allPathEntries;
  3222. if (recurse) {
  3223. std::vector<std::string> tempPathEntries;
  3224. for (const auto& i : pathEntries) {
  3225. if (cmSystemTools::FileIsDirectory(i)) {
  3226. globber.FindFiles(i + "/*");
  3227. tempPathEntries = globber.GetFiles();
  3228. allPathEntries.insert(allPathEntries.end(), tempPathEntries.begin(),
  3229. tempPathEntries.end());
  3230. allPathEntries.emplace_back(i);
  3231. } else {
  3232. allPathEntries.emplace_back(i); // We validate path entries below
  3233. }
  3234. }
  3235. } else {
  3236. allPathEntries = std::move(pathEntries);
  3237. }
  3238. // chmod
  3239. for (const auto& i : allPathEntries) {
  3240. if (!(cmSystemTools::FileExists(i) || cmSystemTools::FileIsDirectory(i))) {
  3241. status.SetError(cmStrCat("does not exist:\n ", i));
  3242. cmSystemTools::SetFatalErrorOccurred();
  3243. return false;
  3244. }
  3245. if (cmSystemTools::FileExists(i, true)) {
  3246. bool success = true;
  3247. const mode_t& filePermissions =
  3248. parsedArgs.FilePermissions ? fperms : perms;
  3249. if (filePermissions) {
  3250. success = SetPermissions(i, filePermissions, status);
  3251. }
  3252. if (!success) {
  3253. return false;
  3254. }
  3255. }
  3256. else if (cmSystemTools::FileIsDirectory(i)) {
  3257. bool success = true;
  3258. const mode_t& directoryPermissions =
  3259. parsedArgs.DirectoryPermissions ? dperms : perms;
  3260. if (directoryPermissions) {
  3261. success = SetPermissions(i, directoryPermissions, status);
  3262. }
  3263. if (!success) {
  3264. return false;
  3265. }
  3266. }
  3267. }
  3268. return true;
  3269. }
  3270. bool HandleChmodCommand(std::vector<std::string> const& args,
  3271. cmExecutionStatus& status)
  3272. {
  3273. return HandleChmodCommandImpl(args, false, status);
  3274. }
  3275. bool HandleChmodRecurseCommand(std::vector<std::string> const& args,
  3276. cmExecutionStatus& status)
  3277. {
  3278. return HandleChmodCommandImpl(args, true, status);
  3279. }
  3280. } // namespace
  3281. bool cmFileCommand(std::vector<std::string> const& args,
  3282. cmExecutionStatus& status)
  3283. {
  3284. if (args.size() < 2) {
  3285. status.SetError("must be called with at least two arguments.");
  3286. return false;
  3287. }
  3288. static cmSubcommandTable const subcommand{
  3289. { "WRITE"_s, HandleWriteCommand },
  3290. { "APPEND"_s, HandleAppendCommand },
  3291. { "DOWNLOAD"_s, HandleDownloadCommand },
  3292. { "UPLOAD"_s, HandleUploadCommand },
  3293. { "READ"_s, HandleReadCommand },
  3294. { "MD5"_s, HandleHashCommand },
  3295. { "SHA1"_s, HandleHashCommand },
  3296. { "SHA224"_s, HandleHashCommand },
  3297. { "SHA256"_s, HandleHashCommand },
  3298. { "SHA384"_s, HandleHashCommand },
  3299. { "SHA512"_s, HandleHashCommand },
  3300. { "SHA3_224"_s, HandleHashCommand },
  3301. { "SHA3_256"_s, HandleHashCommand },
  3302. { "SHA3_384"_s, HandleHashCommand },
  3303. { "SHA3_512"_s, HandleHashCommand },
  3304. { "STRINGS"_s, HandleStringsCommand },
  3305. { "GLOB"_s, HandleGlobCommand },
  3306. { "GLOB_RECURSE"_s, HandleGlobRecurseCommand },
  3307. { "MAKE_DIRECTORY"_s, HandleMakeDirectoryCommand },
  3308. { "RENAME"_s, HandleRename },
  3309. { "COPY_FILE"_s, HandleCopyFile },
  3310. { "REMOVE"_s, HandleRemove },
  3311. { "REMOVE_RECURSE"_s, HandleRemoveRecurse },
  3312. { "COPY"_s, HandleCopyCommand },
  3313. { "INSTALL"_s, HandleInstallCommand },
  3314. { "DIFFERENT"_s, HandleDifferentCommand },
  3315. { "RPATH_CHANGE"_s, HandleRPathChangeCommand },
  3316. { "CHRPATH"_s, HandleRPathChangeCommand },
  3317. { "RPATH_SET"_s, HandleRPathSetCommand },
  3318. { "RPATH_CHECK"_s, HandleRPathCheckCommand },
  3319. { "RPATH_REMOVE"_s, HandleRPathRemoveCommand },
  3320. { "READ_ELF"_s, HandleReadElfCommand },
  3321. { "REAL_PATH"_s, HandleRealPathCommand },
  3322. { "RELATIVE_PATH"_s, HandleRelativePathCommand },
  3323. { "TO_CMAKE_PATH"_s, HandleCMakePathCommand },
  3324. { "TO_NATIVE_PATH"_s, HandleNativePathCommand },
  3325. { "TOUCH"_s, HandleTouchCommand },
  3326. { "TOUCH_NOCREATE"_s, HandleTouchNocreateCommand },
  3327. { "TIMESTAMP"_s, HandleTimestampCommand },
  3328. { "GENERATE"_s, HandleGenerateCommand },
  3329. { "LOCK"_s, HandleLockCommand },
  3330. { "SIZE"_s, HandleSizeCommand },
  3331. { "READ_SYMLINK"_s, HandleReadSymlinkCommand },
  3332. { "CREATE_LINK"_s, HandleCreateLinkCommand },
  3333. { "GET_RUNTIME_DEPENDENCIES"_s, HandleGetRuntimeDependenciesCommand },
  3334. { "CONFIGURE"_s, HandleConfigureCommand },
  3335. { "ARCHIVE_CREATE"_s, HandleArchiveCreateCommand },
  3336. { "ARCHIVE_EXTRACT"_s, HandleArchiveExtractCommand },
  3337. { "CHMOD"_s, HandleChmodCommand },
  3338. { "CHMOD_RECURSE"_s, HandleChmodRecurseCommand },
  3339. };
  3340. return subcommand(args[0], args, status);
  3341. }