cmFileCommand.cxx 122 KB

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