cmMakefile.cxx 155 KB

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