cmMakefile.cxx 146 KB

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