cmFileCommand.cxx 123 KB

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