cmMakefile.cxx 154 KB

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