cmMakefile.cxx 149 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776
  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 "cmConfigure.h" // IWYU pragma: keep
  4. #include "cmMakefile.h"
  5. #include <algorithm>
  6. #include <cassert>
  7. #include <cctype>
  8. #include <cstdio>
  9. #include <cstdlib>
  10. #include <cstring>
  11. #include <sstream>
  12. #include <utility>
  13. #include <cm/iterator>
  14. #include <cm/memory>
  15. #include <cm/optional>
  16. #include <cm/type_traits> // IWYU pragma: keep
  17. #include <cm/vector>
  18. #include <cmext/algorithm>
  19. #include <cmext/string_view>
  20. #ifndef CMAKE_BOOTSTRAP
  21. # include <cm3p/json/value.h>
  22. # include <cm3p/json/writer.h>
  23. #endif
  24. #include "cmsys/FStream.hxx"
  25. #include "cmsys/RegularExpression.hxx"
  26. #include "cmCommandArgumentParserHelper.h"
  27. #include "cmCustomCommand.h"
  28. #include "cmCustomCommandLines.h"
  29. #include "cmExecutionStatus.h"
  30. #include "cmExpandedCommandArgument.h" // IWYU pragma: keep
  31. #include "cmExportBuildFileGenerator.h"
  32. #include "cmFileLockPool.h"
  33. #include "cmFunctionBlocker.h"
  34. #include "cmGeneratedFileStream.h"
  35. #include "cmGeneratorExpression.h"
  36. #include "cmGeneratorExpressionEvaluationFile.h"
  37. #include "cmGlobalGenerator.h"
  38. #include "cmInstallGenerator.h" // IWYU pragma: keep
  39. #include "cmInstallSubdirectoryGenerator.h"
  40. #include "cmList.h"
  41. #include "cmListFileCache.h"
  42. #include "cmLocalGenerator.h"
  43. #include "cmMessageType.h"
  44. #include "cmRange.h"
  45. #include "cmSourceFile.h"
  46. #include "cmSourceFileLocation.h"
  47. #include "cmState.h"
  48. #include "cmStateDirectory.h"
  49. #include "cmStateTypes.h"
  50. #include "cmStringAlgorithms.h"
  51. #include "cmSystemTools.h"
  52. #include "cmTarget.h"
  53. #include "cmTargetLinkLibraryType.h"
  54. #include "cmTest.h"
  55. #include "cmTestGenerator.h" // IWYU pragma: keep
  56. #include "cmVersion.h"
  57. #include "cmWorkingDirectory.h"
  58. #include "cmake.h"
  59. #ifndef CMAKE_BOOTSTRAP
  60. # include "cmMakefileProfilingData.h"
  61. # include "cmVariableWatch.h"
  62. #endif
  63. #ifdef CMake_ENABLE_DEBUGGER
  64. # include "cmDebuggerAdapter.h"
  65. #endif
  66. #ifndef __has_feature
  67. # define __has_feature(x) 0
  68. #endif
  69. // Select a recursion limit that fits within the stack size.
  70. // See stack size flags in '../CompileFlags.cmake'.
  71. #ifndef CMake_DEFAULT_RECURSION_LIMIT
  72. # if __has_feature(address_sanitizer)
  73. # define CMake_DEFAULT_RECURSION_LIMIT 400
  74. # elif defined(_MSC_VER) && defined(_DEBUG)
  75. # define CMake_DEFAULT_RECURSION_LIMIT 600
  76. # elif defined(__ibmxl__) && defined(__linux)
  77. # define CMake_DEFAULT_RECURSION_LIMIT 600
  78. # else
  79. # define CMake_DEFAULT_RECURSION_LIMIT 1000
  80. # endif
  81. #endif
  82. class cmMessenger;
  83. cmDirectoryId::cmDirectoryId(std::string s)
  84. : String(std::move(s))
  85. {
  86. }
  87. // default is not to be building executables
  88. cmMakefile::cmMakefile(cmGlobalGenerator* globalGenerator,
  89. cmStateSnapshot const& snapshot)
  90. : GlobalGenerator(globalGenerator)
  91. , StateSnapshot(snapshot)
  92. {
  93. this->IsSourceFileTryCompile = false;
  94. this->CheckSystemVars = this->GetCMakeInstance()->GetCheckSystemVars();
  95. this->SuppressSideEffects = false;
  96. // Setup the default include complaint regular expression (match nothing).
  97. this->ComplainFileRegularExpression = "^$";
  98. this->DefineFlags = " ";
  99. this->cmDefineRegex.compile("#([ \t]*)cmakedefine[ \t]+([A-Za-z_0-9]*)");
  100. this->cmDefine01Regex.compile("#([ \t]*)cmakedefine01[ \t]+([A-Za-z_0-9]*)");
  101. this->cmAtVarRegex.compile("(@[A-Za-z_0-9/.+-]+@)");
  102. this->cmNamedCurly.compile("^[A-Za-z0-9/_.+-]+{");
  103. this->StateSnapshot =
  104. this->StateSnapshot.GetState()->CreatePolicyScopeSnapshot(
  105. this->StateSnapshot);
  106. // Enter a policy level for this directory.
  107. this->PushPolicy();
  108. // push empty loop block
  109. this->PushLoopBlockBarrier();
  110. // By default the check is not done. It is enabled by
  111. // cmListFileCache in the top level if necessary.
  112. this->CheckCMP0000 = false;
  113. #if !defined(CMAKE_BOOTSTRAP)
  114. this->AddSourceGroup("", "^.*$");
  115. this->AddSourceGroup("Source Files", CM_SOURCE_REGEX);
  116. this->AddSourceGroup("Header Files", CM_HEADER_REGEX);
  117. this->AddSourceGroup("Precompile Header File", CM_PCH_REGEX);
  118. this->AddSourceGroup("CMake Rules", "\\.rule$");
  119. this->AddSourceGroup("Resources", CM_RESOURCE_REGEX);
  120. this->AddSourceGroup("Object Files", "\\.(lo|o|obj)$");
  121. this->ObjectLibrariesSourceGroupIndex = this->SourceGroups.size();
  122. this->SourceGroups.emplace_back("Object Libraries", "^MATCH_NO_SOURCES$");
  123. #endif
  124. }
  125. cmMakefile::~cmMakefile() = default;
  126. cmDirectoryId cmMakefile::GetDirectoryId() const
  127. {
  128. // Use the instance pointer value to uniquely identify this directory.
  129. // If we ever need to expose this to CMake language code we should
  130. // add a read-only property in cmMakefile::GetProperty.
  131. char buf[32];
  132. snprintf(buf, sizeof(buf), "(%p)",
  133. static_cast<void const*>(this)); // cast avoids format warning
  134. return std::string(buf);
  135. }
  136. void cmMakefile::IssueMessage(MessageType t, std::string const& text) const
  137. {
  138. if (!this->ExecutionStatusStack.empty()) {
  139. if ((t == MessageType::FATAL_ERROR) ||
  140. (t == MessageType::INTERNAL_ERROR)) {
  141. this->ExecutionStatusStack.back()->SetNestedError();
  142. }
  143. }
  144. this->GetCMakeInstance()->IssueMessage(t, text, this->Backtrace);
  145. }
  146. Message::LogLevel cmMakefile::GetCurrentLogLevel() const
  147. {
  148. const cmake* cmakeInstance = this->GetCMakeInstance();
  149. const Message::LogLevel logLevelCliOrDefault = cmakeInstance->GetLogLevel();
  150. assert("Expected a valid log level here" &&
  151. logLevelCliOrDefault != Message::LogLevel::LOG_UNDEFINED);
  152. Message::LogLevel result = logLevelCliOrDefault;
  153. // If the log-level was set via the command line option, it takes precedence
  154. // over the CMAKE_MESSAGE_LOG_LEVEL variable.
  155. if (!cmakeInstance->WasLogLevelSetViaCLI()) {
  156. const Message::LogLevel logLevelFromVar = cmake::StringToLogLevel(
  157. this->GetSafeDefinition("CMAKE_MESSAGE_LOG_LEVEL"));
  158. if (logLevelFromVar != Message::LogLevel::LOG_UNDEFINED) {
  159. result = logLevelFromVar;
  160. }
  161. }
  162. return result;
  163. }
  164. bool cmMakefile::CheckCMP0037(std::string const& targetName,
  165. cmStateEnums::TargetType targetType) const
  166. {
  167. MessageType messageType = MessageType::AUTHOR_WARNING;
  168. std::ostringstream e;
  169. bool issueMessage = false;
  170. switch (this->GetPolicyStatus(cmPolicies::CMP0037)) {
  171. case cmPolicies::WARN:
  172. if (targetType != cmStateEnums::INTERFACE_LIBRARY) {
  173. e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0037) << "\n";
  174. issueMessage = true;
  175. }
  176. CM_FALLTHROUGH;
  177. case cmPolicies::OLD:
  178. break;
  179. case cmPolicies::NEW:
  180. case cmPolicies::REQUIRED_IF_USED:
  181. case cmPolicies::REQUIRED_ALWAYS:
  182. issueMessage = true;
  183. messageType = MessageType::FATAL_ERROR;
  184. break;
  185. }
  186. if (issueMessage) {
  187. e << "The target name \"" << targetName
  188. << "\" is reserved or not valid for certain "
  189. "CMake features, such as generator expressions, and may result "
  190. "in undefined behavior.";
  191. this->IssueMessage(messageType, e.str());
  192. if (messageType == MessageType::FATAL_ERROR) {
  193. return false;
  194. }
  195. }
  196. return true;
  197. }
  198. void cmMakefile::MaybeWarnCMP0074(std::string const& rootVar, cmValue rootDef,
  199. cm::optional<std::string> const& rootEnv)
  200. {
  201. // Warn if a <PackageName>_ROOT variable we may use is set.
  202. if ((rootDef || rootEnv) && this->WarnedCMP0074.insert(rootVar).second) {
  203. std::ostringstream w;
  204. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0074) << "\n";
  205. if (rootDef) {
  206. w << "CMake variable " << rootVar << " is set to:\n"
  207. << " " << *rootDef << "\n";
  208. }
  209. if (rootEnv) {
  210. w << "Environment variable " << rootVar << " is set to:\n"
  211. << " " << *rootEnv << "\n";
  212. }
  213. w << "For compatibility, CMake is ignoring the variable.";
  214. this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  215. }
  216. }
  217. void cmMakefile::MaybeWarnCMP0144(std::string const& rootVAR, cmValue rootDEF,
  218. cm::optional<std::string> const& rootENV)
  219. {
  220. // Warn if a <PACKAGENAME>_ROOT variable we may use is set.
  221. if ((rootDEF || rootENV) && this->WarnedCMP0144.insert(rootVAR).second) {
  222. std::ostringstream w;
  223. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0144) << "\n";
  224. if (rootDEF) {
  225. w << "CMake variable " << rootVAR << " is set to:\n"
  226. << " " << *rootDEF << "\n";
  227. }
  228. if (rootENV) {
  229. w << "Environment variable " << rootVAR << " is set to:\n"
  230. << " " << *rootENV << "\n";
  231. }
  232. w << "For compatibility, find_package is ignoring the variable, but "
  233. "code in a .cmake module might still use it.";
  234. this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  235. }
  236. }
  237. cmBTStringRange cmMakefile::GetIncludeDirectoriesEntries() const
  238. {
  239. return this->StateSnapshot.GetDirectory().GetIncludeDirectoriesEntries();
  240. }
  241. cmBTStringRange cmMakefile::GetCompileOptionsEntries() const
  242. {
  243. return this->StateSnapshot.GetDirectory().GetCompileOptionsEntries();
  244. }
  245. cmBTStringRange cmMakefile::GetCompileDefinitionsEntries() const
  246. {
  247. return this->StateSnapshot.GetDirectory().GetCompileDefinitionsEntries();
  248. }
  249. cmBTStringRange cmMakefile::GetLinkOptionsEntries() const
  250. {
  251. return this->StateSnapshot.GetDirectory().GetLinkOptionsEntries();
  252. }
  253. cmBTStringRange cmMakefile::GetLinkDirectoriesEntries() const
  254. {
  255. return this->StateSnapshot.GetDirectory().GetLinkDirectoriesEntries();
  256. }
  257. cmListFileBacktrace cmMakefile::GetBacktrace() const
  258. {
  259. return this->Backtrace;
  260. }
  261. void cmMakefile::PrintCommandTrace(cmListFileFunction const& lff,
  262. cmListFileBacktrace const& bt,
  263. CommandMissingFromStack missing) const
  264. {
  265. // Check if current file in the list of requested to trace...
  266. std::vector<std::string> const& trace_only_this_files =
  267. this->GetCMakeInstance()->GetTraceSources();
  268. std::string const& full_path = bt.Top().FilePath;
  269. std::string const& only_filename = cmSystemTools::GetFilenameName(full_path);
  270. bool trace = trace_only_this_files.empty();
  271. if (!trace) {
  272. for (std::string const& file : trace_only_this_files) {
  273. std::string::size_type const pos = full_path.rfind(file);
  274. trace = (pos != std::string::npos) &&
  275. ((pos + file.size()) == full_path.size()) &&
  276. (only_filename == cmSystemTools::GetFilenameName(file));
  277. if (trace) {
  278. break;
  279. }
  280. }
  281. // Do nothing if current file wasn't requested for trace...
  282. if (!trace) {
  283. return;
  284. }
  285. }
  286. std::ostringstream msg;
  287. std::vector<std::string> args;
  288. std::string temp;
  289. bool expand = this->GetCMakeInstance()->GetTraceExpand();
  290. args.reserve(lff.Arguments().size());
  291. for (cmListFileArgument const& arg : lff.Arguments()) {
  292. if (expand && arg.Delim != cmListFileArgument::Bracket) {
  293. temp = arg.Value;
  294. this->ExpandVariablesInString(temp);
  295. args.push_back(temp);
  296. } else {
  297. args.push_back(arg.Value);
  298. }
  299. }
  300. cm::optional<std::string> const& deferId = bt.Top().DeferId;
  301. switch (this->GetCMakeInstance()->GetTraceFormat()) {
  302. case cmake::TraceFormat::JSONv1: {
  303. #ifndef CMAKE_BOOTSTRAP
  304. Json::Value val;
  305. Json::StreamWriterBuilder builder;
  306. builder["indentation"] = "";
  307. val["file"] = full_path;
  308. val["line"] = static_cast<Json::Value::Int64>(lff.Line());
  309. if (lff.Line() != lff.LineEnd()) {
  310. val["line_end"] = static_cast<Json::Value::Int64>(lff.LineEnd());
  311. }
  312. if (deferId) {
  313. val["defer"] = *deferId;
  314. }
  315. val["cmd"] = lff.OriginalName();
  316. val["args"] = Json::Value(Json::arrayValue);
  317. for (std::string const& arg : args) {
  318. val["args"].append(arg);
  319. }
  320. val["time"] = cmSystemTools::GetTime();
  321. val["frame"] = (missing == CommandMissingFromStack::Yes ? 1 : 0) +
  322. static_cast<Json::Value::UInt64>(this->ExecutionStatusStack.size());
  323. val["global_frame"] = (missing == CommandMissingFromStack::Yes ? 1 : 0) +
  324. static_cast<Json::Value::UInt64>(this->RecursionDepth);
  325. msg << Json::writeString(builder, val);
  326. #endif
  327. break;
  328. }
  329. case cmake::TraceFormat::Human:
  330. msg << full_path << "(" << lff.Line() << "):";
  331. if (deferId) {
  332. msg << "DEFERRED:" << *deferId << ":";
  333. }
  334. msg << " " << lff.OriginalName() << "(";
  335. for (std::string const& arg : args) {
  336. msg << arg << " ";
  337. }
  338. msg << ")";
  339. break;
  340. case cmake::TraceFormat::Undefined:
  341. msg << "INTERNAL ERROR: Trace format is Undefined";
  342. break;
  343. }
  344. auto& f = this->GetCMakeInstance()->GetTraceFile();
  345. if (f) {
  346. f << msg.str() << '\n';
  347. } else {
  348. cmSystemTools::Message(msg.str());
  349. }
  350. }
  351. // Helper class to make sure the call stack is valid.
  352. class cmMakefileCall
  353. {
  354. public:
  355. cmMakefileCall(cmMakefile* mf, cmListFileFunction const& lff,
  356. cm::optional<std::string> deferId, cmExecutionStatus& status)
  357. : Makefile(mf)
  358. {
  359. cmListFileContext const& lfc = cmListFileContext::FromListFileFunction(
  360. lff, this->Makefile->StateSnapshot.GetExecutionListFile(),
  361. std::move(deferId));
  362. this->Makefile->Backtrace = this->Makefile->Backtrace.Push(lfc);
  363. ++this->Makefile->RecursionDepth;
  364. this->Makefile->ExecutionStatusStack.push_back(&status);
  365. #if !defined(CMAKE_BOOTSTRAP)
  366. this->ProfilingDataRAII =
  367. this->Makefile->GetCMakeInstance()->CreateProfilingEntry(
  368. "script", lff.LowerCaseName(), [&lff, &lfc]() -> Json::Value {
  369. Json::Value argsValue = Json::objectValue;
  370. if (!lff.Arguments().empty()) {
  371. std::string args;
  372. for (auto const& a : lff.Arguments()) {
  373. args = cmStrCat(args, args.empty() ? "" : " ", a.Value);
  374. }
  375. argsValue["functionArgs"] = args;
  376. }
  377. argsValue["location"] =
  378. cmStrCat(lfc.FilePath, ':', std::to_string(lfc.Line));
  379. return argsValue;
  380. });
  381. #endif
  382. #ifdef CMake_ENABLE_DEBUGGER
  383. if (this->Makefile->GetCMakeInstance()->GetDebugAdapter() != nullptr) {
  384. this->Makefile->GetCMakeInstance()
  385. ->GetDebugAdapter()
  386. ->OnBeginFunctionCall(mf, lfc.FilePath, lff);
  387. }
  388. #endif
  389. }
  390. ~cmMakefileCall()
  391. {
  392. #if !defined(CMAKE_BOOTSTRAP)
  393. this->ProfilingDataRAII.reset();
  394. #endif
  395. this->Makefile->ExecutionStatusStack.pop_back();
  396. --this->Makefile->RecursionDepth;
  397. this->Makefile->Backtrace = this->Makefile->Backtrace.Pop();
  398. #ifdef CMake_ENABLE_DEBUGGER
  399. if (this->Makefile->GetCMakeInstance()->GetDebugAdapter() != nullptr) {
  400. this->Makefile->GetCMakeInstance()
  401. ->GetDebugAdapter()
  402. ->OnEndFunctionCall();
  403. }
  404. #endif
  405. }
  406. cmMakefileCall(const cmMakefileCall&) = delete;
  407. cmMakefileCall& operator=(const cmMakefileCall&) = delete;
  408. private:
  409. cmMakefile* Makefile;
  410. #if !defined(CMAKE_BOOTSTRAP)
  411. cm::optional<cmMakefileProfilingData::RAII> ProfilingDataRAII;
  412. #endif
  413. };
  414. void cmMakefile::OnExecuteCommand(std::function<void()> callback)
  415. {
  416. this->ExecuteCommandCallback = std::move(callback);
  417. }
  418. bool cmMakefile::ExecuteCommand(const cmListFileFunction& lff,
  419. cmExecutionStatus& status,
  420. cm::optional<std::string> deferId)
  421. {
  422. bool result = true;
  423. // quick return if blocked
  424. if (this->IsFunctionBlocked(lff, status)) {
  425. // No error.
  426. return result;
  427. }
  428. if (this->ExecuteCommandCallback) {
  429. this->ExecuteCommandCallback();
  430. }
  431. // Place this call on the call stack.
  432. cmMakefileCall stack_manager(this, lff, std::move(deferId), status);
  433. static_cast<void>(stack_manager);
  434. // Check for maximum recursion depth.
  435. size_t depthLimit = this->GetRecursionDepthLimit();
  436. if (this->RecursionDepth > depthLimit) {
  437. std::ostringstream e;
  438. e << "Maximum recursion depth of " << depthLimit << " exceeded";
  439. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  440. cmSystemTools::SetFatalErrorOccurred();
  441. return false;
  442. }
  443. // Lookup the command prototype.
  444. if (cmState::Command command =
  445. this->GetState()->GetCommandByExactName(lff.LowerCaseName())) {
  446. // Decide whether to invoke the command.
  447. if (!cmSystemTools::GetFatalErrorOccurred()) {
  448. // if trace is enabled, print out invoke information
  449. if (this->GetCMakeInstance()->GetTrace()) {
  450. this->PrintCommandTrace(lff, this->Backtrace);
  451. }
  452. // Try invoking the command.
  453. bool invokeSucceeded = command(lff.Arguments(), status);
  454. bool hadNestedError = status.GetNestedError();
  455. if (!invokeSucceeded || hadNestedError) {
  456. if (!hadNestedError) {
  457. // The command invocation requested that we report an error.
  458. std::string const error =
  459. cmStrCat(lff.OriginalName(), ' ', status.GetError());
  460. this->IssueMessage(MessageType::FATAL_ERROR, error);
  461. }
  462. result = false;
  463. if (this->GetCMakeInstance()->GetWorkingMode() != cmake::NORMAL_MODE) {
  464. cmSystemTools::SetFatalErrorOccurred();
  465. }
  466. }
  467. }
  468. } else {
  469. if (!cmSystemTools::GetFatalErrorOccurred()) {
  470. std::string error =
  471. cmStrCat("Unknown CMake command \"", lff.OriginalName(), "\".");
  472. this->IssueMessage(MessageType::FATAL_ERROR, error);
  473. result = false;
  474. cmSystemTools::SetFatalErrorOccurred();
  475. }
  476. }
  477. return result;
  478. }
  479. bool cmMakefile::IsImportedTargetGlobalScope() const
  480. {
  481. return this->CurrentImportedTargetScope == ImportedTargetScope::Global;
  482. }
  483. class cmMakefile::IncludeScope
  484. {
  485. public:
  486. IncludeScope(cmMakefile* mf, std::string const& filenametoread,
  487. bool noPolicyScope);
  488. ~IncludeScope();
  489. void Quiet() { this->ReportError = false; }
  490. IncludeScope(const IncludeScope&) = delete;
  491. IncludeScope& operator=(const IncludeScope&) = delete;
  492. private:
  493. cmMakefile* Makefile;
  494. bool NoPolicyScope;
  495. bool CheckCMP0011 = false;
  496. bool ReportError = true;
  497. void EnforceCMP0011();
  498. };
  499. cmMakefile::IncludeScope::IncludeScope(cmMakefile* mf,
  500. std::string const& filenametoread,
  501. bool noPolicyScope)
  502. : Makefile(mf)
  503. , NoPolicyScope(noPolicyScope)
  504. {
  505. this->Makefile->Backtrace = this->Makefile->Backtrace.Push(
  506. cmListFileContext::FromListFilePath(filenametoread));
  507. this->Makefile->PushFunctionBlockerBarrier();
  508. this->Makefile->StateSnapshot =
  509. this->Makefile->GetState()->CreateIncludeFileSnapshot(
  510. this->Makefile->StateSnapshot, filenametoread);
  511. if (!this->NoPolicyScope) {
  512. // Check CMP0011 to determine the policy scope type.
  513. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0011)) {
  514. case cmPolicies::WARN:
  515. // We need to push a scope to detect whether the script sets
  516. // any policies that would affect the includer and therefore
  517. // requires a warning. We use a weak scope to simulate OLD
  518. // behavior by allowing policy changes to affect the includer.
  519. this->Makefile->PushPolicy(true);
  520. this->CheckCMP0011 = true;
  521. break;
  522. case cmPolicies::OLD:
  523. // OLD behavior is to not push a scope at all.
  524. this->NoPolicyScope = true;
  525. break;
  526. case cmPolicies::REQUIRED_IF_USED:
  527. case cmPolicies::REQUIRED_ALWAYS:
  528. // We should never make this policy required, but we handle it
  529. // here just in case.
  530. this->CheckCMP0011 = true;
  531. CM_FALLTHROUGH;
  532. case cmPolicies::NEW:
  533. // NEW behavior is to push a (strong) scope.
  534. this->Makefile->PushPolicy();
  535. break;
  536. }
  537. }
  538. }
  539. cmMakefile::IncludeScope::~IncludeScope()
  540. {
  541. if (!this->NoPolicyScope) {
  542. // If we need to enforce policy CMP0011 then the top entry is the
  543. // one we pushed above. If the entry is empty, then the included
  544. // script did not set any policies that might affect the includer so
  545. // we do not need to enforce the policy.
  546. if (this->CheckCMP0011 &&
  547. !this->Makefile->StateSnapshot.HasDefinedPolicyCMP0011()) {
  548. this->CheckCMP0011 = false;
  549. }
  550. // Pop the scope we pushed for the script.
  551. this->Makefile->PopPolicy();
  552. // We enforce the policy after the script's policy stack entry has
  553. // been removed.
  554. if (this->CheckCMP0011) {
  555. this->EnforceCMP0011();
  556. }
  557. }
  558. this->Makefile->PopSnapshot(this->ReportError);
  559. this->Makefile->PopFunctionBlockerBarrier(this->ReportError);
  560. this->Makefile->Backtrace = this->Makefile->Backtrace.Pop();
  561. }
  562. void cmMakefile::IncludeScope::EnforceCMP0011()
  563. {
  564. // We check the setting of this policy again because the included
  565. // script might actually set this policy for its includer.
  566. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0011)) {
  567. case cmPolicies::WARN:
  568. // Warn because the user did not set this policy.
  569. {
  570. std::ostringstream w;
  571. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0011) << "\n"
  572. << "The included script\n "
  573. << this->Makefile->GetBacktrace().Top().FilePath << "\n"
  574. << "affects policy settings. "
  575. << "CMake is implying the NO_POLICY_SCOPE option for compatibility, "
  576. << "so the effects are applied to the including context.";
  577. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  578. }
  579. break;
  580. case cmPolicies::REQUIRED_IF_USED:
  581. case cmPolicies::REQUIRED_ALWAYS: {
  582. std::ostringstream e;
  583. /* clang-format off */
  584. e << cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0011) << "\n"
  585. << "The included script\n "
  586. << this->Makefile->GetBacktrace().Top().FilePath << "\n"
  587. << "affects policy settings, so it requires this policy to be set.";
  588. /* clang-format on */
  589. this->Makefile->IssueMessage(MessageType::FATAL_ERROR, e.str());
  590. } break;
  591. case cmPolicies::OLD:
  592. case cmPolicies::NEW:
  593. // The script set this policy. We assume the purpose of the
  594. // script is to initialize policies for its includer, and since
  595. // the policy is now set for later scripts, we do not warn.
  596. break;
  597. }
  598. }
  599. bool cmMakefile::ReadDependentFile(const std::string& filename,
  600. bool noPolicyScope)
  601. {
  602. if (cmValue def = this->GetDefinition("CMAKE_CURRENT_LIST_FILE")) {
  603. this->AddDefinition("CMAKE_PARENT_LIST_FILE", *def);
  604. }
  605. std::string filenametoread = cmSystemTools::CollapseFullPath(
  606. filename, this->GetCurrentSourceDirectory());
  607. IncludeScope incScope(this, filenametoread, noPolicyScope);
  608. #ifdef CMake_ENABLE_DEBUGGER
  609. if (this->GetCMakeInstance()->GetDebugAdapter() != nullptr) {
  610. this->GetCMakeInstance()->GetDebugAdapter()->OnBeginFileParse(
  611. this, filenametoread);
  612. }
  613. #endif
  614. cmListFile listFile;
  615. if (!listFile.ParseFile(filenametoread.c_str(), this->GetMessenger(),
  616. this->Backtrace)) {
  617. #ifdef CMake_ENABLE_DEBUGGER
  618. if (this->GetCMakeInstance()->GetDebugAdapter() != nullptr) {
  619. this->GetCMakeInstance()->GetDebugAdapter()->OnEndFileParse();
  620. }
  621. #endif
  622. return false;
  623. }
  624. #ifdef CMake_ENABLE_DEBUGGER
  625. if (this->GetCMakeInstance()->GetDebugAdapter() != nullptr) {
  626. this->GetCMakeInstance()->GetDebugAdapter()->OnEndFileParse();
  627. this->GetCMakeInstance()->GetDebugAdapter()->OnFileParsedSuccessfully(
  628. filenametoread, listFile.Functions);
  629. }
  630. #endif
  631. this->RunListFile(listFile, filenametoread);
  632. if (cmSystemTools::GetFatalErrorOccurred()) {
  633. incScope.Quiet();
  634. }
  635. return true;
  636. }
  637. class cmMakefile::ListFileScope
  638. {
  639. public:
  640. ListFileScope(cmMakefile* mf, std::string const& filenametoread)
  641. : Makefile(mf)
  642. {
  643. this->Makefile->Backtrace = this->Makefile->Backtrace.Push(
  644. cmListFileContext::FromListFilePath(filenametoread));
  645. this->Makefile->StateSnapshot =
  646. this->Makefile->GetState()->CreateInlineListFileSnapshot(
  647. this->Makefile->StateSnapshot, filenametoread);
  648. assert(this->Makefile->StateSnapshot.IsValid());
  649. this->Makefile->PushFunctionBlockerBarrier();
  650. }
  651. ~ListFileScope()
  652. {
  653. this->Makefile->PopSnapshot(this->ReportError);
  654. this->Makefile->PopFunctionBlockerBarrier(this->ReportError);
  655. this->Makefile->Backtrace = this->Makefile->Backtrace.Pop();
  656. }
  657. void Quiet() { this->ReportError = false; }
  658. ListFileScope(const ListFileScope&) = delete;
  659. ListFileScope& operator=(const ListFileScope&) = delete;
  660. private:
  661. cmMakefile* Makefile;
  662. bool ReportError = true;
  663. };
  664. class cmMakefile::DeferScope
  665. {
  666. public:
  667. DeferScope(cmMakefile* mf, std::string const& deferredInFile)
  668. : Makefile(mf)
  669. {
  670. cmListFileContext lfc;
  671. lfc.Line = cmListFileContext::DeferPlaceholderLine;
  672. lfc.FilePath = deferredInFile;
  673. this->Makefile->Backtrace = this->Makefile->Backtrace.Push(lfc);
  674. this->Makefile->DeferRunning = true;
  675. }
  676. ~DeferScope()
  677. {
  678. this->Makefile->DeferRunning = false;
  679. this->Makefile->Backtrace = this->Makefile->Backtrace.Pop();
  680. }
  681. DeferScope(const DeferScope&) = delete;
  682. DeferScope& operator=(const DeferScope&) = delete;
  683. private:
  684. cmMakefile* Makefile;
  685. };
  686. class cmMakefile::DeferCallScope
  687. {
  688. public:
  689. DeferCallScope(cmMakefile* mf, std::string const& deferredFromFile)
  690. : Makefile(mf)
  691. {
  692. this->Makefile->StateSnapshot =
  693. this->Makefile->GetState()->CreateDeferCallSnapshot(
  694. this->Makefile->StateSnapshot, deferredFromFile);
  695. assert(this->Makefile->StateSnapshot.IsValid());
  696. }
  697. ~DeferCallScope() { this->Makefile->PopSnapshot(); }
  698. DeferCallScope(const DeferCallScope&) = delete;
  699. DeferCallScope& operator=(const DeferCallScope&) = delete;
  700. private:
  701. cmMakefile* Makefile;
  702. };
  703. bool cmMakefile::ReadListFile(const std::string& filename)
  704. {
  705. std::string filenametoread = cmSystemTools::CollapseFullPath(
  706. filename, this->GetCurrentSourceDirectory());
  707. ListFileScope scope(this, filenametoread);
  708. #ifdef CMake_ENABLE_DEBUGGER
  709. if (this->GetCMakeInstance()->GetDebugAdapter() != nullptr) {
  710. this->GetCMakeInstance()->GetDebugAdapter()->OnBeginFileParse(
  711. this, filenametoread);
  712. }
  713. #endif
  714. cmListFile listFile;
  715. if (!listFile.ParseFile(filenametoread.c_str(), this->GetMessenger(),
  716. this->Backtrace)) {
  717. #ifdef CMake_ENABLE_DEBUGGER
  718. if (this->GetCMakeInstance()->GetDebugAdapter() != nullptr) {
  719. this->GetCMakeInstance()->GetDebugAdapter()->OnEndFileParse();
  720. }
  721. #endif
  722. return false;
  723. }
  724. #ifdef CMake_ENABLE_DEBUGGER
  725. if (this->GetCMakeInstance()->GetDebugAdapter() != nullptr) {
  726. this->GetCMakeInstance()->GetDebugAdapter()->OnEndFileParse();
  727. this->GetCMakeInstance()->GetDebugAdapter()->OnFileParsedSuccessfully(
  728. filenametoread, listFile.Functions);
  729. }
  730. #endif
  731. this->RunListFile(listFile, filenametoread);
  732. if (cmSystemTools::GetFatalErrorOccurred()) {
  733. scope.Quiet();
  734. }
  735. return true;
  736. }
  737. bool cmMakefile::ReadListFileAsString(const std::string& content,
  738. const std::string& virtualFileName)
  739. {
  740. std::string filenametoread = cmSystemTools::CollapseFullPath(
  741. virtualFileName, this->GetCurrentSourceDirectory());
  742. ListFileScope scope(this, filenametoread);
  743. cmListFile listFile;
  744. if (!listFile.ParseString(content.c_str(), virtualFileName.c_str(),
  745. this->GetMessenger(), this->Backtrace)) {
  746. return false;
  747. }
  748. #ifdef CMake_ENABLE_DEBUGGER
  749. if (this->GetCMakeInstance()->GetDebugAdapter() != nullptr) {
  750. this->GetCMakeInstance()->GetDebugAdapter()->OnFileParsedSuccessfully(
  751. filenametoread, listFile.Functions);
  752. }
  753. #endif
  754. this->RunListFile(listFile, filenametoread);
  755. if (cmSystemTools::GetFatalErrorOccurred()) {
  756. scope.Quiet();
  757. }
  758. return true;
  759. }
  760. void cmMakefile::RunListFile(cmListFile const& listFile,
  761. std::string const& filenametoread,
  762. DeferCommands* defer)
  763. {
  764. // add this list file to the list of dependencies
  765. this->ListFiles.push_back(filenametoread);
  766. std::string currentParentFile =
  767. this->GetSafeDefinition("CMAKE_PARENT_LIST_FILE");
  768. std::string currentFile = this->GetSafeDefinition("CMAKE_CURRENT_LIST_FILE");
  769. this->AddDefinition("CMAKE_CURRENT_LIST_FILE", filenametoread);
  770. this->AddDefinition("CMAKE_CURRENT_LIST_DIR",
  771. cmSystemTools::GetFilenamePath(filenametoread));
  772. this->MarkVariableAsUsed("CMAKE_PARENT_LIST_FILE");
  773. this->MarkVariableAsUsed("CMAKE_CURRENT_LIST_FILE");
  774. this->MarkVariableAsUsed("CMAKE_CURRENT_LIST_DIR");
  775. // Run the parsed commands.
  776. const size_t numberFunctions = listFile.Functions.size();
  777. for (size_t i = 0; i < numberFunctions; ++i) {
  778. cmExecutionStatus status(*this);
  779. this->ExecuteCommand(listFile.Functions[i], status);
  780. if (cmSystemTools::GetFatalErrorOccurred()) {
  781. break;
  782. }
  783. if (status.GetReturnInvoked()) {
  784. this->RaiseScope(status.GetReturnVariables());
  785. // Exit early due to return command.
  786. break;
  787. }
  788. }
  789. // Run any deferred commands.
  790. if (defer) {
  791. // Add a backtrace level indicating calls are deferred.
  792. DeferScope scope(this, filenametoread);
  793. // Iterate by index in case one deferred call schedules another.
  794. // NOLINTNEXTLINE(modernize-loop-convert)
  795. for (size_t i = 0; i < defer->Commands.size(); ++i) {
  796. DeferCommand& d = defer->Commands[i];
  797. if (d.Id.empty()) {
  798. // Canceled.
  799. continue;
  800. }
  801. // Mark as executed.
  802. std::string id = std::move(d.Id);
  803. // The deferred call may have come from another file.
  804. DeferCallScope callScope(this, d.FilePath);
  805. cmExecutionStatus status(*this);
  806. this->ExecuteCommand(d.Command, status, std::move(id));
  807. if (cmSystemTools::GetFatalErrorOccurred()) {
  808. break;
  809. }
  810. }
  811. }
  812. this->AddDefinition("CMAKE_PARENT_LIST_FILE", currentParentFile);
  813. this->AddDefinition("CMAKE_CURRENT_LIST_FILE", currentFile);
  814. this->AddDefinition("CMAKE_CURRENT_LIST_DIR",
  815. cmSystemTools::GetFilenamePath(currentFile));
  816. this->MarkVariableAsUsed("CMAKE_PARENT_LIST_FILE");
  817. this->MarkVariableAsUsed("CMAKE_CURRENT_LIST_FILE");
  818. this->MarkVariableAsUsed("CMAKE_CURRENT_LIST_DIR");
  819. }
  820. void cmMakefile::EnforceDirectoryLevelRules() const
  821. {
  822. // Diagnose a violation of CMP0000 if necessary.
  823. if (this->CheckCMP0000) {
  824. std::ostringstream msg;
  825. msg << "No cmake_minimum_required command is present. "
  826. << "A line of code such as\n"
  827. << " cmake_minimum_required(VERSION " << cmVersion::GetMajorVersion()
  828. << "." << cmVersion::GetMinorVersion() << ")\n"
  829. << "should be added at the top of the file. "
  830. << "The version specified may be lower if you wish to "
  831. << "support older CMake versions for this project. "
  832. << "For more information run "
  833. << "\"cmake --help-policy CMP0000\".";
  834. switch (this->GetPolicyStatus(cmPolicies::CMP0000)) {
  835. case cmPolicies::WARN:
  836. // Warn because the user did not provide a minimum required
  837. // version.
  838. this->GetCMakeInstance()->IssueMessage(MessageType::AUTHOR_WARNING,
  839. msg.str(), this->Backtrace);
  840. CM_FALLTHROUGH;
  841. case cmPolicies::OLD:
  842. // OLD behavior is to use policy version 2.4 set in
  843. // cmListFileCache.
  844. break;
  845. case cmPolicies::REQUIRED_IF_USED:
  846. case cmPolicies::REQUIRED_ALWAYS:
  847. case cmPolicies::NEW:
  848. // NEW behavior is to issue an error.
  849. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR,
  850. msg.str(), this->Backtrace);
  851. cmSystemTools::SetFatalErrorOccurred();
  852. break;
  853. }
  854. }
  855. }
  856. void cmMakefile::AddEvaluationFile(
  857. const std::string& inputFile, const std::string& targetName,
  858. std::unique_ptr<cmCompiledGeneratorExpression> outputName,
  859. std::unique_ptr<cmCompiledGeneratorExpression> condition,
  860. const std::string& newLineCharacter, mode_t permissions, bool inputIsContent)
  861. {
  862. this->EvaluationFiles.push_back(
  863. cm::make_unique<cmGeneratorExpressionEvaluationFile>(
  864. inputFile, targetName, std::move(outputName), std::move(condition),
  865. inputIsContent, newLineCharacter, permissions,
  866. this->GetPolicyStatus(cmPolicies::CMP0070)));
  867. }
  868. const std::vector<std::unique_ptr<cmGeneratorExpressionEvaluationFile>>&
  869. cmMakefile::GetEvaluationFiles() const
  870. {
  871. return this->EvaluationFiles;
  872. }
  873. std::vector<std::unique_ptr<cmExportBuildFileGenerator>> const&
  874. cmMakefile::GetExportBuildFileGenerators() const
  875. {
  876. return this->ExportBuildFileGenerators;
  877. }
  878. void cmMakefile::RemoveExportBuildFileGeneratorCMP0024(
  879. cmExportBuildFileGenerator* gen)
  880. {
  881. auto it =
  882. std::find_if(this->ExportBuildFileGenerators.begin(),
  883. this->ExportBuildFileGenerators.end(),
  884. [gen](std::unique_ptr<cmExportBuildFileGenerator> const& p) {
  885. return p.get() == gen;
  886. });
  887. if (it != this->ExportBuildFileGenerators.end()) {
  888. this->ExportBuildFileGenerators.erase(it);
  889. }
  890. }
  891. void cmMakefile::AddExportBuildFileGenerator(
  892. std::unique_ptr<cmExportBuildFileGenerator> gen)
  893. {
  894. this->ExportBuildFileGenerators.emplace_back(std::move(gen));
  895. }
  896. namespace {
  897. struct file_not_persistent
  898. {
  899. bool operator()(const std::string& path) const
  900. {
  901. return !(path.find("CMakeTmp") == std::string::npos &&
  902. cmSystemTools::FileExists(path));
  903. }
  904. };
  905. }
  906. void cmMakefile::AddGeneratorAction(GeneratorAction&& action)
  907. {
  908. assert(!this->GeneratorActionsInvoked);
  909. this->GeneratorActions.emplace_back(std::move(action), this->Backtrace);
  910. }
  911. void cmMakefile::GeneratorAction::operator()(cmLocalGenerator& lg,
  912. const cmListFileBacktrace& lfbt)
  913. {
  914. if (cc) {
  915. CCAction(lg, lfbt, std::move(cc));
  916. } else {
  917. assert(Action);
  918. Action(lg, lfbt);
  919. }
  920. }
  921. void cmMakefile::DoGenerate(cmLocalGenerator& lg)
  922. {
  923. // do all the variable expansions here
  924. this->ExpandVariablesCMP0019();
  925. // give all the commands a chance to do something
  926. // after the file has been parsed before generation
  927. for (auto& action : this->GeneratorActions) {
  928. action.Value(lg, action.Backtrace);
  929. }
  930. this->GeneratorActionsInvoked = true;
  931. // go through all configured files and see which ones still exist.
  932. // we don't want cmake to re-run if a configured file is created and deleted
  933. // during processing as that would make it a transient file that can't
  934. // influence the build process
  935. cm::erase_if(this->OutputFiles, file_not_persistent());
  936. // if a configured file is used as input for another configured file,
  937. // and then deleted it will show up in the input list files so we
  938. // need to scan those too
  939. cm::erase_if(this->ListFiles, file_not_persistent());
  940. }
  941. // Generate the output file
  942. void cmMakefile::Generate(cmLocalGenerator& lg)
  943. {
  944. this->DoGenerate(lg);
  945. cmValue oldValue = this->GetDefinition("CMAKE_BACKWARDS_COMPATIBILITY");
  946. if (oldValue &&
  947. cmSystemTools::VersionCompare(cmSystemTools::OP_LESS, *oldValue,
  948. "2.4")) {
  949. this->GetCMakeInstance()->IssueMessage(
  950. MessageType::FATAL_ERROR,
  951. "You have set CMAKE_BACKWARDS_COMPATIBILITY to a CMake version less "
  952. "than 2.4. This version of CMake only supports backwards compatibility "
  953. "with CMake 2.4 or later. For compatibility with older versions please "
  954. "use any CMake 2.8.x release or lower.",
  955. this->Backtrace);
  956. }
  957. }
  958. namespace {
  959. // There are still too many implicit backtraces through cmMakefile. As a
  960. // workaround we reset the backtrace temporarily.
  961. struct BacktraceGuard
  962. {
  963. BacktraceGuard(cmListFileBacktrace& lfbt, cmListFileBacktrace current)
  964. : Backtrace(lfbt)
  965. , Previous(lfbt)
  966. {
  967. this->Backtrace = std::move(current);
  968. }
  969. ~BacktraceGuard() { this->Backtrace = std::move(this->Previous); }
  970. private:
  971. cmListFileBacktrace& Backtrace;
  972. cmListFileBacktrace Previous;
  973. };
  974. }
  975. bool cmMakefile::ValidateCustomCommand(
  976. const cmCustomCommandLines& commandLines) const
  977. {
  978. // TODO: More strict?
  979. for (cmCustomCommandLine const& cl : commandLines) {
  980. if (!cl.empty() && !cl[0].empty() && cl[0][0] == '"') {
  981. std::ostringstream e;
  982. e << "COMMAND may not contain literal quotes:\n " << cl[0] << "\n";
  983. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  984. return false;
  985. }
  986. }
  987. return true;
  988. }
  989. cmTarget* cmMakefile::GetCustomCommandTarget(
  990. const std::string& target, cmObjectLibraryCommands objLibCommands,
  991. const cmListFileBacktrace& lfbt) const
  992. {
  993. // Find the target to which to add the custom command.
  994. auto ti = this->Targets.find(target);
  995. if (ti == this->Targets.end()) {
  996. MessageType messageType = MessageType::AUTHOR_WARNING;
  997. bool issueMessage = false;
  998. std::ostringstream e;
  999. switch (this->GetPolicyStatus(cmPolicies::CMP0040)) {
  1000. case cmPolicies::WARN:
  1001. e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0040) << "\n";
  1002. issueMessage = true;
  1003. CM_FALLTHROUGH;
  1004. case cmPolicies::OLD:
  1005. break;
  1006. case cmPolicies::NEW:
  1007. case cmPolicies::REQUIRED_IF_USED:
  1008. case cmPolicies::REQUIRED_ALWAYS:
  1009. issueMessage = true;
  1010. messageType = MessageType::FATAL_ERROR;
  1011. break;
  1012. }
  1013. if (issueMessage) {
  1014. if (cmTarget const* t = this->FindTargetToUse(target)) {
  1015. if (t->IsImported()) {
  1016. e << "TARGET '" << target
  1017. << "' is IMPORTED and does not build here.";
  1018. } else {
  1019. e << "TARGET '" << target << "' was not created in this directory.";
  1020. }
  1021. } else {
  1022. e << "No TARGET '" << target
  1023. << "' has been created in this directory.";
  1024. }
  1025. this->GetCMakeInstance()->IssueMessage(messageType, e.str(), lfbt);
  1026. }
  1027. return nullptr;
  1028. }
  1029. cmTarget* t = &ti->second;
  1030. if (objLibCommands == cmObjectLibraryCommands::Reject &&
  1031. t->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  1032. std::ostringstream e;
  1033. e << "Target \"" << target
  1034. << "\" is an OBJECT library "
  1035. "that may not have PRE_BUILD, PRE_LINK, or POST_BUILD commands.";
  1036. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR, e.str(),
  1037. lfbt);
  1038. return nullptr;
  1039. }
  1040. if (t->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  1041. std::ostringstream e;
  1042. e << "Target \"" << target
  1043. << "\" is an INTERFACE library "
  1044. "that may not have PRE_BUILD, PRE_LINK, or POST_BUILD commands.";
  1045. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR, e.str(),
  1046. lfbt);
  1047. return nullptr;
  1048. }
  1049. return t;
  1050. }
  1051. cmTarget* cmMakefile::AddCustomCommandToTarget(
  1052. const std::string& target, cmCustomCommandType type,
  1053. std::unique_ptr<cmCustomCommand> cc)
  1054. {
  1055. const auto& byproducts = cc->GetByproducts();
  1056. const auto& commandLines = cc->GetCommandLines();
  1057. cmTarget* t = this->GetCustomCommandTarget(
  1058. target, cmObjectLibraryCommands::Reject, this->Backtrace);
  1059. // Validate custom commands.
  1060. if (!t || !this->ValidateCustomCommand(commandLines)) {
  1061. return t;
  1062. }
  1063. // Always create the byproduct sources and mark them generated.
  1064. this->CreateGeneratedOutputs(byproducts);
  1065. cc->RecordPolicyValues(this->GetStateSnapshot());
  1066. // Dispatch command creation to allow generator expressions in outputs.
  1067. this->AddGeneratorAction(
  1068. std::move(cc),
  1069. [=](cmLocalGenerator& lg, const cmListFileBacktrace& lfbt,
  1070. std::unique_ptr<cmCustomCommand> tcc) {
  1071. BacktraceGuard guard(this->Backtrace, lfbt);
  1072. tcc->SetBacktrace(lfbt);
  1073. detail::AddCustomCommandToTarget(lg, cmCommandOrigin::Project, t, type,
  1074. std::move(tcc));
  1075. });
  1076. return t;
  1077. }
  1078. void cmMakefile::AddCustomCommandToOutput(
  1079. std::unique_ptr<cmCustomCommand> cc, const CommandSourceCallback& callback,
  1080. bool replace)
  1081. {
  1082. const auto& outputs = cc->GetOutputs();
  1083. const auto& byproducts = cc->GetByproducts();
  1084. const auto& commandLines = cc->GetCommandLines();
  1085. // Make sure there is at least one output.
  1086. if (outputs.empty()) {
  1087. cmSystemTools::Error("Attempt to add a custom rule with no output!");
  1088. return;
  1089. }
  1090. // Validate custom commands.
  1091. if (!this->ValidateCustomCommand(commandLines)) {
  1092. return;
  1093. }
  1094. // Always create the output sources and mark them generated.
  1095. this->CreateGeneratedOutputs(outputs);
  1096. this->CreateGeneratedOutputs(byproducts);
  1097. cc->RecordPolicyValues(this->GetStateSnapshot());
  1098. // Dispatch command creation to allow generator expressions in outputs.
  1099. this->AddGeneratorAction(
  1100. std::move(cc),
  1101. [=](cmLocalGenerator& lg, const cmListFileBacktrace& lfbt,
  1102. std::unique_ptr<cmCustomCommand> tcc) {
  1103. BacktraceGuard guard(this->Backtrace, lfbt);
  1104. tcc->SetBacktrace(lfbt);
  1105. cmSourceFile* sf = detail::AddCustomCommandToOutput(
  1106. lg, cmCommandOrigin::Project, std::move(tcc), replace);
  1107. if (callback && sf) {
  1108. callback(sf);
  1109. }
  1110. });
  1111. }
  1112. void cmMakefile::AddCustomCommandOldStyle(
  1113. const std::string& target, const std::vector<std::string>& outputs,
  1114. const std::vector<std::string>& depends, const std::string& source,
  1115. const cmCustomCommandLines& commandLines, const char* comment)
  1116. {
  1117. auto cc = cm::make_unique<cmCustomCommand>();
  1118. cc->SetDepends(depends);
  1119. cc->SetCommandLines(commandLines);
  1120. cc->SetComment(comment);
  1121. // Translate the old-style signature to one of the new-style
  1122. // signatures.
  1123. if (source == target) {
  1124. // In the old-style signature if the source and target were the
  1125. // same then it added a post-build rule to the target. Preserve
  1126. // this behavior.
  1127. this->AddCustomCommandToTarget(target, cmCustomCommandType::POST_BUILD,
  1128. std::move(cc));
  1129. return;
  1130. }
  1131. auto ti = this->Targets.find(target);
  1132. cmTarget* t = ti != this->Targets.end() ? &ti->second : nullptr;
  1133. auto addRuleFileToTarget = [=](cmSourceFile* sf) {
  1134. // If the rule was added to the source (and not a .rule file),
  1135. // then add the source to the target to make sure the rule is
  1136. // included.
  1137. if (!sf->GetPropertyAsBool("__CMAKE_RULE")) {
  1138. if (t) {
  1139. t->AddSource(sf->ResolveFullPath());
  1140. } else {
  1141. cmSystemTools::Error("Attempt to add a custom rule to a target "
  1142. "that does not exist yet for target " +
  1143. target);
  1144. }
  1145. }
  1146. };
  1147. // Each output must get its own copy of this rule.
  1148. cmsys::RegularExpression sourceFiles(
  1149. "\\.(C|M|c|c\\+\\+|cc|cpp|cxx|mpp|ixx|cppm|ccm|cxxm|c\\+\\+m|cu|m|mm|"
  1150. "rc|def|r|odl|idl|hpj|bat|h|h\\+\\+|"
  1151. "hm|hpp|hxx|in|txx|inl)$");
  1152. // Choose whether to use a main dependency.
  1153. if (sourceFiles.find(source)) {
  1154. // The source looks like a real file. Use it as the main dependency.
  1155. for (std::string const& output : outputs) {
  1156. auto cc1 = cm::make_unique<cmCustomCommand>(*cc);
  1157. cc1->SetOutputs(output);
  1158. cc1->SetMainDependency(source);
  1159. this->AddCustomCommandToOutput(std::move(cc1), addRuleFileToTarget);
  1160. }
  1161. } else {
  1162. cc->AppendDepends({ source });
  1163. // The source may not be a real file. Do not use a main dependency.
  1164. for (std::string const& output : outputs) {
  1165. auto cc1 = cm::make_unique<cmCustomCommand>(*cc);
  1166. cc1->SetOutputs(output);
  1167. this->AddCustomCommandToOutput(std::move(cc1), addRuleFileToTarget);
  1168. }
  1169. }
  1170. }
  1171. void cmMakefile::AppendCustomCommandToOutput(
  1172. const std::string& output, const std::vector<std::string>& depends,
  1173. const cmImplicitDependsList& implicit_depends,
  1174. const cmCustomCommandLines& commandLines)
  1175. {
  1176. // Validate custom commands.
  1177. if (this->ValidateCustomCommand(commandLines)) {
  1178. // Dispatch command creation to allow generator expressions in outputs.
  1179. this->AddGeneratorAction(
  1180. [=](cmLocalGenerator& lg, const cmListFileBacktrace& lfbt) {
  1181. BacktraceGuard guard(this->Backtrace, lfbt);
  1182. detail::AppendCustomCommandToOutput(lg, lfbt, output, depends,
  1183. implicit_depends, commandLines);
  1184. });
  1185. }
  1186. }
  1187. cmTarget* cmMakefile::AddUtilityCommand(const std::string& utilityName,
  1188. bool excludeFromAll,
  1189. std::unique_ptr<cmCustomCommand> cc)
  1190. {
  1191. const auto& depends = cc->GetDepends();
  1192. const auto& byproducts = cc->GetByproducts();
  1193. const auto& commandLines = cc->GetCommandLines();
  1194. cmTarget* target = this->AddNewUtilityTarget(utilityName, excludeFromAll);
  1195. // Validate custom commands.
  1196. if ((commandLines.empty() && depends.empty()) ||
  1197. !this->ValidateCustomCommand(commandLines)) {
  1198. return target;
  1199. }
  1200. // Always create the byproduct sources and mark them generated.
  1201. this->CreateGeneratedOutputs(byproducts);
  1202. cc->RecordPolicyValues(this->GetStateSnapshot());
  1203. // Dispatch command creation to allow generator expressions in outputs.
  1204. this->AddGeneratorAction(
  1205. std::move(cc),
  1206. [=](cmLocalGenerator& lg, const cmListFileBacktrace& lfbt,
  1207. std::unique_ptr<cmCustomCommand> tcc) {
  1208. BacktraceGuard guard(this->Backtrace, lfbt);
  1209. tcc->SetBacktrace(lfbt);
  1210. detail::AddUtilityCommand(lg, cmCommandOrigin::Project, target,
  1211. std::move(tcc));
  1212. });
  1213. return target;
  1214. }
  1215. static void s_AddDefineFlag(std::string const& flag, std::string& dflags)
  1216. {
  1217. // remove any \n\r
  1218. std::string::size_type initSize = dflags.size();
  1219. dflags += ' ';
  1220. dflags += flag;
  1221. std::string::iterator flagStart = dflags.begin() + initSize + 1;
  1222. std::replace(flagStart, dflags.end(), '\n', ' ');
  1223. std::replace(flagStart, dflags.end(), '\r', ' ');
  1224. }
  1225. void cmMakefile::AddDefineFlag(std::string const& flag)
  1226. {
  1227. if (flag.empty()) {
  1228. return;
  1229. }
  1230. // Update the string used for the old DEFINITIONS property.
  1231. s_AddDefineFlag(flag, this->DefineFlagsOrig);
  1232. // If this is really a definition, update COMPILE_DEFINITIONS.
  1233. if (this->ParseDefineFlag(flag, false)) {
  1234. return;
  1235. }
  1236. // Add this flag that does not look like a definition.
  1237. s_AddDefineFlag(flag, this->DefineFlags);
  1238. }
  1239. static void s_RemoveDefineFlag(std::string const& flag, std::string& dflags)
  1240. {
  1241. std::string::size_type const len = flag.length();
  1242. // Remove all instances of the flag that are surrounded by
  1243. // whitespace or the beginning/end of the string.
  1244. for (std::string::size_type lpos = dflags.find(flag, 0);
  1245. lpos != std::string::npos; lpos = dflags.find(flag, lpos)) {
  1246. std::string::size_type rpos = lpos + len;
  1247. if ((lpos <= 0 || isspace(dflags[lpos - 1])) &&
  1248. (rpos >= dflags.size() || isspace(dflags[rpos]))) {
  1249. dflags.erase(lpos, len);
  1250. } else {
  1251. ++lpos;
  1252. }
  1253. }
  1254. }
  1255. void cmMakefile::RemoveDefineFlag(std::string const& flag)
  1256. {
  1257. // Check the length of the flag to remove.
  1258. if (flag.empty()) {
  1259. return;
  1260. }
  1261. // Update the string used for the old DEFINITIONS property.
  1262. s_RemoveDefineFlag(flag, this->DefineFlagsOrig);
  1263. // If this is really a definition, update COMPILE_DEFINITIONS.
  1264. if (this->ParseDefineFlag(flag, true)) {
  1265. return;
  1266. }
  1267. // Remove this flag that does not look like a definition.
  1268. s_RemoveDefineFlag(flag, this->DefineFlags);
  1269. }
  1270. void cmMakefile::AddCompileDefinition(std::string const& option)
  1271. {
  1272. this->AppendProperty("COMPILE_DEFINITIONS", option);
  1273. }
  1274. void cmMakefile::AddCompileOption(std::string const& option)
  1275. {
  1276. this->AppendProperty("COMPILE_OPTIONS", option);
  1277. }
  1278. void cmMakefile::AddLinkOption(std::string const& option)
  1279. {
  1280. this->AppendProperty("LINK_OPTIONS", option);
  1281. }
  1282. void cmMakefile::AddLinkDirectory(std::string const& directory, bool before)
  1283. {
  1284. if (before) {
  1285. this->StateSnapshot.GetDirectory().PrependLinkDirectoriesEntry(
  1286. BT<std::string>(directory, this->Backtrace));
  1287. } else {
  1288. this->StateSnapshot.GetDirectory().AppendLinkDirectoriesEntry(
  1289. BT<std::string>(directory, this->Backtrace));
  1290. }
  1291. }
  1292. bool cmMakefile::ParseDefineFlag(std::string const& def, bool remove)
  1293. {
  1294. // Create a regular expression to match valid definitions.
  1295. static cmsys::RegularExpression valid("^[-/]D[A-Za-z_][A-Za-z0-9_]*(=.*)?$");
  1296. // Make sure the definition matches.
  1297. if (!valid.find(def)) {
  1298. return false;
  1299. }
  1300. // Definitions with non-trivial values require a policy check.
  1301. static cmsys::RegularExpression trivial(
  1302. "^[-/]D[A-Za-z_][A-Za-z0-9_]*(=[A-Za-z0-9_.]+)?$");
  1303. if (!trivial.find(def)) {
  1304. // This definition has a non-trivial value.
  1305. switch (this->GetPolicyStatus(cmPolicies::CMP0005)) {
  1306. case cmPolicies::WARN:
  1307. this->IssueMessage(MessageType::AUTHOR_WARNING,
  1308. cmPolicies::GetPolicyWarning(cmPolicies::CMP0005));
  1309. CM_FALLTHROUGH;
  1310. case cmPolicies::OLD:
  1311. // OLD behavior is to not escape the value. We should not
  1312. // convert the definition to use the property.
  1313. return false;
  1314. case cmPolicies::REQUIRED_IF_USED:
  1315. case cmPolicies::REQUIRED_ALWAYS:
  1316. this->IssueMessage(
  1317. MessageType::FATAL_ERROR,
  1318. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0005));
  1319. return false;
  1320. case cmPolicies::NEW:
  1321. // NEW behavior is to escape the value. Proceed to convert it
  1322. // to an entry in the property.
  1323. break;
  1324. }
  1325. }
  1326. // Get the definition part after the flag.
  1327. const char* define = def.c_str() + 2;
  1328. if (remove) {
  1329. if (cmValue cdefs = this->GetProperty("COMPILE_DEFINITIONS")) {
  1330. // Expand the list.
  1331. cmList defs{ *cdefs };
  1332. // Recompose the list without the definition.
  1333. defs.remove_items({ define });
  1334. // Store the new list.
  1335. this->SetProperty("COMPILE_DEFINITIONS", defs.to_string());
  1336. }
  1337. } else {
  1338. // Append the definition to the directory property.
  1339. this->AppendProperty("COMPILE_DEFINITIONS", define);
  1340. }
  1341. return true;
  1342. }
  1343. void cmMakefile::InitializeFromParent(cmMakefile* parent)
  1344. {
  1345. this->SystemIncludeDirectories = parent->SystemIncludeDirectories;
  1346. // define flags
  1347. this->DefineFlags = parent->DefineFlags;
  1348. this->DefineFlagsOrig = parent->DefineFlagsOrig;
  1349. // Include transform property. There is no per-config version.
  1350. {
  1351. const char* prop = "IMPLICIT_DEPENDS_INCLUDE_TRANSFORM";
  1352. this->SetProperty(prop, parent->GetProperty(prop));
  1353. }
  1354. // compile definitions property and per-config versions
  1355. cmPolicies::PolicyStatus polSt = this->GetPolicyStatus(cmPolicies::CMP0043);
  1356. if (polSt == cmPolicies::WARN || polSt == cmPolicies::OLD) {
  1357. this->SetProperty("COMPILE_DEFINITIONS",
  1358. parent->GetProperty("COMPILE_DEFINITIONS"));
  1359. std::vector<std::string> configs =
  1360. this->GetGeneratorConfigs(cmMakefile::ExcludeEmptyConfig);
  1361. for (std::string const& config : configs) {
  1362. std::string defPropName =
  1363. cmStrCat("COMPILE_DEFINITIONS_", cmSystemTools::UpperCase(config));
  1364. cmValue prop = parent->GetProperty(defPropName);
  1365. this->SetProperty(defPropName, prop);
  1366. }
  1367. }
  1368. // labels
  1369. this->SetProperty("LABELS", parent->GetProperty("LABELS"));
  1370. // link libraries
  1371. this->SetProperty("LINK_LIBRARIES", parent->GetProperty("LINK_LIBRARIES"));
  1372. // the initial project name
  1373. this->StateSnapshot.SetProjectName(parent->StateSnapshot.GetProjectName());
  1374. // Copy include regular expressions.
  1375. this->ComplainFileRegularExpression = parent->ComplainFileRegularExpression;
  1376. // Imported targets.
  1377. this->ImportedTargets = parent->ImportedTargets;
  1378. // Non-global Alias targets.
  1379. this->AliasTargets = parent->AliasTargets;
  1380. // Recursion depth.
  1381. this->RecursionDepth = parent->RecursionDepth;
  1382. }
  1383. void cmMakefile::AddInstallGenerator(std::unique_ptr<cmInstallGenerator> g)
  1384. {
  1385. if (g) {
  1386. this->InstallGenerators.push_back(std::move(g));
  1387. }
  1388. }
  1389. void cmMakefile::AddTestGenerator(std::unique_ptr<cmTestGenerator> g)
  1390. {
  1391. if (g) {
  1392. this->TestGenerators.push_back(std::move(g));
  1393. }
  1394. }
  1395. void cmMakefile::PushFunctionScope(std::string const& fileName,
  1396. const cmPolicies::PolicyMap& pm)
  1397. {
  1398. this->StateSnapshot = this->GetState()->CreateFunctionCallSnapshot(
  1399. this->StateSnapshot, fileName);
  1400. assert(this->StateSnapshot.IsValid());
  1401. this->PushLoopBlockBarrier();
  1402. #if !defined(CMAKE_BOOTSTRAP)
  1403. this->GetGlobalGenerator()->GetFileLockPool().PushFunctionScope();
  1404. #endif
  1405. this->PushFunctionBlockerBarrier();
  1406. this->PushPolicy(true, pm);
  1407. }
  1408. void cmMakefile::PopFunctionScope(bool reportError)
  1409. {
  1410. this->PopPolicy();
  1411. this->PopSnapshot(reportError);
  1412. this->PopFunctionBlockerBarrier(reportError);
  1413. #if !defined(CMAKE_BOOTSTRAP)
  1414. this->GetGlobalGenerator()->GetFileLockPool().PopFunctionScope();
  1415. #endif
  1416. this->PopLoopBlockBarrier();
  1417. }
  1418. void cmMakefile::PushMacroScope(std::string const& fileName,
  1419. const cmPolicies::PolicyMap& pm)
  1420. {
  1421. this->StateSnapshot =
  1422. this->GetState()->CreateMacroCallSnapshot(this->StateSnapshot, fileName);
  1423. assert(this->StateSnapshot.IsValid());
  1424. this->PushFunctionBlockerBarrier();
  1425. this->PushPolicy(true, pm);
  1426. }
  1427. void cmMakefile::PopMacroScope(bool reportError)
  1428. {
  1429. this->PopPolicy();
  1430. this->PopSnapshot(reportError);
  1431. this->PopFunctionBlockerBarrier(reportError);
  1432. }
  1433. bool cmMakefile::IsRootMakefile() const
  1434. {
  1435. return !this->StateSnapshot.GetBuildsystemDirectoryParent().IsValid();
  1436. }
  1437. class cmMakefile::BuildsystemFileScope
  1438. {
  1439. public:
  1440. BuildsystemFileScope(cmMakefile* mf)
  1441. : Makefile(mf)
  1442. {
  1443. std::string currentStart =
  1444. cmStrCat(this->Makefile->StateSnapshot.GetDirectory().GetCurrentSource(),
  1445. "/CMakeLists.txt");
  1446. this->Makefile->StateSnapshot.SetListFile(currentStart);
  1447. this->Makefile->StateSnapshot =
  1448. this->Makefile->StateSnapshot.GetState()->CreatePolicyScopeSnapshot(
  1449. this->Makefile->StateSnapshot);
  1450. this->Makefile->PushFunctionBlockerBarrier();
  1451. this->GG = mf->GetGlobalGenerator();
  1452. this->CurrentMakefile = this->GG->GetCurrentMakefile();
  1453. this->Snapshot = this->GG->GetCMakeInstance()->GetCurrentSnapshot();
  1454. this->GG->GetCMakeInstance()->SetCurrentSnapshot(this->Snapshot);
  1455. this->GG->SetCurrentMakefile(mf);
  1456. #if !defined(CMAKE_BOOTSTRAP)
  1457. this->GG->GetFileLockPool().PushFileScope();
  1458. #endif
  1459. }
  1460. ~BuildsystemFileScope()
  1461. {
  1462. this->Makefile->PopFunctionBlockerBarrier(this->ReportError);
  1463. this->Makefile->PopSnapshot(this->ReportError);
  1464. #if !defined(CMAKE_BOOTSTRAP)
  1465. this->GG->GetFileLockPool().PopFileScope();
  1466. #endif
  1467. this->GG->SetCurrentMakefile(this->CurrentMakefile);
  1468. this->GG->GetCMakeInstance()->SetCurrentSnapshot(this->Snapshot);
  1469. }
  1470. void Quiet() { this->ReportError = false; }
  1471. BuildsystemFileScope(const BuildsystemFileScope&) = delete;
  1472. BuildsystemFileScope& operator=(const BuildsystemFileScope&) = delete;
  1473. private:
  1474. cmMakefile* Makefile;
  1475. cmGlobalGenerator* GG;
  1476. cmMakefile* CurrentMakefile;
  1477. cmStateSnapshot Snapshot;
  1478. bool ReportError = true;
  1479. };
  1480. void cmMakefile::Configure()
  1481. {
  1482. std::string currentStart = cmStrCat(
  1483. this->StateSnapshot.GetDirectory().GetCurrentSource(), "/CMakeLists.txt");
  1484. // Add the bottom of all backtraces within this directory.
  1485. // We will never pop this scope because it should be available
  1486. // for messages during the generate step too.
  1487. this->Backtrace =
  1488. this->Backtrace.Push(cmListFileContext::FromListFilePath(currentStart));
  1489. BuildsystemFileScope scope(this);
  1490. // make sure the CMakeFiles dir is there
  1491. std::string filesDir = cmStrCat(
  1492. this->StateSnapshot.GetDirectory().GetCurrentBinary(), "/CMakeFiles");
  1493. cmSystemTools::MakeDirectory(filesDir);
  1494. assert(cmSystemTools::FileExists(currentStart, true));
  1495. this->AddDefinition("CMAKE_PARENT_LIST_FILE", currentStart);
  1496. #ifdef CMake_ENABLE_DEBUGGER
  1497. if (this->GetCMakeInstance()->GetDebugAdapter() != nullptr) {
  1498. this->GetCMakeInstance()->GetDebugAdapter()->OnBeginFileParse(
  1499. this, currentStart);
  1500. }
  1501. #endif
  1502. cmListFile listFile;
  1503. if (!listFile.ParseFile(currentStart.c_str(), this->GetMessenger(),
  1504. this->Backtrace)) {
  1505. #ifdef CMake_ENABLE_DEBUGGER
  1506. if (this->GetCMakeInstance()->GetDebugAdapter() != nullptr) {
  1507. this->GetCMakeInstance()->GetDebugAdapter()->OnEndFileParse();
  1508. }
  1509. #endif
  1510. return;
  1511. }
  1512. #ifdef CMake_ENABLE_DEBUGGER
  1513. if (this->GetCMakeInstance()->GetDebugAdapter() != nullptr) {
  1514. this->GetCMakeInstance()->GetDebugAdapter()->OnEndFileParse();
  1515. this->GetCMakeInstance()->GetDebugAdapter()->OnFileParsedSuccessfully(
  1516. currentStart, listFile.Functions);
  1517. }
  1518. #endif
  1519. if (this->IsRootMakefile()) {
  1520. bool hasVersion = false;
  1521. // search for the right policy command
  1522. for (cmListFileFunction const& func : listFile.Functions) {
  1523. if (func.LowerCaseName() == "cmake_minimum_required"_s) {
  1524. hasVersion = true;
  1525. break;
  1526. }
  1527. }
  1528. // if no policy command is found this is an error if they use any
  1529. // non advanced functions or a lot of functions
  1530. if (!hasVersion) {
  1531. bool isProblem = true;
  1532. if (listFile.Functions.size() < 30) {
  1533. // the list of simple commands DO NOT ADD TO THIS LIST!!!!!
  1534. // these commands must have backwards compatibility forever and
  1535. // and that is a lot longer than your tiny mind can comprehend mortal
  1536. std::set<std::string> allowedCommands;
  1537. allowedCommands.insert("project");
  1538. allowedCommands.insert("set");
  1539. allowedCommands.insert("if");
  1540. allowedCommands.insert("endif");
  1541. allowedCommands.insert("else");
  1542. allowedCommands.insert("elseif");
  1543. allowedCommands.insert("add_executable");
  1544. allowedCommands.insert("add_library");
  1545. allowedCommands.insert("target_link_libraries");
  1546. allowedCommands.insert("option");
  1547. allowedCommands.insert("message");
  1548. isProblem = false;
  1549. for (cmListFileFunction const& func : listFile.Functions) {
  1550. if (!cm::contains(allowedCommands, func.LowerCaseName())) {
  1551. isProblem = true;
  1552. break;
  1553. }
  1554. }
  1555. }
  1556. if (isProblem) {
  1557. // Tell the top level cmMakefile to diagnose
  1558. // this violation of CMP0000.
  1559. this->SetCheckCMP0000(true);
  1560. // Implicitly set the version for the user.
  1561. cmPolicies::ApplyPolicyVersion(this, 2, 4, 0,
  1562. cmPolicies::WarnCompat::Off);
  1563. }
  1564. }
  1565. bool hasProject = false;
  1566. // search for a project command
  1567. for (cmListFileFunction const& func : listFile.Functions) {
  1568. if (func.LowerCaseName() == "project"_s) {
  1569. hasProject = true;
  1570. break;
  1571. }
  1572. }
  1573. // if no project command is found, add one
  1574. if (!hasProject) {
  1575. this->GetCMakeInstance()->IssueMessage(
  1576. MessageType::AUTHOR_WARNING,
  1577. "No project() command is present. The top-level CMakeLists.txt "
  1578. "file must contain a literal, direct call to the project() command. "
  1579. "Add a line of code such as\n"
  1580. " project(ProjectName)\n"
  1581. "near the top of the file, but after cmake_minimum_required().\n"
  1582. "CMake is pretending there is a \"project(Project)\" command on "
  1583. "the first line.",
  1584. this->Backtrace);
  1585. cmListFileFunction project{ "project",
  1586. 0,
  1587. 0,
  1588. { { "Project", cmListFileArgument::Unquoted,
  1589. 0 },
  1590. { "__CMAKE_INJECTED_PROJECT_COMMAND__",
  1591. cmListFileArgument::Unquoted, 0 } } };
  1592. listFile.Functions.insert(listFile.Functions.begin(), project);
  1593. }
  1594. }
  1595. this->Defer = cm::make_unique<DeferCommands>();
  1596. this->RunListFile(listFile, currentStart, this->Defer.get());
  1597. this->Defer.reset();
  1598. if (cmSystemTools::GetFatalErrorOccurred()) {
  1599. scope.Quiet();
  1600. }
  1601. // at the end handle any old style subdirs
  1602. std::vector<cmMakefile*> subdirs = this->UnConfiguredDirectories;
  1603. // for each subdir recurse
  1604. auto sdi = subdirs.begin();
  1605. for (; sdi != subdirs.end(); ++sdi) {
  1606. (*sdi)->StateSnapshot.InitializeFromParent_ForSubdirsCommand();
  1607. this->ConfigureSubDirectory(*sdi);
  1608. }
  1609. this->AddCMakeDependFilesFromUser();
  1610. }
  1611. void cmMakefile::ConfigureSubDirectory(cmMakefile* mf)
  1612. {
  1613. mf->InitializeFromParent(this);
  1614. std::string currentStart = mf->GetCurrentSourceDirectory();
  1615. if (this->GetCMakeInstance()->GetDebugOutput()) {
  1616. std::string msg = cmStrCat(" Entering ", currentStart);
  1617. cmSystemTools::Message(msg);
  1618. }
  1619. std::string const currentStartFile =
  1620. cmStrCat(currentStart, "/CMakeLists.txt");
  1621. if (!cmSystemTools::FileExists(currentStartFile, true)) {
  1622. // The file is missing. Check policy CMP0014.
  1623. std::ostringstream e;
  1624. /* clang-format off */
  1625. e << "The source directory\n"
  1626. << " " << currentStart << "\n"
  1627. << "does not contain a CMakeLists.txt file.";
  1628. /* clang-format on */
  1629. switch (this->GetPolicyStatus(cmPolicies::CMP0014)) {
  1630. case cmPolicies::WARN:
  1631. // Print the warning.
  1632. /* clang-format off */
  1633. e << "\n"
  1634. << "CMake does not support this case but it used "
  1635. << "to work accidentally and is being allowed for "
  1636. << "compatibility."
  1637. << "\n"
  1638. << cmPolicies::GetPolicyWarning(cmPolicies::CMP0014);
  1639. /* clang-format on */
  1640. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  1641. CM_FALLTHROUGH;
  1642. case cmPolicies::OLD:
  1643. // OLD behavior does not warn.
  1644. break;
  1645. case cmPolicies::REQUIRED_IF_USED:
  1646. case cmPolicies::REQUIRED_ALWAYS:
  1647. e << "\n" << cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0014);
  1648. CM_FALLTHROUGH;
  1649. case cmPolicies::NEW:
  1650. // NEW behavior prints the error.
  1651. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  1652. break;
  1653. }
  1654. return;
  1655. }
  1656. // finally configure the subdir
  1657. mf->Configure();
  1658. if (this->GetCMakeInstance()->GetDebugOutput()) {
  1659. std::string msg =
  1660. cmStrCat(" Returning to ", this->GetCurrentSourceDirectory());
  1661. cmSystemTools::Message(msg);
  1662. }
  1663. }
  1664. void cmMakefile::AddSubDirectory(const std::string& srcPath,
  1665. const std::string& binPath,
  1666. bool excludeFromAll, bool immediate,
  1667. bool system)
  1668. {
  1669. if (this->DeferRunning) {
  1670. this->IssueMessage(
  1671. MessageType::FATAL_ERROR,
  1672. "Subdirectories may not be created during deferred execution.");
  1673. return;
  1674. }
  1675. // Make sure the binary directory is unique.
  1676. if (!this->EnforceUniqueDir(srcPath, binPath)) {
  1677. return;
  1678. }
  1679. cmStateSnapshot newSnapshot =
  1680. this->GetState()->CreateBuildsystemDirectorySnapshot(this->StateSnapshot);
  1681. newSnapshot.GetDirectory().SetCurrentSource(srcPath);
  1682. newSnapshot.GetDirectory().SetCurrentBinary(binPath);
  1683. cmSystemTools::MakeDirectory(binPath);
  1684. auto subMfu =
  1685. cm::make_unique<cmMakefile>(this->GlobalGenerator, newSnapshot);
  1686. auto* subMf = subMfu.get();
  1687. this->GetGlobalGenerator()->AddMakefile(std::move(subMfu));
  1688. if (excludeFromAll) {
  1689. subMf->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
  1690. }
  1691. if (system) {
  1692. subMf->SetProperty("SYSTEM", "TRUE");
  1693. }
  1694. if (immediate) {
  1695. this->ConfigureSubDirectory(subMf);
  1696. } else {
  1697. this->UnConfiguredDirectories.push_back(subMf);
  1698. }
  1699. this->AddInstallGenerator(cm::make_unique<cmInstallSubdirectoryGenerator>(
  1700. subMf, binPath, this->GetBacktrace()));
  1701. }
  1702. const std::string& cmMakefile::GetCurrentSourceDirectory() const
  1703. {
  1704. return this->StateSnapshot.GetDirectory().GetCurrentSource();
  1705. }
  1706. const std::string& cmMakefile::GetCurrentBinaryDirectory() const
  1707. {
  1708. return this->StateSnapshot.GetDirectory().GetCurrentBinary();
  1709. }
  1710. std::vector<cmTarget*> cmMakefile::GetImportedTargets() const
  1711. {
  1712. std::vector<cmTarget*> tgts;
  1713. tgts.reserve(this->ImportedTargets.size());
  1714. for (auto const& impTarget : this->ImportedTargets) {
  1715. tgts.push_back(impTarget.second);
  1716. }
  1717. return tgts;
  1718. }
  1719. void cmMakefile::AddIncludeDirectories(const std::vector<std::string>& incs,
  1720. bool before)
  1721. {
  1722. if (incs.empty()) {
  1723. return;
  1724. }
  1725. std::string entryString = cmList::to_string(incs);
  1726. if (before) {
  1727. this->StateSnapshot.GetDirectory().PrependIncludeDirectoriesEntry(
  1728. BT<std::string>(entryString, this->Backtrace));
  1729. } else {
  1730. this->StateSnapshot.GetDirectory().AppendIncludeDirectoriesEntry(
  1731. BT<std::string>(entryString, this->Backtrace));
  1732. }
  1733. // Property on each target:
  1734. for (auto& target : this->Targets) {
  1735. cmTarget& t = target.second;
  1736. t.InsertInclude(BT<std::string>(entryString, this->Backtrace), before);
  1737. }
  1738. }
  1739. void cmMakefile::AddSystemIncludeDirectories(const std::set<std::string>& incs)
  1740. {
  1741. if (incs.empty()) {
  1742. return;
  1743. }
  1744. this->SystemIncludeDirectories.insert(incs.begin(), incs.end());
  1745. for (auto& target : this->Targets) {
  1746. cmTarget& t = target.second;
  1747. t.AddSystemIncludeDirectories(incs);
  1748. }
  1749. }
  1750. void cmMakefile::AddDefinition(const std::string& name, cm::string_view value)
  1751. {
  1752. this->StateSnapshot.SetDefinition(name, value);
  1753. #ifndef CMAKE_BOOTSTRAP
  1754. cmVariableWatch* vv = this->GetVariableWatch();
  1755. if (vv) {
  1756. vv->VariableAccessed(name, cmVariableWatch::VARIABLE_MODIFIED_ACCESS,
  1757. value.data(), this);
  1758. }
  1759. #endif
  1760. }
  1761. void cmMakefile::AddDefinitionBool(const std::string& name, bool value)
  1762. {
  1763. this->AddDefinition(name, value ? "ON" : "OFF");
  1764. }
  1765. void cmMakefile::AddCacheDefinition(const std::string& name, cmValue value,
  1766. cmValue doc,
  1767. cmStateEnums::CacheEntryType type,
  1768. bool force)
  1769. {
  1770. cmValue existingValue = this->GetState()->GetInitializedCacheValue(name);
  1771. // must be outside the following if() to keep it alive long enough
  1772. std::string nvalue;
  1773. if (existingValue &&
  1774. (this->GetState()->GetCacheEntryType(name) ==
  1775. cmStateEnums::UNINITIALIZED)) {
  1776. // if this is not a force, then use the value from the cache
  1777. // if it is a force, then use the value being passed in
  1778. if (!force) {
  1779. value = existingValue;
  1780. }
  1781. if (type == cmStateEnums::PATH || type == cmStateEnums::FILEPATH) {
  1782. cmList files(value);
  1783. for (auto& file : files) {
  1784. if (!cmIsOff(file)) {
  1785. file = cmSystemTools::CollapseFullPath(file);
  1786. }
  1787. }
  1788. nvalue = files.to_string();
  1789. value = cmValue{ nvalue };
  1790. this->GetCMakeInstance()->AddCacheEntry(name, value, doc, type);
  1791. value = this->GetState()->GetInitializedCacheValue(name);
  1792. }
  1793. }
  1794. this->GetCMakeInstance()->AddCacheEntry(name, value, doc, type);
  1795. switch (this->GetPolicyStatus(cmPolicies::CMP0126)) {
  1796. case cmPolicies::WARN:
  1797. if (this->PolicyOptionalWarningEnabled("CMAKE_POLICY_WARNING_CMP0126") &&
  1798. this->IsNormalDefinitionSet(name)) {
  1799. this->IssueMessage(
  1800. MessageType::AUTHOR_WARNING,
  1801. cmStrCat(cmPolicies::GetPolicyWarning(cmPolicies::CMP0126),
  1802. "\nFor compatibility with older versions of CMake, normal "
  1803. "variable \"",
  1804. name, "\" will be removed from the current scope."));
  1805. }
  1806. CM_FALLTHROUGH;
  1807. case cmPolicies::OLD:
  1808. // if there was a definition then remove it
  1809. this->StateSnapshot.RemoveDefinition(name);
  1810. break;
  1811. case cmPolicies::NEW:
  1812. case cmPolicies::REQUIRED_IF_USED:
  1813. case cmPolicies::REQUIRED_ALWAYS:
  1814. break;
  1815. }
  1816. }
  1817. void cmMakefile::MarkVariableAsUsed(const std::string& var)
  1818. {
  1819. this->StateSnapshot.GetDefinition(var);
  1820. }
  1821. bool cmMakefile::VariableInitialized(const std::string& var) const
  1822. {
  1823. return this->StateSnapshot.IsInitialized(var);
  1824. }
  1825. void cmMakefile::MaybeWarnUninitialized(std::string const& variable,
  1826. const char* sourceFilename) const
  1827. {
  1828. // check to see if we need to print a warning
  1829. // if strict mode is on and the variable has
  1830. // not been "cleared"/initialized with a set(foo ) call
  1831. if (this->GetCMakeInstance()->GetWarnUninitialized() &&
  1832. !this->VariableInitialized(variable)) {
  1833. if (this->CheckSystemVars ||
  1834. (sourceFilename && this->IsProjectFile(sourceFilename))) {
  1835. std::ostringstream msg;
  1836. msg << "uninitialized variable \'" << variable << "\'";
  1837. this->IssueMessage(MessageType::AUTHOR_WARNING, msg.str());
  1838. }
  1839. }
  1840. }
  1841. void cmMakefile::RemoveDefinition(const std::string& name)
  1842. {
  1843. this->StateSnapshot.RemoveDefinition(name);
  1844. #ifndef CMAKE_BOOTSTRAP
  1845. cmVariableWatch* vv = this->GetVariableWatch();
  1846. if (vv) {
  1847. vv->VariableAccessed(name, cmVariableWatch::VARIABLE_REMOVED_ACCESS,
  1848. nullptr, this);
  1849. }
  1850. #endif
  1851. }
  1852. void cmMakefile::RemoveCacheDefinition(const std::string& name) const
  1853. {
  1854. this->GetState()->RemoveCacheEntry(name);
  1855. }
  1856. void cmMakefile::SetProjectName(std::string const& p)
  1857. {
  1858. this->StateSnapshot.SetProjectName(p);
  1859. }
  1860. void cmMakefile::AddGlobalLinkInformation(cmTarget& target)
  1861. {
  1862. // for these targets do not add anything
  1863. switch (target.GetType()) {
  1864. case cmStateEnums::UTILITY:
  1865. case cmStateEnums::GLOBAL_TARGET:
  1866. case cmStateEnums::INTERFACE_LIBRARY:
  1867. return;
  1868. default:;
  1869. }
  1870. if (cmValue linkLibsProp = this->GetProperty("LINK_LIBRARIES")) {
  1871. cmList linkLibs{ *linkLibsProp };
  1872. for (auto j = linkLibs.begin(); j != linkLibs.end(); ++j) {
  1873. std::string libraryName = *j;
  1874. cmTargetLinkLibraryType libType = GENERAL_LibraryType;
  1875. if (libraryName == "optimized"_s) {
  1876. libType = OPTIMIZED_LibraryType;
  1877. ++j;
  1878. libraryName = *j;
  1879. } else if (libraryName == "debug"_s) {
  1880. libType = DEBUG_LibraryType;
  1881. ++j;
  1882. libraryName = *j;
  1883. }
  1884. // This is equivalent to the target_link_libraries plain signature.
  1885. target.AddLinkLibrary(*this, libraryName, libType);
  1886. target.AppendProperty(
  1887. "INTERFACE_LINK_LIBRARIES",
  1888. target.GetDebugGeneratorExpressions(libraryName, libType));
  1889. }
  1890. }
  1891. }
  1892. void cmMakefile::AddAlias(const std::string& lname, std::string const& tgtName,
  1893. bool globallyVisible)
  1894. {
  1895. this->AliasTargets[lname] = tgtName;
  1896. if (globallyVisible) {
  1897. this->GetGlobalGenerator()->AddAlias(lname, tgtName);
  1898. }
  1899. }
  1900. cmTarget* cmMakefile::AddLibrary(const std::string& lname,
  1901. cmStateEnums::TargetType type,
  1902. const std::vector<std::string>& srcs,
  1903. bool excludeFromAll)
  1904. {
  1905. assert(type == cmStateEnums::STATIC_LIBRARY ||
  1906. type == cmStateEnums::SHARED_LIBRARY ||
  1907. type == cmStateEnums::MODULE_LIBRARY ||
  1908. type == cmStateEnums::OBJECT_LIBRARY ||
  1909. type == cmStateEnums::INTERFACE_LIBRARY);
  1910. cmTarget* target = this->AddNewTarget(type, lname);
  1911. // Clear its dependencies. Otherwise, dependencies might persist
  1912. // over changes in CMakeLists.txt, making the information stale and
  1913. // hence useless.
  1914. target->ClearDependencyInformation(*this);
  1915. if (excludeFromAll) {
  1916. target->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
  1917. }
  1918. target->AddSources(srcs);
  1919. this->AddGlobalLinkInformation(*target);
  1920. return target;
  1921. }
  1922. cmTarget* cmMakefile::AddExecutable(const std::string& exeName,
  1923. const std::vector<std::string>& srcs,
  1924. bool excludeFromAll)
  1925. {
  1926. cmTarget* target = this->AddNewTarget(cmStateEnums::EXECUTABLE, exeName);
  1927. if (excludeFromAll) {
  1928. target->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
  1929. }
  1930. target->AddSources(srcs);
  1931. this->AddGlobalLinkInformation(*target);
  1932. return target;
  1933. }
  1934. cmTarget* cmMakefile::AddNewTarget(cmStateEnums::TargetType type,
  1935. const std::string& name)
  1936. {
  1937. return &this->CreateNewTarget(name, type).first;
  1938. }
  1939. cmTarget* cmMakefile::AddSynthesizedTarget(cmStateEnums::TargetType type,
  1940. const std::string& name)
  1941. {
  1942. return &this
  1943. ->CreateNewTarget(name, type, cmTarget::PerConfig::Yes,
  1944. cmTarget::Visibility::Generated)
  1945. .first;
  1946. }
  1947. std::pair<cmTarget&, bool> cmMakefile::CreateNewTarget(
  1948. const std::string& name, cmStateEnums::TargetType type,
  1949. cmTarget::PerConfig perConfig, cmTarget::Visibility vis)
  1950. {
  1951. auto ib =
  1952. this->Targets.emplace(name, cmTarget(name, type, vis, this, perConfig));
  1953. auto it = ib.first;
  1954. if (!ib.second) {
  1955. return std::make_pair(std::ref(it->second), false);
  1956. }
  1957. this->OrderedTargets.push_back(&it->second);
  1958. this->GetGlobalGenerator()->IndexTarget(&it->second);
  1959. this->GetStateSnapshot().GetDirectory().AddNormalTargetName(name);
  1960. return std::make_pair(std::ref(it->second), true);
  1961. }
  1962. cmTarget* cmMakefile::AddNewUtilityTarget(const std::string& utilityName,
  1963. bool excludeFromAll)
  1964. {
  1965. cmTarget* target = this->AddNewTarget(cmStateEnums::UTILITY, utilityName);
  1966. if (excludeFromAll) {
  1967. target->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
  1968. }
  1969. return target;
  1970. }
  1971. namespace {
  1972. }
  1973. #if !defined(CMAKE_BOOTSTRAP)
  1974. cmSourceGroup* cmMakefile::GetSourceGroup(
  1975. const std::vector<std::string>& name) const
  1976. {
  1977. cmSourceGroup* sg = nullptr;
  1978. // first look for source group starting with the same as the one we want
  1979. for (cmSourceGroup const& srcGroup : this->SourceGroups) {
  1980. std::string const& sgName = srcGroup.GetName();
  1981. if (sgName == name[0]) {
  1982. sg = const_cast<cmSourceGroup*>(&srcGroup);
  1983. break;
  1984. }
  1985. }
  1986. if (sg != nullptr) {
  1987. // iterate through its children to find match source group
  1988. for (unsigned int i = 1; i < name.size(); ++i) {
  1989. sg = sg->LookupChild(name[i]);
  1990. if (sg == nullptr) {
  1991. break;
  1992. }
  1993. }
  1994. }
  1995. return sg;
  1996. }
  1997. void cmMakefile::AddSourceGroup(const std::string& name, const char* regex)
  1998. {
  1999. std::vector<std::string> nameVector;
  2000. nameVector.push_back(name);
  2001. this->AddSourceGroup(nameVector, regex);
  2002. }
  2003. void cmMakefile::AddSourceGroup(const std::vector<std::string>& name,
  2004. const char* regex)
  2005. {
  2006. cmSourceGroup* sg = nullptr;
  2007. std::vector<std::string> currentName;
  2008. int i = 0;
  2009. const int lastElement = static_cast<int>(name.size() - 1);
  2010. for (i = lastElement; i >= 0; --i) {
  2011. currentName.assign(name.begin(), name.begin() + i + 1);
  2012. sg = this->GetSourceGroup(currentName);
  2013. if (sg != nullptr) {
  2014. break;
  2015. }
  2016. }
  2017. // i now contains the index of the last found component
  2018. if (i == lastElement) {
  2019. // group already exists, replace its regular expression
  2020. if (regex && sg) {
  2021. // We only want to set the regular expression. If there are already
  2022. // source files in the group, we don't want to remove them.
  2023. sg->SetGroupRegex(regex);
  2024. }
  2025. return;
  2026. }
  2027. if (i == -1) {
  2028. // group does not exist nor belong to any existing group
  2029. // add its first component
  2030. this->SourceGroups.emplace_back(name[0], regex);
  2031. sg = this->GetSourceGroup(currentName);
  2032. i = 0; // last component found
  2033. }
  2034. if (!sg) {
  2035. cmSystemTools::Error("Could not create source group ");
  2036. return;
  2037. }
  2038. // build the whole source group path
  2039. for (++i; i <= lastElement; ++i) {
  2040. sg->AddChild(cmSourceGroup(name[i], nullptr, sg->GetFullName().c_str()));
  2041. sg = sg->LookupChild(name[i]);
  2042. }
  2043. sg->SetGroupRegex(regex);
  2044. }
  2045. cmSourceGroup* cmMakefile::GetOrCreateSourceGroup(
  2046. const std::vector<std::string>& folders)
  2047. {
  2048. cmSourceGroup* sg = this->GetSourceGroup(folders);
  2049. if (sg == nullptr) {
  2050. this->AddSourceGroup(folders);
  2051. sg = this->GetSourceGroup(folders);
  2052. }
  2053. return sg;
  2054. }
  2055. cmSourceGroup* cmMakefile::GetOrCreateSourceGroup(const std::string& name)
  2056. {
  2057. std::string delimiters;
  2058. if (cmValue p = this->GetDefinition("SOURCE_GROUP_DELIMITER")) {
  2059. delimiters = *p;
  2060. } else {
  2061. delimiters = "/\\";
  2062. }
  2063. return this->GetOrCreateSourceGroup(cmTokenize(name, delimiters));
  2064. }
  2065. /**
  2066. * Find a source group whose regular expression matches the filename
  2067. * part of the given source name. Search backward through the list of
  2068. * source groups, and take the first matching group found. This way
  2069. * non-inherited SOURCE_GROUP commands will have precedence over
  2070. * inherited ones.
  2071. */
  2072. cmSourceGroup* cmMakefile::FindSourceGroup(
  2073. const std::string& source, std::vector<cmSourceGroup>& groups) const
  2074. {
  2075. // First search for a group that lists the file explicitly.
  2076. for (auto sg = groups.rbegin(); sg != groups.rend(); ++sg) {
  2077. cmSourceGroup* result = sg->MatchChildrenFiles(source);
  2078. if (result) {
  2079. return result;
  2080. }
  2081. }
  2082. // Now search for a group whose regex matches the file.
  2083. for (auto sg = groups.rbegin(); sg != groups.rend(); ++sg) {
  2084. cmSourceGroup* result = sg->MatchChildrenRegex(source);
  2085. if (result) {
  2086. return result;
  2087. }
  2088. }
  2089. // Shouldn't get here, but just in case, return the default group.
  2090. return groups.data();
  2091. }
  2092. #endif
  2093. static bool mightExpandVariablesCMP0019(const char* s)
  2094. {
  2095. return s && *s && strstr(s, "${") && strchr(s, '}');
  2096. }
  2097. void cmMakefile::ExpandVariablesCMP0019()
  2098. {
  2099. // Drop this ancient compatibility behavior with a policy.
  2100. cmPolicies::PolicyStatus pol = this->GetPolicyStatus(cmPolicies::CMP0019);
  2101. if (pol != cmPolicies::OLD && pol != cmPolicies::WARN) {
  2102. return;
  2103. }
  2104. std::ostringstream w;
  2105. cmValue includeDirs = this->GetProperty("INCLUDE_DIRECTORIES");
  2106. if (includeDirs && mightExpandVariablesCMP0019(includeDirs->c_str())) {
  2107. std::string dirs = *includeDirs;
  2108. this->ExpandVariablesInString(dirs, true, true);
  2109. if (pol == cmPolicies::WARN && dirs != *includeDirs) {
  2110. /* clang-format off */
  2111. w << "Evaluated directory INCLUDE_DIRECTORIES\n"
  2112. << " " << *includeDirs << "\n"
  2113. << "as\n"
  2114. << " " << dirs << "\n";
  2115. /* clang-format on */
  2116. }
  2117. this->SetProperty("INCLUDE_DIRECTORIES", dirs);
  2118. }
  2119. // Also for each target's INCLUDE_DIRECTORIES property:
  2120. for (auto& target : this->Targets) {
  2121. cmTarget& t = target.second;
  2122. if (t.GetType() == cmStateEnums::INTERFACE_LIBRARY ||
  2123. t.GetType() == cmStateEnums::GLOBAL_TARGET) {
  2124. continue;
  2125. }
  2126. includeDirs = t.GetProperty("INCLUDE_DIRECTORIES");
  2127. if (includeDirs && mightExpandVariablesCMP0019(includeDirs->c_str())) {
  2128. std::string dirs = *includeDirs;
  2129. this->ExpandVariablesInString(dirs, true, true);
  2130. if (pol == cmPolicies::WARN && dirs != *includeDirs) {
  2131. /* clang-format off */
  2132. w << "Evaluated target " << t.GetName() << " INCLUDE_DIRECTORIES\n"
  2133. << " " << *includeDirs << "\n"
  2134. << "as\n"
  2135. << " " << dirs << "\n";
  2136. /* clang-format on */
  2137. }
  2138. t.SetProperty("INCLUDE_DIRECTORIES", dirs);
  2139. }
  2140. }
  2141. if (cmValue linkDirsProp = this->GetProperty("LINK_DIRECTORIES")) {
  2142. if (mightExpandVariablesCMP0019(linkDirsProp->c_str())) {
  2143. std::string d = *linkDirsProp;
  2144. const std::string orig = d;
  2145. this->ExpandVariablesInString(d, true, true);
  2146. if (pol == cmPolicies::WARN && d != orig) {
  2147. /* clang-format off */
  2148. w << "Evaluated link directories\n"
  2149. << " " << orig << "\n"
  2150. << "as\n"
  2151. << " " << d << "\n";
  2152. /* clang-format on */
  2153. }
  2154. }
  2155. }
  2156. if (cmValue linkLibsProp = this->GetProperty("LINK_LIBRARIES")) {
  2157. cmList linkLibs{ *linkLibsProp };
  2158. for (auto l = linkLibs.begin(); l != linkLibs.end(); ++l) {
  2159. std::string libName = *l;
  2160. if (libName == "optimized"_s || libName == "debug"_s) {
  2161. ++l;
  2162. libName = *l;
  2163. }
  2164. if (mightExpandVariablesCMP0019(libName.c_str())) {
  2165. const std::string orig = libName;
  2166. this->ExpandVariablesInString(libName, true, true);
  2167. if (pol == cmPolicies::WARN && libName != orig) {
  2168. /* clang-format off */
  2169. w << "Evaluated link library\n"
  2170. << " " << orig << "\n"
  2171. << "as\n"
  2172. << " " << libName << "\n";
  2173. /* clang-format on */
  2174. }
  2175. }
  2176. }
  2177. }
  2178. if (!w.str().empty()) {
  2179. std::ostringstream m;
  2180. /* clang-format off */
  2181. m << cmPolicies::GetPolicyWarning(cmPolicies::CMP0019)
  2182. << "\n"
  2183. << "The following variable evaluations were encountered:\n"
  2184. << w.str();
  2185. /* clang-format on */
  2186. this->GetCMakeInstance()->IssueMessage(MessageType::AUTHOR_WARNING,
  2187. m.str(), this->Backtrace);
  2188. }
  2189. }
  2190. bool cmMakefile::IsOn(const std::string& name) const
  2191. {
  2192. return cmIsOn(this->GetDefinition(name));
  2193. }
  2194. bool cmMakefile::IsSet(const std::string& name) const
  2195. {
  2196. cmValue value = this->GetDefinition(name);
  2197. if (!value) {
  2198. return false;
  2199. }
  2200. if (value->empty()) {
  2201. return false;
  2202. }
  2203. if (cmIsNOTFOUND(*value)) {
  2204. return false;
  2205. }
  2206. return true;
  2207. }
  2208. bool cmMakefile::PlatformIs32Bit() const
  2209. {
  2210. if (cmValue plat_abi = this->GetDefinition("CMAKE_INTERNAL_PLATFORM_ABI")) {
  2211. if (*plat_abi == "ELF X32"_s) {
  2212. return false;
  2213. }
  2214. }
  2215. if (cmValue sizeof_dptr = this->GetDefinition("CMAKE_SIZEOF_VOID_P")) {
  2216. return atoi(sizeof_dptr->c_str()) == 4;
  2217. }
  2218. return false;
  2219. }
  2220. bool cmMakefile::PlatformIs64Bit() const
  2221. {
  2222. if (cmValue sizeof_dptr = this->GetDefinition("CMAKE_SIZEOF_VOID_P")) {
  2223. return atoi(sizeof_dptr->c_str()) == 8;
  2224. }
  2225. return false;
  2226. }
  2227. bool cmMakefile::PlatformIsx32() const
  2228. {
  2229. if (cmValue plat_abi = this->GetDefinition("CMAKE_INTERNAL_PLATFORM_ABI")) {
  2230. if (*plat_abi == "ELF X32"_s) {
  2231. return true;
  2232. }
  2233. }
  2234. return false;
  2235. }
  2236. cmMakefile::AppleSDK cmMakefile::GetAppleSDKType() const
  2237. {
  2238. std::string sdkRoot;
  2239. sdkRoot = this->GetSafeDefinition("CMAKE_OSX_SYSROOT");
  2240. sdkRoot = cmSystemTools::LowerCase(sdkRoot);
  2241. struct
  2242. {
  2243. std::string name;
  2244. AppleSDK sdk;
  2245. } const sdkDatabase[]{
  2246. { "appletvos", AppleSDK::AppleTVOS },
  2247. { "appletvsimulator", AppleSDK::AppleTVSimulator },
  2248. { "iphoneos", AppleSDK::IPhoneOS },
  2249. { "iphonesimulator", AppleSDK::IPhoneSimulator },
  2250. { "watchos", AppleSDK::WatchOS },
  2251. { "watchsimulator", AppleSDK::WatchSimulator },
  2252. { "xros", AppleSDK::XROS },
  2253. { "xrsimulator", AppleSDK::XRSimulator },
  2254. };
  2255. for (auto const& entry : sdkDatabase) {
  2256. if (cmHasPrefix(sdkRoot, entry.name) ||
  2257. sdkRoot.find(cmStrCat('/', entry.name)) != std::string::npos) {
  2258. return entry.sdk;
  2259. }
  2260. }
  2261. return AppleSDK::MacOS;
  2262. }
  2263. bool cmMakefile::PlatformIsAppleEmbedded() const
  2264. {
  2265. return this->GetAppleSDKType() != AppleSDK::MacOS;
  2266. }
  2267. bool cmMakefile::PlatformSupportsAppleTextStubs() const
  2268. {
  2269. return this->IsOn("APPLE") && this->IsSet("CMAKE_TAPI");
  2270. }
  2271. const char* cmMakefile::GetSONameFlag(const std::string& language) const
  2272. {
  2273. std::string name = "CMAKE_SHARED_LIBRARY_SONAME";
  2274. if (!language.empty()) {
  2275. name += "_";
  2276. name += language;
  2277. }
  2278. name += "_FLAG";
  2279. return this->GetDefinition(name).GetCStr();
  2280. }
  2281. bool cmMakefile::CanIWriteThisFile(std::string const& fileName) const
  2282. {
  2283. if (!this->IsOn("CMAKE_DISABLE_SOURCE_CHANGES")) {
  2284. return true;
  2285. }
  2286. // If we are doing an in-source build, then the test will always fail
  2287. if (cmSystemTools::SameFile(this->GetHomeDirectory(),
  2288. this->GetHomeOutputDirectory())) {
  2289. return !this->IsOn("CMAKE_DISABLE_IN_SOURCE_BUILD");
  2290. }
  2291. return !cmSystemTools::IsSubDirectory(fileName, this->GetHomeDirectory()) ||
  2292. cmSystemTools::IsSubDirectory(fileName, this->GetHomeOutputDirectory()) ||
  2293. cmSystemTools::SameFile(fileName, this->GetHomeOutputDirectory());
  2294. }
  2295. const std::string& cmMakefile::GetRequiredDefinition(
  2296. const std::string& name) const
  2297. {
  2298. static std::string const empty;
  2299. cmValue def = this->GetDefinition(name);
  2300. if (!def) {
  2301. cmSystemTools::Error("Error required internal CMake variable not "
  2302. "set, cmake may not be built correctly.\n"
  2303. "Missing variable is:\n" +
  2304. name);
  2305. return empty;
  2306. }
  2307. return *def;
  2308. }
  2309. bool cmMakefile::IsDefinitionSet(const std::string& name) const
  2310. {
  2311. cmValue def = this->StateSnapshot.GetDefinition(name);
  2312. if (!def) {
  2313. def = this->GetState()->GetInitializedCacheValue(name);
  2314. }
  2315. #ifndef CMAKE_BOOTSTRAP
  2316. if (cmVariableWatch* vv = this->GetVariableWatch()) {
  2317. if (!def) {
  2318. vv->VariableAccessed(
  2319. name, cmVariableWatch::UNKNOWN_VARIABLE_DEFINED_ACCESS, nullptr, this);
  2320. }
  2321. }
  2322. #endif
  2323. return def != nullptr;
  2324. }
  2325. bool cmMakefile::IsNormalDefinitionSet(const std::string& name) const
  2326. {
  2327. cmValue def = this->StateSnapshot.GetDefinition(name);
  2328. #ifndef CMAKE_BOOTSTRAP
  2329. if (cmVariableWatch* vv = this->GetVariableWatch()) {
  2330. if (!def) {
  2331. vv->VariableAccessed(
  2332. name, cmVariableWatch::UNKNOWN_VARIABLE_DEFINED_ACCESS, nullptr, this);
  2333. }
  2334. }
  2335. #endif
  2336. return def != nullptr;
  2337. }
  2338. cmValue cmMakefile::GetDefinition(const std::string& name) const
  2339. {
  2340. cmValue def = this->StateSnapshot.GetDefinition(name);
  2341. if (!def) {
  2342. def = this->GetState()->GetInitializedCacheValue(name);
  2343. }
  2344. #ifndef CMAKE_BOOTSTRAP
  2345. cmVariableWatch* vv = this->GetVariableWatch();
  2346. if (vv && !this->SuppressSideEffects) {
  2347. bool const watch_function_executed =
  2348. vv->VariableAccessed(name,
  2349. def ? cmVariableWatch::VARIABLE_READ_ACCESS
  2350. : cmVariableWatch::UNKNOWN_VARIABLE_READ_ACCESS,
  2351. def.GetCStr(), this);
  2352. if (watch_function_executed) {
  2353. // A callback was executed and may have caused re-allocation of the
  2354. // variable storage. Look it up again for now.
  2355. // FIXME: Refactor variable storage to avoid this problem.
  2356. def = this->StateSnapshot.GetDefinition(name);
  2357. if (!def) {
  2358. def = this->GetState()->GetInitializedCacheValue(name);
  2359. }
  2360. }
  2361. }
  2362. #endif
  2363. return def;
  2364. }
  2365. const std::string& cmMakefile::GetSafeDefinition(const std::string& name) const
  2366. {
  2367. return this->GetDefinition(name);
  2368. }
  2369. std::vector<std::string> cmMakefile::GetDefinitions() const
  2370. {
  2371. std::vector<std::string> res = this->StateSnapshot.ClosureKeys();
  2372. cm::append(res, this->GetState()->GetCacheEntryKeys());
  2373. std::sort(res.begin(), res.end());
  2374. return res;
  2375. }
  2376. const std::string& cmMakefile::ExpandVariablesInString(
  2377. std::string& source) const
  2378. {
  2379. return this->ExpandVariablesInString(source, false, false);
  2380. }
  2381. const std::string& cmMakefile::ExpandVariablesInString(
  2382. std::string& source, bool escapeQuotes, bool noEscapes, bool atOnly,
  2383. const char* filename, long line, bool removeEmpty, bool replaceAt) const
  2384. {
  2385. bool compareResults = false;
  2386. MessageType mtype = MessageType::LOG;
  2387. std::string errorstr;
  2388. std::string original;
  2389. // Sanity check the @ONLY mode.
  2390. if (atOnly && (!noEscapes || !removeEmpty)) {
  2391. // This case should never be called. At-only is for
  2392. // configure-file/string which always does no escapes.
  2393. this->IssueMessage(MessageType::INTERNAL_ERROR,
  2394. "ExpandVariablesInString @ONLY called "
  2395. "on something with escapes.");
  2396. return source;
  2397. }
  2398. // Variables used in the WARN case.
  2399. std::string newResult;
  2400. std::string newErrorstr;
  2401. MessageType newError = MessageType::LOG;
  2402. switch (this->GetPolicyStatus(cmPolicies::CMP0053)) {
  2403. case cmPolicies::WARN: {
  2404. // Save the original string for the warning.
  2405. original = source;
  2406. newResult = source;
  2407. compareResults = true;
  2408. // Suppress variable watches to avoid calling hooks twice. Suppress new
  2409. // dereferences since the OLD behavior is still what is actually used.
  2410. this->SuppressSideEffects = true;
  2411. newError = this->ExpandVariablesInStringNew(
  2412. newErrorstr, newResult, escapeQuotes, noEscapes, atOnly, filename,
  2413. line, replaceAt);
  2414. this->SuppressSideEffects = false;
  2415. CM_FALLTHROUGH;
  2416. }
  2417. case cmPolicies::OLD:
  2418. mtype = this->ExpandVariablesInStringOld(errorstr, source, escapeQuotes,
  2419. noEscapes, atOnly, filename,
  2420. line, removeEmpty, true);
  2421. break;
  2422. case cmPolicies::REQUIRED_IF_USED:
  2423. case cmPolicies::REQUIRED_ALWAYS:
  2424. // Messaging here would be *very* verbose.
  2425. case cmPolicies::NEW:
  2426. mtype = this->ExpandVariablesInStringNew(errorstr, source, escapeQuotes,
  2427. noEscapes, atOnly, filename,
  2428. line, replaceAt);
  2429. break;
  2430. }
  2431. // If it's an error in either case, just report the error...
  2432. if (mtype != MessageType::LOG) {
  2433. if (mtype == MessageType::FATAL_ERROR) {
  2434. cmSystemTools::SetFatalErrorOccurred();
  2435. }
  2436. this->IssueMessage(mtype, errorstr);
  2437. }
  2438. // ...otherwise, see if there's a difference that needs to be warned about.
  2439. else if (compareResults && (newResult != source || newError != mtype)) {
  2440. std::string msg =
  2441. cmStrCat(cmPolicies::GetPolicyWarning(cmPolicies::CMP0053), '\n');
  2442. std::string msg_input = original;
  2443. cmSystemTools::ReplaceString(msg_input, "\n", "\n ");
  2444. msg += "For input:\n '";
  2445. msg += msg_input;
  2446. msg += "'\n";
  2447. std::string msg_old = source;
  2448. cmSystemTools::ReplaceString(msg_old, "\n", "\n ");
  2449. msg += "the old evaluation rules produce:\n '";
  2450. msg += msg_old;
  2451. msg += "'\n";
  2452. if (newError == mtype) {
  2453. std::string msg_new = newResult;
  2454. cmSystemTools::ReplaceString(msg_new, "\n", "\n ");
  2455. msg += "but the new evaluation rules produce:\n '";
  2456. msg += msg_new;
  2457. msg += "'\n";
  2458. } else {
  2459. std::string msg_err = newErrorstr;
  2460. cmSystemTools::ReplaceString(msg_err, "\n", "\n ");
  2461. msg += "but the new evaluation rules produce an error:\n ";
  2462. msg += msg_err;
  2463. msg += "\n";
  2464. }
  2465. msg +=
  2466. "Using the old result for compatibility since the policy is not set.";
  2467. this->IssueMessage(MessageType::AUTHOR_WARNING, msg);
  2468. }
  2469. return source;
  2470. }
  2471. MessageType cmMakefile::ExpandVariablesInStringOld(
  2472. std::string& errorstr, std::string& source, bool escapeQuotes,
  2473. bool noEscapes, bool atOnly, const char* filename, long line,
  2474. bool removeEmpty, bool replaceAt) const
  2475. {
  2476. // Fast path strings without any special characters.
  2477. if (source.find_first_of("$@\\") == std::string::npos) {
  2478. return MessageType::LOG;
  2479. }
  2480. // Special-case the @ONLY mode.
  2481. if (atOnly) {
  2482. // Store an original copy of the input.
  2483. std::string input = source;
  2484. // Start with empty output.
  2485. source.clear();
  2486. // Look for one @VAR@ at a time.
  2487. const char* in = input.c_str();
  2488. while (this->cmAtVarRegex.find(in)) {
  2489. // Get the range of the string to replace.
  2490. const char* first = in + this->cmAtVarRegex.start();
  2491. const char* last = in + this->cmAtVarRegex.end();
  2492. // Store the unchanged part of the string now.
  2493. source.append(in, first - in);
  2494. // Lookup the definition of VAR.
  2495. std::string var(first + 1, last - first - 2);
  2496. if (cmValue val = this->GetDefinition(var)) {
  2497. // Store the value in the output escaping as requested.
  2498. if (escapeQuotes) {
  2499. source.append(cmEscapeQuotes(*val));
  2500. } else {
  2501. source.append(*val);
  2502. }
  2503. }
  2504. // Continue looking for @VAR@ further along the string.
  2505. in = last;
  2506. }
  2507. // Append the rest of the unchanged part of the string.
  2508. source.append(in);
  2509. return MessageType::LOG;
  2510. }
  2511. // This method replaces ${VAR} and @VAR@ where VAR is looked up
  2512. // with GetDefinition(), if not found in the map, nothing is expanded.
  2513. // It also supports the $ENV{VAR} syntax where VAR is looked up in
  2514. // the current environment variables.
  2515. cmCommandArgumentParserHelper parser;
  2516. parser.SetMakefile(this);
  2517. parser.SetLineFile(line, filename);
  2518. parser.SetEscapeQuotes(escapeQuotes);
  2519. parser.SetNoEscapeMode(noEscapes);
  2520. parser.SetReplaceAtSyntax(replaceAt);
  2521. parser.SetRemoveEmpty(removeEmpty);
  2522. int res = parser.ParseString(source, 0);
  2523. const char* emsg = parser.GetError();
  2524. MessageType mtype = MessageType::LOG;
  2525. if (res && !emsg[0]) {
  2526. source = parser.GetResult();
  2527. } else {
  2528. // Construct the main error message.
  2529. std::ostringstream error;
  2530. error << "Syntax error in cmake code ";
  2531. if (filename && line > 0) {
  2532. // This filename and line number may be more specific than the
  2533. // command context because one command invocation can have
  2534. // arguments on multiple lines.
  2535. error << "at\n"
  2536. << " " << filename << ":" << line << "\n";
  2537. }
  2538. error << "when parsing string\n"
  2539. << " " << source << "\n";
  2540. error << emsg;
  2541. // If the parser failed ("res" is false) then this is a real
  2542. // argument parsing error, so the policy applies. Otherwise the
  2543. // parser reported an error message without failing because the
  2544. // helper implementation is unhappy, which has always reported an
  2545. // error.
  2546. mtype = MessageType::FATAL_ERROR;
  2547. if (!res) {
  2548. // This is a real argument parsing error. Use policy CMP0010 to
  2549. // decide whether it is an error.
  2550. switch (this->GetPolicyStatus(cmPolicies::CMP0010)) {
  2551. case cmPolicies::WARN:
  2552. error << "\n" << cmPolicies::GetPolicyWarning(cmPolicies::CMP0010);
  2553. CM_FALLTHROUGH;
  2554. case cmPolicies::OLD:
  2555. // OLD behavior is to just warn and continue.
  2556. mtype = MessageType::AUTHOR_WARNING;
  2557. break;
  2558. case cmPolicies::REQUIRED_IF_USED:
  2559. case cmPolicies::REQUIRED_ALWAYS:
  2560. error << "\n"
  2561. << cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0010);
  2562. break;
  2563. case cmPolicies::NEW:
  2564. // NEW behavior is to report the error.
  2565. break;
  2566. }
  2567. }
  2568. errorstr = error.str();
  2569. }
  2570. return mtype;
  2571. }
  2572. enum t_domain
  2573. {
  2574. NORMAL,
  2575. ENVIRONMENT,
  2576. CACHE
  2577. };
  2578. struct t_lookup
  2579. {
  2580. t_domain domain = NORMAL;
  2581. size_t loc = 0;
  2582. };
  2583. bool cmMakefile::IsProjectFile(const char* filename) const
  2584. {
  2585. return cmSystemTools::IsSubDirectory(filename, this->GetHomeDirectory()) ||
  2586. (cmSystemTools::IsSubDirectory(filename, this->GetHomeOutputDirectory()) &&
  2587. !cmSystemTools::IsSubDirectory(filename, "/CMakeFiles"));
  2588. }
  2589. size_t cmMakefile::GetRecursionDepthLimit() const
  2590. {
  2591. size_t depth = CMake_DEFAULT_RECURSION_LIMIT;
  2592. if (cmValue depthStr =
  2593. this->GetDefinition("CMAKE_MAXIMUM_RECURSION_DEPTH")) {
  2594. unsigned long depthUL;
  2595. if (cmStrToULong(depthStr.GetCStr(), &depthUL)) {
  2596. depth = depthUL;
  2597. }
  2598. } else if (cm::optional<std::string> depthEnv =
  2599. cmSystemTools::GetEnvVar("CMAKE_MAXIMUM_RECURSION_DEPTH")) {
  2600. unsigned long depthUL;
  2601. if (cmStrToULong(*depthEnv, &depthUL)) {
  2602. depth = depthUL;
  2603. }
  2604. }
  2605. return depth;
  2606. }
  2607. size_t cmMakefile::GetRecursionDepth() const
  2608. {
  2609. return this->RecursionDepth;
  2610. }
  2611. void cmMakefile::SetRecursionDepth(size_t recursionDepth)
  2612. {
  2613. this->RecursionDepth = recursionDepth;
  2614. }
  2615. std::string cmMakefile::NewDeferId() const
  2616. {
  2617. return this->GetGlobalGenerator()->NewDeferId();
  2618. }
  2619. bool cmMakefile::DeferCall(std::string id, std::string file,
  2620. cmListFileFunction lff)
  2621. {
  2622. if (!this->Defer) {
  2623. return false;
  2624. }
  2625. this->Defer->Commands.emplace_back(
  2626. DeferCommand{ std::move(id), std::move(file), std::move(lff) });
  2627. return true;
  2628. }
  2629. bool cmMakefile::DeferCancelCall(std::string const& id)
  2630. {
  2631. if (!this->Defer) {
  2632. return false;
  2633. }
  2634. for (DeferCommand& dc : this->Defer->Commands) {
  2635. if (dc.Id == id) {
  2636. dc.Id.clear();
  2637. }
  2638. }
  2639. return true;
  2640. }
  2641. cm::optional<std::string> cmMakefile::DeferGetCallIds() const
  2642. {
  2643. cm::optional<std::string> ids;
  2644. if (this->Defer) {
  2645. ids = cmList::to_string(
  2646. cmMakeRange(this->Defer->Commands)
  2647. .filter([](DeferCommand const& dc) -> bool { return !dc.Id.empty(); })
  2648. .transform(
  2649. [](DeferCommand const& dc) -> std::string const& { return dc.Id; }));
  2650. }
  2651. return ids;
  2652. }
  2653. cm::optional<std::string> cmMakefile::DeferGetCall(std::string const& id) const
  2654. {
  2655. cm::optional<std::string> call;
  2656. if (this->Defer) {
  2657. std::string tmp;
  2658. for (DeferCommand const& dc : this->Defer->Commands) {
  2659. if (dc.Id == id) {
  2660. tmp = dc.Command.OriginalName();
  2661. for (cmListFileArgument const& arg : dc.Command.Arguments()) {
  2662. tmp = cmStrCat(tmp, ';', arg.Value);
  2663. }
  2664. break;
  2665. }
  2666. }
  2667. call = std::move(tmp);
  2668. }
  2669. return call;
  2670. }
  2671. MessageType cmMakefile::ExpandVariablesInStringNew(
  2672. std::string& errorstr, std::string& source, bool escapeQuotes,
  2673. bool noEscapes, bool atOnly, const char* filename, long line,
  2674. bool replaceAt) const
  2675. {
  2676. // This method replaces ${VAR} and @VAR@ where VAR is looked up
  2677. // with GetDefinition(), if not found in the map, nothing is expanded.
  2678. // It also supports the $ENV{VAR} syntax where VAR is looked up in
  2679. // the current environment variables.
  2680. const char* in = source.c_str();
  2681. const char* last = in;
  2682. std::string result;
  2683. result.reserve(source.size());
  2684. std::vector<t_lookup> openstack;
  2685. bool error = false;
  2686. bool done = false;
  2687. MessageType mtype = MessageType::LOG;
  2688. cmState* state = this->GetCMakeInstance()->GetState();
  2689. static const std::string lineVar = "CMAKE_CURRENT_LIST_LINE";
  2690. do {
  2691. char inc = *in;
  2692. switch (inc) {
  2693. case '}':
  2694. if (!openstack.empty()) {
  2695. t_lookup var = openstack.back();
  2696. openstack.pop_back();
  2697. result.append(last, in - last);
  2698. std::string const& lookup = result.substr(var.loc);
  2699. cmValue value = nullptr;
  2700. std::string varresult;
  2701. std::string svalue;
  2702. switch (var.domain) {
  2703. case NORMAL:
  2704. if (filename && lookup == lineVar) {
  2705. cmListFileContext const& top = this->Backtrace.Top();
  2706. if (top.DeferId) {
  2707. varresult = cmStrCat("DEFERRED:"_s, *top.DeferId);
  2708. } else {
  2709. varresult = std::to_string(line);
  2710. }
  2711. } else {
  2712. value = this->GetDefinition(lookup);
  2713. }
  2714. break;
  2715. case ENVIRONMENT:
  2716. if (cmSystemTools::GetEnv(lookup, svalue)) {
  2717. value = cmValue(svalue);
  2718. }
  2719. break;
  2720. case CACHE:
  2721. value = state->GetCacheEntryValue(lookup);
  2722. break;
  2723. }
  2724. // Get the string we're meant to append to.
  2725. if (value) {
  2726. if (escapeQuotes) {
  2727. varresult = cmEscapeQuotes(*value);
  2728. } else {
  2729. varresult = *value;
  2730. }
  2731. } else if (!this->SuppressSideEffects) {
  2732. this->MaybeWarnUninitialized(lookup, filename);
  2733. }
  2734. result.replace(var.loc, result.size() - var.loc, varresult);
  2735. // Start looking from here on out.
  2736. last = in + 1;
  2737. }
  2738. break;
  2739. case '$':
  2740. if (!atOnly) {
  2741. t_lookup lookup;
  2742. const char* next = in + 1;
  2743. const char* start = nullptr;
  2744. char nextc = *next;
  2745. if (nextc == '{') {
  2746. // Looking for a variable.
  2747. start = in + 2;
  2748. lookup.domain = NORMAL;
  2749. } else if (nextc == '<') {
  2750. } else if (!nextc) {
  2751. result.append(last, next - last);
  2752. last = next;
  2753. } else if (cmHasLiteralPrefix(next, "ENV{")) {
  2754. // Looking for an environment variable.
  2755. start = in + 5;
  2756. lookup.domain = ENVIRONMENT;
  2757. } else if (cmHasLiteralPrefix(next, "CACHE{")) {
  2758. // Looking for a cache variable.
  2759. start = in + 7;
  2760. lookup.domain = CACHE;
  2761. } else {
  2762. if (this->cmNamedCurly.find(next)) {
  2763. errorstr = "Syntax $" +
  2764. std::string(next, this->cmNamedCurly.end()) +
  2765. "{} is not supported. Only ${}, $ENV{}, "
  2766. "and $CACHE{} are allowed.";
  2767. mtype = MessageType::FATAL_ERROR;
  2768. error = true;
  2769. }
  2770. }
  2771. if (start) {
  2772. result.append(last, in - last);
  2773. last = start;
  2774. in = start - 1;
  2775. lookup.loc = result.size();
  2776. openstack.push_back(lookup);
  2777. }
  2778. break;
  2779. }
  2780. CM_FALLTHROUGH;
  2781. case '\\':
  2782. if (!noEscapes) {
  2783. const char* next = in + 1;
  2784. char nextc = *next;
  2785. if (nextc == 't') {
  2786. result.append(last, in - last);
  2787. result.push_back('\t');
  2788. last = next + 1;
  2789. } else if (nextc == 'n') {
  2790. result.append(last, in - last);
  2791. result.push_back('\n');
  2792. last = next + 1;
  2793. } else if (nextc == 'r') {
  2794. result.append(last, in - last);
  2795. result.push_back('\r');
  2796. last = next + 1;
  2797. } else if (nextc == ';' && openstack.empty()) {
  2798. // Handled in ExpandListArgument; pass the backslash literally.
  2799. } else if (isalnum(nextc) || nextc == '\0') {
  2800. errorstr += "Invalid character escape '\\";
  2801. if (nextc) {
  2802. errorstr += nextc;
  2803. errorstr += "'.";
  2804. } else {
  2805. errorstr += "' (at end of input).";
  2806. }
  2807. error = true;
  2808. } else {
  2809. // Take what we've found so far, skipping the escape character.
  2810. result.append(last, in - last);
  2811. // Start tracking from the next character.
  2812. last = in + 1;
  2813. }
  2814. // Skip the next character since it was escaped, but don't read past
  2815. // the end of the string.
  2816. if (*last) {
  2817. ++in;
  2818. }
  2819. }
  2820. break;
  2821. case '\n':
  2822. // Onto the next line.
  2823. ++line;
  2824. break;
  2825. case '\0':
  2826. done = true;
  2827. break;
  2828. case '@':
  2829. if (replaceAt) {
  2830. const char* nextAt = strchr(in + 1, '@');
  2831. if (nextAt && nextAt != in + 1 &&
  2832. nextAt ==
  2833. in + 1 +
  2834. strspn(in + 1,
  2835. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  2836. "abcdefghijklmnopqrstuvwxyz"
  2837. "0123456789/_.+-")) {
  2838. std::string variable(in + 1, nextAt - in - 1);
  2839. std::string varresult;
  2840. if (filename && variable == lineVar) {
  2841. varresult = std::to_string(line);
  2842. } else {
  2843. cmValue def = this->GetDefinition(variable);
  2844. if (def) {
  2845. varresult = *def;
  2846. } else if (!this->SuppressSideEffects) {
  2847. this->MaybeWarnUninitialized(variable, filename);
  2848. }
  2849. }
  2850. if (escapeQuotes) {
  2851. varresult = cmEscapeQuotes(varresult);
  2852. }
  2853. // Skip over the variable.
  2854. result.append(last, in - last);
  2855. result.append(varresult);
  2856. in = nextAt;
  2857. last = in + 1;
  2858. break;
  2859. }
  2860. }
  2861. // Failed to find a valid @ expansion; treat it as literal.
  2862. CM_FALLTHROUGH;
  2863. default: {
  2864. if (!openstack.empty() &&
  2865. !(isalnum(inc) || inc == '_' || inc == '/' || inc == '.' ||
  2866. inc == '+' || inc == '-')) {
  2867. errorstr += "Invalid character (\'";
  2868. errorstr += inc;
  2869. result.append(last, in - last);
  2870. errorstr += cmStrCat("\') in a variable name: "
  2871. "'",
  2872. result.substr(openstack.back().loc), '\'');
  2873. mtype = MessageType::FATAL_ERROR;
  2874. error = true;
  2875. }
  2876. break;
  2877. }
  2878. }
  2879. // Look at the next character.
  2880. } while (!error && !done && *++in);
  2881. // Check for open variable references yet.
  2882. if (!error && !openstack.empty()) {
  2883. // There's an open variable reference waiting. Policy CMP0010 flags
  2884. // whether this is an error or not. The new parser now enforces
  2885. // CMP0010 as well.
  2886. errorstr += "There is an unterminated variable reference.";
  2887. error = true;
  2888. }
  2889. if (error) {
  2890. std::ostringstream emsg;
  2891. emsg << "Syntax error in cmake code ";
  2892. if (filename) {
  2893. // This filename and line number may be more specific than the
  2894. // command context because one command invocation can have
  2895. // arguments on multiple lines.
  2896. emsg << "at\n"
  2897. << " " << filename << ":" << line << "\n";
  2898. }
  2899. emsg << "when parsing string\n"
  2900. << " " << source << "\n";
  2901. emsg << errorstr;
  2902. mtype = MessageType::FATAL_ERROR;
  2903. errorstr = emsg.str();
  2904. } else {
  2905. // Append the rest of the unchanged part of the string.
  2906. result.append(last);
  2907. source = result;
  2908. }
  2909. return mtype;
  2910. }
  2911. void cmMakefile::RemoveVariablesInString(std::string& source,
  2912. bool atOnly) const
  2913. {
  2914. if (!atOnly) {
  2915. cmsys::RegularExpression var("(\\${[A-Za-z_0-9]*})");
  2916. while (var.find(source)) {
  2917. source.erase(var.start(), var.end() - var.start());
  2918. }
  2919. }
  2920. if (!atOnly) {
  2921. cmsys::RegularExpression varb("(\\$ENV{[A-Za-z_0-9]*})");
  2922. while (varb.find(source)) {
  2923. source.erase(varb.start(), varb.end() - varb.start());
  2924. }
  2925. }
  2926. cmsys::RegularExpression var2("(@[A-Za-z_0-9]*@)");
  2927. while (var2.find(source)) {
  2928. source.erase(var2.start(), var2.end() - var2.start());
  2929. }
  2930. }
  2931. void cmMakefile::InitCMAKE_CONFIGURATION_TYPES(std::string const& genDefault)
  2932. {
  2933. if (this->GetDefinition("CMAKE_CONFIGURATION_TYPES")) {
  2934. return;
  2935. }
  2936. std::string initConfigs;
  2937. if (this->GetCMakeInstance()->GetIsInTryCompile() ||
  2938. !cmSystemTools::GetEnv("CMAKE_CONFIGURATION_TYPES", initConfigs)) {
  2939. initConfigs = genDefault;
  2940. }
  2941. this->AddCacheDefinition(
  2942. "CMAKE_CONFIGURATION_TYPES", initConfigs,
  2943. "Semicolon separated list of supported configuration types, "
  2944. "only supports Debug, Release, MinSizeRel, and RelWithDebInfo, "
  2945. "anything else will be ignored.",
  2946. cmStateEnums::STRING);
  2947. }
  2948. std::string cmMakefile::GetDefaultConfiguration() const
  2949. {
  2950. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  2951. return std::string{};
  2952. }
  2953. return this->GetSafeDefinition("CMAKE_BUILD_TYPE");
  2954. }
  2955. std::vector<std::string> cmMakefile::GetGeneratorConfigs(
  2956. GeneratorConfigQuery mode) const
  2957. {
  2958. cmList configs;
  2959. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  2960. configs.assign(this->GetDefinition("CMAKE_CONFIGURATION_TYPES"));
  2961. } else if (mode != cmMakefile::OnlyMultiConfig) {
  2962. const std::string& buildType = this->GetSafeDefinition("CMAKE_BUILD_TYPE");
  2963. if (!buildType.empty()) {
  2964. configs.emplace_back(buildType);
  2965. }
  2966. }
  2967. if (mode == cmMakefile::IncludeEmptyConfig && configs.empty()) {
  2968. configs.emplace_back();
  2969. }
  2970. return std::move(configs.data());
  2971. }
  2972. bool cmMakefile::IsFunctionBlocked(const cmListFileFunction& lff,
  2973. cmExecutionStatus& status)
  2974. {
  2975. // if there are no blockers get out of here
  2976. if (this->FunctionBlockers.empty()) {
  2977. return false;
  2978. }
  2979. return this->FunctionBlockers.top()->IsFunctionBlocked(lff, status);
  2980. }
  2981. void cmMakefile::PushFunctionBlockerBarrier()
  2982. {
  2983. this->FunctionBlockerBarriers.push_back(this->FunctionBlockers.size());
  2984. }
  2985. void cmMakefile::PopFunctionBlockerBarrier(bool reportError)
  2986. {
  2987. // Remove any extra entries pushed on the barrier.
  2988. FunctionBlockersType::size_type barrier =
  2989. this->FunctionBlockerBarriers.back();
  2990. while (this->FunctionBlockers.size() > barrier) {
  2991. std::unique_ptr<cmFunctionBlocker> fb(
  2992. std::move(this->FunctionBlockers.top()));
  2993. this->FunctionBlockers.pop();
  2994. if (reportError) {
  2995. // Report the context in which the unclosed block was opened.
  2996. cmListFileContext const& lfc = fb->GetStartingContext();
  2997. std::ostringstream e;
  2998. /* clang-format off */
  2999. e << "A logical block opening on the line\n"
  3000. << " " << lfc << "\n"
  3001. << "is not closed.";
  3002. /* clang-format on */
  3003. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  3004. reportError = false;
  3005. }
  3006. }
  3007. // Remove the barrier.
  3008. this->FunctionBlockerBarriers.pop_back();
  3009. }
  3010. void cmMakefile::PushLoopBlock()
  3011. {
  3012. assert(!this->LoopBlockCounter.empty());
  3013. this->LoopBlockCounter.top()++;
  3014. }
  3015. void cmMakefile::PopLoopBlock()
  3016. {
  3017. assert(!this->LoopBlockCounter.empty());
  3018. assert(this->LoopBlockCounter.top() > 0);
  3019. this->LoopBlockCounter.top()--;
  3020. }
  3021. void cmMakefile::PushLoopBlockBarrier()
  3022. {
  3023. this->LoopBlockCounter.push(0);
  3024. }
  3025. void cmMakefile::PopLoopBlockBarrier()
  3026. {
  3027. assert(!this->LoopBlockCounter.empty());
  3028. assert(this->LoopBlockCounter.top() == 0);
  3029. this->LoopBlockCounter.pop();
  3030. }
  3031. bool cmMakefile::IsLoopBlock() const
  3032. {
  3033. assert(!this->LoopBlockCounter.empty());
  3034. return !this->LoopBlockCounter.empty() && this->LoopBlockCounter.top() > 0;
  3035. }
  3036. bool cmMakefile::ExpandArguments(std::vector<cmListFileArgument> const& inArgs,
  3037. std::vector<std::string>& outArgs) const
  3038. {
  3039. std::string const& filename = this->GetBacktrace().Top().FilePath;
  3040. std::string value;
  3041. outArgs.reserve(inArgs.size());
  3042. for (cmListFileArgument const& i : inArgs) {
  3043. // No expansion in a bracket argument.
  3044. if (i.Delim == cmListFileArgument::Bracket) {
  3045. outArgs.push_back(i.Value);
  3046. continue;
  3047. }
  3048. // Expand the variables in the argument.
  3049. value = i.Value;
  3050. this->ExpandVariablesInString(value, false, false, false, filename.c_str(),
  3051. i.Line, false, false);
  3052. // If the argument is quoted, it should be one argument.
  3053. // Otherwise, it may be a list of arguments.
  3054. if (i.Delim == cmListFileArgument::Quoted) {
  3055. outArgs.push_back(value);
  3056. } else {
  3057. cmExpandList(value, outArgs);
  3058. }
  3059. }
  3060. return !cmSystemTools::GetFatalErrorOccurred();
  3061. }
  3062. bool cmMakefile::ExpandArguments(
  3063. std::vector<cmListFileArgument> const& inArgs,
  3064. std::vector<cmExpandedCommandArgument>& outArgs) const
  3065. {
  3066. std::string const& filename = this->GetBacktrace().Top().FilePath;
  3067. std::string value;
  3068. outArgs.reserve(inArgs.size());
  3069. for (cmListFileArgument const& i : inArgs) {
  3070. // No expansion in a bracket argument.
  3071. if (i.Delim == cmListFileArgument::Bracket) {
  3072. outArgs.emplace_back(i.Value, true);
  3073. continue;
  3074. }
  3075. // Expand the variables in the argument.
  3076. value = i.Value;
  3077. this->ExpandVariablesInString(value, false, false, false, filename.c_str(),
  3078. i.Line, false, false);
  3079. // If the argument is quoted, it should be one argument.
  3080. // Otherwise, it may be a list of arguments.
  3081. if (i.Delim == cmListFileArgument::Quoted) {
  3082. outArgs.emplace_back(value, true);
  3083. } else {
  3084. cmList stringArgs{ value };
  3085. for (std::string const& stringArg : stringArgs) {
  3086. outArgs.emplace_back(stringArg, false);
  3087. }
  3088. }
  3089. }
  3090. return !cmSystemTools::GetFatalErrorOccurred();
  3091. }
  3092. void cmMakefile::AddFunctionBlocker(std::unique_ptr<cmFunctionBlocker> fb)
  3093. {
  3094. if (!this->ExecutionStatusStack.empty()) {
  3095. // Record the context in which the blocker is created.
  3096. fb->SetStartingContext(this->Backtrace.Top());
  3097. }
  3098. this->FunctionBlockers.push(std::move(fb));
  3099. }
  3100. std::unique_ptr<cmFunctionBlocker> cmMakefile::RemoveFunctionBlocker()
  3101. {
  3102. assert(!this->FunctionBlockers.empty());
  3103. assert(this->FunctionBlockerBarriers.empty() ||
  3104. this->FunctionBlockers.size() > this->FunctionBlockerBarriers.back());
  3105. auto b = std::move(this->FunctionBlockers.top());
  3106. this->FunctionBlockers.pop();
  3107. return b;
  3108. }
  3109. std::string const& cmMakefile::GetHomeDirectory() const
  3110. {
  3111. return this->GetCMakeInstance()->GetHomeDirectory();
  3112. }
  3113. std::string const& cmMakefile::GetHomeOutputDirectory() const
  3114. {
  3115. return this->GetCMakeInstance()->GetHomeOutputDirectory();
  3116. }
  3117. void cmMakefile::SetScriptModeFile(std::string const& scriptfile)
  3118. {
  3119. this->AddDefinition("CMAKE_SCRIPT_MODE_FILE", scriptfile);
  3120. }
  3121. void cmMakefile::SetArgcArgv(const std::vector<std::string>& args)
  3122. {
  3123. this->AddDefinition("CMAKE_ARGC", std::to_string(args.size()));
  3124. // this->MarkVariableAsUsed("CMAKE_ARGC");
  3125. for (unsigned int t = 0; t < args.size(); ++t) {
  3126. std::ostringstream tmpStream;
  3127. tmpStream << "CMAKE_ARGV" << t;
  3128. this->AddDefinition(tmpStream.str(), args[t]);
  3129. // this->MarkVariableAsUsed(tmpStream.str().c_str());
  3130. }
  3131. }
  3132. cmSourceFile* cmMakefile::GetSource(const std::string& sourceName,
  3133. cmSourceFileLocationKind kind) const
  3134. {
  3135. // First check "Known" paths (avoids the creation of cmSourceFileLocation)
  3136. if (kind == cmSourceFileLocationKind::Known) {
  3137. auto sfsi = this->KnownFileSearchIndex.find(sourceName);
  3138. if (sfsi != this->KnownFileSearchIndex.end()) {
  3139. return sfsi->second;
  3140. }
  3141. }
  3142. cmSourceFileLocation sfl(this, sourceName, kind);
  3143. auto name = this->GetCMakeInstance()->StripExtension(sfl.GetName());
  3144. #if defined(_WIN32) || defined(__APPLE__)
  3145. name = cmSystemTools::LowerCase(name);
  3146. #endif
  3147. auto sfsi = this->SourceFileSearchIndex.find(name);
  3148. if (sfsi != this->SourceFileSearchIndex.end()) {
  3149. for (auto* sf : sfsi->second) {
  3150. if (sf->Matches(sfl)) {
  3151. return sf;
  3152. }
  3153. }
  3154. }
  3155. return nullptr;
  3156. }
  3157. cmSourceFile* cmMakefile::CreateSource(const std::string& sourceName,
  3158. bool generated,
  3159. cmSourceFileLocationKind kind)
  3160. {
  3161. auto sf = cm::make_unique<cmSourceFile>(this, sourceName, generated, kind);
  3162. auto name =
  3163. this->GetCMakeInstance()->StripExtension(sf->GetLocation().GetName());
  3164. #if defined(_WIN32) || defined(__APPLE__)
  3165. name = cmSystemTools::LowerCase(name);
  3166. #endif
  3167. this->SourceFileSearchIndex[name].push_back(sf.get());
  3168. // for "Known" paths add direct lookup (used for faster lookup in GetSource)
  3169. if (kind == cmSourceFileLocationKind::Known) {
  3170. this->KnownFileSearchIndex[sourceName] = sf.get();
  3171. }
  3172. this->SourceFiles.push_back(std::move(sf));
  3173. return this->SourceFiles.back().get();
  3174. }
  3175. cmSourceFile* cmMakefile::GetOrCreateSource(const std::string& sourceName,
  3176. bool generated,
  3177. cmSourceFileLocationKind kind)
  3178. {
  3179. if (cmSourceFile* esf = this->GetSource(sourceName, kind)) {
  3180. return esf;
  3181. }
  3182. return this->CreateSource(sourceName, generated, kind);
  3183. }
  3184. cmSourceFile* cmMakefile::GetOrCreateGeneratedSource(
  3185. const std::string& sourceName)
  3186. {
  3187. cmSourceFile* sf =
  3188. this->GetOrCreateSource(sourceName, true, cmSourceFileLocationKind::Known);
  3189. sf->MarkAsGenerated(); // In case we did not create the source file.
  3190. return sf;
  3191. }
  3192. void cmMakefile::CreateGeneratedOutputs(
  3193. const std::vector<std::string>& outputs)
  3194. {
  3195. for (std::string const& o : outputs) {
  3196. if (cmGeneratorExpression::Find(o) == std::string::npos) {
  3197. this->GetOrCreateGeneratedSource(o);
  3198. }
  3199. }
  3200. }
  3201. void cmMakefile::AddTargetObject(std::string const& tgtName,
  3202. std::string const& objFile)
  3203. {
  3204. cmSourceFile* sf =
  3205. this->GetOrCreateSource(objFile, true, cmSourceFileLocationKind::Known);
  3206. sf->SetObjectLibrary(tgtName);
  3207. sf->SetProperty("EXTERNAL_OBJECT", "1");
  3208. #if !defined(CMAKE_BOOTSTRAP)
  3209. this->SourceGroups[this->ObjectLibrariesSourceGroupIndex].AddGroupFile(
  3210. sf->ResolveFullPath());
  3211. #endif
  3212. }
  3213. void cmMakefile::EnableLanguage(std::vector<std::string> const& languages,
  3214. bool optional)
  3215. {
  3216. if (this->DeferRunning) {
  3217. this->IssueMessage(
  3218. MessageType::FATAL_ERROR,
  3219. "Languages may not be enabled during deferred execution.");
  3220. return;
  3221. }
  3222. if (const char* def = this->GetGlobalGenerator()->GetCMakeCFGIntDir()) {
  3223. this->AddDefinition("CMAKE_CFG_INTDIR", def);
  3224. }
  3225. std::vector<std::string> unique_languages;
  3226. {
  3227. std::vector<std::string> duplicate_languages;
  3228. for (std::string const& language : languages) {
  3229. if (!cm::contains(unique_languages, language)) {
  3230. unique_languages.push_back(language);
  3231. } else if (!cm::contains(duplicate_languages, language)) {
  3232. duplicate_languages.push_back(language);
  3233. }
  3234. }
  3235. if (!duplicate_languages.empty()) {
  3236. auto quantity = duplicate_languages.size() == 1 ? " has"_s : "s have"_s;
  3237. this->IssueMessage(
  3238. MessageType::AUTHOR_WARNING,
  3239. cmStrCat("Languages to be enabled may not be specified more "
  3240. "than once at the same time. The following language",
  3241. quantity, " been specified multiple times: ",
  3242. cmJoin(duplicate_languages, ", ")));
  3243. }
  3244. }
  3245. // If RC is explicitly listed we need to do it after other languages.
  3246. // On some platforms we enable RC implicitly while enabling others.
  3247. // Do not let that look like recursive enable_language(RC).
  3248. std::vector<std::string> languages_without_RC;
  3249. std::vector<std::string> languages_for_RC;
  3250. languages_without_RC.reserve(unique_languages.size());
  3251. for (std::string const& language : unique_languages) {
  3252. if (language == "RC"_s) {
  3253. languages_for_RC.push_back(language);
  3254. } else {
  3255. languages_without_RC.push_back(language);
  3256. }
  3257. }
  3258. if (!languages_without_RC.empty()) {
  3259. this->GetGlobalGenerator()->EnableLanguage(languages_without_RC, this,
  3260. optional);
  3261. }
  3262. if (!languages_for_RC.empty()) {
  3263. this->GetGlobalGenerator()->EnableLanguage(languages_for_RC, this,
  3264. optional);
  3265. }
  3266. }
  3267. int cmMakefile::TryCompile(const std::string& srcdir,
  3268. const std::string& bindir,
  3269. const std::string& projectName,
  3270. const std::string& targetName, bool fast, int jobs,
  3271. const std::vector<std::string>* cmakeArgs,
  3272. std::string& output)
  3273. {
  3274. this->IsSourceFileTryCompile = fast;
  3275. // does the binary directory exist ? If not create it...
  3276. if (!cmSystemTools::FileIsDirectory(bindir)) {
  3277. cmSystemTools::MakeDirectory(bindir);
  3278. }
  3279. // change to the tests directory and run cmake
  3280. // use the cmake object instead of calling cmake
  3281. cmWorkingDirectory workdir(bindir);
  3282. if (workdir.Failed()) {
  3283. this->IssueMessage(MessageType::FATAL_ERROR,
  3284. cmStrCat("Failed to set working directory to ", bindir,
  3285. " : ",
  3286. std::strerror(workdir.GetLastResult())));
  3287. cmSystemTools::SetFatalErrorOccurred();
  3288. this->IsSourceFileTryCompile = false;
  3289. return 1;
  3290. }
  3291. // make sure the same generator is used
  3292. // use this program as the cmake to be run, it should not
  3293. // be run that way but the cmake object requires a vailid path
  3294. cmake cm(cmake::RoleProject, cmState::Project,
  3295. cmState::ProjectKind::TryCompile);
  3296. auto gg = cm.CreateGlobalGenerator(this->GetGlobalGenerator()->GetName());
  3297. if (!gg) {
  3298. this->IssueMessage(MessageType::INTERNAL_ERROR,
  3299. "Global generator '" +
  3300. this->GetGlobalGenerator()->GetName() +
  3301. "' could not be created.");
  3302. cmSystemTools::SetFatalErrorOccurred();
  3303. this->IsSourceFileTryCompile = false;
  3304. return 1;
  3305. }
  3306. gg->RecursionDepth = this->RecursionDepth;
  3307. cm.SetGlobalGenerator(std::move(gg));
  3308. // copy trace state
  3309. cm.SetTraceRedirect(this->GetCMakeInstance());
  3310. // do a configure
  3311. cm.SetHomeDirectory(srcdir);
  3312. cm.SetHomeOutputDirectory(bindir);
  3313. cm.SetGeneratorInstance(this->GetSafeDefinition("CMAKE_GENERATOR_INSTANCE"));
  3314. cm.SetGeneratorPlatform(this->GetSafeDefinition("CMAKE_GENERATOR_PLATFORM"));
  3315. cm.SetGeneratorToolset(this->GetSafeDefinition("CMAKE_GENERATOR_TOOLSET"));
  3316. cm.LoadCache();
  3317. if (!cm.GetGlobalGenerator()->IsMultiConfig()) {
  3318. if (cmValue config =
  3319. this->GetDefinition("CMAKE_TRY_COMPILE_CONFIGURATION")) {
  3320. // Tell the single-configuration generator which one to use.
  3321. // Add this before the user-provided CMake arguments in case
  3322. // one of the arguments is -DCMAKE_BUILD_TYPE=...
  3323. cm.AddCacheEntry("CMAKE_BUILD_TYPE", config, "Build configuration",
  3324. cmStateEnums::STRING);
  3325. }
  3326. }
  3327. cmValue recursionDepth =
  3328. this->GetDefinition("CMAKE_MAXIMUM_RECURSION_DEPTH");
  3329. if (recursionDepth) {
  3330. cm.AddCacheEntry("CMAKE_MAXIMUM_RECURSION_DEPTH", recursionDepth,
  3331. "Maximum recursion depth", cmStateEnums::STRING);
  3332. }
  3333. // if cmake args were provided then pass them in
  3334. if (cmakeArgs) {
  3335. // FIXME: Workaround to ignore unused CLI variables in try-compile.
  3336. //
  3337. // Ideally we should use SetArgs for options like --no-warn-unused-cli.
  3338. // However, there is a subtle problem when certain arguments are passed to
  3339. // a macro wrapping around try_compile or try_run that does not escape
  3340. // semicolons in its parameters but just passes ${ARGV} or ${ARGN}. In
  3341. // this case a list argument like "-DVAR=a;b" gets split into multiple
  3342. // cmake arguments "-DVAR=a" and "b". Currently SetCacheArgs ignores
  3343. // argument "b" and uses just "-DVAR=a", leading to a subtle bug in that
  3344. // the try_compile or try_run does not get the proper value of VAR. If we
  3345. // call SetArgs here then it would treat "b" as the source directory and
  3346. // cause an error such as "The source directory .../CMakeFiles/CMakeTmp/b
  3347. // does not exist", thus breaking the try_compile or try_run completely.
  3348. //
  3349. // Strictly speaking the bug is in the wrapper macro because the CMake
  3350. // language has always flattened nested lists and the macro should escape
  3351. // the semicolons in its arguments before forwarding them. However, this
  3352. // bug is so subtle that projects typically work anyway, usually because
  3353. // the value VAR=a is sufficient for the try_compile or try_run to get the
  3354. // correct result. Calling SetArgs here would break such projects that
  3355. // previously built. Instead we work around the issue by never reporting
  3356. // unused arguments and ignoring options such as --no-warn-unused-cli.
  3357. cm.SetWarnUnusedCli(false);
  3358. // cm.SetArgs(*cmakeArgs, true);
  3359. cm.SetCacheArgs(*cmakeArgs);
  3360. }
  3361. // to save time we pass the EnableLanguage info directly
  3362. cm.GetGlobalGenerator()->EnableLanguagesFromGenerator(
  3363. this->GetGlobalGenerator(), this);
  3364. if (this->IsOn("CMAKE_SUPPRESS_DEVELOPER_WARNINGS")) {
  3365. cm.AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_WARNINGS", "TRUE", "",
  3366. cmStateEnums::INTERNAL);
  3367. } else {
  3368. cm.AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_WARNINGS", "FALSE", "",
  3369. cmStateEnums::INTERNAL);
  3370. }
  3371. if (cm.Configure() != 0) {
  3372. this->IssueMessage(MessageType::FATAL_ERROR,
  3373. "Failed to configure test project build system.");
  3374. cmSystemTools::SetFatalErrorOccurred();
  3375. this->IsSourceFileTryCompile = false;
  3376. return 1;
  3377. }
  3378. if (cm.Generate() != 0) {
  3379. this->IssueMessage(MessageType::FATAL_ERROR,
  3380. "Failed to generate test project build system.");
  3381. cmSystemTools::SetFatalErrorOccurred();
  3382. this->IsSourceFileTryCompile = false;
  3383. return 1;
  3384. }
  3385. // finally call the generator to actually build the resulting project
  3386. int ret = this->GetGlobalGenerator()->TryCompile(
  3387. jobs, srcdir, bindir, projectName, targetName, fast, output, this);
  3388. this->IsSourceFileTryCompile = false;
  3389. return ret;
  3390. }
  3391. bool cmMakefile::GetIsSourceFileTryCompile() const
  3392. {
  3393. return this->IsSourceFileTryCompile;
  3394. }
  3395. cmake* cmMakefile::GetCMakeInstance() const
  3396. {
  3397. return this->GlobalGenerator->GetCMakeInstance();
  3398. }
  3399. cmMessenger* cmMakefile::GetMessenger() const
  3400. {
  3401. return this->GetCMakeInstance()->GetMessenger();
  3402. }
  3403. cmGlobalGenerator* cmMakefile::GetGlobalGenerator() const
  3404. {
  3405. return this->GlobalGenerator;
  3406. }
  3407. #ifndef CMAKE_BOOTSTRAP
  3408. cmVariableWatch* cmMakefile::GetVariableWatch() const
  3409. {
  3410. if (this->GetCMakeInstance() &&
  3411. this->GetCMakeInstance()->GetVariableWatch()) {
  3412. return this->GetCMakeInstance()->GetVariableWatch();
  3413. }
  3414. return nullptr;
  3415. }
  3416. #endif
  3417. cmState* cmMakefile::GetState() const
  3418. {
  3419. return this->GetCMakeInstance()->GetState();
  3420. }
  3421. void cmMakefile::DisplayStatus(const std::string& message, float s) const
  3422. {
  3423. cmake* cm = this->GetCMakeInstance();
  3424. if (cm->GetWorkingMode() == cmake::FIND_PACKAGE_MODE) {
  3425. // don't output any STATUS message in FIND_PACKAGE_MODE, since they will
  3426. // directly be fed to the compiler, which will be confused.
  3427. return;
  3428. }
  3429. cm->UpdateProgress(message, s);
  3430. #ifdef CMake_ENABLE_DEBUGGER
  3431. if (cm->GetDebugAdapter() != nullptr) {
  3432. cm->GetDebugAdapter()->OnMessageOutput(MessageType::MESSAGE, message);
  3433. }
  3434. #endif
  3435. }
  3436. std::string cmMakefile::GetModulesFile(const std::string& filename,
  3437. bool& system, bool debug,
  3438. std::string& debugBuffer) const
  3439. {
  3440. std::string result;
  3441. // We search the module always in CMAKE_ROOT and in CMAKE_MODULE_PATH,
  3442. // and then decide based on the policy setting which one to return.
  3443. // See CMP0017 for more details.
  3444. // The specific problem was that KDE 4.5.0 installs a
  3445. // FindPackageHandleStandardArgs.cmake which doesn't have the new features
  3446. // of FPHSA.cmake introduced in CMake 2.8.3 yet, and by setting
  3447. // CMAKE_MODULE_PATH also e.g. FindZLIB.cmake from cmake included
  3448. // FPHSA.cmake from kdelibs and not from CMake, and tried to use the
  3449. // new features, which were not there in the version from kdelibs, and so
  3450. // failed ("
  3451. std::string moduleInCMakeRoot;
  3452. std::string moduleInCMakeModulePath;
  3453. // Always search in CMAKE_MODULE_PATH:
  3454. cmValue cmakeModulePath = this->GetDefinition("CMAKE_MODULE_PATH");
  3455. if (cmakeModulePath) {
  3456. cmList modulePath{ *cmakeModulePath };
  3457. // Look through the possible module directories.
  3458. for (std::string itempl : modulePath) {
  3459. cmSystemTools::ConvertToUnixSlashes(itempl);
  3460. itempl += "/";
  3461. itempl += filename;
  3462. if (cmSystemTools::FileExists(itempl)) {
  3463. moduleInCMakeModulePath = itempl;
  3464. break;
  3465. }
  3466. if (debug) {
  3467. debugBuffer = cmStrCat(debugBuffer, " ", itempl, "\n");
  3468. }
  3469. }
  3470. }
  3471. // Always search in the standard modules location.
  3472. moduleInCMakeRoot =
  3473. cmStrCat(cmSystemTools::GetCMakeRoot(), "/Modules/", filename);
  3474. cmSystemTools::ConvertToUnixSlashes(moduleInCMakeRoot);
  3475. if (!cmSystemTools::FileExists(moduleInCMakeRoot)) {
  3476. if (debug) {
  3477. debugBuffer = cmStrCat(debugBuffer, " ", moduleInCMakeRoot, "\n");
  3478. }
  3479. moduleInCMakeRoot.clear();
  3480. }
  3481. // Normally, prefer the files found in CMAKE_MODULE_PATH. Only when the file
  3482. // from which we are being called is located itself in CMAKE_ROOT, then
  3483. // prefer results from CMAKE_ROOT depending on the policy setting.
  3484. system = false;
  3485. result = moduleInCMakeModulePath;
  3486. if (result.empty()) {
  3487. system = true;
  3488. result = moduleInCMakeRoot;
  3489. }
  3490. if (!moduleInCMakeModulePath.empty() && !moduleInCMakeRoot.empty()) {
  3491. cmValue currentFile = this->GetDefinition("CMAKE_CURRENT_LIST_FILE");
  3492. std::string mods = cmStrCat(cmSystemTools::GetCMakeRoot(), "/Modules/");
  3493. if (currentFile && cmSystemTools::IsSubDirectory(*currentFile, mods)) {
  3494. switch (this->GetPolicyStatus(cmPolicies::CMP0017)) {
  3495. case cmPolicies::WARN: {
  3496. std::ostringstream e;
  3497. /* clang-format off */
  3498. e << "File " << *currentFile << " includes "
  3499. << moduleInCMakeModulePath
  3500. << " (found via CMAKE_MODULE_PATH) which shadows "
  3501. << moduleInCMakeRoot << ". This may cause errors later on .\n"
  3502. << cmPolicies::GetPolicyWarning(cmPolicies::CMP0017);
  3503. /* clang-format on */
  3504. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  3505. CM_FALLTHROUGH;
  3506. }
  3507. case cmPolicies::OLD:
  3508. system = false;
  3509. result = moduleInCMakeModulePath;
  3510. break;
  3511. case cmPolicies::REQUIRED_IF_USED:
  3512. case cmPolicies::REQUIRED_ALWAYS:
  3513. case cmPolicies::NEW:
  3514. system = true;
  3515. result = moduleInCMakeRoot;
  3516. break;
  3517. }
  3518. }
  3519. }
  3520. return result;
  3521. }
  3522. void cmMakefile::ConfigureString(const std::string& input, std::string& output,
  3523. bool atOnly, bool escapeQuotes) const
  3524. {
  3525. // Split input to handle one line at a time.
  3526. std::string::const_iterator lineStart = input.begin();
  3527. while (lineStart != input.end()) {
  3528. // Find the end of this line.
  3529. std::string::const_iterator lineEnd = lineStart;
  3530. while (lineEnd != input.end() && *lineEnd != '\n') {
  3531. ++lineEnd;
  3532. }
  3533. // Copy the line.
  3534. std::string line(lineStart, lineEnd);
  3535. // Skip the newline character.
  3536. bool haveNewline = (lineEnd != input.end());
  3537. if (haveNewline) {
  3538. ++lineEnd;
  3539. }
  3540. // Replace #cmakedefine instances.
  3541. if (this->cmDefineRegex.find(line)) {
  3542. cmValue def = this->GetDefinition(this->cmDefineRegex.match(2));
  3543. if (!cmIsOff(def)) {
  3544. const std::string indentation = this->cmDefineRegex.match(1);
  3545. cmSystemTools::ReplaceString(line,
  3546. cmStrCat("#", indentation, "cmakedefine"),
  3547. cmStrCat("#", indentation, "define"));
  3548. output += line;
  3549. } else {
  3550. output += "/* #undef ";
  3551. output += this->cmDefineRegex.match(2);
  3552. output += " */";
  3553. }
  3554. } else if (this->cmDefine01Regex.find(line)) {
  3555. const std::string indentation = this->cmDefine01Regex.match(1);
  3556. cmValue def = this->GetDefinition(this->cmDefine01Regex.match(2));
  3557. cmSystemTools::ReplaceString(line,
  3558. cmStrCat("#", indentation, "cmakedefine01"),
  3559. cmStrCat("#", indentation, "define"));
  3560. output += line;
  3561. if (!cmIsOff(def)) {
  3562. output += " 1";
  3563. } else {
  3564. output += " 0";
  3565. }
  3566. } else {
  3567. output += line;
  3568. }
  3569. if (haveNewline) {
  3570. output += "\n";
  3571. }
  3572. // Move to the next line.
  3573. lineStart = lineEnd;
  3574. }
  3575. // Perform variable replacements.
  3576. const char* filename = nullptr;
  3577. long lineNumber = -1;
  3578. if (!this->Backtrace.Empty()) {
  3579. const auto& currentTrace = this->Backtrace.Top();
  3580. filename = currentTrace.FilePath.c_str();
  3581. lineNumber = currentTrace.Line;
  3582. }
  3583. this->ExpandVariablesInString(output, escapeQuotes, true, atOnly, filename,
  3584. lineNumber, true, true);
  3585. }
  3586. int cmMakefile::ConfigureFile(const std::string& infile,
  3587. const std::string& outfile, bool copyonly,
  3588. bool atOnly, bool escapeQuotes,
  3589. mode_t permissions, cmNewLineStyle newLine)
  3590. {
  3591. int res = 1;
  3592. if (!this->CanIWriteThisFile(outfile)) {
  3593. cmSystemTools::Error(cmStrCat("Attempt to write file: ", outfile,
  3594. " into a source directory."));
  3595. return 0;
  3596. }
  3597. if (!cmSystemTools::FileExists(infile)) {
  3598. cmSystemTools::Error(cmStrCat("File ", infile, " does not exist."));
  3599. return 0;
  3600. }
  3601. std::string soutfile = outfile;
  3602. const std::string& sinfile = infile;
  3603. this->AddCMakeDependFile(sinfile);
  3604. cmSystemTools::ConvertToUnixSlashes(soutfile);
  3605. // Re-generate if non-temporary outputs are missing.
  3606. // when we finalize the configuration we will remove all
  3607. // output files that now don't exist.
  3608. this->AddCMakeOutputFile(soutfile);
  3609. if (permissions == 0) {
  3610. cmSystemTools::GetPermissions(sinfile, permissions);
  3611. }
  3612. std::string::size_type pos = soutfile.rfind('/');
  3613. if (pos != std::string::npos) {
  3614. std::string path = soutfile.substr(0, pos);
  3615. cmSystemTools::MakeDirectory(path);
  3616. }
  3617. if (copyonly) {
  3618. if (!cmSystemTools::CopyFileIfDifferent(sinfile, soutfile)) {
  3619. this->IssueMessage(MessageType::FATAL_ERROR,
  3620. cmSystemTools::GetLastSystemError());
  3621. return 0;
  3622. }
  3623. if (!cmSystemTools::SetPermissions(soutfile, permissions)) {
  3624. this->IssueMessage(MessageType::FATAL_ERROR,
  3625. cmSystemTools::GetLastSystemError());
  3626. return 0;
  3627. }
  3628. } else {
  3629. std::string newLineCharacters;
  3630. std::ios::openmode omode = std::ios::out | std::ios::trunc;
  3631. if (newLine.IsValid()) {
  3632. newLineCharacters = newLine.GetCharacters();
  3633. omode |= std::ios::binary;
  3634. } else {
  3635. newLineCharacters = "\n";
  3636. }
  3637. std::string tempOutputFile = cmStrCat(soutfile, ".tmp");
  3638. cmsys::ofstream fout(tempOutputFile.c_str(), omode);
  3639. if (!fout) {
  3640. cmSystemTools::Error("Could not open file for write in copy operation " +
  3641. tempOutputFile);
  3642. cmSystemTools::ReportLastSystemError("");
  3643. return 0;
  3644. }
  3645. cmsys::ifstream fin(sinfile.c_str());
  3646. if (!fin) {
  3647. cmSystemTools::Error("Could not open file for read in copy operation " +
  3648. sinfile);
  3649. return 0;
  3650. }
  3651. cmsys::FStream::BOM bom = cmsys::FStream::ReadBOM(fin);
  3652. if (bom != cmsys::FStream::BOM_None && bom != cmsys::FStream::BOM_UTF8) {
  3653. std::ostringstream e;
  3654. e << "File starts with a Byte-Order-Mark that is not UTF-8:\n "
  3655. << sinfile;
  3656. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  3657. return 0;
  3658. }
  3659. // rewind to copy BOM to output file
  3660. fin.seekg(0);
  3661. // now copy input to output and expand variables in the
  3662. // input file at the same time
  3663. std::string inLine;
  3664. std::string outLine;
  3665. while (cmSystemTools::GetLineFromStream(fin, inLine)) {
  3666. outLine.clear();
  3667. this->ConfigureString(inLine, outLine, atOnly, escapeQuotes);
  3668. fout << outLine << newLineCharacters;
  3669. }
  3670. // close the files before attempting to copy
  3671. fin.close();
  3672. fout.close();
  3673. if (!cmSystemTools::CopyFileIfDifferent(tempOutputFile, soutfile)) {
  3674. this->IssueMessage(MessageType::FATAL_ERROR,
  3675. cmSystemTools::GetLastSystemError());
  3676. res = 0;
  3677. } else {
  3678. if (!cmSystemTools::SetPermissions(soutfile, permissions)) {
  3679. this->IssueMessage(MessageType::FATAL_ERROR,
  3680. cmSystemTools::GetLastSystemError());
  3681. res = 0;
  3682. }
  3683. }
  3684. cmSystemTools::RemoveFile(tempOutputFile);
  3685. }
  3686. return res;
  3687. }
  3688. void cmMakefile::SetProperty(const std::string& prop, cmValue value)
  3689. {
  3690. this->StateSnapshot.GetDirectory().SetProperty(prop, value, this->Backtrace);
  3691. }
  3692. void cmMakefile::AppendProperty(const std::string& prop,
  3693. const std::string& value, bool asString)
  3694. {
  3695. this->StateSnapshot.GetDirectory().AppendProperty(prop, value, asString,
  3696. this->Backtrace);
  3697. }
  3698. cmValue cmMakefile::GetProperty(const std::string& prop) const
  3699. {
  3700. // Check for computed properties.
  3701. static std::string output;
  3702. if (prop == "TESTS"_s) {
  3703. std::vector<std::string> keys;
  3704. // get list of keys
  3705. const auto* t = this;
  3706. std::transform(
  3707. t->Tests.begin(), t->Tests.end(), std::back_inserter(keys),
  3708. [](decltype(t->Tests)::value_type const& pair) { return pair.first; });
  3709. output = cmList::to_string(keys);
  3710. return cmValue(output);
  3711. }
  3712. return this->StateSnapshot.GetDirectory().GetProperty(prop);
  3713. }
  3714. cmValue cmMakefile::GetProperty(const std::string& prop, bool chain) const
  3715. {
  3716. return this->StateSnapshot.GetDirectory().GetProperty(prop, chain);
  3717. }
  3718. bool cmMakefile::GetPropertyAsBool(const std::string& prop) const
  3719. {
  3720. return cmIsOn(this->GetProperty(prop));
  3721. }
  3722. std::vector<std::string> cmMakefile::GetPropertyKeys() const
  3723. {
  3724. return this->StateSnapshot.GetDirectory().GetPropertyKeys();
  3725. }
  3726. cmTarget* cmMakefile::FindLocalNonAliasTarget(const std::string& name) const
  3727. {
  3728. auto i = this->Targets.find(name);
  3729. if (i != this->Targets.end()) {
  3730. return &i->second;
  3731. }
  3732. return nullptr;
  3733. }
  3734. cmTest* cmMakefile::CreateTest(const std::string& testName)
  3735. {
  3736. cmTest* test = this->GetTest(testName);
  3737. if (test) {
  3738. return test;
  3739. }
  3740. auto newTest = cm::make_unique<cmTest>(this);
  3741. test = newTest.get();
  3742. newTest->SetName(testName);
  3743. this->Tests[testName] = std::move(newTest);
  3744. return test;
  3745. }
  3746. cmTest* cmMakefile::GetTest(const std::string& testName) const
  3747. {
  3748. auto mi = this->Tests.find(testName);
  3749. if (mi != this->Tests.end()) {
  3750. return mi->second.get();
  3751. }
  3752. return nullptr;
  3753. }
  3754. void cmMakefile::GetTests(const std::string& config,
  3755. std::vector<cmTest*>& tests) const
  3756. {
  3757. for (const auto& generator : this->GetTestGenerators()) {
  3758. if (generator->TestsForConfig(config)) {
  3759. tests.push_back(generator->GetTest());
  3760. }
  3761. }
  3762. }
  3763. void cmMakefile::AddCMakeDependFilesFromUser()
  3764. {
  3765. cmList deps;
  3766. if (cmValue deps_str = this->GetProperty("CMAKE_CONFIGURE_DEPENDS")) {
  3767. deps.assign(*deps_str);
  3768. }
  3769. for (auto const& dep : deps) {
  3770. if (cmSystemTools::FileIsFullPath(dep)) {
  3771. this->AddCMakeDependFile(dep);
  3772. } else {
  3773. std::string f = cmStrCat(this->GetCurrentSourceDirectory(), '/', dep);
  3774. this->AddCMakeDependFile(f);
  3775. }
  3776. }
  3777. }
  3778. std::string cmMakefile::FormatListFileStack() const
  3779. {
  3780. std::vector<std::string> listFiles;
  3781. cmStateSnapshot snp = this->StateSnapshot;
  3782. while (snp.IsValid()) {
  3783. listFiles.push_back(snp.GetExecutionListFile());
  3784. snp = snp.GetCallStackParent();
  3785. }
  3786. std::reverse(listFiles.begin(), listFiles.end());
  3787. std::ostringstream tmp;
  3788. size_t depth = listFiles.size();
  3789. if (depth > 0) {
  3790. auto it = listFiles.end();
  3791. do {
  3792. if (depth != listFiles.size()) {
  3793. tmp << "\n ";
  3794. }
  3795. --it;
  3796. tmp << "[";
  3797. tmp << depth;
  3798. tmp << "]\t";
  3799. tmp << *it;
  3800. depth--;
  3801. } while (it != listFiles.begin());
  3802. }
  3803. return tmp.str();
  3804. }
  3805. void cmMakefile::PushScope()
  3806. {
  3807. this->StateSnapshot =
  3808. this->GetState()->CreateVariableScopeSnapshot(this->StateSnapshot);
  3809. this->PushLoopBlockBarrier();
  3810. #if !defined(CMAKE_BOOTSTRAP)
  3811. this->GetGlobalGenerator()->GetFileLockPool().PushFunctionScope();
  3812. #endif
  3813. }
  3814. void cmMakefile::PopScope()
  3815. {
  3816. #if !defined(CMAKE_BOOTSTRAP)
  3817. this->GetGlobalGenerator()->GetFileLockPool().PopFunctionScope();
  3818. #endif
  3819. this->PopLoopBlockBarrier();
  3820. this->PopSnapshot();
  3821. }
  3822. void cmMakefile::RaiseScope(const std::string& var, const char* varDef)
  3823. {
  3824. if (var.empty()) {
  3825. return;
  3826. }
  3827. if (!this->StateSnapshot.RaiseScope(var, varDef)) {
  3828. std::ostringstream m;
  3829. m << "Cannot set \"" << var << "\": current scope has no parent.";
  3830. this->IssueMessage(MessageType::AUTHOR_WARNING, m.str());
  3831. return;
  3832. }
  3833. #ifndef CMAKE_BOOTSTRAP
  3834. cmVariableWatch* vv = this->GetVariableWatch();
  3835. if (vv) {
  3836. vv->VariableAccessed(var, cmVariableWatch::VARIABLE_MODIFIED_ACCESS,
  3837. varDef, this);
  3838. }
  3839. #endif
  3840. }
  3841. void cmMakefile::RaiseScope(const std::vector<std::string>& variables)
  3842. {
  3843. for (auto const& varName : variables) {
  3844. if (this->IsNormalDefinitionSet(varName)) {
  3845. this->RaiseScope(varName, this->GetDefinition(varName));
  3846. } else {
  3847. // unset variable in parent scope
  3848. this->RaiseScope(varName, nullptr);
  3849. }
  3850. }
  3851. }
  3852. cmTarget* cmMakefile::AddImportedTarget(const std::string& name,
  3853. cmStateEnums::TargetType type,
  3854. bool global)
  3855. {
  3856. // Create the target.
  3857. std::unique_ptr<cmTarget> target(
  3858. new cmTarget(name, type,
  3859. global ? cmTarget::Visibility::ImportedGlobally
  3860. : cmTarget::Visibility::Imported,
  3861. this, cmTarget::PerConfig::Yes));
  3862. // Add to the set of available imported targets.
  3863. this->ImportedTargets[name] = target.get();
  3864. this->GetGlobalGenerator()->IndexTarget(target.get());
  3865. this->GetStateSnapshot().GetDirectory().AddImportedTargetName(name);
  3866. // Transfer ownership to this cmMakefile object.
  3867. this->ImportedTargetsOwned.push_back(std::move(target));
  3868. return this->ImportedTargetsOwned.back().get();
  3869. }
  3870. cmTarget* cmMakefile::FindTargetToUse(const std::string& name,
  3871. bool excludeAliases) const
  3872. {
  3873. // Look for an imported target. These take priority because they
  3874. // are more local in scope and do not have to be globally unique.
  3875. auto targetName = name;
  3876. if (!excludeAliases) {
  3877. // Look for local alias targets.
  3878. auto alias = this->AliasTargets.find(name);
  3879. if (alias != this->AliasTargets.end()) {
  3880. targetName = alias->second;
  3881. }
  3882. }
  3883. auto imported = this->ImportedTargets.find(targetName);
  3884. if (imported != this->ImportedTargets.end()) {
  3885. return imported->second;
  3886. }
  3887. // Look for a target built in this directory.
  3888. if (cmTarget* t = this->FindLocalNonAliasTarget(name)) {
  3889. return t;
  3890. }
  3891. // Look for a target built in this project.
  3892. return this->GetGlobalGenerator()->FindTarget(name, excludeAliases);
  3893. }
  3894. bool cmMakefile::IsAlias(const std::string& name) const
  3895. {
  3896. if (cm::contains(this->AliasTargets, name)) {
  3897. return true;
  3898. }
  3899. return this->GetGlobalGenerator()->IsAlias(name);
  3900. }
  3901. bool cmMakefile::EnforceUniqueName(std::string const& name, std::string& msg,
  3902. bool isCustom) const
  3903. {
  3904. if (this->IsAlias(name)) {
  3905. std::ostringstream e;
  3906. e << "cannot create target \"" << name
  3907. << "\" because an alias with the same name already exists.";
  3908. msg = e.str();
  3909. return false;
  3910. }
  3911. if (cmTarget* existing = this->FindTargetToUse(name)) {
  3912. // The name given conflicts with an existing target. Produce an
  3913. // error in a compatible way.
  3914. if (existing->IsImported()) {
  3915. // Imported targets were not supported in previous versions.
  3916. // This is new code, so we can make it an error.
  3917. std::ostringstream e;
  3918. e << "cannot create target \"" << name
  3919. << "\" because an imported target with the same name already exists.";
  3920. msg = e.str();
  3921. return false;
  3922. }
  3923. // target names must be globally unique
  3924. switch (this->GetPolicyStatus(cmPolicies::CMP0002)) {
  3925. case cmPolicies::WARN:
  3926. this->IssueMessage(MessageType::AUTHOR_WARNING,
  3927. cmPolicies::GetPolicyWarning(cmPolicies::CMP0002));
  3928. CM_FALLTHROUGH;
  3929. case cmPolicies::OLD:
  3930. return true;
  3931. case cmPolicies::REQUIRED_IF_USED:
  3932. case cmPolicies::REQUIRED_ALWAYS:
  3933. this->IssueMessage(
  3934. MessageType::FATAL_ERROR,
  3935. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0002));
  3936. return true;
  3937. case cmPolicies::NEW:
  3938. break;
  3939. }
  3940. // The conflict is with a non-imported target.
  3941. // Allow this if the user has requested support.
  3942. cmake* cm = this->GetCMakeInstance();
  3943. if (isCustom && existing->GetType() == cmStateEnums::UTILITY &&
  3944. this != existing->GetMakefile() &&
  3945. cm->GetState()->GetGlobalPropertyAsBool(
  3946. "ALLOW_DUPLICATE_CUSTOM_TARGETS")) {
  3947. return true;
  3948. }
  3949. // Produce an error that tells the user how to work around the
  3950. // problem.
  3951. std::ostringstream e;
  3952. e << "cannot create target \"" << name
  3953. << "\" because another target with the same name already exists. "
  3954. << "The existing target is ";
  3955. switch (existing->GetType()) {
  3956. case cmStateEnums::EXECUTABLE:
  3957. e << "an executable ";
  3958. break;
  3959. case cmStateEnums::STATIC_LIBRARY:
  3960. e << "a static library ";
  3961. break;
  3962. case cmStateEnums::SHARED_LIBRARY:
  3963. e << "a shared library ";
  3964. break;
  3965. case cmStateEnums::MODULE_LIBRARY:
  3966. e << "a module library ";
  3967. break;
  3968. case cmStateEnums::UTILITY:
  3969. e << "a custom target ";
  3970. break;
  3971. case cmStateEnums::INTERFACE_LIBRARY:
  3972. e << "an interface library ";
  3973. break;
  3974. default:
  3975. break;
  3976. }
  3977. e << "created in source directory \""
  3978. << existing->GetMakefile()->GetCurrentSourceDirectory() << "\". "
  3979. << "See documentation for policy CMP0002 for more details.";
  3980. msg = e.str();
  3981. return false;
  3982. }
  3983. return true;
  3984. }
  3985. bool cmMakefile::EnforceUniqueDir(const std::string& srcPath,
  3986. const std::string& binPath) const
  3987. {
  3988. // Make sure the binary directory is unique.
  3989. cmGlobalGenerator* gg = this->GetGlobalGenerator();
  3990. if (gg->BinaryDirectoryIsNew(binPath)) {
  3991. return true;
  3992. }
  3993. std::ostringstream e;
  3994. switch (this->GetPolicyStatus(cmPolicies::CMP0013)) {
  3995. case cmPolicies::WARN:
  3996. // Print the warning.
  3997. /* clang-format off */
  3998. e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0013)
  3999. << "\n"
  4000. << "The binary directory\n"
  4001. << " " << binPath << "\n"
  4002. << "is already used to build a source directory. "
  4003. << "This command uses it to build source directory\n"
  4004. << " " << srcPath << "\n"
  4005. << "which can generate conflicting build files. "
  4006. << "CMake does not support this use case but it used "
  4007. << "to work accidentally and is being allowed for "
  4008. << "compatibility.";
  4009. /* clang-format on */
  4010. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  4011. CM_FALLTHROUGH;
  4012. case cmPolicies::OLD:
  4013. // OLD behavior does not warn.
  4014. return true;
  4015. case cmPolicies::REQUIRED_IF_USED:
  4016. case cmPolicies::REQUIRED_ALWAYS:
  4017. e << cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0013) << "\n";
  4018. CM_FALLTHROUGH;
  4019. case cmPolicies::NEW:
  4020. // NEW behavior prints the error.
  4021. /* clang-format off */
  4022. e << "The binary directory\n"
  4023. << " " << binPath << "\n"
  4024. << "is already used to build a source directory. "
  4025. << "It cannot be used to build source directory\n"
  4026. << " " << srcPath << "\n"
  4027. << "Specify a unique binary directory name.";
  4028. /* clang-format on */
  4029. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  4030. break;
  4031. }
  4032. return false;
  4033. }
  4034. static std::string const matchVariables[] = {
  4035. "CMAKE_MATCH_0", "CMAKE_MATCH_1", "CMAKE_MATCH_2", "CMAKE_MATCH_3",
  4036. "CMAKE_MATCH_4", "CMAKE_MATCH_5", "CMAKE_MATCH_6", "CMAKE_MATCH_7",
  4037. "CMAKE_MATCH_8", "CMAKE_MATCH_9"
  4038. };
  4039. static std::string const nMatchesVariable = "CMAKE_MATCH_COUNT";
  4040. void cmMakefile::ClearMatches()
  4041. {
  4042. cmValue nMatchesStr = this->GetDefinition(nMatchesVariable);
  4043. if (!nMatchesStr) {
  4044. return;
  4045. }
  4046. int nMatches = atoi(nMatchesStr->c_str());
  4047. for (int i = 0; i <= nMatches; i++) {
  4048. std::string const& var = matchVariables[i];
  4049. std::string const& s = this->GetSafeDefinition(var);
  4050. if (!s.empty()) {
  4051. this->AddDefinition(var, "");
  4052. this->MarkVariableAsUsed(var);
  4053. }
  4054. }
  4055. this->AddDefinition(nMatchesVariable, "0");
  4056. this->MarkVariableAsUsed(nMatchesVariable);
  4057. }
  4058. void cmMakefile::StoreMatches(cmsys::RegularExpression& re)
  4059. {
  4060. char highest = 0;
  4061. for (int i = 0; i < 10; i++) {
  4062. std::string const& m = re.match(i);
  4063. if (!m.empty()) {
  4064. std::string const& var = matchVariables[i];
  4065. this->AddDefinition(var, m);
  4066. this->MarkVariableAsUsed(var);
  4067. highest = static_cast<char>('0' + i);
  4068. }
  4069. }
  4070. char nMatches[] = { highest, '\0' };
  4071. this->AddDefinition(nMatchesVariable, nMatches);
  4072. this->MarkVariableAsUsed(nMatchesVariable);
  4073. }
  4074. cmStateSnapshot cmMakefile::GetStateSnapshot() const
  4075. {
  4076. return this->StateSnapshot;
  4077. }
  4078. const char* cmMakefile::GetDefineFlagsCMP0059() const
  4079. {
  4080. return this->DefineFlagsOrig.c_str();
  4081. }
  4082. cmPolicies::PolicyStatus cmMakefile::GetPolicyStatus(cmPolicies::PolicyID id,
  4083. bool parent_scope) const
  4084. {
  4085. return this->StateSnapshot.GetPolicy(id, parent_scope);
  4086. }
  4087. bool cmMakefile::PolicyOptionalWarningEnabled(std::string const& var) const
  4088. {
  4089. // Check for an explicit CMAKE_POLICY_WARNING_CMP<NNNN> setting.
  4090. if (cmValue val = this->GetDefinition(var)) {
  4091. return cmIsOn(val);
  4092. }
  4093. // Enable optional policy warnings with --debug-output, --trace,
  4094. // or --trace-expand.
  4095. cmake* cm = this->GetCMakeInstance();
  4096. return cm->GetDebugOutput() || cm->GetTrace();
  4097. }
  4098. bool cmMakefile::SetPolicy(const char* id, cmPolicies::PolicyStatus status)
  4099. {
  4100. cmPolicies::PolicyID pid;
  4101. if (!cmPolicies::GetPolicyID(id, /* out */ pid)) {
  4102. std::ostringstream e;
  4103. e << "Policy \"" << id << "\" is not known to this version of CMake.";
  4104. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  4105. return false;
  4106. }
  4107. return this->SetPolicy(pid, status);
  4108. }
  4109. bool cmMakefile::SetPolicy(cmPolicies::PolicyID id,
  4110. cmPolicies::PolicyStatus status)
  4111. {
  4112. // A REQUIRED_ALWAYS policy may be set only to NEW.
  4113. if (status != cmPolicies::NEW &&
  4114. cmPolicies::GetPolicyStatus(id) == cmPolicies::REQUIRED_ALWAYS) {
  4115. std::string msg = cmPolicies::GetRequiredAlwaysPolicyError(id);
  4116. this->IssueMessage(MessageType::FATAL_ERROR, msg);
  4117. return false;
  4118. }
  4119. // Deprecate old policies.
  4120. if (status == cmPolicies::OLD && id <= cmPolicies::CMP0120 &&
  4121. !(this->GetCMakeInstance()->GetIsInTryCompile() &&
  4122. (
  4123. // Policies set by cmCoreTryCompile::TryCompileCode.
  4124. id == cmPolicies::CMP0065 || id == cmPolicies::CMP0083 ||
  4125. id == cmPolicies::CMP0091 || id == cmPolicies::CMP0104)) &&
  4126. (!this->IsSet("CMAKE_WARN_DEPRECATED") ||
  4127. this->IsOn("CMAKE_WARN_DEPRECATED"))) {
  4128. this->IssueMessage(MessageType::DEPRECATION_WARNING,
  4129. cmPolicies::GetPolicyDeprecatedWarning(id));
  4130. }
  4131. this->StateSnapshot.SetPolicy(id, status);
  4132. return true;
  4133. }
  4134. cmMakefile::PolicyPushPop::PolicyPushPop(cmMakefile* m)
  4135. : Makefile(m)
  4136. {
  4137. this->Makefile->PushPolicy();
  4138. }
  4139. cmMakefile::PolicyPushPop::~PolicyPushPop()
  4140. {
  4141. this->Makefile->PopPolicy();
  4142. }
  4143. void cmMakefile::PushPolicy(bool weak, cmPolicies::PolicyMap const& pm)
  4144. {
  4145. this->StateSnapshot.PushPolicy(pm, weak);
  4146. }
  4147. void cmMakefile::PopPolicy()
  4148. {
  4149. if (!this->StateSnapshot.PopPolicy()) {
  4150. this->IssueMessage(MessageType::FATAL_ERROR,
  4151. "cmake_policy POP without matching PUSH");
  4152. }
  4153. }
  4154. void cmMakefile::PopSnapshot(bool reportError)
  4155. {
  4156. // cmStateSnapshot manages nested policy scopes within it.
  4157. // Since the scope corresponding to the snapshot is closing,
  4158. // reject any still-open nested policy scopes with an error.
  4159. while (this->StateSnapshot.CanPopPolicyScope()) {
  4160. if (reportError) {
  4161. this->IssueMessage(MessageType::FATAL_ERROR,
  4162. "cmake_policy PUSH without matching POP");
  4163. reportError = false;
  4164. }
  4165. this->PopPolicy();
  4166. }
  4167. this->StateSnapshot = this->GetState()->Pop(this->StateSnapshot);
  4168. assert(this->StateSnapshot.IsValid());
  4169. }
  4170. bool cmMakefile::SetPolicyVersion(std::string const& version_min,
  4171. std::string const& version_max)
  4172. {
  4173. return cmPolicies::ApplyPolicyVersion(this, version_min, version_max,
  4174. cmPolicies::WarnCompat::On);
  4175. }
  4176. cmMakefile::VariablePushPop::VariablePushPop(cmMakefile* m)
  4177. : Makefile(m)
  4178. {
  4179. this->Makefile->StateSnapshot =
  4180. this->Makefile->GetState()->CreateVariableScopeSnapshot(
  4181. this->Makefile->StateSnapshot);
  4182. }
  4183. cmMakefile::VariablePushPop::~VariablePushPop()
  4184. {
  4185. this->Makefile->PopSnapshot();
  4186. }
  4187. bool cmMakefile::HasCMP0054AlreadyBeenReported(
  4188. cmListFileContext const& context) const
  4189. {
  4190. return !this->CMP0054ReportedIds.insert(context).second;
  4191. }
  4192. void cmMakefile::RecordPolicies(cmPolicies::PolicyMap& pm) const
  4193. {
  4194. /* Record the setting of every policy. */
  4195. using PolicyID = cmPolicies::PolicyID;
  4196. for (PolicyID pid = cmPolicies::CMP0000; pid != cmPolicies::CMPCOUNT;
  4197. pid = static_cast<PolicyID>(pid + 1)) {
  4198. pm.Set(pid, this->GetPolicyStatus(pid));
  4199. }
  4200. }
  4201. bool cmMakefile::IgnoreErrorsCMP0061() const
  4202. {
  4203. bool ignoreErrors = true;
  4204. switch (this->GetPolicyStatus(cmPolicies::CMP0061)) {
  4205. case cmPolicies::WARN:
  4206. // No warning for this policy!
  4207. CM_FALLTHROUGH;
  4208. case cmPolicies::OLD:
  4209. break;
  4210. case cmPolicies::REQUIRED_IF_USED:
  4211. case cmPolicies::REQUIRED_ALWAYS:
  4212. case cmPolicies::NEW:
  4213. ignoreErrors = false;
  4214. break;
  4215. }
  4216. return ignoreErrors;
  4217. }
  4218. cmMakefile::FunctionPushPop::FunctionPushPop(cmMakefile* mf,
  4219. const std::string& fileName,
  4220. cmPolicies::PolicyMap const& pm)
  4221. : Makefile(mf)
  4222. {
  4223. this->Makefile->PushFunctionScope(fileName, pm);
  4224. }
  4225. cmMakefile::FunctionPushPop::~FunctionPushPop()
  4226. {
  4227. this->Makefile->PopFunctionScope(this->ReportError);
  4228. }
  4229. cmMakefile::MacroPushPop::MacroPushPop(cmMakefile* mf,
  4230. const std::string& fileName,
  4231. const cmPolicies::PolicyMap& pm)
  4232. : Makefile(mf)
  4233. {
  4234. this->Makefile->PushMacroScope(fileName, pm);
  4235. }
  4236. cmMakefile::MacroPushPop::~MacroPushPop()
  4237. {
  4238. this->Makefile->PopMacroScope(this->ReportError);
  4239. }
  4240. cmMakefile::DebugFindPkgRAII::DebugFindPkgRAII(cmMakefile* mf,
  4241. std::string const& pkg)
  4242. : Makefile(mf)
  4243. , OldValue(this->Makefile->DebugFindPkg)
  4244. {
  4245. this->Makefile->DebugFindPkg =
  4246. this->Makefile->GetCMakeInstance()->GetDebugFindPkgOutput(pkg);
  4247. }
  4248. cmMakefile::DebugFindPkgRAII::~DebugFindPkgRAII()
  4249. {
  4250. this->Makefile->DebugFindPkg = this->OldValue;
  4251. }
  4252. bool cmMakefile::GetDebugFindPkgMode() const
  4253. {
  4254. return this->DebugFindPkg;
  4255. }