cmMakefile.cxx 149 KB

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