cmMakefile.cxx 154 KB

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