cmMakefile.cxx 170 KB

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