cmMakefile.cxx 168 KB

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