cmMakefile.cxx 155 KB

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