cmFileCommand.cxx 116 KB

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