cmMakefile.cxx 147 KB

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