cmMakefile.cxx 150 KB

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