cmMakefile.cxx 152 KB

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