cmFileCommand.cxx 117 KB

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