cmMakefile.cxx 168 KB

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