cmFileCommand.cxx 124 KB

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