cmFileCommand.cxx 128 KB

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