cmMakefile.cxx 170 KB

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