cmFileCommand.cxx 126 KB

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