cmFileCommand.cxx 119 KB

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