cmMakefile.cxx 158 KB

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