cmMakefile.cxx 157 KB

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