cmMakefile.cxx 175 KB

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