cmFileCommand.cxx 126 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052
  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. fout->write(chPtr, realsize);
  1562. }
  1563. return realsize;
  1564. }
  1565. size_t cmWriteToMemoryCallback(void* ptr, size_t size, size_t nmemb,
  1566. void* data)
  1567. {
  1568. int realsize = static_cast<int>(size * nmemb);
  1569. char const* chPtr = static_cast<char*>(ptr);
  1570. cm::append(*static_cast<cmFileCommandVectorOfChar*>(data), chPtr,
  1571. chPtr + realsize);
  1572. return realsize;
  1573. }
  1574. int cmFileCommandCurlDebugCallback(CURL*, curl_infotype type, char* chPtr,
  1575. size_t size, void* data)
  1576. {
  1577. cmFileCommandVectorOfChar& vec =
  1578. *static_cast<cmFileCommandVectorOfChar*>(data);
  1579. switch (type) {
  1580. case CURLINFO_TEXT:
  1581. case CURLINFO_HEADER_IN:
  1582. case CURLINFO_HEADER_OUT:
  1583. cm::append(vec, chPtr, chPtr + size);
  1584. break;
  1585. case CURLINFO_DATA_IN:
  1586. case CURLINFO_DATA_OUT:
  1587. case CURLINFO_SSL_DATA_IN:
  1588. case CURLINFO_SSL_DATA_OUT: {
  1589. char buf[128];
  1590. int n =
  1591. snprintf(buf, sizeof(buf), "[%" KWIML_INT_PRIu64 " bytes data]\n",
  1592. static_cast<KWIML_INT_uint64_t>(size));
  1593. if (n > 0) {
  1594. cm::append(vec, buf, buf + n);
  1595. }
  1596. } break;
  1597. default:
  1598. break;
  1599. }
  1600. return 0;
  1601. }
  1602. # if defined(LIBCURL_VERSION_NUM) && LIBCURL_VERSION_NUM >= 0x072000
  1603. CURLoption const CM_CURLOPT_XFERINFOFUNCTION = CURLOPT_XFERINFOFUNCTION;
  1604. using cm_curl_off_t = curl_off_t;
  1605. # else
  1606. CURLoption const CM_CURLOPT_XFERINFOFUNCTION = CURLOPT_PROGRESSFUNCTION;
  1607. using cm_curl_off_t = double;
  1608. # endif
  1609. class cURLProgressHelper
  1610. {
  1611. public:
  1612. cURLProgressHelper(cmMakefile* mf, char const* text)
  1613. : Makefile(mf)
  1614. , Text(text)
  1615. {
  1616. }
  1617. bool UpdatePercentage(cm_curl_off_t value, cm_curl_off_t total,
  1618. std::string& status)
  1619. {
  1620. long OldPercentage = this->CurrentPercentage;
  1621. if (total > 0) {
  1622. this->CurrentPercentage = std::lround(
  1623. static_cast<double>(value) / static_cast<double>(total) * 100.0);
  1624. if (this->CurrentPercentage > 100) {
  1625. // Avoid extra progress reports for unexpected data beyond total.
  1626. this->CurrentPercentage = 100;
  1627. }
  1628. }
  1629. bool updated = (OldPercentage != this->CurrentPercentage);
  1630. if (updated) {
  1631. status =
  1632. cmStrCat('[', this->Text, ' ', this->CurrentPercentage, "% complete]");
  1633. }
  1634. return updated;
  1635. }
  1636. cmMakefile* GetMakefile() { return this->Makefile; }
  1637. private:
  1638. long CurrentPercentage = -1;
  1639. cmMakefile* Makefile;
  1640. std::string Text;
  1641. };
  1642. int cmFileDownloadProgressCallback(void* clientp, cm_curl_off_t dltotal,
  1643. cm_curl_off_t dlnow, cm_curl_off_t ultotal,
  1644. cm_curl_off_t ulnow)
  1645. {
  1646. cURLProgressHelper* helper = reinterpret_cast<cURLProgressHelper*>(clientp);
  1647. static_cast<void>(ultotal);
  1648. static_cast<void>(ulnow);
  1649. std::string status;
  1650. if (helper->UpdatePercentage(dlnow, dltotal, status)) {
  1651. cmMakefile* mf = helper->GetMakefile();
  1652. mf->DisplayStatus(status, -1);
  1653. }
  1654. return 0;
  1655. }
  1656. int cmFileUploadProgressCallback(void* clientp, cm_curl_off_t dltotal,
  1657. cm_curl_off_t dlnow, cm_curl_off_t ultotal,
  1658. cm_curl_off_t ulnow)
  1659. {
  1660. cURLProgressHelper* helper = reinterpret_cast<cURLProgressHelper*>(clientp);
  1661. static_cast<void>(dltotal);
  1662. static_cast<void>(dlnow);
  1663. std::string status;
  1664. if (helper->UpdatePercentage(ulnow, ultotal, status)) {
  1665. cmMakefile* mf = helper->GetMakefile();
  1666. mf->DisplayStatus(status, -1);
  1667. }
  1668. return 0;
  1669. }
  1670. class cURLEasyGuard
  1671. {
  1672. public:
  1673. cURLEasyGuard(CURL* easy)
  1674. : Easy(easy)
  1675. {
  1676. }
  1677. ~cURLEasyGuard()
  1678. {
  1679. if (this->Easy) {
  1680. ::curl_easy_cleanup(this->Easy);
  1681. }
  1682. }
  1683. cURLEasyGuard(cURLEasyGuard const&) = delete;
  1684. cURLEasyGuard& operator=(cURLEasyGuard const&) = delete;
  1685. void release() { this->Easy = nullptr; }
  1686. private:
  1687. ::CURL* Easy;
  1688. };
  1689. #endif
  1690. #define check_curl_result(result, errstr) \
  1691. do { \
  1692. if (result != CURLE_OK) { \
  1693. std::string e(errstr); \
  1694. e += ::curl_easy_strerror(result); \
  1695. status.SetError(e); \
  1696. return false; \
  1697. } \
  1698. } while (false)
  1699. bool HandleDownloadCommand(std::vector<std::string> const& args,
  1700. cmExecutionStatus& status)
  1701. {
  1702. #if !defined(CMAKE_BOOTSTRAP)
  1703. auto i = args.begin();
  1704. if (args.size() < 2) {
  1705. status.SetError("DOWNLOAD must be called with at least two arguments.");
  1706. return false;
  1707. }
  1708. ++i; // Get rid of subcommand
  1709. std::string url = *i;
  1710. ++i;
  1711. std::string file;
  1712. long timeout = 0;
  1713. long inactivity_timeout = 0;
  1714. std::string logVar;
  1715. std::string statusVar;
  1716. cm::optional<std::string> tlsVersionOpt;
  1717. cm::optional<bool> tlsVerifyOpt;
  1718. cmValue cainfo = status.GetMakefile().GetDefinition("CMAKE_TLS_CAINFO");
  1719. std::string netrc_level =
  1720. status.GetMakefile().GetSafeDefinition("CMAKE_NETRC");
  1721. std::string netrc_file =
  1722. status.GetMakefile().GetSafeDefinition("CMAKE_NETRC_FILE");
  1723. std::string expectedHash;
  1724. std::string hashMatchMSG;
  1725. std::unique_ptr<cmCryptoHash> hash;
  1726. bool showProgress = false;
  1727. std::string userpwd;
  1728. std::vector<std::string> curl_headers;
  1729. std::vector<std::pair<std::string, cm::optional<std::string>>> curl_ranges;
  1730. while (i != args.end()) {
  1731. if (*i == "TIMEOUT") {
  1732. ++i;
  1733. if (i != args.end()) {
  1734. timeout = atol(i->c_str());
  1735. } else {
  1736. status.SetError("DOWNLOAD missing time for TIMEOUT.");
  1737. return false;
  1738. }
  1739. } else if (*i == "INACTIVITY_TIMEOUT") {
  1740. ++i;
  1741. if (i != args.end()) {
  1742. inactivity_timeout = atol(i->c_str());
  1743. } else {
  1744. status.SetError("DOWNLOAD missing time for INACTIVITY_TIMEOUT.");
  1745. return false;
  1746. }
  1747. } else if (*i == "LOG") {
  1748. ++i;
  1749. if (i == args.end()) {
  1750. status.SetError("DOWNLOAD missing VAR for LOG.");
  1751. return false;
  1752. }
  1753. logVar = *i;
  1754. } else if (*i == "STATUS") {
  1755. ++i;
  1756. if (i == args.end()) {
  1757. status.SetError("DOWNLOAD missing VAR for STATUS.");
  1758. return false;
  1759. }
  1760. statusVar = *i;
  1761. } else if (*i == "TLS_VERSION") {
  1762. ++i;
  1763. if (i != args.end()) {
  1764. tlsVersionOpt = *i;
  1765. } else {
  1766. status.SetError("DOWNLOAD missing value for TLS_VERSION.");
  1767. return false;
  1768. }
  1769. } else if (*i == "TLS_VERIFY") {
  1770. ++i;
  1771. if (i != args.end()) {
  1772. tlsVerifyOpt = cmIsOn(*i);
  1773. } else {
  1774. status.SetError("DOWNLOAD missing bool value for TLS_VERIFY.");
  1775. return false;
  1776. }
  1777. } else if (*i == "TLS_CAINFO") {
  1778. ++i;
  1779. if (i != args.end()) {
  1780. cainfo = cmValue(*i);
  1781. } else {
  1782. status.SetError("DOWNLOAD missing file value for TLS_CAINFO.");
  1783. return false;
  1784. }
  1785. } else if (*i == "NETRC_FILE") {
  1786. ++i;
  1787. if (i != args.end()) {
  1788. netrc_file = *i;
  1789. } else {
  1790. status.SetError("DOWNLOAD missing file value for NETRC_FILE.");
  1791. return false;
  1792. }
  1793. } else if (*i == "NETRC") {
  1794. ++i;
  1795. if (i != args.end()) {
  1796. netrc_level = *i;
  1797. } else {
  1798. status.SetError("DOWNLOAD missing level value for NETRC.");
  1799. return false;
  1800. }
  1801. } else if (*i == "EXPECTED_MD5") {
  1802. ++i;
  1803. if (i == args.end()) {
  1804. status.SetError("DOWNLOAD missing sum value for EXPECTED_MD5.");
  1805. return false;
  1806. }
  1807. hash = cm::make_unique<cmCryptoHash>(cmCryptoHash::AlgoMD5);
  1808. hashMatchMSG = "MD5 sum";
  1809. expectedHash = cmSystemTools::LowerCase(*i);
  1810. } else if (*i == "SHOW_PROGRESS") {
  1811. showProgress = true;
  1812. } else if (*i == "EXPECTED_HASH") {
  1813. ++i;
  1814. if (i == args.end()) {
  1815. status.SetError("DOWNLOAD missing ALGO=value for EXPECTED_HASH.");
  1816. return false;
  1817. }
  1818. std::string::size_type pos = i->find("=");
  1819. if (pos == std::string::npos) {
  1820. std::string err =
  1821. cmStrCat("DOWNLOAD EXPECTED_HASH expects ALGO=value but got: ", *i);
  1822. status.SetError(err);
  1823. return false;
  1824. }
  1825. std::string algo = i->substr(0, pos);
  1826. expectedHash = cmSystemTools::LowerCase(i->substr(pos + 1));
  1827. hash = cmCryptoHash::New(algo);
  1828. if (!hash) {
  1829. std::string err =
  1830. cmStrCat("DOWNLOAD EXPECTED_HASH given unknown ALGO: ", algo);
  1831. status.SetError(err);
  1832. return false;
  1833. }
  1834. hashMatchMSG = algo + " hash";
  1835. } else if (*i == "USERPWD") {
  1836. ++i;
  1837. if (i == args.end()) {
  1838. status.SetError("DOWNLOAD missing string for USERPWD.");
  1839. return false;
  1840. }
  1841. userpwd = *i;
  1842. } else if (*i == "HTTPHEADER") {
  1843. ++i;
  1844. if (i == args.end()) {
  1845. status.SetError("DOWNLOAD missing string for HTTPHEADER.");
  1846. return false;
  1847. }
  1848. curl_headers.push_back(*i);
  1849. } else if (*i == "RANGE_START") {
  1850. ++i;
  1851. if (i == args.end()) {
  1852. status.SetError("DOWNLOAD missing value for RANGE_START.");
  1853. return false;
  1854. }
  1855. curl_ranges.emplace_back(*i, cm::nullopt);
  1856. } else if (*i == "RANGE_END") {
  1857. ++i;
  1858. if (curl_ranges.empty()) {
  1859. curl_ranges.emplace_back("0", *i);
  1860. } else {
  1861. auto& last_range = curl_ranges.back();
  1862. if (!last_range.second.has_value()) {
  1863. last_range.second = *i;
  1864. } else {
  1865. status.SetError("Multiple RANGE_END values is provided without "
  1866. "the corresponding RANGE_START.");
  1867. return false;
  1868. }
  1869. }
  1870. } else if (file.empty()) {
  1871. file = *i;
  1872. } else {
  1873. // Do not return error for compatibility reason.
  1874. std::string err = cmStrCat("Unexpected argument: ", *i);
  1875. status.GetMakefile().IssueMessage(MessageType::AUTHOR_WARNING, err);
  1876. }
  1877. ++i;
  1878. }
  1879. if (!tlsVerifyOpt.has_value()) {
  1880. if (cmValue v = status.GetMakefile().GetDefinition("CMAKE_TLS_VERIFY")) {
  1881. tlsVerifyOpt = v.IsOn();
  1882. }
  1883. }
  1884. if (!tlsVerifyOpt.has_value()) {
  1885. if (cm::optional<std::string> v =
  1886. cmSystemTools::GetEnvVar("CMAKE_TLS_VERIFY")) {
  1887. tlsVerifyOpt = cmIsOn(*v);
  1888. }
  1889. }
  1890. bool tlsVerifyDefaulted = false;
  1891. if (!tlsVerifyOpt.has_value()) {
  1892. tlsVerifyOpt = TLS_VERIFY_DEFAULT;
  1893. tlsVerifyDefaulted = true;
  1894. }
  1895. if (!tlsVersionOpt.has_value()) {
  1896. if (cmValue v = status.GetMakefile().GetDefinition("CMAKE_TLS_VERSION")) {
  1897. tlsVersionOpt = *v;
  1898. }
  1899. }
  1900. if (!tlsVersionOpt.has_value()) {
  1901. if (cm::optional<std::string> v =
  1902. cmSystemTools::GetEnvVar("CMAKE_TLS_VERSION")) {
  1903. tlsVersionOpt = std::move(v);
  1904. }
  1905. }
  1906. bool tlsVersionDefaulted = false;
  1907. if (!tlsVersionOpt.has_value()) {
  1908. tlsVersionOpt = TLS_VERSION_DEFAULT;
  1909. tlsVersionDefaulted = true;
  1910. }
  1911. // Can't calculate hash if we don't save the file.
  1912. // TODO Incrementally calculate hash in the write callback as the file is
  1913. // being downloaded so this check can be relaxed.
  1914. if (file.empty() && hash) {
  1915. status.SetError("DOWNLOAD cannot calculate hash if file is not saved.");
  1916. return false;
  1917. }
  1918. // If file exists already, and caller specified an expected md5 or sha,
  1919. // and the existing file already has the expected hash, then simply
  1920. // return.
  1921. //
  1922. if (!file.empty() && cmSystemTools::FileExists(file) && hash.get()) {
  1923. std::string msg;
  1924. std::string actualHash = hash->HashFile(file);
  1925. if (actualHash == expectedHash) {
  1926. msg = cmStrCat("skipping download as file already exists with expected ",
  1927. hashMatchMSG, '"');
  1928. if (!statusVar.empty()) {
  1929. status.GetMakefile().AddDefinition(statusVar, cmStrCat(0, ";\"", msg));
  1930. }
  1931. return true;
  1932. }
  1933. }
  1934. // Make sure parent directory exists so we can write to the file
  1935. // as we receive downloaded bits from curl...
  1936. //
  1937. if (!file.empty()) {
  1938. std::string dir = cmSystemTools::GetFilenamePath(file);
  1939. if (!dir.empty() && !cmSystemTools::FileExists(dir) &&
  1940. !cmSystemTools::MakeDirectory(dir)) {
  1941. std::string errstring = "DOWNLOAD error: cannot create directory '" +
  1942. dir +
  1943. "' - Specify file by full path name and verify that you "
  1944. "have directory creation and file write privileges.";
  1945. status.SetError(errstring);
  1946. return false;
  1947. }
  1948. }
  1949. cmsys::ofstream fout;
  1950. if (!file.empty()) {
  1951. fout.open(file.c_str(), std::ios::binary);
  1952. if (!fout) {
  1953. status.SetError("DOWNLOAD cannot open file for write.");
  1954. return false;
  1955. }
  1956. }
  1957. url = cmCurlFixFileURL(url);
  1958. ::CURL* curl;
  1959. cmCurlInitOnce();
  1960. ::curl_global_init(CURL_GLOBAL_DEFAULT);
  1961. curl = cm_curl_easy_init();
  1962. if (!curl) {
  1963. status.SetError("DOWNLOAD error initializing curl.");
  1964. return false;
  1965. }
  1966. cURLEasyGuard g_curl(curl);
  1967. ::CURLcode res = ::curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  1968. check_curl_result(res, "DOWNLOAD cannot set url: ");
  1969. // enable HTTP ERROR parsing
  1970. res = ::curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  1971. check_curl_result(res, "DOWNLOAD cannot set http failure option: ");
  1972. curl_version_info_data* cv = curl_version_info(CURLVERSION_FIRST);
  1973. res = ::curl_easy_setopt(
  1974. curl, CURLOPT_USERAGENT,
  1975. cmStrCat("curl/", cv ? cv->version : LIBCURL_VERSION).c_str());
  1976. check_curl_result(res, "DOWNLOAD cannot set user agent option: ");
  1977. res = ::curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cmWriteToFileCallback);
  1978. check_curl_result(res, "DOWNLOAD cannot set write function: ");
  1979. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION,
  1980. cmFileCommandCurlDebugCallback);
  1981. check_curl_result(res, "DOWNLOAD cannot set debug function: ");
  1982. if (tlsVersionOpt.has_value()) {
  1983. if (cm::optional<int> v = cmCurlParseTLSVersion(*tlsVersionOpt)) {
  1984. res = ::curl_easy_setopt(curl, CURLOPT_SSLVERSION, *v);
  1985. if (tlsVersionDefaulted && res == CURLE_NOT_BUILT_IN) {
  1986. res = CURLE_OK;
  1987. }
  1988. check_curl_result(res,
  1989. cmStrCat("DOWNLOAD cannot set TLS/SSL version ",
  1990. *tlsVersionOpt, ": "));
  1991. } else {
  1992. status.SetError(
  1993. cmStrCat("DOWNLOAD given unknown TLS/SSL version ", *tlsVersionOpt));
  1994. return false;
  1995. }
  1996. }
  1997. // check to see if TLS verification is requested
  1998. if (tlsVerifyOpt.has_value() && tlsVerifyOpt.value()) {
  1999. res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1);
  2000. check_curl_result(res, "DOWNLOAD cannot set TLS/SSL Verify on: ");
  2001. } else {
  2002. res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
  2003. check_curl_result(res, "DOWNLOAD cannot set TLS/SSL Verify off: ");
  2004. }
  2005. for (auto const& range : curl_ranges) {
  2006. std::string curl_range = range.first + '-' +
  2007. (range.second.has_value() ? range.second.value() : "");
  2008. res = ::curl_easy_setopt(curl, CURLOPT_RANGE, curl_range.c_str());
  2009. check_curl_result(res, "DOWNLOAD cannot set range: ");
  2010. }
  2011. // check to see if a CAINFO file has been specified
  2012. // command arg comes first
  2013. std::string const& cainfo_err = cmCurlSetCAInfo(curl, cainfo);
  2014. if (!cainfo_err.empty()) {
  2015. status.SetError(cainfo_err);
  2016. return false;
  2017. }
  2018. // check to see if netrc parameters have been specified
  2019. // local command args takes precedence over CMAKE_NETRC*
  2020. netrc_level = cmSystemTools::UpperCase(netrc_level);
  2021. std::string const& netrc_option_err =
  2022. cmCurlSetNETRCOption(curl, netrc_level, netrc_file);
  2023. if (!netrc_option_err.empty()) {
  2024. status.SetError(netrc_option_err);
  2025. return false;
  2026. }
  2027. cmFileCommandVectorOfChar chunkDebug;
  2028. res = ::curl_easy_setopt(curl, CURLOPT_WRITEDATA,
  2029. file.empty() ? nullptr : &fout);
  2030. check_curl_result(res, "DOWNLOAD cannot set write data: ");
  2031. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, &chunkDebug);
  2032. check_curl_result(res, "DOWNLOAD cannot set debug data: ");
  2033. res = ::curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  2034. check_curl_result(res, "DOWNLOAD cannot set follow-redirect option: ");
  2035. if (!logVar.empty()) {
  2036. res = ::curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  2037. check_curl_result(res, "DOWNLOAD cannot set verbose: ");
  2038. }
  2039. if (timeout > 0) {
  2040. res = ::curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  2041. check_curl_result(res, "DOWNLOAD cannot set timeout: ");
  2042. }
  2043. if (inactivity_timeout > 0) {
  2044. // Give up if there is no progress for a long time.
  2045. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1);
  2046. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, inactivity_timeout);
  2047. }
  2048. // Need the progress helper's scope to last through the duration of
  2049. // the curl_easy_perform call... so this object is declared at function
  2050. // scope intentionally, rather than inside the "if(showProgress)"
  2051. // block...
  2052. //
  2053. cURLProgressHelper helper(&status.GetMakefile(), "download");
  2054. if (showProgress) {
  2055. res = ::curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
  2056. check_curl_result(res, "DOWNLOAD cannot set noprogress value: ");
  2057. res = ::curl_easy_setopt(curl, CM_CURLOPT_XFERINFOFUNCTION,
  2058. cmFileDownloadProgressCallback);
  2059. check_curl_result(res, "DOWNLOAD cannot set progress function: ");
  2060. res = ::curl_easy_setopt(curl, CURLOPT_PROGRESSDATA,
  2061. reinterpret_cast<void*>(&helper));
  2062. check_curl_result(res, "DOWNLOAD cannot set progress data: ");
  2063. }
  2064. if (!userpwd.empty()) {
  2065. res = ::curl_easy_setopt(curl, CURLOPT_USERPWD, userpwd.c_str());
  2066. check_curl_result(res, "DOWNLOAD cannot set user password: ");
  2067. }
  2068. struct curl_slist* headers = nullptr;
  2069. for (std::string const& h : curl_headers) {
  2070. headers = ::curl_slist_append(headers, h.c_str());
  2071. }
  2072. ::curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  2073. res = ::curl_easy_perform(curl);
  2074. ::curl_slist_free_all(headers);
  2075. /* always cleanup */
  2076. g_curl.release();
  2077. ::curl_easy_cleanup(curl);
  2078. if (!statusVar.empty()) {
  2079. std::string m = curl_easy_strerror(res);
  2080. if ((res == CURLE_SSL_CONNECT_ERROR ||
  2081. res == CURLE_PEER_FAILED_VERIFICATION) &&
  2082. tlsVerifyDefaulted) {
  2083. m = cmStrCat(
  2084. std::move(m),
  2085. ". If this is due to https certificate verification failure, one may "
  2086. "set environment variable CMAKE_TLS_VERIFY=0 to suppress it.");
  2087. }
  2088. status.GetMakefile().AddDefinition(
  2089. statusVar, cmStrCat(static_cast<int>(res), ";\"", std::move(m), '"'));
  2090. }
  2091. ::curl_global_cleanup();
  2092. // Ensure requested curl logs are returned (especially in case of failure)
  2093. //
  2094. if (!logVar.empty()) {
  2095. chunkDebug.push_back(0);
  2096. status.GetMakefile().AddDefinition(logVar, chunkDebug.data());
  2097. }
  2098. // Explicitly flush/close so we can measure the md5 accurately.
  2099. //
  2100. if (!file.empty()) {
  2101. fout.flush();
  2102. fout.close();
  2103. }
  2104. // Verify MD5 sum if requested:
  2105. //
  2106. if (hash) {
  2107. if (res != CURLE_OK) {
  2108. status.SetError(cmStrCat(
  2109. "DOWNLOAD cannot compute hash on failed download\n"
  2110. " status: [",
  2111. static_cast<int>(res), ";\"", ::curl_easy_strerror(res), "\"]"));
  2112. return false;
  2113. }
  2114. std::string actualHash = hash->HashFile(file);
  2115. if (actualHash.empty()) {
  2116. status.SetError("DOWNLOAD cannot compute hash on downloaded file");
  2117. return false;
  2118. }
  2119. if (expectedHash != actualHash) {
  2120. if (!statusVar.empty() && res == 0) {
  2121. status.GetMakefile().AddDefinition(statusVar,
  2122. "1;HASH mismatch: "
  2123. "expected: " +
  2124. expectedHash +
  2125. " actual: " + actualHash);
  2126. }
  2127. status.SetError(cmStrCat("DOWNLOAD HASH mismatch\n"
  2128. " for file: [",
  2129. file,
  2130. "]\n"
  2131. " expected hash: [",
  2132. expectedHash,
  2133. "]\n"
  2134. " actual hash: [",
  2135. actualHash, "]\n"));
  2136. return false;
  2137. }
  2138. }
  2139. return true;
  2140. #else
  2141. status.SetError("DOWNLOAD not supported by bootstrap cmake.");
  2142. return false;
  2143. #endif
  2144. }
  2145. bool HandleUploadCommand(std::vector<std::string> const& args,
  2146. cmExecutionStatus& status)
  2147. {
  2148. #if !defined(CMAKE_BOOTSTRAP)
  2149. if (args.size() < 3) {
  2150. status.SetError("UPLOAD must be called with at least three arguments.");
  2151. return false;
  2152. }
  2153. auto i = args.begin();
  2154. ++i;
  2155. std::string filename = *i;
  2156. ++i;
  2157. std::string url = *i;
  2158. ++i;
  2159. long timeout = 0;
  2160. long inactivity_timeout = 0;
  2161. std::string logVar;
  2162. std::string statusVar;
  2163. bool showProgress = false;
  2164. cm::optional<std::string> tlsVersionOpt;
  2165. cm::optional<bool> tlsVerifyOpt;
  2166. cmValue cainfo = status.GetMakefile().GetDefinition("CMAKE_TLS_CAINFO");
  2167. std::string userpwd;
  2168. std::string netrc_level =
  2169. status.GetMakefile().GetSafeDefinition("CMAKE_NETRC");
  2170. std::string netrc_file =
  2171. status.GetMakefile().GetSafeDefinition("CMAKE_NETRC_FILE");
  2172. std::vector<std::string> curl_headers;
  2173. while (i != args.end()) {
  2174. if (*i == "TIMEOUT") {
  2175. ++i;
  2176. if (i != args.end()) {
  2177. timeout = atol(i->c_str());
  2178. } else {
  2179. status.SetError("UPLOAD missing time for TIMEOUT.");
  2180. return false;
  2181. }
  2182. } else if (*i == "INACTIVITY_TIMEOUT") {
  2183. ++i;
  2184. if (i != args.end()) {
  2185. inactivity_timeout = atol(i->c_str());
  2186. } else {
  2187. status.SetError("UPLOAD missing time for INACTIVITY_TIMEOUT.");
  2188. return false;
  2189. }
  2190. } else if (*i == "LOG") {
  2191. ++i;
  2192. if (i == args.end()) {
  2193. status.SetError("UPLOAD missing VAR for LOG.");
  2194. return false;
  2195. }
  2196. logVar = *i;
  2197. } else if (*i == "STATUS") {
  2198. ++i;
  2199. if (i == args.end()) {
  2200. status.SetError("UPLOAD missing VAR for STATUS.");
  2201. return false;
  2202. }
  2203. statusVar = *i;
  2204. } else if (*i == "SHOW_PROGRESS") {
  2205. showProgress = true;
  2206. } else if (*i == "TLS_VERSION") {
  2207. ++i;
  2208. if (i != args.end()) {
  2209. tlsVersionOpt = *i;
  2210. } else {
  2211. status.SetError("UPLOAD missing value for TLS_VERSION.");
  2212. return false;
  2213. }
  2214. } else if (*i == "TLS_VERIFY") {
  2215. ++i;
  2216. if (i != args.end()) {
  2217. tlsVerifyOpt = cmIsOn(*i);
  2218. } else {
  2219. status.SetError("UPLOAD missing bool value for TLS_VERIFY.");
  2220. return false;
  2221. }
  2222. } else if (*i == "TLS_CAINFO") {
  2223. ++i;
  2224. if (i != args.end()) {
  2225. cainfo = cmValue(*i);
  2226. } else {
  2227. status.SetError("UPLOAD missing file value for TLS_CAINFO.");
  2228. return false;
  2229. }
  2230. } else if (*i == "NETRC_FILE") {
  2231. ++i;
  2232. if (i != args.end()) {
  2233. netrc_file = *i;
  2234. } else {
  2235. status.SetError("UPLOAD missing file value for NETRC_FILE.");
  2236. return false;
  2237. }
  2238. } else if (*i == "NETRC") {
  2239. ++i;
  2240. if (i != args.end()) {
  2241. netrc_level = *i;
  2242. } else {
  2243. status.SetError("UPLOAD missing level value for NETRC.");
  2244. return false;
  2245. }
  2246. } else if (*i == "USERPWD") {
  2247. ++i;
  2248. if (i == args.end()) {
  2249. status.SetError("UPLOAD missing string for USERPWD.");
  2250. return false;
  2251. }
  2252. userpwd = *i;
  2253. } else if (*i == "HTTPHEADER") {
  2254. ++i;
  2255. if (i == args.end()) {
  2256. status.SetError("UPLOAD missing string for HTTPHEADER.");
  2257. return false;
  2258. }
  2259. curl_headers.push_back(*i);
  2260. } else {
  2261. // Do not return error for compatibility reason.
  2262. std::string err = cmStrCat("Unexpected argument: ", *i);
  2263. status.GetMakefile().IssueMessage(MessageType::AUTHOR_WARNING, err);
  2264. }
  2265. ++i;
  2266. }
  2267. if (!tlsVerifyOpt.has_value()) {
  2268. if (cmValue v = status.GetMakefile().GetDefinition("CMAKE_TLS_VERIFY")) {
  2269. tlsVerifyOpt = v.IsOn();
  2270. }
  2271. }
  2272. if (!tlsVerifyOpt.has_value()) {
  2273. if (cm::optional<std::string> v =
  2274. cmSystemTools::GetEnvVar("CMAKE_TLS_VERIFY")) {
  2275. tlsVerifyOpt = cmIsOn(*v);
  2276. }
  2277. }
  2278. bool tlsVerifyDefaulted = false;
  2279. if (!tlsVerifyOpt.has_value()) {
  2280. tlsVerifyOpt = TLS_VERIFY_DEFAULT;
  2281. tlsVerifyDefaulted = true;
  2282. }
  2283. if (!tlsVersionOpt.has_value()) {
  2284. if (cmValue v = status.GetMakefile().GetDefinition("CMAKE_TLS_VERSION")) {
  2285. tlsVersionOpt = *v;
  2286. }
  2287. }
  2288. if (!tlsVersionOpt.has_value()) {
  2289. if (cm::optional<std::string> v =
  2290. cmSystemTools::GetEnvVar("CMAKE_TLS_VERSION")) {
  2291. tlsVersionOpt = std::move(v);
  2292. }
  2293. }
  2294. bool tlsVersionDefaulted = false;
  2295. if (!tlsVersionOpt.has_value()) {
  2296. tlsVersionOpt = TLS_VERSION_DEFAULT;
  2297. tlsVersionDefaulted = true;
  2298. }
  2299. // Open file for reading:
  2300. //
  2301. FILE* fin = cmsys::SystemTools::Fopen(filename, "rb");
  2302. if (!fin) {
  2303. std::string errStr =
  2304. cmStrCat("UPLOAD cannot open file '", filename, "' for reading.");
  2305. status.SetError(errStr);
  2306. return false;
  2307. }
  2308. unsigned long file_size = cmsys::SystemTools::FileLength(filename);
  2309. url = cmCurlFixFileURL(url);
  2310. ::CURL* curl;
  2311. cmCurlInitOnce();
  2312. ::curl_global_init(CURL_GLOBAL_DEFAULT);
  2313. curl = cm_curl_easy_init();
  2314. if (!curl) {
  2315. status.SetError("UPLOAD error initializing curl.");
  2316. fclose(fin);
  2317. return false;
  2318. }
  2319. cURLEasyGuard g_curl(curl);
  2320. // enable HTTP ERROR parsing
  2321. ::CURLcode res = ::curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  2322. check_curl_result(res, "UPLOAD cannot set fail on error flag: ");
  2323. // enable uploading
  2324. res = ::curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
  2325. check_curl_result(res, "UPLOAD cannot set upload flag: ");
  2326. res = ::curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  2327. check_curl_result(res, "UPLOAD cannot set url: ");
  2328. res =
  2329. ::curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cmWriteToMemoryCallback);
  2330. check_curl_result(res, "UPLOAD cannot set write function: ");
  2331. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION,
  2332. cmFileCommandCurlDebugCallback);
  2333. check_curl_result(res, "UPLOAD cannot set debug function: ");
  2334. if (tlsVersionOpt.has_value()) {
  2335. if (cm::optional<int> v = cmCurlParseTLSVersion(*tlsVersionOpt)) {
  2336. res = ::curl_easy_setopt(curl, CURLOPT_SSLVERSION, *v);
  2337. if (tlsVersionDefaulted && res == CURLE_NOT_BUILT_IN) {
  2338. res = CURLE_OK;
  2339. }
  2340. check_curl_result(
  2341. res,
  2342. cmStrCat("UPLOAD cannot set TLS/SSL version ", *tlsVersionOpt, ": "));
  2343. } else {
  2344. status.SetError(
  2345. cmStrCat("UPLOAD given unknown TLS/SSL version ", *tlsVersionOpt));
  2346. return false;
  2347. }
  2348. }
  2349. // check to see if TLS verification is requested
  2350. if (tlsVerifyOpt.has_value() && tlsVerifyOpt.value()) {
  2351. res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1);
  2352. check_curl_result(res, "UPLOAD cannot set TLS/SSL Verify on: ");
  2353. } else {
  2354. res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
  2355. check_curl_result(res, "UPLOAD cannot set TLS/SSL Verify off: ");
  2356. }
  2357. // check to see if a CAINFO file has been specified
  2358. // command arg comes first
  2359. std::string const& cainfo_err = cmCurlSetCAInfo(curl, cainfo);
  2360. if (!cainfo_err.empty()) {
  2361. status.SetError(cainfo_err);
  2362. return false;
  2363. }
  2364. cmFileCommandVectorOfChar chunkResponse;
  2365. cmFileCommandVectorOfChar chunkDebug;
  2366. res = ::curl_easy_setopt(curl, CURLOPT_WRITEDATA, &chunkResponse);
  2367. check_curl_result(res, "UPLOAD cannot set write data: ");
  2368. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, &chunkDebug);
  2369. check_curl_result(res, "UPLOAD cannot set debug data: ");
  2370. res = ::curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  2371. check_curl_result(res, "UPLOAD cannot set follow-redirect option: ");
  2372. if (!logVar.empty()) {
  2373. res = ::curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  2374. check_curl_result(res, "UPLOAD cannot set verbose: ");
  2375. }
  2376. if (timeout > 0) {
  2377. res = ::curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  2378. check_curl_result(res, "UPLOAD cannot set timeout: ");
  2379. }
  2380. if (inactivity_timeout > 0) {
  2381. // Give up if there is no progress for a long time.
  2382. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1);
  2383. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, inactivity_timeout);
  2384. }
  2385. // Need the progress helper's scope to last through the duration of
  2386. // the curl_easy_perform call... so this object is declared at function
  2387. // scope intentionally, rather than inside the "if(showProgress)"
  2388. // block...
  2389. //
  2390. cURLProgressHelper helper(&status.GetMakefile(), "upload");
  2391. if (showProgress) {
  2392. res = ::curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
  2393. check_curl_result(res, "UPLOAD cannot set noprogress value: ");
  2394. res = ::curl_easy_setopt(curl, CM_CURLOPT_XFERINFOFUNCTION,
  2395. cmFileUploadProgressCallback);
  2396. check_curl_result(res, "UPLOAD cannot set progress function: ");
  2397. res = ::curl_easy_setopt(curl, CURLOPT_PROGRESSDATA,
  2398. reinterpret_cast<void*>(&helper));
  2399. check_curl_result(res, "UPLOAD cannot set progress data: ");
  2400. }
  2401. // now specify which file to upload
  2402. res = ::curl_easy_setopt(curl, CURLOPT_INFILE, fin);
  2403. check_curl_result(res, "UPLOAD cannot set input file: ");
  2404. // and give the size of the upload (optional)
  2405. res =
  2406. ::curl_easy_setopt(curl, CURLOPT_INFILESIZE, static_cast<long>(file_size));
  2407. check_curl_result(res, "UPLOAD cannot set input file size: ");
  2408. if (!userpwd.empty()) {
  2409. res = ::curl_easy_setopt(curl, CURLOPT_USERPWD, userpwd.c_str());
  2410. check_curl_result(res, "UPLOAD cannot set user password: ");
  2411. }
  2412. // check to see if netrc parameters have been specified
  2413. // local command args takes precedence over CMAKE_NETRC*
  2414. netrc_level = cmSystemTools::UpperCase(netrc_level);
  2415. std::string const& netrc_option_err =
  2416. cmCurlSetNETRCOption(curl, netrc_level, netrc_file);
  2417. if (!netrc_option_err.empty()) {
  2418. status.SetError(netrc_option_err);
  2419. return false;
  2420. }
  2421. struct curl_slist* headers = nullptr;
  2422. for (std::string const& h : curl_headers) {
  2423. headers = ::curl_slist_append(headers, h.c_str());
  2424. }
  2425. ::curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  2426. res = ::curl_easy_perform(curl);
  2427. ::curl_slist_free_all(headers);
  2428. /* always cleanup */
  2429. g_curl.release();
  2430. ::curl_easy_cleanup(curl);
  2431. if (!statusVar.empty()) {
  2432. std::string m = curl_easy_strerror(res);
  2433. if ((res == CURLE_SSL_CONNECT_ERROR ||
  2434. res == CURLE_PEER_FAILED_VERIFICATION) &&
  2435. tlsVerifyDefaulted) {
  2436. m = cmStrCat(
  2437. std::move(m),
  2438. ". If this is due to https certificate verification failure, one may "
  2439. "set environment variable CMAKE_TLS_VERIFY=0 to suppress it.");
  2440. }
  2441. status.GetMakefile().AddDefinition(
  2442. statusVar, cmStrCat(static_cast<int>(res), ";\"", std::move(m), '"'));
  2443. }
  2444. ::curl_global_cleanup();
  2445. fclose(fin);
  2446. fin = nullptr;
  2447. if (!logVar.empty()) {
  2448. std::string log;
  2449. if (!chunkResponse.empty()) {
  2450. chunkResponse.push_back(0);
  2451. log += "Response:\n";
  2452. log += chunkResponse.data();
  2453. log += "\n";
  2454. }
  2455. if (!chunkDebug.empty()) {
  2456. chunkDebug.push_back(0);
  2457. log += "Debug:\n";
  2458. log += chunkDebug.data();
  2459. log += "\n";
  2460. }
  2461. status.GetMakefile().AddDefinition(logVar, log);
  2462. }
  2463. return true;
  2464. #else
  2465. status.SetError("UPLOAD not supported by bootstrap cmake.");
  2466. return false;
  2467. #endif
  2468. }
  2469. void AddEvaluationFile(std::string const& inputName,
  2470. std::string const& targetName,
  2471. std::string const& outputExpr,
  2472. std::string const& condition, bool inputIsContent,
  2473. std::string const& newLineCharacter, mode_t permissions,
  2474. cmExecutionStatus& status)
  2475. {
  2476. cmListFileBacktrace lfbt = status.GetMakefile().GetBacktrace();
  2477. cmGeneratorExpression outputGe(*status.GetMakefile().GetCMakeInstance(),
  2478. lfbt);
  2479. std::unique_ptr<cmCompiledGeneratorExpression> outputCge =
  2480. outputGe.Parse(outputExpr);
  2481. cmGeneratorExpression conditionGe(*status.GetMakefile().GetCMakeInstance(),
  2482. lfbt);
  2483. std::unique_ptr<cmCompiledGeneratorExpression> conditionCge =
  2484. conditionGe.Parse(condition);
  2485. status.GetMakefile().AddEvaluationFile(
  2486. inputName, targetName, std::move(outputCge), std::move(conditionCge),
  2487. newLineCharacter, permissions, inputIsContent);
  2488. }
  2489. bool HandleGenerateCommand(std::vector<std::string> const& args,
  2490. cmExecutionStatus& status)
  2491. {
  2492. if (args.size() < 5) {
  2493. status.SetError("Incorrect arguments to GENERATE subcommand.");
  2494. return false;
  2495. }
  2496. struct Arguments : public ArgumentParser::ParseResult
  2497. {
  2498. cm::optional<std::string> Output;
  2499. cm::optional<std::string> Input;
  2500. cm::optional<std::string> Content;
  2501. cm::optional<std::string> Condition;
  2502. cm::optional<std::string> Target;
  2503. cm::optional<std::string> NewLineStyle;
  2504. bool NoSourcePermissions = false;
  2505. bool UseSourcePermissions = false;
  2506. ArgumentParser::NonEmpty<std::vector<std::string>> FilePermissions;
  2507. std::vector<cm::string_view> ParsedKeywords;
  2508. };
  2509. static auto const parser =
  2510. cmArgumentParser<Arguments>{}
  2511. .Bind("OUTPUT"_s, &Arguments::Output)
  2512. .Bind("INPUT"_s, &Arguments::Input)
  2513. .Bind("CONTENT"_s, &Arguments::Content)
  2514. .Bind("CONDITION"_s, &Arguments::Condition)
  2515. .Bind("TARGET"_s, &Arguments::Target)
  2516. .Bind("NO_SOURCE_PERMISSIONS"_s, &Arguments::NoSourcePermissions)
  2517. .Bind("USE_SOURCE_PERMISSIONS"_s, &Arguments::UseSourcePermissions)
  2518. .Bind("FILE_PERMISSIONS"_s, &Arguments::FilePermissions)
  2519. .Bind("NEWLINE_STYLE"_s, &Arguments::NewLineStyle)
  2520. .BindParsedKeywords(&Arguments::ParsedKeywords);
  2521. std::vector<std::string> unparsedArguments;
  2522. Arguments const arguments =
  2523. parser.Parse(cmMakeRange(args).advance(1), &unparsedArguments);
  2524. if (arguments.MaybeReportError(status.GetMakefile())) {
  2525. return true;
  2526. }
  2527. if (!unparsedArguments.empty()) {
  2528. status.SetError("Unknown argument to GENERATE subcommand.");
  2529. return false;
  2530. }
  2531. if (!arguments.Output || arguments.ParsedKeywords[0] != "OUTPUT"_s) {
  2532. status.SetError("GENERATE requires OUTPUT as first option.");
  2533. return false;
  2534. }
  2535. std::string const& output = *arguments.Output;
  2536. if (!arguments.Input && !arguments.Content) {
  2537. status.SetError("GENERATE requires INPUT or CONTENT option.");
  2538. return false;
  2539. }
  2540. bool const inputIsContent = arguments.ParsedKeywords[1] == "CONTENT"_s;
  2541. if (!inputIsContent && arguments.ParsedKeywords[1] != "INPUT") {
  2542. status.SetError("Unknown argument to GENERATE subcommand.");
  2543. return false;
  2544. }
  2545. std::string const& input =
  2546. inputIsContent ? *arguments.Content : *arguments.Input;
  2547. if (arguments.Condition && arguments.Condition->empty()) {
  2548. status.SetError("CONDITION of sub-command GENERATE must not be empty "
  2549. "if specified.");
  2550. return false;
  2551. }
  2552. std::string const& condition =
  2553. arguments.Condition ? *arguments.Condition : std::string();
  2554. if (arguments.Target && arguments.Target->empty()) {
  2555. status.SetError("TARGET of sub-command GENERATE must not be empty "
  2556. "if specified.");
  2557. return false;
  2558. }
  2559. std::string const& target =
  2560. arguments.Target ? *arguments.Target : std::string();
  2561. cmNewLineStyle newLineStyle;
  2562. if (arguments.NewLineStyle) {
  2563. std::string errorMessage;
  2564. if (!newLineStyle.ReadFromArguments(args, errorMessage)) {
  2565. status.SetError(cmStrCat("GENERATE ", errorMessage));
  2566. return false;
  2567. }
  2568. }
  2569. if (arguments.NoSourcePermissions && arguments.UseSourcePermissions) {
  2570. status.SetError("given both NO_SOURCE_PERMISSIONS and "
  2571. "USE_SOURCE_PERMISSIONS. Only one option allowed.");
  2572. return false;
  2573. }
  2574. if (!arguments.FilePermissions.empty()) {
  2575. if (arguments.NoSourcePermissions) {
  2576. status.SetError("given both NO_SOURCE_PERMISSIONS and "
  2577. "FILE_PERMISSIONS. Only one option allowed.");
  2578. return false;
  2579. }
  2580. if (arguments.UseSourcePermissions) {
  2581. status.SetError("given both USE_SOURCE_PERMISSIONS and "
  2582. "FILE_PERMISSIONS. Only one option allowed.");
  2583. return false;
  2584. }
  2585. }
  2586. if (arguments.UseSourcePermissions) {
  2587. if (inputIsContent) {
  2588. status.SetError("given USE_SOURCE_PERMISSIONS without a file INPUT.");
  2589. return false;
  2590. }
  2591. }
  2592. mode_t permissions = 0;
  2593. if (arguments.NoSourcePermissions) {
  2594. permissions |= cmFSPermissions::mode_owner_read;
  2595. permissions |= cmFSPermissions::mode_owner_write;
  2596. permissions |= cmFSPermissions::mode_group_read;
  2597. permissions |= cmFSPermissions::mode_world_read;
  2598. }
  2599. if (!arguments.FilePermissions.empty()) {
  2600. std::vector<std::string> invalidOptions;
  2601. for (auto const& e : arguments.FilePermissions) {
  2602. if (!cmFSPermissions::stringToModeT(e, permissions)) {
  2603. invalidOptions.push_back(e);
  2604. }
  2605. }
  2606. if (!invalidOptions.empty()) {
  2607. std::ostringstream oss;
  2608. oss << "given invalid permission ";
  2609. for (auto i = 0u; i < invalidOptions.size(); i++) {
  2610. if (i == 0u) {
  2611. oss << "\"" << invalidOptions[i] << "\"";
  2612. } else {
  2613. oss << ",\"" << invalidOptions[i] << "\"";
  2614. }
  2615. }
  2616. oss << ".";
  2617. status.SetError(oss.str());
  2618. return false;
  2619. }
  2620. }
  2621. AddEvaluationFile(input, target, output, condition, inputIsContent,
  2622. newLineStyle.GetCharacters(), permissions, status);
  2623. return true;
  2624. }
  2625. bool HandleLockCommand(std::vector<std::string> const& args,
  2626. cmExecutionStatus& status)
  2627. {
  2628. #if !defined(CMAKE_BOOTSTRAP)
  2629. // Default values
  2630. bool directory = false;
  2631. bool release = false;
  2632. enum Guard
  2633. {
  2634. GUARD_FUNCTION,
  2635. GUARD_FILE,
  2636. GUARD_PROCESS
  2637. };
  2638. Guard guard = GUARD_PROCESS;
  2639. std::string resultVariable;
  2640. unsigned long timeout = static_cast<unsigned long>(-1);
  2641. // Parse arguments
  2642. if (args.size() < 2) {
  2643. status.GetMakefile().IssueMessage(
  2644. MessageType::FATAL_ERROR,
  2645. "sub-command LOCK requires at least two arguments.");
  2646. return false;
  2647. }
  2648. std::string path = args[1];
  2649. for (unsigned i = 2; i < args.size(); ++i) {
  2650. if (args[i] == "DIRECTORY") {
  2651. directory = true;
  2652. } else if (args[i] == "RELEASE") {
  2653. release = true;
  2654. } else if (args[i] == "GUARD") {
  2655. ++i;
  2656. char const* merr = "expected FUNCTION, FILE or PROCESS after GUARD";
  2657. if (i >= args.size()) {
  2658. status.GetMakefile().IssueMessage(MessageType::FATAL_ERROR, merr);
  2659. return false;
  2660. }
  2661. if (args[i] == "FUNCTION") {
  2662. guard = GUARD_FUNCTION;
  2663. } else if (args[i] == "FILE") {
  2664. guard = GUARD_FILE;
  2665. } else if (args[i] == "PROCESS") {
  2666. guard = GUARD_PROCESS;
  2667. } else {
  2668. status.GetMakefile().IssueMessage(
  2669. MessageType::FATAL_ERROR,
  2670. cmStrCat(merr, ", but got:\n \"", args[i], "\"."));
  2671. return false;
  2672. }
  2673. } else if (args[i] == "RESULT_VARIABLE") {
  2674. ++i;
  2675. if (i >= args.size()) {
  2676. status.GetMakefile().IssueMessage(
  2677. MessageType::FATAL_ERROR,
  2678. "expected variable name after RESULT_VARIABLE");
  2679. return false;
  2680. }
  2681. resultVariable = args[i];
  2682. } else if (args[i] == "TIMEOUT") {
  2683. ++i;
  2684. if (i >= args.size()) {
  2685. status.GetMakefile().IssueMessage(
  2686. MessageType::FATAL_ERROR, "expected timeout value after TIMEOUT");
  2687. return false;
  2688. }
  2689. long scanned;
  2690. if (!cmStrToLong(args[i], &scanned) || scanned < 0) {
  2691. status.GetMakefile().IssueMessage(
  2692. MessageType::FATAL_ERROR,
  2693. cmStrCat("TIMEOUT value \"", args[i],
  2694. "\" is not an unsigned integer."));
  2695. return false;
  2696. }
  2697. timeout = static_cast<unsigned long>(scanned);
  2698. } else {
  2699. status.GetMakefile().IssueMessage(
  2700. MessageType::FATAL_ERROR,
  2701. cmStrCat("expected DIRECTORY, RELEASE, GUARD, RESULT_VARIABLE or ",
  2702. "TIMEOUT\nbut got: \"", args[i], "\"."));
  2703. return false;
  2704. }
  2705. }
  2706. if (directory) {
  2707. path += "/cmake.lock";
  2708. }
  2709. // Unify path (remove '//', '/../', ...)
  2710. path = cmSystemTools::CollapseFullPath(
  2711. path, status.GetMakefile().GetCurrentSourceDirectory());
  2712. // Create file and directories if needed
  2713. std::string parentDir = cmSystemTools::GetParentDirectory(path);
  2714. if (!cmSystemTools::MakeDirectory(parentDir)) {
  2715. status.GetMakefile().IssueMessage(
  2716. MessageType::FATAL_ERROR,
  2717. cmStrCat("directory\n \"", parentDir,
  2718. "\"\ncreation failed (check permissions)."));
  2719. cmSystemTools::SetFatalErrorOccurred();
  2720. return false;
  2721. }
  2722. FILE* file = cmsys::SystemTools::Fopen(path, "w");
  2723. if (!file) {
  2724. status.GetMakefile().IssueMessage(
  2725. MessageType::FATAL_ERROR,
  2726. cmStrCat("file\n \"", path,
  2727. "\"\ncreation failed (check permissions)."));
  2728. cmSystemTools::SetFatalErrorOccurred();
  2729. return false;
  2730. }
  2731. fclose(file);
  2732. // Actual lock/unlock
  2733. cmFileLockPool& lockPool =
  2734. status.GetMakefile().GetGlobalGenerator()->GetFileLockPool();
  2735. cmFileLockResult fileLockResult(cmFileLockResult::MakeOk());
  2736. if (release) {
  2737. fileLockResult = lockPool.Release(path);
  2738. } else {
  2739. switch (guard) {
  2740. case GUARD_FUNCTION:
  2741. fileLockResult = lockPool.LockFunctionScope(path, timeout);
  2742. break;
  2743. case GUARD_FILE:
  2744. fileLockResult = lockPool.LockFileScope(path, timeout);
  2745. break;
  2746. case GUARD_PROCESS:
  2747. fileLockResult = lockPool.LockProcessScope(path, timeout);
  2748. break;
  2749. default:
  2750. cmSystemTools::SetFatalErrorOccurred();
  2751. return false;
  2752. }
  2753. }
  2754. std::string const result = fileLockResult.GetOutputMessage();
  2755. if (resultVariable.empty() && !fileLockResult.IsOk()) {
  2756. status.GetMakefile().IssueMessage(
  2757. MessageType::FATAL_ERROR,
  2758. cmStrCat("error locking file\n \"", path, "\"\n", result, '.'));
  2759. cmSystemTools::SetFatalErrorOccurred();
  2760. return false;
  2761. }
  2762. if (!resultVariable.empty()) {
  2763. status.GetMakefile().AddDefinition(resultVariable, result);
  2764. }
  2765. return true;
  2766. #else
  2767. static_cast<void>(args);
  2768. status.SetError("sub-command LOCK not implemented in bootstrap cmake");
  2769. return false;
  2770. #endif
  2771. }
  2772. bool HandleTimestampCommand(std::vector<std::string> const& args,
  2773. cmExecutionStatus& status)
  2774. {
  2775. if (args.size() < 3) {
  2776. status.SetError("sub-command TIMESTAMP requires at least two arguments.");
  2777. return false;
  2778. }
  2779. if (args.size() > 5) {
  2780. status.SetError("sub-command TIMESTAMP takes at most four arguments.");
  2781. return false;
  2782. }
  2783. unsigned int argsIndex = 1;
  2784. std::string filename = args[argsIndex++];
  2785. if (!cmsys::SystemTools::FileIsFullPath(filename)) {
  2786. filename = cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/',
  2787. filename);
  2788. }
  2789. std::string const& outputVariable = args[argsIndex++];
  2790. std::string formatString;
  2791. if (args.size() > argsIndex && args[argsIndex] != "UTC") {
  2792. formatString = args[argsIndex++];
  2793. }
  2794. bool utcFlag = false;
  2795. if (args.size() > argsIndex) {
  2796. if (args[argsIndex] == "UTC") {
  2797. utcFlag = true;
  2798. } else {
  2799. std::string e = " TIMESTAMP sub-command does not recognize option " +
  2800. args[argsIndex] + ".";
  2801. status.SetError(e);
  2802. return false;
  2803. }
  2804. }
  2805. cmTimestamp timestamp;
  2806. std::string result =
  2807. timestamp.FileModificationTime(filename.c_str(), formatString, utcFlag);
  2808. status.GetMakefile().AddDefinition(outputVariable, result);
  2809. return true;
  2810. }
  2811. bool HandleSizeCommand(std::vector<std::string> const& args,
  2812. cmExecutionStatus& status)
  2813. {
  2814. if (args.size() != 3) {
  2815. status.SetError(
  2816. cmStrCat(args[0], " requires a file name and output variable"));
  2817. return false;
  2818. }
  2819. unsigned int argsIndex = 1;
  2820. std::string const& filename = args[argsIndex++];
  2821. std::string const& outputVariable = args[argsIndex++];
  2822. if (!cmSystemTools::FileExists(filename, true)) {
  2823. status.SetError(
  2824. cmStrCat("SIZE requested of path that is not readable:\n ", filename));
  2825. return false;
  2826. }
  2827. status.GetMakefile().AddDefinition(
  2828. outputVariable, std::to_string(cmSystemTools::FileLength(filename)));
  2829. return true;
  2830. }
  2831. bool HandleReadSymlinkCommand(std::vector<std::string> const& args,
  2832. cmExecutionStatus& status)
  2833. {
  2834. if (args.size() != 3) {
  2835. status.SetError(
  2836. cmStrCat(args[0], " requires a file name and output variable"));
  2837. return false;
  2838. }
  2839. std::string const& filename = args[1];
  2840. std::string const& outputVariable = args[2];
  2841. std::string result;
  2842. if (!cmSystemTools::ReadSymlink(filename, result)) {
  2843. status.SetError(cmStrCat(
  2844. "READ_SYMLINK requested of path that is not a symlink:\n ", filename));
  2845. return false;
  2846. }
  2847. status.GetMakefile().AddDefinition(outputVariable, result);
  2848. return true;
  2849. }
  2850. bool HandleCreateLinkCommand(std::vector<std::string> const& args,
  2851. cmExecutionStatus& status)
  2852. {
  2853. if (args.size() < 3) {
  2854. status.SetError("CREATE_LINK must be called with at least two additional "
  2855. "arguments");
  2856. return false;
  2857. }
  2858. std::string const& fileName = args[1];
  2859. std::string const& newFileName = args[2];
  2860. struct Arguments
  2861. {
  2862. std::string Result;
  2863. bool CopyOnError = false;
  2864. bool Symbolic = false;
  2865. };
  2866. static auto const parser =
  2867. cmArgumentParser<Arguments>{}
  2868. .Bind("RESULT"_s, &Arguments::Result)
  2869. .Bind("COPY_ON_ERROR"_s, &Arguments::CopyOnError)
  2870. .Bind("SYMBOLIC"_s, &Arguments::Symbolic);
  2871. std::vector<std::string> unconsumedArgs;
  2872. Arguments const arguments =
  2873. parser.Parse(cmMakeRange(args).advance(3), &unconsumedArgs);
  2874. if (!unconsumedArgs.empty()) {
  2875. status.SetError("unknown argument: \"" + unconsumedArgs.front() + '\"');
  2876. return false;
  2877. }
  2878. // The system error message generated in the operation.
  2879. std::string result;
  2880. // Check if the paths are distinct.
  2881. if (fileName == newFileName) {
  2882. result = "CREATE_LINK cannot use same file and newfile";
  2883. if (!arguments.Result.empty()) {
  2884. status.GetMakefile().AddDefinition(arguments.Result, result);
  2885. return true;
  2886. }
  2887. status.SetError(result);
  2888. return false;
  2889. }
  2890. // Hard link requires original file to exist.
  2891. if (!arguments.Symbolic && !cmSystemTools::FileExists(fileName)) {
  2892. result = "Cannot hard link \'" + fileName + "\' as it does not exist.";
  2893. if (!arguments.Result.empty()) {
  2894. status.GetMakefile().AddDefinition(arguments.Result, result);
  2895. return true;
  2896. }
  2897. status.SetError(result);
  2898. return false;
  2899. }
  2900. // Check if the new file already exists and remove it.
  2901. if (cmSystemTools::PathExists(newFileName) &&
  2902. !cmSystemTools::RemoveFile(newFileName)) {
  2903. auto err = cmStrCat("Failed to create link '", newFileName,
  2904. "' because existing path cannot be removed: ",
  2905. cmSystemTools::GetLastSystemError(), '\n');
  2906. if (!arguments.Result.empty()) {
  2907. status.GetMakefile().AddDefinition(arguments.Result, err);
  2908. return true;
  2909. }
  2910. status.SetError(err);
  2911. return false;
  2912. }
  2913. // Whether the operation completed successfully.
  2914. bool completed = false;
  2915. // Check if the command requires a symbolic link.
  2916. if (arguments.Symbolic) {
  2917. cmsys::Status linked =
  2918. cmSystemTools::CreateSymlinkQuietly(fileName, newFileName);
  2919. if (linked) {
  2920. completed = true;
  2921. } else {
  2922. result = cmStrCat("failed to create symbolic link '", newFileName,
  2923. "': ", linked.GetString());
  2924. }
  2925. } else {
  2926. cmsys::Status linked =
  2927. cmSystemTools::CreateLinkQuietly(fileName, newFileName);
  2928. if (linked) {
  2929. completed = true;
  2930. } else {
  2931. result = cmStrCat("failed to create link '", newFileName,
  2932. "': ", linked.GetString());
  2933. }
  2934. }
  2935. // Check if copy-on-error is enabled in the arguments.
  2936. if (!completed && arguments.CopyOnError) {
  2937. cmsys::Status copied =
  2938. cmsys::SystemTools::CopyFileAlways(fileName, newFileName);
  2939. if (copied) {
  2940. completed = true;
  2941. } else {
  2942. result = "Copy failed: " + copied.GetString();
  2943. }
  2944. }
  2945. // Check if the operation was successful.
  2946. if (completed) {
  2947. result = "0";
  2948. } else if (arguments.Result.empty()) {
  2949. // The operation failed and the result is not reported in a variable.
  2950. status.SetError(result);
  2951. return false;
  2952. }
  2953. if (!arguments.Result.empty()) {
  2954. status.GetMakefile().AddDefinition(arguments.Result, result);
  2955. }
  2956. return true;
  2957. }
  2958. bool HandleGetRuntimeDependenciesCommand(std::vector<std::string> const& args,
  2959. cmExecutionStatus& status)
  2960. {
  2961. std::string platform =
  2962. status.GetMakefile().GetSafeDefinition("CMAKE_HOST_SYSTEM_NAME");
  2963. if (!cmRuntimeDependencyArchive::PlatformSupportsRuntimeDependencies(
  2964. platform)) {
  2965. status.SetError(
  2966. cmStrCat("GET_RUNTIME_DEPENDENCIES is not supported on system \"",
  2967. platform, '"'));
  2968. cmSystemTools::SetFatalErrorOccurred();
  2969. return false;
  2970. }
  2971. if (status.GetMakefile().GetState()->GetMode() == cmState::Project) {
  2972. status.GetMakefile().IssueMessage(
  2973. MessageType::AUTHOR_WARNING,
  2974. "You have used file(GET_RUNTIME_DEPENDENCIES)"
  2975. " in project mode. This is probably not what "
  2976. "you intended to do. Instead, please consider"
  2977. " using it in an install(CODE) or "
  2978. "install(SCRIPT) command. For example:"
  2979. "\n install(CODE [["
  2980. "\n file(GET_RUNTIME_DEPENDENCIES"
  2981. "\n # ..."
  2982. "\n )"
  2983. "\n ]])");
  2984. }
  2985. struct Arguments : public ArgumentParser::ParseResult
  2986. {
  2987. std::string ResolvedDependenciesVar;
  2988. std::string UnresolvedDependenciesVar;
  2989. std::string ConflictingDependenciesPrefix;
  2990. std::string RPathPrefix;
  2991. std::string BundleExecutable;
  2992. ArgumentParser::MaybeEmpty<std::vector<std::string>> Executables;
  2993. ArgumentParser::MaybeEmpty<std::vector<std::string>> Libraries;
  2994. ArgumentParser::MaybeEmpty<std::vector<std::string>> Directories;
  2995. ArgumentParser::MaybeEmpty<std::vector<std::string>> Modules;
  2996. ArgumentParser::MaybeEmpty<std::vector<std::string>> PreIncludeRegexes;
  2997. ArgumentParser::MaybeEmpty<std::vector<std::string>> PreExcludeRegexes;
  2998. ArgumentParser::MaybeEmpty<std::vector<std::string>> PostIncludeRegexes;
  2999. ArgumentParser::MaybeEmpty<std::vector<std::string>> PostExcludeRegexes;
  3000. ArgumentParser::MaybeEmpty<std::vector<std::string>> PostIncludeFiles;
  3001. ArgumentParser::MaybeEmpty<std::vector<std::string>> PostExcludeFiles;
  3002. ArgumentParser::MaybeEmpty<std::vector<std::string>>
  3003. PostExcludeFilesStrict;
  3004. };
  3005. static auto const parser =
  3006. cmArgumentParser<Arguments>{}
  3007. .Bind("RESOLVED_DEPENDENCIES_VAR"_s, &Arguments::ResolvedDependenciesVar)
  3008. .Bind("UNRESOLVED_DEPENDENCIES_VAR"_s,
  3009. &Arguments::UnresolvedDependenciesVar)
  3010. .Bind("CONFLICTING_DEPENDENCIES_PREFIX"_s,
  3011. &Arguments::ConflictingDependenciesPrefix)
  3012. .Bind("RPATH_PREFIX"_s, &Arguments::RPathPrefix)
  3013. .Bind("BUNDLE_EXECUTABLE"_s, &Arguments::BundleExecutable)
  3014. .Bind("EXECUTABLES"_s, &Arguments::Executables)
  3015. .Bind("LIBRARIES"_s, &Arguments::Libraries)
  3016. .Bind("MODULES"_s, &Arguments::Modules)
  3017. .Bind("DIRECTORIES"_s, &Arguments::Directories)
  3018. .Bind("PRE_INCLUDE_REGEXES"_s, &Arguments::PreIncludeRegexes)
  3019. .Bind("PRE_EXCLUDE_REGEXES"_s, &Arguments::PreExcludeRegexes)
  3020. .Bind("POST_INCLUDE_REGEXES"_s, &Arguments::PostIncludeRegexes)
  3021. .Bind("POST_EXCLUDE_REGEXES"_s, &Arguments::PostExcludeRegexes)
  3022. .Bind("POST_INCLUDE_FILES"_s, &Arguments::PostIncludeFiles)
  3023. .Bind("POST_EXCLUDE_FILES"_s, &Arguments::PostExcludeFiles)
  3024. .Bind("POST_EXCLUDE_FILES_STRICT"_s, &Arguments::PostExcludeFilesStrict);
  3025. std::vector<std::string> unrecognizedArguments;
  3026. auto parsedArgs =
  3027. parser.Parse(cmMakeRange(args).advance(1), &unrecognizedArguments);
  3028. auto argIt = unrecognizedArguments.begin();
  3029. if (argIt != unrecognizedArguments.end()) {
  3030. status.SetError(cmStrCat("Unrecognized argument: \"", *argIt, '"'));
  3031. cmSystemTools::SetFatalErrorOccurred();
  3032. return false;
  3033. }
  3034. if (parsedArgs.MaybeReportError(status.GetMakefile())) {
  3035. cmSystemTools::SetFatalErrorOccurred();
  3036. return true;
  3037. }
  3038. cmRuntimeDependencyArchive archive(
  3039. status, parsedArgs.Directories, parsedArgs.BundleExecutable,
  3040. parsedArgs.PreIncludeRegexes, parsedArgs.PreExcludeRegexes,
  3041. parsedArgs.PostIncludeRegexes, parsedArgs.PostExcludeRegexes,
  3042. std::move(parsedArgs.PostIncludeFiles),
  3043. std::move(parsedArgs.PostExcludeFiles),
  3044. std::move(parsedArgs.PostExcludeFilesStrict));
  3045. if (!archive.Prepare()) {
  3046. cmSystemTools::SetFatalErrorOccurred();
  3047. return false;
  3048. }
  3049. if (!archive.GetRuntimeDependencies(
  3050. parsedArgs.Executables, parsedArgs.Libraries, parsedArgs.Modules)) {
  3051. cmSystemTools::SetFatalErrorOccurred();
  3052. return false;
  3053. }
  3054. std::vector<std::string> deps;
  3055. std::vector<std::string> unresolvedDeps;
  3056. std::vector<std::string> conflictingDeps;
  3057. for (auto const& val : archive.GetResolvedPaths()) {
  3058. bool unique = true;
  3059. auto it = val.second.begin();
  3060. assert(it != val.second.end());
  3061. auto const& firstPath = *it;
  3062. while (++it != val.second.end()) {
  3063. if (!cmSystemTools::SameFile(firstPath, *it)) {
  3064. unique = false;
  3065. break;
  3066. }
  3067. }
  3068. if (unique) {
  3069. deps.push_back(firstPath);
  3070. if (!parsedArgs.RPathPrefix.empty()) {
  3071. status.GetMakefile().AddDefinition(
  3072. parsedArgs.RPathPrefix + "_" + firstPath,
  3073. cmList::to_string(archive.GetRPaths().at(firstPath)));
  3074. }
  3075. } else if (!parsedArgs.ConflictingDependenciesPrefix.empty()) {
  3076. conflictingDeps.push_back(val.first);
  3077. std::vector<std::string> paths;
  3078. paths.insert(paths.begin(), val.second.begin(), val.second.end());
  3079. std::string varName =
  3080. parsedArgs.ConflictingDependenciesPrefix + "_" + val.first;
  3081. std::string pathsStr = cmList::to_string(paths);
  3082. status.GetMakefile().AddDefinition(varName, pathsStr);
  3083. } else {
  3084. std::ostringstream e;
  3085. e << "Multiple conflicting paths found for " << val.first << ":";
  3086. for (auto const& path : val.second) {
  3087. e << "\n " << path;
  3088. }
  3089. status.SetError(e.str());
  3090. cmSystemTools::SetFatalErrorOccurred();
  3091. return false;
  3092. }
  3093. }
  3094. if (!archive.GetUnresolvedPaths().empty()) {
  3095. if (!parsedArgs.UnresolvedDependenciesVar.empty()) {
  3096. unresolvedDeps.insert(unresolvedDeps.begin(),
  3097. archive.GetUnresolvedPaths().begin(),
  3098. archive.GetUnresolvedPaths().end());
  3099. } else {
  3100. std::ostringstream e;
  3101. e << "Could not resolve runtime dependencies:";
  3102. for (auto const& path : archive.GetUnresolvedPaths()) {
  3103. e << "\n " << path;
  3104. }
  3105. status.SetError(e.str());
  3106. cmSystemTools::SetFatalErrorOccurred();
  3107. return false;
  3108. }
  3109. }
  3110. if (!parsedArgs.ResolvedDependenciesVar.empty()) {
  3111. std::string val = cmList::to_string(deps);
  3112. status.GetMakefile().AddDefinition(parsedArgs.ResolvedDependenciesVar,
  3113. val);
  3114. }
  3115. if (!parsedArgs.UnresolvedDependenciesVar.empty()) {
  3116. std::string val = cmList::to_string(unresolvedDeps);
  3117. status.GetMakefile().AddDefinition(parsedArgs.UnresolvedDependenciesVar,
  3118. val);
  3119. }
  3120. if (!parsedArgs.ConflictingDependenciesPrefix.empty()) {
  3121. std::string val = cmList::to_string(conflictingDeps);
  3122. status.GetMakefile().AddDefinition(
  3123. parsedArgs.ConflictingDependenciesPrefix + "_FILENAMES", val);
  3124. }
  3125. return true;
  3126. }
  3127. bool HandleConfigureCommand(std::vector<std::string> const& args,
  3128. cmExecutionStatus& status)
  3129. {
  3130. struct Arguments : public ArgumentParser::ParseResult
  3131. {
  3132. cm::optional<std::string> Output;
  3133. cm::optional<std::string> Content;
  3134. bool EscapeQuotes = false;
  3135. bool AtOnly = false;
  3136. // "NEWLINE_STYLE" requires one value, but we use a custom check below.
  3137. ArgumentParser::Maybe<std::string> NewlineStyle;
  3138. };
  3139. static auto const parser =
  3140. cmArgumentParser<Arguments>{}
  3141. .Bind("OUTPUT"_s, &Arguments::Output)
  3142. .Bind("CONTENT"_s, &Arguments::Content)
  3143. .Bind("ESCAPE_QUOTES"_s, &Arguments::EscapeQuotes)
  3144. .Bind("@ONLY"_s, &Arguments::AtOnly)
  3145. .Bind("NEWLINE_STYLE"_s, &Arguments::NewlineStyle);
  3146. std::vector<std::string> unrecognizedArguments;
  3147. auto parsedArgs =
  3148. parser.Parse(cmMakeRange(args).advance(1), &unrecognizedArguments);
  3149. auto argIt = unrecognizedArguments.begin();
  3150. if (argIt != unrecognizedArguments.end()) {
  3151. status.SetError(
  3152. cmStrCat("CONFIGURE Unrecognized argument: \"", *argIt, '"'));
  3153. cmSystemTools::SetFatalErrorOccurred();
  3154. return false;
  3155. }
  3156. if (parsedArgs.MaybeReportError(status.GetMakefile())) {
  3157. cmSystemTools::SetFatalErrorOccurred();
  3158. return true;
  3159. }
  3160. if (!parsedArgs.Output) {
  3161. status.SetError("CONFIGURE OUTPUT option is mandatory.");
  3162. cmSystemTools::SetFatalErrorOccurred();
  3163. return false;
  3164. }
  3165. if (!parsedArgs.Content) {
  3166. status.SetError("CONFIGURE CONTENT option is mandatory.");
  3167. cmSystemTools::SetFatalErrorOccurred();
  3168. return false;
  3169. }
  3170. std::string errorMessage;
  3171. cmNewLineStyle newLineStyle;
  3172. if (!newLineStyle.ReadFromArguments(args, errorMessage)) {
  3173. status.SetError(cmStrCat("CONFIGURE ", errorMessage));
  3174. return false;
  3175. }
  3176. // Check for generator expressions
  3177. std::string outputFile = cmSystemTools::CollapseFullPath(
  3178. *parsedArgs.Output, status.GetMakefile().GetCurrentBinaryDirectory());
  3179. std::string::size_type pos = outputFile.find_first_of("<>");
  3180. if (pos != std::string::npos) {
  3181. status.SetError(cmStrCat("CONFIGURE called with OUTPUT containing a \"",
  3182. outputFile[pos],
  3183. "\". This character is not allowed."));
  3184. return false;
  3185. }
  3186. cmMakefile& makeFile = status.GetMakefile();
  3187. if (!makeFile.CanIWriteThisFile(outputFile)) {
  3188. cmSystemTools::Error("Attempt to write file: " + outputFile +
  3189. " into a source directory.");
  3190. return false;
  3191. }
  3192. cmSystemTools::ConvertToUnixSlashes(outputFile);
  3193. // Re-generate if non-temporary outputs are missing.
  3194. // when we finalize the configuration we will remove all
  3195. // output files that now don't exist.
  3196. makeFile.AddCMakeOutputFile(outputFile);
  3197. // Create output directory
  3198. std::string::size_type const slashPos = outputFile.rfind('/');
  3199. if (slashPos != std::string::npos) {
  3200. std::string const path = outputFile.substr(0, slashPos);
  3201. cmSystemTools::MakeDirectory(path);
  3202. }
  3203. std::string newLineCharacters = "\n";
  3204. bool open_with_binary_flag = false;
  3205. if (newLineStyle.IsValid()) {
  3206. newLineCharacters = newLineStyle.GetCharacters();
  3207. open_with_binary_flag = true;
  3208. }
  3209. cmGeneratedFileStream fout;
  3210. fout.Open(outputFile, false, open_with_binary_flag);
  3211. if (!fout) {
  3212. cmSystemTools::Error("Could not open file for write in copy operation " +
  3213. outputFile);
  3214. cmSystemTools::ReportLastSystemError("");
  3215. return false;
  3216. }
  3217. fout.SetCopyIfDifferent(true);
  3218. // copy input to output and expand variables from input at the same time
  3219. std::stringstream sin(*parsedArgs.Content, std::ios::in);
  3220. std::string inLine;
  3221. std::string outLine;
  3222. bool hasNewLine = false;
  3223. while (cmSystemTools::GetLineFromStream(sin, inLine, &hasNewLine)) {
  3224. outLine.clear();
  3225. makeFile.ConfigureString(inLine, outLine, parsedArgs.AtOnly,
  3226. parsedArgs.EscapeQuotes);
  3227. fout << outLine;
  3228. if (hasNewLine || newLineStyle.IsValid()) {
  3229. fout << newLineCharacters;
  3230. }
  3231. }
  3232. // close file before attempting to copy
  3233. fout.close();
  3234. return true;
  3235. }
  3236. bool HandleArchiveCreateCommand(std::vector<std::string> const& args,
  3237. cmExecutionStatus& status)
  3238. {
  3239. struct Arguments : public ArgumentParser::ParseResult
  3240. {
  3241. std::string Output;
  3242. std::string Format;
  3243. std::string Compression;
  3244. std::string CompressionLevel;
  3245. // "MTIME" should require one value, but it has long been accidentally
  3246. // accepted without one and treated as if an empty value were given.
  3247. // Fixing this would require a policy.
  3248. ArgumentParser::Maybe<std::string> MTime;
  3249. std::string WorkingDirectory;
  3250. bool Verbose = false;
  3251. // "PATHS" requires at least one value, but use a custom check below.
  3252. ArgumentParser::MaybeEmpty<std::vector<std::string>> Paths;
  3253. };
  3254. static auto const parser =
  3255. cmArgumentParser<Arguments>{}
  3256. .Bind("OUTPUT"_s, &Arguments::Output)
  3257. .Bind("FORMAT"_s, &Arguments::Format)
  3258. .Bind("COMPRESSION"_s, &Arguments::Compression)
  3259. .Bind("COMPRESSION_LEVEL"_s, &Arguments::CompressionLevel)
  3260. .Bind("MTIME"_s, &Arguments::MTime)
  3261. .Bind("WORKING_DIRECTORY"_s, &Arguments::WorkingDirectory)
  3262. .Bind("VERBOSE"_s, &Arguments::Verbose)
  3263. .Bind("PATHS"_s, &Arguments::Paths);
  3264. std::vector<std::string> unrecognizedArguments;
  3265. auto parsedArgs =
  3266. parser.Parse(cmMakeRange(args).advance(1), &unrecognizedArguments);
  3267. auto argIt = unrecognizedArguments.begin();
  3268. if (argIt != unrecognizedArguments.end()) {
  3269. status.SetError(cmStrCat("Unrecognized argument: \"", *argIt, '"'));
  3270. cmSystemTools::SetFatalErrorOccurred();
  3271. return false;
  3272. }
  3273. if (parsedArgs.MaybeReportError(status.GetMakefile())) {
  3274. cmSystemTools::SetFatalErrorOccurred();
  3275. return true;
  3276. }
  3277. char const* knownFormats[] = {
  3278. "7zip", "gnutar", "pax", "paxr", "raw", "zip"
  3279. };
  3280. if (!parsedArgs.Format.empty() &&
  3281. !cm::contains(knownFormats, parsedArgs.Format)) {
  3282. status.SetError(
  3283. cmStrCat("archive format ", parsedArgs.Format, " not supported"));
  3284. cmSystemTools::SetFatalErrorOccurred();
  3285. return false;
  3286. }
  3287. char const* zipFileFormats[] = { "7zip", "zip" };
  3288. if (!parsedArgs.Compression.empty() &&
  3289. cm::contains(zipFileFormats, parsedArgs.Format)) {
  3290. status.SetError(cmStrCat("archive format ", parsedArgs.Format,
  3291. " does not support COMPRESSION arguments"));
  3292. cmSystemTools::SetFatalErrorOccurred();
  3293. return false;
  3294. }
  3295. static std::map<std::string, cmSystemTools::cmTarCompression>
  3296. compressionTypeMap = { { "None", cmSystemTools::TarCompressNone },
  3297. { "BZip2", cmSystemTools::TarCompressBZip2 },
  3298. { "GZip", cmSystemTools::TarCompressGZip },
  3299. { "XZ", cmSystemTools::TarCompressXZ },
  3300. { "Zstd", cmSystemTools::TarCompressZstd } };
  3301. cmSystemTools::cmTarCompression compress = cmSystemTools::TarCompressNone;
  3302. auto typeIt = compressionTypeMap.find(parsedArgs.Compression);
  3303. if (typeIt != compressionTypeMap.end()) {
  3304. compress = typeIt->second;
  3305. } else if (!parsedArgs.Compression.empty()) {
  3306. status.SetError(cmStrCat("compression type ", parsedArgs.Compression,
  3307. " is not supported"));
  3308. cmSystemTools::SetFatalErrorOccurred();
  3309. return false;
  3310. }
  3311. int compressionLevel = 0;
  3312. int minCompressionLevel = 0;
  3313. int maxCompressionLevel = 9;
  3314. if (compress == cmSystemTools::TarCompressZstd) {
  3315. maxCompressionLevel = 19;
  3316. }
  3317. if (!parsedArgs.CompressionLevel.empty()) {
  3318. if (parsedArgs.CompressionLevel.size() != 1 &&
  3319. !std::isdigit(parsedArgs.CompressionLevel[0])) {
  3320. status.SetError(
  3321. cmStrCat("compression level ", parsedArgs.CompressionLevel, " for ",
  3322. parsedArgs.Compression, " should be in range ",
  3323. minCompressionLevel, " to ", maxCompressionLevel));
  3324. cmSystemTools::SetFatalErrorOccurred();
  3325. return false;
  3326. }
  3327. compressionLevel = std::stoi(parsedArgs.CompressionLevel);
  3328. if (compressionLevel < minCompressionLevel ||
  3329. compressionLevel > maxCompressionLevel) {
  3330. status.SetError(
  3331. cmStrCat("compression level ", parsedArgs.CompressionLevel, " for ",
  3332. parsedArgs.Compression, " should be in range ",
  3333. minCompressionLevel, " to ", maxCompressionLevel));
  3334. cmSystemTools::SetFatalErrorOccurred();
  3335. return false;
  3336. }
  3337. if (compress == cmSystemTools::TarCompressNone) {
  3338. status.SetError(cmStrCat("compression level is not supported for "
  3339. "compression \"None\"",
  3340. parsedArgs.Compression));
  3341. cmSystemTools::SetFatalErrorOccurred();
  3342. return false;
  3343. }
  3344. }
  3345. if (parsedArgs.Paths.empty()) {
  3346. status.SetError("ARCHIVE_CREATE requires a non-empty list of PATHS");
  3347. cmSystemTools::SetFatalErrorOccurred();
  3348. return false;
  3349. }
  3350. if (!cmSystemTools::CreateTar(parsedArgs.Output, parsedArgs.Paths,
  3351. parsedArgs.WorkingDirectory, compress,
  3352. parsedArgs.Verbose, parsedArgs.MTime,
  3353. parsedArgs.Format, compressionLevel)) {
  3354. status.SetError(cmStrCat("failed to compress: ", parsedArgs.Output));
  3355. cmSystemTools::SetFatalErrorOccurred();
  3356. return false;
  3357. }
  3358. return true;
  3359. }
  3360. bool HandleArchiveExtractCommand(std::vector<std::string> const& args,
  3361. cmExecutionStatus& status)
  3362. {
  3363. struct Arguments : public ArgumentParser::ParseResult
  3364. {
  3365. std::string Input;
  3366. bool Verbose = false;
  3367. bool ListOnly = false;
  3368. std::string Destination;
  3369. ArgumentParser::MaybeEmpty<std::vector<std::string>> Patterns;
  3370. bool Touch = false;
  3371. };
  3372. static auto const parser = cmArgumentParser<Arguments>{}
  3373. .Bind("INPUT"_s, &Arguments::Input)
  3374. .Bind("VERBOSE"_s, &Arguments::Verbose)
  3375. .Bind("LIST_ONLY"_s, &Arguments::ListOnly)
  3376. .Bind("DESTINATION"_s, &Arguments::Destination)
  3377. .Bind("PATTERNS"_s, &Arguments::Patterns)
  3378. .Bind("TOUCH"_s, &Arguments::Touch);
  3379. std::vector<std::string> unrecognizedArguments;
  3380. auto parsedArgs =
  3381. parser.Parse(cmMakeRange(args).advance(1), &unrecognizedArguments);
  3382. auto argIt = unrecognizedArguments.begin();
  3383. if (argIt != unrecognizedArguments.end()) {
  3384. status.SetError(cmStrCat("Unrecognized argument: \"", *argIt, '"'));
  3385. cmSystemTools::SetFatalErrorOccurred();
  3386. return false;
  3387. }
  3388. if (parsedArgs.MaybeReportError(status.GetMakefile())) {
  3389. cmSystemTools::SetFatalErrorOccurred();
  3390. return true;
  3391. }
  3392. std::string inFile = parsedArgs.Input;
  3393. if (parsedArgs.ListOnly) {
  3394. if (!cmSystemTools::ListTar(inFile, parsedArgs.Patterns,
  3395. parsedArgs.Verbose)) {
  3396. status.SetError(cmStrCat("failed to list: ", inFile));
  3397. cmSystemTools::SetFatalErrorOccurred();
  3398. return false;
  3399. }
  3400. } else {
  3401. std::string destDir = status.GetMakefile().GetCurrentBinaryDirectory();
  3402. if (!parsedArgs.Destination.empty()) {
  3403. if (cmSystemTools::FileIsFullPath(parsedArgs.Destination)) {
  3404. destDir = parsedArgs.Destination;
  3405. } else {
  3406. destDir = cmStrCat(destDir, '/', parsedArgs.Destination);
  3407. }
  3408. if (!cmSystemTools::MakeDirectory(destDir)) {
  3409. status.SetError(cmStrCat("failed to create directory: ", destDir));
  3410. cmSystemTools::SetFatalErrorOccurred();
  3411. return false;
  3412. }
  3413. if (!cmSystemTools::FileIsFullPath(inFile)) {
  3414. inFile =
  3415. cmStrCat(cmSystemTools::GetLogicalWorkingDirectory(), '/', inFile);
  3416. }
  3417. }
  3418. cmWorkingDirectory workdir(destDir);
  3419. if (workdir.Failed()) {
  3420. status.SetError(workdir.GetError());
  3421. cmSystemTools::SetFatalErrorOccurred();
  3422. return false;
  3423. }
  3424. if (!cmSystemTools::ExtractTar(
  3425. inFile, parsedArgs.Patterns,
  3426. parsedArgs.Touch ? cmSystemTools::cmTarExtractTimestamps::No
  3427. : cmSystemTools::cmTarExtractTimestamps::Yes,
  3428. parsedArgs.Verbose)) {
  3429. status.SetError(cmStrCat("failed to extract: ", inFile));
  3430. cmSystemTools::SetFatalErrorOccurred();
  3431. return false;
  3432. }
  3433. }
  3434. return true;
  3435. }
  3436. bool ValidateAndConvertPermissions(
  3437. cm::optional<ArgumentParser::NonEmpty<std::vector<std::string>>> const&
  3438. permissions,
  3439. mode_t& perms, cmExecutionStatus& status)
  3440. {
  3441. if (!permissions) {
  3442. return true;
  3443. }
  3444. for (auto const& i : *permissions) {
  3445. if (!cmFSPermissions::stringToModeT(i, perms)) {
  3446. status.SetError(i + " is an invalid permission specifier");
  3447. cmSystemTools::SetFatalErrorOccurred();
  3448. return false;
  3449. }
  3450. }
  3451. return true;
  3452. }
  3453. bool SetPermissions(std::string const& filename, mode_t const& perms,
  3454. cmExecutionStatus& status)
  3455. {
  3456. if (!cmSystemTools::SetPermissions(filename, perms)) {
  3457. status.SetError("Failed to set permissions for " + filename);
  3458. cmSystemTools::SetFatalErrorOccurred();
  3459. return false;
  3460. }
  3461. return true;
  3462. }
  3463. bool HandleChmodCommandImpl(std::vector<std::string> const& args, bool recurse,
  3464. cmExecutionStatus& status)
  3465. {
  3466. mode_t perms = 0;
  3467. mode_t fperms = 0;
  3468. mode_t dperms = 0;
  3469. cmsys::Glob globber;
  3470. globber.SetRecurse(recurse);
  3471. globber.SetRecurseListDirs(recurse);
  3472. struct Arguments : public ArgumentParser::ParseResult
  3473. {
  3474. cm::optional<ArgumentParser::NonEmpty<std::vector<std::string>>>
  3475. Permissions;
  3476. cm::optional<ArgumentParser::NonEmpty<std::vector<std::string>>>
  3477. FilePermissions;
  3478. cm::optional<ArgumentParser::NonEmpty<std::vector<std::string>>>
  3479. DirectoryPermissions;
  3480. };
  3481. static auto const parser =
  3482. cmArgumentParser<Arguments>{}
  3483. .Bind("PERMISSIONS"_s, &Arguments::Permissions)
  3484. .Bind("FILE_PERMISSIONS"_s, &Arguments::FilePermissions)
  3485. .Bind("DIRECTORY_PERMISSIONS"_s, &Arguments::DirectoryPermissions);
  3486. std::vector<std::string> pathEntries;
  3487. Arguments parsedArgs =
  3488. parser.Parse(cmMakeRange(args).advance(1), &pathEntries);
  3489. // check validity of arguments
  3490. if (!parsedArgs.Permissions && !parsedArgs.FilePermissions &&
  3491. !parsedArgs.DirectoryPermissions) // no permissions given
  3492. {
  3493. status.SetError("No permissions given");
  3494. cmSystemTools::SetFatalErrorOccurred();
  3495. return false;
  3496. }
  3497. if (parsedArgs.Permissions && parsedArgs.FilePermissions &&
  3498. parsedArgs.DirectoryPermissions) // all keywords are used
  3499. {
  3500. status.SetError("Remove either PERMISSIONS or FILE_PERMISSIONS or "
  3501. "DIRECTORY_PERMISSIONS from the invocation");
  3502. cmSystemTools::SetFatalErrorOccurred();
  3503. return false;
  3504. }
  3505. if (parsedArgs.MaybeReportError(status.GetMakefile())) {
  3506. cmSystemTools::SetFatalErrorOccurred();
  3507. return true;
  3508. }
  3509. // validate permissions
  3510. bool validatePermissions =
  3511. ValidateAndConvertPermissions(parsedArgs.Permissions, perms, status) &&
  3512. ValidateAndConvertPermissions(parsedArgs.FilePermissions, fperms,
  3513. status) &&
  3514. ValidateAndConvertPermissions(parsedArgs.DirectoryPermissions, dperms,
  3515. status);
  3516. if (!validatePermissions) {
  3517. return false;
  3518. }
  3519. std::vector<std::string> allPathEntries;
  3520. if (recurse) {
  3521. std::vector<std::string> tempPathEntries;
  3522. for (auto const& i : pathEntries) {
  3523. if (cmSystemTools::FileIsDirectory(i)) {
  3524. globber.FindFiles(i + "/*");
  3525. tempPathEntries = globber.GetFiles();
  3526. allPathEntries.insert(allPathEntries.end(), tempPathEntries.begin(),
  3527. tempPathEntries.end());
  3528. allPathEntries.emplace_back(i);
  3529. } else {
  3530. allPathEntries.emplace_back(i); // We validate path entries below
  3531. }
  3532. }
  3533. } else {
  3534. allPathEntries = std::move(pathEntries);
  3535. }
  3536. // chmod
  3537. for (auto const& i : allPathEntries) {
  3538. if (!(cmSystemTools::FileExists(i) || cmSystemTools::FileIsDirectory(i))) {
  3539. status.SetError(cmStrCat("does not exist:\n ", i));
  3540. cmSystemTools::SetFatalErrorOccurred();
  3541. return false;
  3542. }
  3543. if (cmSystemTools::FileExists(i, true)) {
  3544. bool success = true;
  3545. mode_t const& filePermissions =
  3546. parsedArgs.FilePermissions ? fperms : perms;
  3547. if (filePermissions) {
  3548. success = SetPermissions(i, filePermissions, status);
  3549. }
  3550. if (!success) {
  3551. return false;
  3552. }
  3553. }
  3554. else if (cmSystemTools::FileIsDirectory(i)) {
  3555. bool success = true;
  3556. mode_t const& directoryPermissions =
  3557. parsedArgs.DirectoryPermissions ? dperms : perms;
  3558. if (directoryPermissions) {
  3559. success = SetPermissions(i, directoryPermissions, status);
  3560. }
  3561. if (!success) {
  3562. return false;
  3563. }
  3564. }
  3565. }
  3566. return true;
  3567. }
  3568. bool HandleChmodCommand(std::vector<std::string> const& args,
  3569. cmExecutionStatus& status)
  3570. {
  3571. return HandleChmodCommandImpl(args, false, status);
  3572. }
  3573. bool HandleChmodRecurseCommand(std::vector<std::string> const& args,
  3574. cmExecutionStatus& status)
  3575. {
  3576. return HandleChmodCommandImpl(args, true, status);
  3577. }
  3578. } // namespace
  3579. bool cmFileCommand(std::vector<std::string> const& args,
  3580. cmExecutionStatus& status)
  3581. {
  3582. if (args.empty()) {
  3583. status.SetError(
  3584. "given no arguments, but it requires at least a sub-command.");
  3585. return false;
  3586. }
  3587. static cmSubcommandTable const subcommand{
  3588. { "WRITE"_s, HandleWriteCommand },
  3589. { "APPEND"_s, HandleAppendCommand },
  3590. { "DOWNLOAD"_s, HandleDownloadCommand },
  3591. { "UPLOAD"_s, HandleUploadCommand },
  3592. { "READ"_s, HandleReadCommand },
  3593. { "MD5"_s, HandleHashCommand },
  3594. { "SHA1"_s, HandleHashCommand },
  3595. { "SHA224"_s, HandleHashCommand },
  3596. { "SHA256"_s, HandleHashCommand },
  3597. { "SHA384"_s, HandleHashCommand },
  3598. { "SHA512"_s, HandleHashCommand },
  3599. { "SHA3_224"_s, HandleHashCommand },
  3600. { "SHA3_256"_s, HandleHashCommand },
  3601. { "SHA3_384"_s, HandleHashCommand },
  3602. { "SHA3_512"_s, HandleHashCommand },
  3603. { "STRINGS"_s, HandleStringsCommand },
  3604. { "GLOB"_s, HandleGlobCommand },
  3605. { "GLOB_RECURSE"_s, HandleGlobRecurseCommand },
  3606. { "MAKE_DIRECTORY"_s, HandleMakeDirectoryCommand },
  3607. { "RENAME"_s, HandleRename },
  3608. { "COPY_FILE"_s, HandleCopyFile },
  3609. { "REMOVE"_s, HandleRemove },
  3610. { "REMOVE_RECURSE"_s, HandleRemoveRecurse },
  3611. { "COPY"_s, HandleCopyCommand },
  3612. { "INSTALL"_s, HandleInstallCommand },
  3613. { "DIFFERENT"_s, HandleDifferentCommand },
  3614. { "RPATH_CHANGE"_s, HandleRPathChangeCommand },
  3615. { "CHRPATH"_s, HandleRPathChangeCommand },
  3616. { "RPATH_SET"_s, HandleRPathSetCommand },
  3617. { "RPATH_CHECK"_s, HandleRPathCheckCommand },
  3618. { "RPATH_REMOVE"_s, HandleRPathRemoveCommand },
  3619. { "READ_ELF"_s, HandleReadElfCommand },
  3620. { "READ_MACHO"_s, HandleReadMachoCommand },
  3621. { "REAL_PATH"_s, HandleRealPathCommand },
  3622. { "RELATIVE_PATH"_s, HandleRelativePathCommand },
  3623. { "TO_CMAKE_PATH"_s, HandleCMakePathCommand },
  3624. { "TO_NATIVE_PATH"_s, HandleNativePathCommand },
  3625. { "TOUCH"_s, HandleTouchCommand },
  3626. { "TOUCH_NOCREATE"_s, HandleTouchNocreateCommand },
  3627. { "TIMESTAMP"_s, HandleTimestampCommand },
  3628. { "GENERATE"_s, HandleGenerateCommand },
  3629. { "LOCK"_s, HandleLockCommand },
  3630. { "SIZE"_s, HandleSizeCommand },
  3631. { "READ_SYMLINK"_s, HandleReadSymlinkCommand },
  3632. { "CREATE_LINK"_s, HandleCreateLinkCommand },
  3633. { "GET_RUNTIME_DEPENDENCIES"_s, HandleGetRuntimeDependenciesCommand },
  3634. { "CONFIGURE"_s, HandleConfigureCommand },
  3635. { "ARCHIVE_CREATE"_s, HandleArchiveCreateCommand },
  3636. { "ARCHIVE_EXTRACT"_s, HandleArchiveExtractCommand },
  3637. { "CHMOD"_s, HandleChmodCommand },
  3638. { "CHMOD_RECURSE"_s, HandleChmodRecurseCommand },
  3639. };
  3640. return subcommand(args[0], args, status);
  3641. }