cmMakefile.cxx 150 KB

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