cmFileCommand.cxx 119 KB

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