cmMakefile.cxx 147 KB

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