cmMakefile.cxx 131 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file LICENSE.rst or https://cmake.org/licensing for details. */
  3. #include "cmConfigure.h" // IWYU pragma: keep
  4. #include "cmMakefile.h"
  5. #include <algorithm>
  6. #include <cassert>
  7. #include <cctype>
  8. #include <cstdio>
  9. #include <cstdlib>
  10. #include <cstring>
  11. #include <sstream>
  12. #include <utility>
  13. #include <cm/iterator>
  14. #include <cm/memory>
  15. #include <cm/optional>
  16. #include <cm/type_traits> // IWYU pragma: keep
  17. #include <cm/vector>
  18. #include <cmext/algorithm>
  19. #include <cmext/string_view>
  20. #ifndef CMAKE_BOOTSTRAP
  21. # include <cm3p/json/value.h>
  22. # include <cm3p/json/writer.h>
  23. #endif
  24. #include "cmsys/FStream.hxx"
  25. #include "cmsys/RegularExpression.hxx"
  26. #include "cmCustomCommand.h"
  27. #include "cmCustomCommandLines.h"
  28. #include "cmCustomCommandTypes.h"
  29. #include "cmExecutionStatus.h"
  30. #include "cmExpandedCommandArgument.h" // IWYU pragma: keep
  31. #include "cmExportBuildFileGenerator.h"
  32. #include "cmFileLockPool.h"
  33. #include "cmFunctionBlocker.h"
  34. #include "cmGeneratedFileStream.h"
  35. #include "cmGeneratorExpression.h"
  36. #include "cmGeneratorExpressionEvaluationFile.h"
  37. #include "cmGlobalGenerator.h"
  38. #include "cmInstallGenerator.h" // IWYU pragma: keep
  39. #include "cmInstallSubdirectoryGenerator.h"
  40. #include "cmList.h"
  41. #include "cmListFileCache.h"
  42. #include "cmLocalGenerator.h"
  43. #include "cmMessageType.h"
  44. #include "cmRange.h"
  45. #include "cmSourceFile.h"
  46. #include "cmSourceFileLocation.h"
  47. #include "cmStack.h"
  48. #include "cmState.h"
  49. #include "cmStateDirectory.h"
  50. #include "cmStateTypes.h"
  51. #include "cmStringAlgorithms.h"
  52. #include "cmSystemTools.h"
  53. #include "cmTarget.h"
  54. #include "cmTargetLinkLibraryType.h"
  55. #include "cmTest.h"
  56. #include "cmTestGenerator.h" // IWYU pragma: keep
  57. #include "cmVersion.h"
  58. #include "cmWorkingDirectory.h"
  59. #include "cmake.h"
  60. #ifndef CMAKE_BOOTSTRAP
  61. # include "cmMakefileProfilingData.h"
  62. # include "cmVariableWatch.h"
  63. #endif
  64. #ifdef CMake_ENABLE_DEBUGGER
  65. # include "cmDebuggerAdapter.h"
  66. #endif
  67. #ifndef __has_feature
  68. # define __has_feature(x) 0
  69. #endif
  70. // Select a recursion limit that fits within the stack size.
  71. // See stack size flags in '../CompileFlags.cmake'.
  72. #ifndef CMake_DEFAULT_RECURSION_LIMIT
  73. # if __has_feature(address_sanitizer)
  74. # define CMake_DEFAULT_RECURSION_LIMIT 400
  75. # elif defined(_MSC_VER) && defined(_DEBUG)
  76. # define CMake_DEFAULT_RECURSION_LIMIT 600
  77. # elif defined(__ibmxl__) && defined(__linux)
  78. # define CMake_DEFAULT_RECURSION_LIMIT 600
  79. # else
  80. # define CMake_DEFAULT_RECURSION_LIMIT 1000
  81. # endif
  82. #endif
  83. namespace {
  84. std::string const kCMAKE_CURRENT_LIST_DIR = "CMAKE_CURRENT_LIST_DIR";
  85. std::string const kCMAKE_CURRENT_LIST_FILE = "CMAKE_CURRENT_LIST_FILE";
  86. std::string const kCMAKE_PARENT_LIST_FILE = "CMAKE_PARENT_LIST_FILE";
  87. class FileScopeBase
  88. {
  89. protected:
  90. cmMakefile* Makefile;
  91. private:
  92. std::string OldCurrent;
  93. cm::optional<std::string> OldParent;
  94. public:
  95. FileScopeBase(cmMakefile* mf)
  96. : Makefile(mf)
  97. {
  98. }
  99. void PushListFileVars(std::string const& newCurrent)
  100. {
  101. if (cmValue p = this->Makefile->GetDefinition(kCMAKE_PARENT_LIST_FILE)) {
  102. this->OldParent = *p;
  103. }
  104. if (cmValue c = this->Makefile->GetDefinition(kCMAKE_CURRENT_LIST_FILE)) {
  105. this->OldCurrent = *c;
  106. this->Makefile->AddDefinition(kCMAKE_PARENT_LIST_FILE, this->OldCurrent);
  107. this->Makefile->MarkVariableAsUsed(kCMAKE_PARENT_LIST_FILE);
  108. }
  109. this->Makefile->AddDefinition(kCMAKE_CURRENT_LIST_FILE, newCurrent);
  110. this->Makefile->AddDefinition(kCMAKE_CURRENT_LIST_DIR,
  111. cmSystemTools::GetFilenamePath(newCurrent));
  112. this->Makefile->MarkVariableAsUsed(kCMAKE_CURRENT_LIST_FILE);
  113. this->Makefile->MarkVariableAsUsed(kCMAKE_CURRENT_LIST_DIR);
  114. }
  115. void PopListFileVars()
  116. {
  117. if (this->OldParent) {
  118. this->Makefile->AddDefinition(kCMAKE_PARENT_LIST_FILE, *this->OldParent);
  119. this->Makefile->MarkVariableAsUsed(kCMAKE_PARENT_LIST_FILE);
  120. } else {
  121. this->Makefile->RemoveDefinition(kCMAKE_PARENT_LIST_FILE);
  122. }
  123. this->Makefile->AddDefinition(kCMAKE_CURRENT_LIST_FILE, this->OldCurrent);
  124. this->Makefile->AddDefinition(
  125. kCMAKE_CURRENT_LIST_DIR,
  126. cmSystemTools::GetFilenamePath(this->OldCurrent));
  127. this->Makefile->MarkVariableAsUsed(kCMAKE_CURRENT_LIST_FILE);
  128. this->Makefile->MarkVariableAsUsed(kCMAKE_CURRENT_LIST_DIR);
  129. }
  130. };
  131. }
  132. class cmMessenger;
  133. cmDirectoryId::cmDirectoryId(std::string s)
  134. : String(std::move(s))
  135. {
  136. }
  137. // default is not to be building executables
  138. cmMakefile::cmMakefile(cmGlobalGenerator* globalGenerator,
  139. cmStateSnapshot const& snapshot)
  140. : GlobalGenerator(globalGenerator)
  141. , StateSnapshot(snapshot)
  142. {
  143. this->IsSourceFileTryCompile = false;
  144. this->CheckSystemVars = this->GetCMakeInstance()->GetCheckSystemVars();
  145. // Setup the default include complaint regular expression (match nothing).
  146. this->ComplainFileRegularExpression = "^$";
  147. this->DefineFlags = " ";
  148. this->cmDefineRegex.compile("#([ \t]*)cmakedefine[ \t]+([A-Za-z_0-9]*)");
  149. this->cmDefine01Regex.compile("#([ \t]*)cmakedefine01[ \t]+([A-Za-z_0-9]*)");
  150. this->cmNamedCurly.compile("^[A-Za-z0-9/_.+-]+{");
  151. this->StateSnapshot =
  152. this->StateSnapshot.GetState()->CreatePolicyScopeSnapshot(
  153. this->StateSnapshot);
  154. // Enter a policy level for this directory.
  155. this->PushPolicy();
  156. // push empty loop block
  157. this->PushLoopBlockBarrier();
  158. // By default the check is not done. It is enabled by
  159. // cmMakefile::Configure in the top level if necessary.
  160. this->CheckCMP0000 = false;
  161. #if !defined(CMAKE_BOOTSTRAP)
  162. this->AddSourceGroup("", "^.*$");
  163. this->AddSourceGroup("Source Files", CM_SOURCE_REGEX);
  164. this->AddSourceGroup("Header Files", CM_HEADER_REGEX);
  165. this->AddSourceGroup("Precompile Header File", CM_PCH_REGEX);
  166. this->AddSourceGroup("CMake Rules", "\\.rule$");
  167. this->AddSourceGroup("Resources", CM_RESOURCE_REGEX);
  168. this->AddSourceGroup("Object Files", "\\.(lo|o|obj)$");
  169. this->ObjectLibrariesSourceGroupIndex = this->SourceGroups.size();
  170. this->SourceGroups.emplace_back("Object Libraries", "^MATCH_NO_SOURCES$");
  171. #endif
  172. }
  173. cmMakefile::~cmMakefile() = default;
  174. cmDirectoryId cmMakefile::GetDirectoryId() const
  175. {
  176. // Use the instance pointer value to uniquely identify this directory.
  177. // If we ever need to expose this to CMake language code we should
  178. // add a read-only property in cmMakefile::GetProperty.
  179. char buf[32];
  180. snprintf(buf, sizeof(buf), "(%p)",
  181. static_cast<void const*>(this)); // cast avoids format warning
  182. return std::string(buf);
  183. }
  184. void cmMakefile::IssueMessage(MessageType t, std::string const& text) const
  185. {
  186. if (!this->ExecutionStatusStack.empty()) {
  187. if ((t == MessageType::FATAL_ERROR) ||
  188. (t == MessageType::INTERNAL_ERROR)) {
  189. this->ExecutionStatusStack.back()->SetNestedError();
  190. }
  191. }
  192. this->GetCMakeInstance()->IssueMessage(t, text, this->Backtrace);
  193. }
  194. Message::LogLevel cmMakefile::GetCurrentLogLevel() const
  195. {
  196. cmake const* cmakeInstance = this->GetCMakeInstance();
  197. Message::LogLevel const logLevelCliOrDefault = cmakeInstance->GetLogLevel();
  198. assert("Expected a valid log level here" &&
  199. logLevelCliOrDefault != Message::LogLevel::LOG_UNDEFINED);
  200. Message::LogLevel result = logLevelCliOrDefault;
  201. // If the log-level was set via the command line option, it takes precedence
  202. // over the CMAKE_MESSAGE_LOG_LEVEL variable.
  203. if (!cmakeInstance->WasLogLevelSetViaCLI()) {
  204. Message::LogLevel const logLevelFromVar = cmake::StringToLogLevel(
  205. this->GetSafeDefinition("CMAKE_MESSAGE_LOG_LEVEL"));
  206. if (logLevelFromVar != Message::LogLevel::LOG_UNDEFINED) {
  207. result = logLevelFromVar;
  208. }
  209. }
  210. return result;
  211. }
  212. void cmMakefile::IssueInvalidTargetNameError(
  213. std::string const& targetName) const
  214. {
  215. this->IssueMessage(
  216. MessageType::FATAL_ERROR,
  217. cmStrCat("The target name \"", targetName,
  218. "\" is reserved or not valid for certain "
  219. "CMake features, such as generator expressions, and may result "
  220. "in undefined behavior."));
  221. }
  222. void cmMakefile::MaybeWarnCMP0074(std::string const& rootVar, cmValue rootDef,
  223. cm::optional<std::string> const& rootEnv)
  224. {
  225. // Warn if a <PackageName>_ROOT variable we may use is set.
  226. if ((rootDef || rootEnv) && this->WarnedCMP0074.insert(rootVar).second) {
  227. auto e = cmStrCat(cmPolicies::GetPolicyWarning(cmPolicies::CMP0074), '\n');
  228. if (rootDef) {
  229. e += cmStrCat("CMake variable ", rootVar, " is set to:\n ", *rootDef,
  230. '\n');
  231. }
  232. if (rootEnv) {
  233. e += cmStrCat("Environment variable ", rootVar, " is set to:\n ",
  234. *rootEnv, '\n');
  235. }
  236. e += "For compatibility, CMake is ignoring the variable.";
  237. this->IssueMessage(MessageType::AUTHOR_WARNING, e);
  238. }
  239. }
  240. void cmMakefile::MaybeWarnCMP0144(std::string const& rootVar, cmValue rootDef,
  241. cm::optional<std::string> const& rootEnv)
  242. {
  243. // Warn if a <PACKAGENAME>_ROOT variable we may use is set.
  244. if ((rootDef || rootEnv) && this->WarnedCMP0144.insert(rootVar).second) {
  245. auto e = cmStrCat(cmPolicies::GetPolicyWarning(cmPolicies::CMP0144), '\n');
  246. if (rootDef) {
  247. e += cmStrCat("CMake variable ", rootVar, " is set to:\n ", *rootDef,
  248. '\n');
  249. }
  250. if (rootEnv) {
  251. e += cmStrCat("Environment variable ", rootVar, " is set to:\n ",
  252. *rootEnv, '\n');
  253. }
  254. e += "For compatibility, find_package is ignoring the variable, but "
  255. "code in a .cmake module might still use it.";
  256. this->IssueMessage(MessageType::AUTHOR_WARNING, e);
  257. }
  258. }
  259. cmBTStringRange cmMakefile::GetIncludeDirectoriesEntries() const
  260. {
  261. return this->StateSnapshot.GetDirectory().GetIncludeDirectoriesEntries();
  262. }
  263. cmBTStringRange cmMakefile::GetCompileOptionsEntries() const
  264. {
  265. return this->StateSnapshot.GetDirectory().GetCompileOptionsEntries();
  266. }
  267. cmBTStringRange cmMakefile::GetCompileDefinitionsEntries() const
  268. {
  269. return this->StateSnapshot.GetDirectory().GetCompileDefinitionsEntries();
  270. }
  271. cmBTStringRange cmMakefile::GetLinkOptionsEntries() const
  272. {
  273. return this->StateSnapshot.GetDirectory().GetLinkOptionsEntries();
  274. }
  275. cmBTStringRange cmMakefile::GetLinkDirectoriesEntries() const
  276. {
  277. return this->StateSnapshot.GetDirectory().GetLinkDirectoriesEntries();
  278. }
  279. cmListFileBacktrace cmMakefile::GetBacktrace() const
  280. {
  281. return this->Backtrace;
  282. }
  283. cmFindPackageStack cmMakefile::GetFindPackageStack() const
  284. {
  285. return this->FindPackageStack;
  286. }
  287. void cmMakefile::PrintCommandTrace(cmListFileFunction const& lff,
  288. cmListFileBacktrace const& bt,
  289. CommandMissingFromStack missing) const
  290. {
  291. // Check if current file in the list of requested to trace...
  292. std::vector<std::string> const& trace_only_this_files =
  293. this->GetCMakeInstance()->GetTraceSources();
  294. std::string const& full_path = bt.Top().FilePath;
  295. std::string const& only_filename = cmSystemTools::GetFilenameName(full_path);
  296. bool trace = trace_only_this_files.empty();
  297. if (!trace) {
  298. for (std::string const& file : trace_only_this_files) {
  299. std::string::size_type const pos = full_path.rfind(file);
  300. trace = (pos != std::string::npos) &&
  301. ((pos + file.size()) == full_path.size()) &&
  302. (only_filename == cmSystemTools::GetFilenameName(file));
  303. if (trace) {
  304. break;
  305. }
  306. }
  307. // Do nothing if current file wasn't requested for trace...
  308. if (!trace) {
  309. return;
  310. }
  311. }
  312. std::vector<std::string> args;
  313. std::string temp;
  314. bool expand = this->GetCMakeInstance()->GetTraceExpand();
  315. args.reserve(lff.Arguments().size());
  316. for (cmListFileArgument const& arg : lff.Arguments()) {
  317. if (expand && arg.Delim != cmListFileArgument::Bracket) {
  318. temp = arg.Value;
  319. this->ExpandVariablesInString(temp);
  320. args.push_back(temp);
  321. } else {
  322. args.push_back(arg.Value);
  323. }
  324. }
  325. cm::optional<std::string> const& deferId = bt.Top().DeferId;
  326. std::ostringstream msg;
  327. switch (this->GetCMakeInstance()->GetTraceFormat()) {
  328. case cmake::TraceFormat::JSONv1: {
  329. #ifndef CMAKE_BOOTSTRAP
  330. Json::Value val;
  331. Json::StreamWriterBuilder builder;
  332. builder["indentation"] = "";
  333. val["file"] = full_path;
  334. val["line"] = static_cast<Json::Value::Int64>(lff.Line());
  335. if (lff.Line() != lff.LineEnd()) {
  336. val["line_end"] = static_cast<Json::Value::Int64>(lff.LineEnd());
  337. }
  338. if (deferId) {
  339. val["defer"] = *deferId;
  340. }
  341. val["cmd"] = lff.OriginalName();
  342. val["args"] = Json::Value(Json::arrayValue);
  343. for (std::string const& arg : args) {
  344. val["args"].append(arg);
  345. }
  346. val["time"] = cmSystemTools::GetTime();
  347. val["frame"] = int(missing == CommandMissingFromStack::Yes) +
  348. static_cast<Json::Value::UInt64>(this->ExecutionStatusStack.size());
  349. val["global_frame"] = int(missing == CommandMissingFromStack::Yes) +
  350. static_cast<Json::Value::UInt64>(this->RecursionDepth);
  351. msg << Json::writeString(builder, val);
  352. #endif
  353. break;
  354. }
  355. case cmake::TraceFormat::Human:
  356. msg << full_path << '(' << lff.Line() << "):";
  357. if (deferId) {
  358. msg << "DEFERRED:" << *deferId << ':';
  359. }
  360. msg << " " << lff.OriginalName() << '(';
  361. for (std::string const& arg : args) {
  362. msg << arg << ' ';
  363. }
  364. msg << ')';
  365. break;
  366. case cmake::TraceFormat::Undefined:
  367. msg << "INTERNAL ERROR: Trace format is Undefined";
  368. break;
  369. }
  370. auto& f = this->GetCMakeInstance()->GetTraceFile();
  371. if (f) {
  372. f << msg.str() << '\n';
  373. } else {
  374. cmSystemTools::Message(msg.str());
  375. }
  376. }
  377. cmMakefile::CallRAII::CallRAII(cmMakefile* mf, std::string const& file,
  378. cmExecutionStatus& status)
  379. : CallRAII(mf, cmListFileContext::FromListFilePath(file), status)
  380. {
  381. }
  382. cmMakefile::CallRAII::CallRAII(cmMakefile* mf, cmListFileContext const& lfc,
  383. cmExecutionStatus& status)
  384. : Makefile{ mf }
  385. {
  386. this->Makefile->Backtrace = this->Makefile->Backtrace.Push(lfc);
  387. ++this->Makefile->RecursionDepth;
  388. this->Makefile->ExecutionStatusStack.push_back(&status);
  389. }
  390. cmMakefile::CallRAII::~CallRAII()
  391. {
  392. if (this->Makefile) {
  393. this->Detach();
  394. }
  395. }
  396. cmMakefile* cmMakefile::CallRAII::Detach()
  397. {
  398. assert(this->Makefile);
  399. this->Makefile->ExecutionStatusStack.pop_back();
  400. --this->Makefile->RecursionDepth;
  401. this->Makefile->Backtrace = this->Makefile->Backtrace.Pop();
  402. auto* const mf = this->Makefile;
  403. this->Makefile = nullptr;
  404. return mf;
  405. }
  406. // Helper class to make sure the call stack is valid.
  407. class cmMakefile::CallScope : public CallRAII
  408. {
  409. public:
  410. CallScope(cmMakefile* mf, cmListFileFunction const& lff,
  411. cm::optional<std::string> deferId, cmExecutionStatus& status)
  412. : CallScope{ mf, lff,
  413. cmListFileContext::FromListFileFunction(
  414. lff, mf->StateSnapshot.GetExecutionListFile(),
  415. std::move(deferId)),
  416. status }
  417. {
  418. }
  419. CallScope(cmMakefile* mf, cmListFileFunction const& lff,
  420. cmListFileContext const& lfc, cmExecutionStatus& status)
  421. : CallRAII{ mf, lfc, status }
  422. {
  423. #if !defined(CMAKE_BOOTSTRAP)
  424. this->ProfilingDataRAII =
  425. this->Makefile->GetCMakeInstance()->CreateProfilingEntry(
  426. "script", lff.LowerCaseName(), [&lff, &lfc]() -> Json::Value {
  427. Json::Value argsValue = Json::objectValue;
  428. if (!lff.Arguments().empty()) {
  429. std::string args;
  430. for (auto const& a : lff.Arguments()) {
  431. args = cmStrCat(args, args.empty() ? "" : " ", a.Value);
  432. }
  433. argsValue["functionArgs"] = args;
  434. }
  435. argsValue["location"] = cmStrCat(lfc.FilePath, ':', lfc.Line);
  436. return argsValue;
  437. });
  438. #endif
  439. #ifdef CMake_ENABLE_DEBUGGER
  440. if (this->Makefile->GetCMakeInstance()->GetDebugAdapter()) {
  441. this->Makefile->GetCMakeInstance()
  442. ->GetDebugAdapter()
  443. ->OnBeginFunctionCall(mf, lfc.FilePath, lff);
  444. }
  445. #endif
  446. }
  447. ~CallScope()
  448. {
  449. #if !defined(CMAKE_BOOTSTRAP)
  450. this->ProfilingDataRAII.reset();
  451. #endif
  452. auto* const mf = this->Detach();
  453. #ifdef CMake_ENABLE_DEBUGGER
  454. if (mf->GetCMakeInstance()->GetDebugAdapter()) {
  455. mf->GetCMakeInstance()->GetDebugAdapter()->OnEndFunctionCall();
  456. }
  457. #else
  458. static_cast<void>(mf);
  459. #endif
  460. }
  461. CallScope(CallScope const&) = delete;
  462. CallScope& operator=(CallScope const&) = delete;
  463. private:
  464. #if !defined(CMAKE_BOOTSTRAP)
  465. cm::optional<cmMakefileProfilingData::RAII> ProfilingDataRAII;
  466. #endif
  467. };
  468. void cmMakefile::OnExecuteCommand(std::function<void()> callback)
  469. {
  470. this->ExecuteCommandCallback = std::move(callback);
  471. }
  472. bool cmMakefile::ExecuteCommand(cmListFileFunction const& lff,
  473. cmExecutionStatus& status,
  474. cm::optional<std::string> deferId)
  475. {
  476. bool result = true;
  477. // quick return if blocked
  478. if (this->IsFunctionBlocked(lff, status)) {
  479. // No error.
  480. return result;
  481. }
  482. // Place this call on the call stack.
  483. CallScope stack_manager(this, lff, std::move(deferId), status);
  484. static_cast<void>(stack_manager);
  485. // Check for maximum recursion depth.
  486. size_t depthLimit = this->GetRecursionDepthLimit();
  487. if (this->RecursionDepth > depthLimit) {
  488. this->IssueMessage(
  489. MessageType::FATAL_ERROR,
  490. cmStrCat("Maximum recursion depth of ", depthLimit, " exceeded"));
  491. cmSystemTools::SetFatalErrorOccurred();
  492. return false;
  493. }
  494. // Lookup the command prototype.
  495. if (cmState::Command command =
  496. this->GetState()->GetCommandByExactName(lff.LowerCaseName())) {
  497. // Decide whether to invoke the command.
  498. if (!cmSystemTools::GetFatalErrorOccurred()) {
  499. // if trace is enabled, print out invoke information
  500. if (this->GetCMakeInstance()->GetTrace()) {
  501. this->PrintCommandTrace(lff, this->Backtrace);
  502. }
  503. // Try invoking the command.
  504. bool invokeSucceeded = command(lff.Arguments(), status);
  505. bool hadNestedError = status.GetNestedError();
  506. if (!invokeSucceeded || hadNestedError) {
  507. if (!hadNestedError) {
  508. // The command invocation requested that we report an error.
  509. std::string const error =
  510. cmStrCat(lff.OriginalName(), ' ', status.GetError());
  511. this->IssueMessage(MessageType::FATAL_ERROR, error);
  512. }
  513. result = false;
  514. if (this->GetCMakeInstance()->GetCommandFailureAction() ==
  515. cmake::CommandFailureAction::FATAL_ERROR) {
  516. cmSystemTools::SetFatalErrorOccurred();
  517. }
  518. }
  519. if (this->GetCMakeInstance()->HasScriptModeExitCode() &&
  520. this->GetCMakeInstance()->GetWorkingMode() == cmake::SCRIPT_MODE) {
  521. // pass-through the exit code from inner cmake_language(EXIT) ,
  522. // possibly from include() or similar command...
  523. status.SetExitCode(this->GetCMakeInstance()->GetScriptModeExitCode());
  524. }
  525. }
  526. } else {
  527. if (!cmSystemTools::GetFatalErrorOccurred()) {
  528. std::string error =
  529. cmStrCat("Unknown CMake command \"", lff.OriginalName(), "\".");
  530. this->IssueMessage(MessageType::FATAL_ERROR, error);
  531. result = false;
  532. cmSystemTools::SetFatalErrorOccurred();
  533. }
  534. }
  535. if (this->ExecuteCommandCallback) {
  536. this->ExecuteCommandCallback();
  537. }
  538. return result;
  539. }
  540. bool cmMakefile::IsImportedTargetGlobalScope() const
  541. {
  542. return this->CurrentImportedTargetScope == ImportedTargetScope::Global;
  543. }
  544. class cmMakefile::IncludeScope : public FileScopeBase
  545. {
  546. public:
  547. IncludeScope(cmMakefile* mf, std::string const& filenametoread,
  548. bool noPolicyScope);
  549. ~IncludeScope();
  550. void Quiet() { this->ReportError = false; }
  551. IncludeScope(IncludeScope const&) = delete;
  552. IncludeScope& operator=(IncludeScope const&) = delete;
  553. private:
  554. bool NoPolicyScope;
  555. bool ReportError = true;
  556. };
  557. cmMakefile::IncludeScope::IncludeScope(cmMakefile* mf,
  558. std::string const& filenametoread,
  559. bool noPolicyScope)
  560. : FileScopeBase(mf)
  561. , NoPolicyScope(noPolicyScope)
  562. {
  563. this->Makefile->Backtrace = this->Makefile->Backtrace.Push(
  564. cmListFileContext::FromListFilePath(filenametoread));
  565. this->Makefile->PushFunctionBlockerBarrier();
  566. this->Makefile->StateSnapshot =
  567. this->Makefile->GetState()->CreateIncludeFileSnapshot(
  568. this->Makefile->StateSnapshot, filenametoread);
  569. if (!this->NoPolicyScope) {
  570. this->Makefile->PushPolicy();
  571. }
  572. this->PushListFileVars(filenametoread);
  573. }
  574. cmMakefile::IncludeScope::~IncludeScope()
  575. {
  576. this->PopListFileVars();
  577. if (!this->NoPolicyScope) {
  578. // Pop the scope we pushed for the script.
  579. this->Makefile->PopPolicy();
  580. }
  581. this->Makefile->PopSnapshot(this->ReportError);
  582. this->Makefile->PopFunctionBlockerBarrier(this->ReportError);
  583. this->Makefile->Backtrace = this->Makefile->Backtrace.Pop();
  584. }
  585. bool cmMakefile::ReadDependentFile(std::string const& filename,
  586. bool noPolicyScope)
  587. {
  588. std::string filenametoread = cmSystemTools::CollapseFullPath(
  589. filename, this->GetCurrentSourceDirectory());
  590. IncludeScope incScope(this, filenametoread, noPolicyScope);
  591. #ifdef CMake_ENABLE_DEBUGGER
  592. if (this->GetCMakeInstance()->GetDebugAdapter()) {
  593. this->GetCMakeInstance()->GetDebugAdapter()->OnBeginFileParse(
  594. this, filenametoread);
  595. }
  596. #endif
  597. cmListFile listFile;
  598. if (!listFile.ParseFile(filenametoread.c_str(), this->GetMessenger(),
  599. this->Backtrace)) {
  600. #ifdef CMake_ENABLE_DEBUGGER
  601. if (this->GetCMakeInstance()->GetDebugAdapter()) {
  602. this->GetCMakeInstance()->GetDebugAdapter()->OnEndFileParse();
  603. }
  604. #endif
  605. return false;
  606. }
  607. #ifdef CMake_ENABLE_DEBUGGER
  608. if (this->GetCMakeInstance()->GetDebugAdapter()) {
  609. this->GetCMakeInstance()->GetDebugAdapter()->OnEndFileParse();
  610. this->GetCMakeInstance()->GetDebugAdapter()->OnFileParsedSuccessfully(
  611. filenametoread, listFile.Functions);
  612. }
  613. #endif
  614. this->RunListFile(listFile, filenametoread);
  615. if (cmSystemTools::GetFatalErrorOccurred()) {
  616. incScope.Quiet();
  617. }
  618. return true;
  619. }
  620. class cmMakefile::ListFileScope : public FileScopeBase
  621. {
  622. public:
  623. ListFileScope(cmMakefile* mf, std::string const& filenametoread)
  624. : FileScopeBase(mf)
  625. {
  626. this->Makefile->Backtrace = this->Makefile->Backtrace.Push(
  627. cmListFileContext::FromListFilePath(filenametoread));
  628. this->Makefile->StateSnapshot =
  629. this->Makefile->GetState()->CreateInlineListFileSnapshot(
  630. this->Makefile->StateSnapshot, filenametoread);
  631. assert(this->Makefile->StateSnapshot.IsValid());
  632. this->Makefile->PushFunctionBlockerBarrier();
  633. this->PushListFileVars(filenametoread);
  634. }
  635. ~ListFileScope()
  636. {
  637. this->PopListFileVars();
  638. this->Makefile->PopSnapshot(this->ReportError);
  639. this->Makefile->PopFunctionBlockerBarrier(this->ReportError);
  640. this->Makefile->Backtrace = this->Makefile->Backtrace.Pop();
  641. }
  642. void Quiet() { this->ReportError = false; }
  643. ListFileScope(ListFileScope const&) = delete;
  644. ListFileScope& operator=(ListFileScope const&) = delete;
  645. private:
  646. bool ReportError = true;
  647. };
  648. class cmMakefile::DeferScope
  649. {
  650. public:
  651. DeferScope(cmMakefile* mf, std::string const& deferredInFile)
  652. : Makefile(mf)
  653. {
  654. cmListFileContext lfc;
  655. lfc.Line = cmListFileContext::DeferPlaceholderLine;
  656. lfc.FilePath = deferredInFile;
  657. this->Makefile->Backtrace = this->Makefile->Backtrace.Push(lfc);
  658. this->Makefile->DeferRunning = true;
  659. }
  660. ~DeferScope()
  661. {
  662. this->Makefile->DeferRunning = false;
  663. this->Makefile->Backtrace = this->Makefile->Backtrace.Pop();
  664. }
  665. DeferScope(DeferScope const&) = delete;
  666. DeferScope& operator=(DeferScope const&) = delete;
  667. private:
  668. cmMakefile* Makefile;
  669. };
  670. class cmMakefile::DeferCallScope
  671. {
  672. public:
  673. DeferCallScope(cmMakefile* mf, std::string const& deferredFromFile)
  674. : Makefile(mf)
  675. {
  676. this->Makefile->StateSnapshot =
  677. this->Makefile->GetState()->CreateDeferCallSnapshot(
  678. this->Makefile->StateSnapshot, deferredFromFile);
  679. assert(this->Makefile->StateSnapshot.IsValid());
  680. }
  681. ~DeferCallScope() { this->Makefile->PopSnapshot(); }
  682. DeferCallScope(DeferCallScope const&) = delete;
  683. DeferCallScope& operator=(DeferCallScope const&) = delete;
  684. private:
  685. cmMakefile* Makefile;
  686. };
  687. bool cmMakefile::ReadListFile(std::string const& filename)
  688. {
  689. std::string filenametoread = cmSystemTools::CollapseFullPath(
  690. filename, this->GetCurrentSourceDirectory());
  691. ListFileScope scope(this, filenametoread);
  692. #ifdef CMake_ENABLE_DEBUGGER
  693. if (this->GetCMakeInstance()->GetDebugAdapter()) {
  694. this->GetCMakeInstance()->GetDebugAdapter()->OnBeginFileParse(
  695. this, filenametoread);
  696. }
  697. #endif
  698. cmListFile listFile;
  699. if (!listFile.ParseFile(filenametoread.c_str(), this->GetMessenger(),
  700. this->Backtrace)) {
  701. #ifdef CMake_ENABLE_DEBUGGER
  702. if (this->GetCMakeInstance()->GetDebugAdapter()) {
  703. this->GetCMakeInstance()->GetDebugAdapter()->OnEndFileParse();
  704. }
  705. #endif
  706. return false;
  707. }
  708. #ifdef CMake_ENABLE_DEBUGGER
  709. if (this->GetCMakeInstance()->GetDebugAdapter()) {
  710. this->GetCMakeInstance()->GetDebugAdapter()->OnEndFileParse();
  711. this->GetCMakeInstance()->GetDebugAdapter()->OnFileParsedSuccessfully(
  712. filenametoread, listFile.Functions);
  713. }
  714. #endif
  715. this->RunListFile(listFile, filenametoread);
  716. if (cmSystemTools::GetFatalErrorOccurred()) {
  717. scope.Quiet();
  718. }
  719. return true;
  720. }
  721. bool cmMakefile::ReadListFileAsString(std::string const& content,
  722. std::string const& virtualFileName)
  723. {
  724. std::string filenametoread = cmSystemTools::CollapseFullPath(
  725. virtualFileName, this->GetCurrentSourceDirectory());
  726. ListFileScope scope(this, filenametoread);
  727. cmListFile listFile;
  728. if (!listFile.ParseString(content.c_str(), virtualFileName.c_str(),
  729. this->GetMessenger(), this->Backtrace)) {
  730. return false;
  731. }
  732. #ifdef CMake_ENABLE_DEBUGGER
  733. if (this->GetCMakeInstance()->GetDebugAdapter()) {
  734. this->GetCMakeInstance()->GetDebugAdapter()->OnFileParsedSuccessfully(
  735. filenametoread, listFile.Functions);
  736. }
  737. #endif
  738. this->RunListFile(listFile, filenametoread);
  739. if (cmSystemTools::GetFatalErrorOccurred()) {
  740. scope.Quiet();
  741. }
  742. return true;
  743. }
  744. void cmMakefile::RunListFile(cmListFile const& listFile,
  745. std::string const& filenametoread,
  746. DeferCommands* defer)
  747. {
  748. // add this list file to the list of dependencies
  749. this->ListFiles.push_back(filenametoread);
  750. // Run the parsed commands.
  751. size_t const numberFunctions = listFile.Functions.size();
  752. for (size_t i = 0; i < numberFunctions; ++i) {
  753. cmExecutionStatus status(*this);
  754. this->ExecuteCommand(listFile.Functions[i], status);
  755. if (cmSystemTools::GetFatalErrorOccurred()) {
  756. break;
  757. }
  758. if (status.HasExitCode()) {
  759. // cmake_language EXIT was requested, early break.
  760. this->GetCMakeInstance()->SetScriptModeExitCode(status.GetExitCode());
  761. break;
  762. }
  763. if (status.GetReturnInvoked()) {
  764. this->RaiseScope(status.GetReturnVariables());
  765. // Exit early due to return command.
  766. break;
  767. }
  768. }
  769. // Run any deferred commands.
  770. if (defer) {
  771. // Add a backtrace level indicating calls are deferred.
  772. DeferScope scope(this, filenametoread);
  773. // Iterate by index in case one deferred call schedules another.
  774. // NOLINTNEXTLINE(modernize-loop-convert)
  775. for (size_t i = 0; i < defer->Commands.size(); ++i) {
  776. DeferCommand& d = defer->Commands[i];
  777. if (d.Id.empty()) {
  778. // Canceled.
  779. continue;
  780. }
  781. // Mark as executed.
  782. std::string id = std::move(d.Id);
  783. // The deferred call may have come from another file.
  784. DeferCallScope callScope(this, d.FilePath);
  785. cmExecutionStatus status(*this);
  786. this->ExecuteCommand(d.Command, status, std::move(id));
  787. if (cmSystemTools::GetFatalErrorOccurred()) {
  788. break;
  789. }
  790. }
  791. }
  792. }
  793. void cmMakefile::EnforceDirectoryLevelRules() const
  794. {
  795. // Diagnose a violation of CMP0000 if necessary.
  796. if (this->CheckCMP0000) {
  797. std::string e =
  798. cmStrCat("No cmake_minimum_required command is present. "
  799. "A line of code such as\n"
  800. " cmake_minimum_required(VERSION ",
  801. cmVersion::GetMajorVersion(), '.', cmVersion::GetMinorVersion(),
  802. ")\n"
  803. "should be added at the top of the file. "
  804. "The version specified may be lower if you wish to "
  805. "support older CMake versions for this project. "
  806. "For more information run "
  807. "\"cmake --help-policy CMP0000\".");
  808. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR, e,
  809. this->Backtrace);
  810. cmSystemTools::SetFatalErrorOccurred();
  811. }
  812. }
  813. void cmMakefile::AddEvaluationFile(
  814. std::string const& inputFile, std::string const& targetName,
  815. std::unique_ptr<cmCompiledGeneratorExpression> outputName,
  816. std::unique_ptr<cmCompiledGeneratorExpression> condition,
  817. std::string const& newLineCharacter, mode_t permissions, bool inputIsContent)
  818. {
  819. this->EvaluationFiles.push_back(
  820. cm::make_unique<cmGeneratorExpressionEvaluationFile>(
  821. inputFile, targetName, std::move(outputName), std::move(condition),
  822. inputIsContent, newLineCharacter, permissions,
  823. this->GetPolicyStatus(cmPolicies::CMP0070)));
  824. }
  825. std::vector<std::unique_ptr<cmGeneratorExpressionEvaluationFile>> const&
  826. cmMakefile::GetEvaluationFiles() const
  827. {
  828. return this->EvaluationFiles;
  829. }
  830. std::vector<std::unique_ptr<cmExportBuildFileGenerator>> const&
  831. cmMakefile::GetExportBuildFileGenerators() const
  832. {
  833. return this->ExportBuildFileGenerators;
  834. }
  835. void cmMakefile::AddExportBuildFileGenerator(
  836. std::unique_ptr<cmExportBuildFileGenerator> gen)
  837. {
  838. this->ExportBuildFileGenerators.emplace_back(std::move(gen));
  839. }
  840. namespace {
  841. struct file_not_persistent
  842. {
  843. bool operator()(std::string const& path) const
  844. {
  845. return !(path.find("CMakeTmp") == std::string::npos &&
  846. cmSystemTools::FileExists(path));
  847. }
  848. };
  849. }
  850. void cmMakefile::AddGeneratorAction(GeneratorAction&& action)
  851. {
  852. assert(!this->GeneratorActionsInvoked);
  853. this->GeneratorActions.emplace_back(std::move(action), this->Backtrace);
  854. }
  855. void cmMakefile::GeneratorAction::operator()(cmLocalGenerator& lg,
  856. cmListFileBacktrace const& lfbt,
  857. GeneratorActionWhen when)
  858. {
  859. if (this->When != when) {
  860. return;
  861. }
  862. if (cc) {
  863. CCAction(lg, lfbt, std::move(cc));
  864. } else {
  865. assert(Action);
  866. Action(lg, lfbt);
  867. }
  868. }
  869. void cmMakefile::DoGenerate(cmLocalGenerator& lg)
  870. {
  871. // give all the commands a chance to do something
  872. // after the file has been parsed before generation
  873. for (auto& action : this->GeneratorActions) {
  874. action.Value(lg, action.Backtrace, GeneratorActionWhen::AfterConfigure);
  875. }
  876. this->GeneratorActionsInvoked = true;
  877. // go through all configured files and see which ones still exist.
  878. // we don't want cmake to re-run if a configured file is created and deleted
  879. // during processing as that would make it a transient file that can't
  880. // influence the build process
  881. cm::erase_if(this->OutputFiles, file_not_persistent());
  882. // if a configured file is used as input for another configured file,
  883. // and then deleted it will show up in the input list files so we
  884. // need to scan those too
  885. cm::erase_if(this->ListFiles, file_not_persistent());
  886. }
  887. // Generate the output file
  888. void cmMakefile::Generate(cmLocalGenerator& lg)
  889. {
  890. this->DoGenerate(lg);
  891. cmValue oldValue = this->GetDefinition("CMAKE_BACKWARDS_COMPATIBILITY");
  892. if (oldValue &&
  893. cmSystemTools::VersionCompare(cmSystemTools::OP_LESS, *oldValue,
  894. "2.4")) {
  895. this->GetCMakeInstance()->IssueMessage(
  896. MessageType::FATAL_ERROR,
  897. "You have set CMAKE_BACKWARDS_COMPATIBILITY to a CMake version less "
  898. "than 2.4. This version of CMake only supports backwards compatibility "
  899. "with CMake 2.4 or later. For compatibility with older versions please "
  900. "use any CMake 2.8.x release or lower.",
  901. this->Backtrace);
  902. }
  903. }
  904. void cmMakefile::GenerateAfterGeneratorTargets(cmLocalGenerator& lg)
  905. {
  906. for (auto& action : this->GeneratorActions) {
  907. action.Value(lg, action.Backtrace,
  908. GeneratorActionWhen::AfterGeneratorTargets);
  909. }
  910. }
  911. namespace {
  912. // There are still too many implicit backtraces through cmMakefile. As a
  913. // workaround we reset the backtrace temporarily.
  914. struct BacktraceGuard
  915. {
  916. BacktraceGuard(cmListFileBacktrace& lfbt, cmListFileBacktrace current)
  917. : Backtrace(lfbt)
  918. , Previous(lfbt)
  919. {
  920. this->Backtrace = std::move(current);
  921. }
  922. ~BacktraceGuard() { this->Backtrace = std::move(this->Previous); }
  923. private:
  924. cmListFileBacktrace& Backtrace;
  925. cmListFileBacktrace Previous;
  926. };
  927. }
  928. bool cmMakefile::ValidateCustomCommand(
  929. cmCustomCommandLines const& commandLines) const
  930. {
  931. // TODO: More strict?
  932. auto const it =
  933. std::find_if(commandLines.begin(), commandLines.end(),
  934. [](cmCustomCommandLine const& cl) {
  935. return !cl.empty() && !cl[0].empty() && cl[0][0] == '"';
  936. });
  937. if (it != commandLines.end()) {
  938. this->IssueMessage(
  939. MessageType::FATAL_ERROR,
  940. cmStrCat("COMMAND may not contain literal quotes:\n ", (*it)[0], '\n'));
  941. return false;
  942. }
  943. return true;
  944. }
  945. cmTarget* cmMakefile::GetCustomCommandTarget(
  946. std::string const& target, cmObjectLibraryCommands objLibCommands,
  947. cmListFileBacktrace const& lfbt) const
  948. {
  949. auto realTarget = target;
  950. auto ai = this->AliasTargets.find(target);
  951. if (ai != this->AliasTargets.end()) {
  952. realTarget = ai->second;
  953. }
  954. // Find the target to which to add the custom command.
  955. auto ti = this->Targets.find(realTarget);
  956. if (ti == this->Targets.end()) {
  957. std::string e;
  958. if (cmTarget const* t = this->FindTargetToUse(target)) {
  959. if (t->IsImported()) {
  960. e += cmStrCat("TARGET '", target,
  961. "' is IMPORTED and does not build here.");
  962. } else {
  963. e +=
  964. cmStrCat("TARGET '", target, "' was not created in this directory.");
  965. }
  966. } else {
  967. e += cmStrCat("No TARGET '", target,
  968. "' has been created in this directory.");
  969. }
  970. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR, e, lfbt);
  971. return nullptr;
  972. }
  973. cmTarget* t = &ti->second;
  974. if (objLibCommands == cmObjectLibraryCommands::Reject &&
  975. t->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  976. auto e = cmStrCat(
  977. "Target \"", target,
  978. "\" is an OBJECT library "
  979. "that may not have PRE_BUILD, PRE_LINK, or POST_BUILD commands.");
  980. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR, e, lfbt);
  981. return nullptr;
  982. }
  983. if (t->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  984. auto e = cmStrCat(
  985. "Target \"", target,
  986. "\" is an INTERFACE library "
  987. "that may not have PRE_BUILD, PRE_LINK, or POST_BUILD commands.");
  988. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR, e, lfbt);
  989. return nullptr;
  990. }
  991. return t;
  992. }
  993. cmTarget* cmMakefile::AddCustomCommandToTarget(
  994. std::string const& target, cmCustomCommandType type,
  995. std::unique_ptr<cmCustomCommand> cc)
  996. {
  997. auto const& byproducts = cc->GetByproducts();
  998. auto const& commandLines = cc->GetCommandLines();
  999. cmTarget* t = this->GetCustomCommandTarget(
  1000. target, cmObjectLibraryCommands::Reject, this->Backtrace);
  1001. // Validate custom commands.
  1002. if (!t || !this->ValidateCustomCommand(commandLines)) {
  1003. return t;
  1004. }
  1005. // Always create the byproduct sources and mark them generated.
  1006. this->CreateGeneratedOutputs(byproducts);
  1007. cc->RecordPolicyValues(this->GetStateSnapshot());
  1008. // Dispatch command creation to allow generator expressions in outputs.
  1009. this->AddGeneratorAction(
  1010. std::move(cc),
  1011. [this, t, type](cmLocalGenerator& lg, cmListFileBacktrace const& lfbt,
  1012. std::unique_ptr<cmCustomCommand> tcc) {
  1013. BacktraceGuard guard(this->Backtrace, lfbt);
  1014. tcc->SetBacktrace(lfbt);
  1015. detail::AddCustomCommandToTarget(lg, cmCommandOrigin::Project, t, type,
  1016. std::move(tcc));
  1017. });
  1018. return t;
  1019. }
  1020. void cmMakefile::AddCustomCommandToOutput(
  1021. std::unique_ptr<cmCustomCommand> cc, CommandSourceCallback const& callback,
  1022. bool replace)
  1023. {
  1024. auto const& outputs = cc->GetOutputs();
  1025. auto const& byproducts = cc->GetByproducts();
  1026. auto const& commandLines = cc->GetCommandLines();
  1027. // Make sure there is at least one output.
  1028. if (outputs.empty()) {
  1029. cmSystemTools::Error("Attempt to add a custom rule with no output!");
  1030. return;
  1031. }
  1032. // Validate custom commands.
  1033. if (!this->ValidateCustomCommand(commandLines)) {
  1034. return;
  1035. }
  1036. // Always create the output sources and mark them generated.
  1037. this->CreateGeneratedOutputs(outputs);
  1038. this->CreateGeneratedOutputs(byproducts);
  1039. cc->RecordPolicyValues(this->GetStateSnapshot());
  1040. // Dispatch command creation to allow generator expressions in outputs.
  1041. this->AddGeneratorAction(
  1042. std::move(cc),
  1043. [this, replace, callback](cmLocalGenerator& lg,
  1044. cmListFileBacktrace const& lfbt,
  1045. std::unique_ptr<cmCustomCommand> tcc) {
  1046. BacktraceGuard guard(this->Backtrace, lfbt);
  1047. tcc->SetBacktrace(lfbt);
  1048. cmSourceFile* sf = detail::AddCustomCommandToOutput(
  1049. lg, cmCommandOrigin::Project, std::move(tcc), replace);
  1050. if (callback && sf) {
  1051. callback(sf);
  1052. }
  1053. });
  1054. }
  1055. void cmMakefile::AppendCustomCommandToOutput(
  1056. std::string const& output, std::vector<std::string> const& depends,
  1057. cmImplicitDependsList const& implicit_depends,
  1058. cmCustomCommandLines const& commandLines)
  1059. {
  1060. // Validate custom commands.
  1061. if (this->ValidateCustomCommand(commandLines)) {
  1062. // Dispatch command creation to allow generator expressions in outputs.
  1063. this->AddGeneratorAction(
  1064. [this, output, depends, implicit_depends,
  1065. commandLines](cmLocalGenerator& lg, cmListFileBacktrace const& lfbt) {
  1066. BacktraceGuard guard(this->Backtrace, lfbt);
  1067. detail::AppendCustomCommandToOutput(lg, lfbt, output, depends,
  1068. implicit_depends, commandLines);
  1069. });
  1070. }
  1071. }
  1072. cmTarget* cmMakefile::AddUtilityCommand(std::string const& utilityName,
  1073. bool excludeFromAll,
  1074. std::unique_ptr<cmCustomCommand> cc)
  1075. {
  1076. auto const& depends = cc->GetDepends();
  1077. auto const& byproducts = cc->GetByproducts();
  1078. auto const& commandLines = cc->GetCommandLines();
  1079. cmTarget* target = this->AddNewUtilityTarget(utilityName, excludeFromAll);
  1080. // Validate custom commands.
  1081. if ((commandLines.empty() && depends.empty()) ||
  1082. !this->ValidateCustomCommand(commandLines)) {
  1083. return target;
  1084. }
  1085. // Always create the byproduct sources and mark them generated.
  1086. this->CreateGeneratedOutputs(byproducts);
  1087. cc->RecordPolicyValues(this->GetStateSnapshot());
  1088. // Dispatch command creation to allow generator expressions in outputs.
  1089. this->AddGeneratorAction(
  1090. std::move(cc),
  1091. [this, target](cmLocalGenerator& lg, cmListFileBacktrace const& lfbt,
  1092. std::unique_ptr<cmCustomCommand> tcc) {
  1093. BacktraceGuard guard(this->Backtrace, lfbt);
  1094. tcc->SetBacktrace(lfbt);
  1095. detail::AddUtilityCommand(lg, cmCommandOrigin::Project, target,
  1096. std::move(tcc));
  1097. });
  1098. return target;
  1099. }
  1100. static void s_AddDefineFlag(std::string const& flag, std::string& dflags)
  1101. {
  1102. // remove any \n\r
  1103. std::string::size_type initSize = dflags.size();
  1104. dflags += ' ';
  1105. dflags += flag;
  1106. std::string::iterator flagStart = dflags.begin() + initSize + 1;
  1107. std::replace(flagStart, dflags.end(), '\n', ' ');
  1108. std::replace(flagStart, dflags.end(), '\r', ' ');
  1109. }
  1110. void cmMakefile::AddDefineFlag(std::string const& flag)
  1111. {
  1112. if (flag.empty()) {
  1113. return;
  1114. }
  1115. // If this is really a definition, update COMPILE_DEFINITIONS.
  1116. if (this->ParseDefineFlag(flag, false)) {
  1117. return;
  1118. }
  1119. // Add this flag that does not look like a definition.
  1120. s_AddDefineFlag(flag, this->DefineFlags);
  1121. }
  1122. static void s_RemoveDefineFlag(std::string const& flag, std::string& dflags)
  1123. {
  1124. std::string::size_type const len = flag.length();
  1125. // Remove all instances of the flag that are surrounded by
  1126. // whitespace or the beginning/end of the string.
  1127. for (std::string::size_type lpos = dflags.find(flag, 0);
  1128. lpos != std::string::npos; lpos = dflags.find(flag, lpos)) {
  1129. std::string::size_type rpos = lpos + len;
  1130. if ((lpos <= 0 || cmIsSpace(dflags[lpos - 1])) &&
  1131. (rpos >= dflags.size() || cmIsSpace(dflags[rpos]))) {
  1132. dflags.erase(lpos, len);
  1133. } else {
  1134. ++lpos;
  1135. }
  1136. }
  1137. }
  1138. void cmMakefile::RemoveDefineFlag(std::string const& flag)
  1139. {
  1140. // Check the length of the flag to remove.
  1141. if (flag.empty()) {
  1142. return;
  1143. }
  1144. // If this is really a definition, update COMPILE_DEFINITIONS.
  1145. if (this->ParseDefineFlag(flag, true)) {
  1146. return;
  1147. }
  1148. // Remove this flag that does not look like a definition.
  1149. s_RemoveDefineFlag(flag, this->DefineFlags);
  1150. }
  1151. void cmMakefile::AddCompileDefinition(std::string const& option)
  1152. {
  1153. this->AppendProperty("COMPILE_DEFINITIONS", option);
  1154. }
  1155. void cmMakefile::AddCompileOption(std::string const& option)
  1156. {
  1157. this->AppendProperty("COMPILE_OPTIONS", option);
  1158. }
  1159. void cmMakefile::AddLinkOption(std::string const& option)
  1160. {
  1161. this->AppendProperty("LINK_OPTIONS", option);
  1162. }
  1163. void cmMakefile::AddLinkDirectory(std::string const& directory, bool before)
  1164. {
  1165. if (before) {
  1166. this->StateSnapshot.GetDirectory().PrependLinkDirectoriesEntry(
  1167. BT<std::string>(directory, this->Backtrace));
  1168. } else {
  1169. this->StateSnapshot.GetDirectory().AppendLinkDirectoriesEntry(
  1170. BT<std::string>(directory, this->Backtrace));
  1171. }
  1172. }
  1173. bool cmMakefile::ParseDefineFlag(std::string const& def, bool remove)
  1174. {
  1175. // Create a regular expression to match valid definitions.
  1176. static cmsys::RegularExpression valid("^[-/]D[A-Za-z_][A-Za-z0-9_]*(=.*)?$");
  1177. // Make sure the definition matches.
  1178. if (!valid.find(def)) {
  1179. return false;
  1180. }
  1181. // Get the definition part after the flag.
  1182. char const* define = def.c_str() + 2;
  1183. if (remove) {
  1184. if (cmValue cdefs = this->GetProperty("COMPILE_DEFINITIONS")) {
  1185. // Expand the list.
  1186. cmList defs{ *cdefs };
  1187. // Recompose the list without the definition.
  1188. defs.remove_items({ define });
  1189. // Store the new list.
  1190. this->SetProperty("COMPILE_DEFINITIONS", defs.to_string());
  1191. }
  1192. } else {
  1193. // Append the definition to the directory property.
  1194. this->AppendProperty("COMPILE_DEFINITIONS", define);
  1195. }
  1196. return true;
  1197. }
  1198. void cmMakefile::InitializeFromParent(cmMakefile* parent)
  1199. {
  1200. this->SystemIncludeDirectories = parent->SystemIncludeDirectories;
  1201. // define flags
  1202. this->DefineFlags = parent->DefineFlags;
  1203. // Include transform property. There is no per-config version.
  1204. {
  1205. char const* prop = "IMPLICIT_DEPENDS_INCLUDE_TRANSFORM";
  1206. this->SetProperty(prop, parent->GetProperty(prop));
  1207. }
  1208. // labels
  1209. this->SetProperty("LABELS", parent->GetProperty("LABELS"));
  1210. // link libraries
  1211. this->SetProperty("LINK_LIBRARIES", parent->GetProperty("LINK_LIBRARIES"));
  1212. // the initial project name
  1213. this->StateSnapshot.SetProjectName(parent->StateSnapshot.GetProjectName());
  1214. // Copy include regular expressions.
  1215. this->ComplainFileRegularExpression = parent->ComplainFileRegularExpression;
  1216. // Imported targets.
  1217. this->ImportedTargets = parent->ImportedTargets;
  1218. // Non-global Alias targets.
  1219. this->AliasTargets = parent->AliasTargets;
  1220. // Recursion depth.
  1221. this->RecursionDepth = parent->RecursionDepth;
  1222. }
  1223. void cmMakefile::AddInstallGenerator(std::unique_ptr<cmInstallGenerator> g)
  1224. {
  1225. if (g) {
  1226. this->InstallGenerators.push_back(std::move(g));
  1227. }
  1228. }
  1229. void cmMakefile::AddTestGenerator(std::unique_ptr<cmTestGenerator> g)
  1230. {
  1231. if (g) {
  1232. this->TestGenerators.push_back(std::move(g));
  1233. }
  1234. }
  1235. void cmMakefile::PushFunctionScope(std::string const& fileName,
  1236. cmPolicies::PolicyMap const& pm)
  1237. {
  1238. this->StateSnapshot = this->GetState()->CreateFunctionCallSnapshot(
  1239. this->StateSnapshot, fileName);
  1240. assert(this->StateSnapshot.IsValid());
  1241. this->PushLoopBlockBarrier();
  1242. #if !defined(CMAKE_BOOTSTRAP)
  1243. this->GetGlobalGenerator()->GetFileLockPool().PushFunctionScope();
  1244. #endif
  1245. this->PushFunctionBlockerBarrier();
  1246. this->PushPolicy(true, pm);
  1247. }
  1248. void cmMakefile::PopFunctionScope(bool reportError)
  1249. {
  1250. this->PopPolicy();
  1251. this->PopSnapshot(reportError);
  1252. this->PopFunctionBlockerBarrier(reportError);
  1253. #if !defined(CMAKE_BOOTSTRAP)
  1254. this->GetGlobalGenerator()->GetFileLockPool().PopFunctionScope();
  1255. #endif
  1256. this->PopLoopBlockBarrier();
  1257. }
  1258. void cmMakefile::PushMacroScope(std::string const& fileName,
  1259. cmPolicies::PolicyMap const& pm)
  1260. {
  1261. this->StateSnapshot =
  1262. this->GetState()->CreateMacroCallSnapshot(this->StateSnapshot, fileName);
  1263. assert(this->StateSnapshot.IsValid());
  1264. this->PushFunctionBlockerBarrier();
  1265. this->PushPolicy(true, pm);
  1266. }
  1267. void cmMakefile::PopMacroScope(bool reportError)
  1268. {
  1269. this->PopPolicy();
  1270. this->PopSnapshot(reportError);
  1271. this->PopFunctionBlockerBarrier(reportError);
  1272. }
  1273. bool cmMakefile::IsRootMakefile() const
  1274. {
  1275. return !this->StateSnapshot.GetBuildsystemDirectoryParent().IsValid();
  1276. }
  1277. class cmMakefile::BuildsystemFileScope : public FileScopeBase
  1278. {
  1279. public:
  1280. BuildsystemFileScope(cmMakefile* mf)
  1281. : FileScopeBase(mf)
  1282. {
  1283. std::string currentStart =
  1284. this->Makefile->GetCMakeInstance()->GetCMakeListFile(
  1285. this->Makefile->StateSnapshot.GetDirectory().GetCurrentSource());
  1286. this->Makefile->StateSnapshot.SetListFile(currentStart);
  1287. this->Makefile->StateSnapshot =
  1288. this->Makefile->StateSnapshot.GetState()->CreatePolicyScopeSnapshot(
  1289. this->Makefile->StateSnapshot);
  1290. this->Makefile->PushFunctionBlockerBarrier();
  1291. this->PushListFileVars(currentStart);
  1292. this->GG = mf->GetGlobalGenerator();
  1293. this->CurrentMakefile = this->GG->GetCurrentMakefile();
  1294. this->Snapshot = this->GG->GetCMakeInstance()->GetCurrentSnapshot();
  1295. this->GG->GetCMakeInstance()->SetCurrentSnapshot(this->Snapshot);
  1296. this->GG->SetCurrentMakefile(mf);
  1297. #if !defined(CMAKE_BOOTSTRAP)
  1298. this->GG->GetFileLockPool().PushFileScope();
  1299. #endif
  1300. }
  1301. ~BuildsystemFileScope()
  1302. {
  1303. this->PopListFileVars();
  1304. this->Makefile->PopFunctionBlockerBarrier(this->ReportError);
  1305. this->Makefile->PopSnapshot(this->ReportError);
  1306. #if !defined(CMAKE_BOOTSTRAP)
  1307. this->GG->GetFileLockPool().PopFileScope();
  1308. #endif
  1309. this->GG->SetCurrentMakefile(this->CurrentMakefile);
  1310. this->GG->GetCMakeInstance()->SetCurrentSnapshot(this->Snapshot);
  1311. }
  1312. void Quiet() { this->ReportError = false; }
  1313. BuildsystemFileScope(BuildsystemFileScope const&) = delete;
  1314. BuildsystemFileScope& operator=(BuildsystemFileScope const&) = delete;
  1315. private:
  1316. cmGlobalGenerator* GG;
  1317. cmMakefile* CurrentMakefile;
  1318. cmStateSnapshot Snapshot;
  1319. bool ReportError = true;
  1320. };
  1321. void cmMakefile::Configure()
  1322. {
  1323. std::string currentStart = this->GetCMakeInstance()->GetCMakeListFile(
  1324. this->StateSnapshot.GetDirectory().GetCurrentSource());
  1325. // Add the bottom of all backtraces within this directory.
  1326. // We will never pop this scope because it should be available
  1327. // for messages during the generate step too.
  1328. this->Backtrace =
  1329. this->Backtrace.Push(cmListFileContext::FromListFilePath(currentStart));
  1330. BuildsystemFileScope scope(this);
  1331. // make sure the CMakeFiles dir is there
  1332. std::string filesDir = cmStrCat(
  1333. this->StateSnapshot.GetDirectory().GetCurrentBinary(), "/CMakeFiles");
  1334. cmSystemTools::MakeDirectory(filesDir);
  1335. assert(cmSystemTools::FileExists(currentStart, true));
  1336. // In the top-most directory, cmake_minimum_required() may not have been
  1337. // called yet, so ApplyPolicyVersion() may not have handled the default
  1338. // policy value. Check them here.
  1339. if (this->GetPolicyStatus(cmPolicies::CMP0198) == cmPolicies::WARN) {
  1340. if (cmValue defaultValue =
  1341. this->GetDefinition("CMAKE_POLICY_DEFAULT_CMP0198")) {
  1342. if (*defaultValue == "NEW") {
  1343. this->SetPolicy(cmPolicies::CMP0198, cmPolicies::NEW);
  1344. } else if (*defaultValue == "OLD") {
  1345. this->SetPolicy(cmPolicies::CMP0198, cmPolicies::OLD);
  1346. }
  1347. }
  1348. }
  1349. // Set CMAKE_PARENT_LIST_FILE for CMakeLists.txt based on CMP0198 policy
  1350. this->UpdateParentListFileVariable();
  1351. #ifdef CMake_ENABLE_DEBUGGER
  1352. if (this->GetCMakeInstance()->GetDebugAdapter()) {
  1353. this->GetCMakeInstance()->GetDebugAdapter()->OnBeginFileParse(
  1354. this, currentStart);
  1355. }
  1356. #endif
  1357. cmListFile listFile;
  1358. if (!listFile.ParseFile(currentStart.c_str(), this->GetMessenger(),
  1359. this->Backtrace)) {
  1360. #ifdef CMake_ENABLE_DEBUGGER
  1361. if (this->GetCMakeInstance()->GetDebugAdapter()) {
  1362. this->GetCMakeInstance()->GetDebugAdapter()->OnEndFileParse();
  1363. }
  1364. #endif
  1365. return;
  1366. }
  1367. #ifdef CMake_ENABLE_DEBUGGER
  1368. if (this->GetCMakeInstance()->GetDebugAdapter()) {
  1369. this->GetCMakeInstance()->GetDebugAdapter()->OnEndFileParse();
  1370. this->GetCMakeInstance()->GetDebugAdapter()->OnFileParsedSuccessfully(
  1371. currentStart, listFile.Functions);
  1372. }
  1373. #endif
  1374. if (this->IsRootMakefile()) {
  1375. bool hasVersion = false;
  1376. // search for the right policy command
  1377. for (cmListFileFunction const& func : listFile.Functions) {
  1378. if (func.LowerCaseName() == "cmake_minimum_required"_s) {
  1379. hasVersion = true;
  1380. break;
  1381. }
  1382. }
  1383. // if no policy command is found this is an error if they use any
  1384. // non advanced functions or a lot of functions
  1385. if (!hasVersion) {
  1386. bool isProblem = true;
  1387. if (listFile.Functions.size() < 30) {
  1388. // the list of simple commands DO NOT ADD TO THIS LIST!!!!!
  1389. // these commands must have backwards compatibility forever and
  1390. // and that is a lot longer than your tiny mind can comprehend mortal
  1391. std::set<std::string> allowedCommands;
  1392. allowedCommands.insert("project");
  1393. allowedCommands.insert("set");
  1394. allowedCommands.insert("if");
  1395. allowedCommands.insert("endif");
  1396. allowedCommands.insert("else");
  1397. allowedCommands.insert("elseif");
  1398. allowedCommands.insert("add_executable");
  1399. allowedCommands.insert("add_library");
  1400. allowedCommands.insert("target_link_libraries");
  1401. allowedCommands.insert("option");
  1402. allowedCommands.insert("message");
  1403. isProblem = false;
  1404. for (cmListFileFunction const& func : listFile.Functions) {
  1405. if (!cm::contains(allowedCommands, func.LowerCaseName())) {
  1406. isProblem = true;
  1407. break;
  1408. }
  1409. }
  1410. }
  1411. if (isProblem) {
  1412. // Tell the top level cmMakefile to diagnose
  1413. // this violation of CMP0000.
  1414. this->SetCheckCMP0000(true);
  1415. // Implicitly set the version for the user.
  1416. cmPolicies::ApplyPolicyVersion(this, 3, 5, 0,
  1417. cmPolicies::WarnCompat::Off);
  1418. }
  1419. }
  1420. bool hasProject = false;
  1421. // search for a project command
  1422. for (cmListFileFunction const& func : listFile.Functions) {
  1423. if (func.LowerCaseName() == "project"_s) {
  1424. hasProject = true;
  1425. break;
  1426. }
  1427. }
  1428. // if no project command is found, add one
  1429. if (!hasProject) {
  1430. this->GetCMakeInstance()->IssueMessage(
  1431. MessageType::AUTHOR_WARNING,
  1432. "No project() command is present. The top-level CMakeLists.txt "
  1433. "file must contain a literal, direct call to the project() command. "
  1434. "Add a line of code such as\n"
  1435. " project(ProjectName)\n"
  1436. "near the top of the file, but after cmake_minimum_required().\n"
  1437. "CMake is pretending there is a \"project(Project)\" command on "
  1438. "the first line.",
  1439. this->Backtrace);
  1440. cmListFileFunction project{
  1441. "project", 0, 0, { { "Project", cmListFileArgument::Unquoted, 0 } }
  1442. };
  1443. listFile.Functions.insert(listFile.Functions.begin(), project);
  1444. }
  1445. }
  1446. this->Defer = cm::make_unique<DeferCommands>();
  1447. this->RunListFile(listFile, currentStart, this->Defer.get());
  1448. this->Defer.reset();
  1449. if (cmSystemTools::GetFatalErrorOccurred()) {
  1450. scope.Quiet();
  1451. }
  1452. // at the end handle any old style subdirs
  1453. std::vector<cmMakefile*> subdirs = this->UnConfiguredDirectories;
  1454. // for each subdir recurse
  1455. auto sdi = subdirs.begin();
  1456. for (; sdi != subdirs.end(); ++sdi) {
  1457. (*sdi)->StateSnapshot.InitializeFromParent_ForSubdirsCommand();
  1458. this->ConfigureSubDirectory(*sdi);
  1459. }
  1460. this->AddCMakeDependFilesFromUser();
  1461. }
  1462. void cmMakefile::ConfigureSubDirectory(cmMakefile* mf)
  1463. {
  1464. mf->InitializeFromParent(this);
  1465. std::string currentStart = mf->GetCurrentSourceDirectory();
  1466. if (this->GetCMakeInstance()->GetDebugOutput()) {
  1467. std::string msg = cmStrCat(" Entering ", currentStart);
  1468. cmSystemTools::Message(msg);
  1469. }
  1470. std::string currentStartFile =
  1471. this->GetCMakeInstance()->GetCMakeListFile(currentStart);
  1472. if (!cmSystemTools::FileExists(currentStartFile, true)) {
  1473. this->IssueMessage(MessageType::FATAL_ERROR,
  1474. cmStrCat("The source directory\n ", currentStart,
  1475. "\n"
  1476. "does not contain a CMakeLists.txt file."));
  1477. return;
  1478. }
  1479. // finally configure the subdir
  1480. mf->Configure();
  1481. if (this->GetCMakeInstance()->GetDebugOutput()) {
  1482. auto msg =
  1483. cmStrCat(" Returning to ", this->GetCurrentSourceDirectory());
  1484. cmSystemTools::Message(msg);
  1485. }
  1486. }
  1487. void cmMakefile::AddSubDirectory(std::string const& srcPath,
  1488. std::string const& binPath,
  1489. bool excludeFromAll, bool immediate,
  1490. bool system)
  1491. {
  1492. if (this->DeferRunning) {
  1493. this->IssueMessage(
  1494. MessageType::FATAL_ERROR,
  1495. "Subdirectories may not be created during deferred execution.");
  1496. return;
  1497. }
  1498. // Make sure the binary directory is unique.
  1499. if (!this->EnforceUniqueDir(srcPath, binPath)) {
  1500. return;
  1501. }
  1502. cmStateSnapshot newSnapshot =
  1503. this->GetState()->CreateBuildsystemDirectorySnapshot(this->StateSnapshot);
  1504. newSnapshot.GetDirectory().SetCurrentSource(srcPath);
  1505. newSnapshot.GetDirectory().SetCurrentBinary(binPath);
  1506. cmSystemTools::MakeDirectory(binPath);
  1507. auto subMfu =
  1508. cm::make_unique<cmMakefile>(this->GlobalGenerator, newSnapshot);
  1509. auto* subMf = subMfu.get();
  1510. this->GetGlobalGenerator()->AddMakefile(std::move(subMfu));
  1511. if (excludeFromAll) {
  1512. subMf->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
  1513. }
  1514. if (system) {
  1515. subMf->SetProperty("SYSTEM", "TRUE");
  1516. }
  1517. if (immediate) {
  1518. this->ConfigureSubDirectory(subMf);
  1519. } else {
  1520. this->UnConfiguredDirectories.push_back(subMf);
  1521. }
  1522. this->AddInstallGenerator(cm::make_unique<cmInstallSubdirectoryGenerator>(
  1523. subMf, binPath, this->GetBacktrace()));
  1524. }
  1525. std::string const& cmMakefile::GetCurrentSourceDirectory() const
  1526. {
  1527. return this->StateSnapshot.GetDirectory().GetCurrentSource();
  1528. }
  1529. std::string const& cmMakefile::GetCurrentBinaryDirectory() const
  1530. {
  1531. return this->StateSnapshot.GetDirectory().GetCurrentBinary();
  1532. }
  1533. cmTarget* cmMakefile::FindImportedTarget(std::string const& name) const
  1534. {
  1535. auto const i = this->ImportedTargets.find(name);
  1536. if (i != this->ImportedTargets.end()) {
  1537. return i->second;
  1538. }
  1539. return nullptr;
  1540. }
  1541. std::vector<cmTarget*> cmMakefile::GetImportedTargets() const
  1542. {
  1543. std::vector<cmTarget*> tgts;
  1544. tgts.reserve(this->ImportedTargets.size());
  1545. for (auto const& impTarget : this->ImportedTargets) {
  1546. tgts.push_back(impTarget.second);
  1547. }
  1548. return tgts;
  1549. }
  1550. void cmMakefile::AddIncludeDirectories(std::vector<std::string> const& incs,
  1551. bool before)
  1552. {
  1553. if (incs.empty()) {
  1554. return;
  1555. }
  1556. std::string entryString = cmList::to_string(incs);
  1557. if (before) {
  1558. this->StateSnapshot.GetDirectory().PrependIncludeDirectoriesEntry(
  1559. BT<std::string>(entryString, this->Backtrace));
  1560. } else {
  1561. this->StateSnapshot.GetDirectory().AppendIncludeDirectoriesEntry(
  1562. BT<std::string>(entryString, this->Backtrace));
  1563. }
  1564. // Property on each target:
  1565. for (auto& target : this->Targets) {
  1566. cmTarget& t = target.second;
  1567. t.InsertInclude(BT<std::string>(entryString, this->Backtrace), before);
  1568. }
  1569. }
  1570. void cmMakefile::AddSystemIncludeDirectories(std::set<std::string> const& incs)
  1571. {
  1572. if (incs.empty()) {
  1573. return;
  1574. }
  1575. this->SystemIncludeDirectories.insert(incs.begin(), incs.end());
  1576. for (auto& target : this->Targets) {
  1577. cmTarget& t = target.second;
  1578. t.AddSystemIncludeDirectories(incs);
  1579. }
  1580. }
  1581. void cmMakefile::AddDefinition(std::string const& name, cm::string_view value)
  1582. {
  1583. this->StateSnapshot.SetDefinition(name, value);
  1584. #ifndef CMAKE_BOOTSTRAP
  1585. cmVariableWatch* vv = this->GetVariableWatch();
  1586. if (vv) {
  1587. vv->VariableAccessed(name, cmVariableWatch::VARIABLE_MODIFIED_ACCESS,
  1588. value.data(), this);
  1589. }
  1590. #endif
  1591. }
  1592. void cmMakefile::AddDefinitionBool(std::string const& name, bool value)
  1593. {
  1594. this->AddDefinition(name, value ? "ON" : "OFF");
  1595. }
  1596. void cmMakefile::AddCacheDefinition(std::string const& name, cmValue value,
  1597. cmValue doc,
  1598. cmStateEnums::CacheEntryType type,
  1599. bool force)
  1600. {
  1601. cmValue existingValue = this->GetState()->GetInitializedCacheValue(name);
  1602. // must be outside the following if() to keep it alive long enough
  1603. std::string nvalue;
  1604. if (existingValue &&
  1605. (this->GetState()->GetCacheEntryType(name) ==
  1606. cmStateEnums::UNINITIALIZED)) {
  1607. // if this is not a force, then use the value from the cache
  1608. // if it is a force, then use the value being passed in
  1609. if (!force) {
  1610. value = existingValue;
  1611. }
  1612. if (type == cmStateEnums::PATH || type == cmStateEnums::FILEPATH) {
  1613. cmList files(value);
  1614. for (auto& file : files) {
  1615. if (!cmIsOff(file)) {
  1616. file = cmSystemTools::ToNormalizedPathOnDisk(file);
  1617. }
  1618. }
  1619. nvalue = files.to_string();
  1620. value = cmValue{ nvalue };
  1621. this->GetCMakeInstance()->AddCacheEntry(name, value, doc, type);
  1622. value = this->GetState()->GetInitializedCacheValue(name);
  1623. }
  1624. }
  1625. this->GetCMakeInstance()->AddCacheEntry(name, value, doc, type);
  1626. switch (this->GetPolicyStatus(cmPolicies::CMP0126)) {
  1627. case cmPolicies::WARN:
  1628. if (this->PolicyOptionalWarningEnabled("CMAKE_POLICY_WARNING_CMP0126") &&
  1629. this->IsNormalDefinitionSet(name)) {
  1630. this->IssueMessage(
  1631. MessageType::AUTHOR_WARNING,
  1632. cmStrCat(cmPolicies::GetPolicyWarning(cmPolicies::CMP0126),
  1633. "\nFor compatibility with older versions of CMake, normal "
  1634. "variable \"",
  1635. name, "\" will be removed from the current scope."));
  1636. }
  1637. CM_FALLTHROUGH;
  1638. case cmPolicies::OLD:
  1639. // if there was a definition then remove it
  1640. this->StateSnapshot.RemoveDefinition(name);
  1641. break;
  1642. case cmPolicies::NEW:
  1643. break;
  1644. }
  1645. }
  1646. void cmMakefile::MarkVariableAsUsed(std::string const& var)
  1647. {
  1648. this->StateSnapshot.GetDefinition(var);
  1649. }
  1650. bool cmMakefile::VariableInitialized(std::string const& var) const
  1651. {
  1652. return this->StateSnapshot.IsInitialized(var);
  1653. }
  1654. void cmMakefile::MaybeWarnUninitialized(std::string const& variable,
  1655. char const* sourceFilename) const
  1656. {
  1657. // check to see if we need to print a warning
  1658. // if strict mode is on and the variable has
  1659. // not been "cleared"/initialized with a set(foo ) call
  1660. if (this->GetCMakeInstance()->GetWarnUninitialized() &&
  1661. !this->VariableInitialized(variable)) {
  1662. if (this->CheckSystemVars ||
  1663. (sourceFilename && this->IsProjectFile(sourceFilename))) {
  1664. this->IssueMessage(MessageType::AUTHOR_WARNING,
  1665. cmStrCat("uninitialized variable '", variable, '\''));
  1666. }
  1667. }
  1668. }
  1669. void cmMakefile::RemoveDefinition(std::string const& name)
  1670. {
  1671. this->StateSnapshot.RemoveDefinition(name);
  1672. #ifndef CMAKE_BOOTSTRAP
  1673. cmVariableWatch* vv = this->GetVariableWatch();
  1674. if (vv) {
  1675. vv->VariableAccessed(name, cmVariableWatch::VARIABLE_REMOVED_ACCESS,
  1676. nullptr, this);
  1677. }
  1678. #endif
  1679. }
  1680. void cmMakefile::RemoveCacheDefinition(std::string const& name) const
  1681. {
  1682. this->GetState()->RemoveCacheEntry(name);
  1683. }
  1684. void cmMakefile::SetProjectName(std::string const& p)
  1685. {
  1686. this->StateSnapshot.SetProjectName(p);
  1687. }
  1688. void cmMakefile::AddGlobalLinkInformation(cmTarget& target)
  1689. {
  1690. // for these targets do not add anything
  1691. switch (target.GetType()) {
  1692. case cmStateEnums::UTILITY:
  1693. case cmStateEnums::GLOBAL_TARGET:
  1694. case cmStateEnums::INTERFACE_LIBRARY:
  1695. return;
  1696. default:;
  1697. }
  1698. if (cmValue linkLibsProp = this->GetProperty("LINK_LIBRARIES")) {
  1699. cmList linkLibs{ *linkLibsProp };
  1700. for (auto j = linkLibs.begin(); j != linkLibs.end(); ++j) {
  1701. std::string libraryName = *j;
  1702. cmTargetLinkLibraryType libType = GENERAL_LibraryType;
  1703. if (libraryName == "optimized"_s) {
  1704. libType = OPTIMIZED_LibraryType;
  1705. ++j;
  1706. libraryName = *j;
  1707. } else if (libraryName == "debug"_s) {
  1708. libType = DEBUG_LibraryType;
  1709. ++j;
  1710. libraryName = *j;
  1711. }
  1712. // This is equivalent to the target_link_libraries plain signature.
  1713. target.AddLinkLibrary(*this, libraryName, libType);
  1714. target.AppendProperty(
  1715. "INTERFACE_LINK_LIBRARIES",
  1716. target.GetDebugGeneratorExpressions(libraryName, libType));
  1717. }
  1718. }
  1719. }
  1720. void cmMakefile::AddAlias(std::string const& lname, std::string const& tgtName,
  1721. bool globallyVisible)
  1722. {
  1723. this->AliasTargets[lname] = tgtName;
  1724. if (globallyVisible) {
  1725. this->GetGlobalGenerator()->AddAlias(lname, tgtName);
  1726. }
  1727. }
  1728. cmTarget* cmMakefile::AddLibrary(std::string const& lname,
  1729. cmStateEnums::TargetType type,
  1730. std::vector<std::string> const& srcs,
  1731. bool excludeFromAll)
  1732. {
  1733. assert(type == cmStateEnums::STATIC_LIBRARY ||
  1734. type == cmStateEnums::SHARED_LIBRARY ||
  1735. type == cmStateEnums::MODULE_LIBRARY ||
  1736. type == cmStateEnums::OBJECT_LIBRARY ||
  1737. type == cmStateEnums::INTERFACE_LIBRARY);
  1738. cmTarget* target = this->AddNewTarget(type, lname);
  1739. // Clear its dependencies. Otherwise, dependencies might persist
  1740. // over changes in CMakeLists.txt, making the information stale and
  1741. // hence useless.
  1742. target->ClearDependencyInformation(*this);
  1743. if (excludeFromAll) {
  1744. target->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
  1745. }
  1746. target->AddSources(srcs);
  1747. this->AddGlobalLinkInformation(*target);
  1748. return target;
  1749. }
  1750. cmTarget* cmMakefile::AddExecutable(std::string const& exeName,
  1751. std::vector<std::string> const& srcs,
  1752. bool excludeFromAll)
  1753. {
  1754. cmTarget* target = this->AddNewTarget(cmStateEnums::EXECUTABLE, exeName);
  1755. if (excludeFromAll) {
  1756. target->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
  1757. }
  1758. target->AddSources(srcs);
  1759. this->AddGlobalLinkInformation(*target);
  1760. return target;
  1761. }
  1762. cmTarget* cmMakefile::AddNewTarget(cmStateEnums::TargetType type,
  1763. std::string const& name)
  1764. {
  1765. return &this->CreateNewTarget(name, type).first;
  1766. }
  1767. cmTarget* cmMakefile::AddSynthesizedTarget(cmStateEnums::TargetType type,
  1768. std::string const& name)
  1769. {
  1770. return &this
  1771. ->CreateNewTarget(name, type, cmTarget::PerConfig::Yes,
  1772. cmTarget::Visibility::Generated)
  1773. .first;
  1774. }
  1775. std::pair<cmTarget&, bool> cmMakefile::CreateNewTarget(
  1776. std::string const& name, cmStateEnums::TargetType type,
  1777. cmTarget::PerConfig perConfig, cmTarget::Visibility vis)
  1778. {
  1779. auto ib =
  1780. this->Targets.emplace(name, cmTarget(name, type, vis, this, perConfig));
  1781. auto it = ib.first;
  1782. if (!ib.second) {
  1783. return std::make_pair(std::ref(it->second), false);
  1784. }
  1785. this->OrderedTargets.push_back(&it->second);
  1786. this->GetGlobalGenerator()->IndexTarget(&it->second);
  1787. this->GetStateSnapshot().GetDirectory().AddNormalTargetName(name);
  1788. return std::make_pair(std::ref(it->second), true);
  1789. }
  1790. cmTarget* cmMakefile::AddNewUtilityTarget(std::string const& utilityName,
  1791. bool excludeFromAll)
  1792. {
  1793. cmTarget* target = this->AddNewTarget(cmStateEnums::UTILITY, utilityName);
  1794. if (excludeFromAll) {
  1795. target->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
  1796. }
  1797. return target;
  1798. }
  1799. namespace {
  1800. }
  1801. #if !defined(CMAKE_BOOTSTRAP)
  1802. cmSourceGroup* cmMakefile::GetSourceGroup(
  1803. std::vector<std::string> const& name) const
  1804. {
  1805. cmSourceGroup* sg = nullptr;
  1806. // first look for source group starting with the same as the one we want
  1807. for (cmSourceGroup const& srcGroup : this->SourceGroups) {
  1808. std::string const& sgName = srcGroup.GetName();
  1809. if (sgName == name[0]) {
  1810. sg = const_cast<cmSourceGroup*>(&srcGroup);
  1811. break;
  1812. }
  1813. }
  1814. if (sg) {
  1815. // iterate through its children to find match source group
  1816. for (unsigned int i = 1; i < name.size(); ++i) {
  1817. sg = sg->LookupChild(name[i]);
  1818. if (!sg) {
  1819. break;
  1820. }
  1821. }
  1822. }
  1823. return sg;
  1824. }
  1825. void cmMakefile::AddSourceGroup(std::string const& name, char const* regex)
  1826. {
  1827. std::vector<std::string> nameVector;
  1828. nameVector.push_back(name);
  1829. this->AddSourceGroup(nameVector, regex);
  1830. }
  1831. void cmMakefile::AddSourceGroup(std::vector<std::string> const& name,
  1832. char const* regex)
  1833. {
  1834. cmSourceGroup* sg = nullptr;
  1835. std::vector<std::string> currentName;
  1836. int i = 0;
  1837. int const lastElement = static_cast<int>(name.size() - 1);
  1838. for (i = lastElement; i >= 0; --i) {
  1839. currentName.assign(name.begin(), name.begin() + i + 1);
  1840. sg = this->GetSourceGroup(currentName);
  1841. if (sg) {
  1842. break;
  1843. }
  1844. }
  1845. // i now contains the index of the last found component
  1846. if (i == lastElement) {
  1847. // group already exists, replace its regular expression
  1848. if (regex && sg) {
  1849. // We only want to set the regular expression. If there are already
  1850. // source files in the group, we don't want to remove them.
  1851. sg->SetGroupRegex(regex);
  1852. }
  1853. return;
  1854. }
  1855. if (i == -1) {
  1856. // group does not exist nor belong to any existing group
  1857. // add its first component
  1858. this->SourceGroups.emplace_back(name[0], regex);
  1859. sg = this->GetSourceGroup(currentName);
  1860. i = 0; // last component found
  1861. }
  1862. if (!sg) {
  1863. cmSystemTools::Error("Could not create source group ");
  1864. return;
  1865. }
  1866. // build the whole source group path
  1867. for (++i; i <= lastElement; ++i) {
  1868. sg->AddChild(cmSourceGroup(name[i], nullptr, sg->GetFullName().c_str()));
  1869. sg = sg->LookupChild(name[i]);
  1870. }
  1871. sg->SetGroupRegex(regex);
  1872. }
  1873. cmSourceGroup* cmMakefile::GetOrCreateSourceGroup(
  1874. std::vector<std::string> const& folders)
  1875. {
  1876. cmSourceGroup* sg = this->GetSourceGroup(folders);
  1877. if (!sg) {
  1878. this->AddSourceGroup(folders);
  1879. sg = this->GetSourceGroup(folders);
  1880. }
  1881. return sg;
  1882. }
  1883. cmSourceGroup* cmMakefile::GetOrCreateSourceGroup(std::string const& name)
  1884. {
  1885. auto p = this->GetDefinition("SOURCE_GROUP_DELIMITER");
  1886. return this->GetOrCreateSourceGroup(
  1887. cmTokenize(name, p ? cm::string_view(*p) : R"(\/)"_s));
  1888. }
  1889. /**
  1890. * Find a source group whose regular expression matches the filename
  1891. * part of the given source name. Search backward through the list of
  1892. * source groups, and take the first matching group found. This way
  1893. * non-inherited SOURCE_GROUP commands will have precedence over
  1894. * inherited ones.
  1895. */
  1896. cmSourceGroup* cmMakefile::FindSourceGroup(
  1897. std::string const& source, std::vector<cmSourceGroup>& groups) const
  1898. {
  1899. // First search for a group that lists the file explicitly.
  1900. for (auto sg = groups.rbegin(); sg != groups.rend(); ++sg) {
  1901. cmSourceGroup* result = sg->MatchChildrenFiles(source);
  1902. if (result) {
  1903. return result;
  1904. }
  1905. }
  1906. // Now search for a group whose regex matches the file.
  1907. for (auto sg = groups.rbegin(); sg != groups.rend(); ++sg) {
  1908. cmSourceGroup* result = sg->MatchChildrenRegex(source);
  1909. if (result) {
  1910. return result;
  1911. }
  1912. }
  1913. // Shouldn't get here, but just in case, return the default group.
  1914. return groups.data();
  1915. }
  1916. #endif
  1917. bool cmMakefile::IsOn(std::string const& name) const
  1918. {
  1919. return this->GetDefinition(name).IsOn();
  1920. }
  1921. bool cmMakefile::IsSet(std::string const& name) const
  1922. {
  1923. cmValue value = this->GetDefinition(name);
  1924. if (!value) {
  1925. return false;
  1926. }
  1927. if (value->empty()) {
  1928. return false;
  1929. }
  1930. if (cmIsNOTFOUND(*value)) {
  1931. return false;
  1932. }
  1933. return true;
  1934. }
  1935. bool cmMakefile::PlatformIs32Bit() const
  1936. {
  1937. if (cmValue plat_abi = this->GetDefinition("CMAKE_INTERNAL_PLATFORM_ABI")) {
  1938. if (*plat_abi == "ELF X32"_s) {
  1939. return false;
  1940. }
  1941. }
  1942. if (cmValue sizeof_dptr = this->GetDefinition("CMAKE_SIZEOF_VOID_P")) {
  1943. return atoi(sizeof_dptr->c_str()) == 4;
  1944. }
  1945. return false;
  1946. }
  1947. bool cmMakefile::PlatformIs64Bit() const
  1948. {
  1949. if (cmValue sizeof_dptr = this->GetDefinition("CMAKE_SIZEOF_VOID_P")) {
  1950. return atoi(sizeof_dptr->c_str()) == 8;
  1951. }
  1952. return false;
  1953. }
  1954. bool cmMakefile::PlatformIsx32() const
  1955. {
  1956. if (cmValue plat_abi = this->GetDefinition("CMAKE_INTERNAL_PLATFORM_ABI")) {
  1957. if (*plat_abi == "ELF X32"_s) {
  1958. return true;
  1959. }
  1960. }
  1961. return false;
  1962. }
  1963. cmMakefile::AppleSDK cmMakefile::GetAppleSDKType() const
  1964. {
  1965. std::string sdkRoot;
  1966. sdkRoot = this->GetSafeDefinition("CMAKE_OSX_SYSROOT");
  1967. sdkRoot = cmSystemTools::LowerCase(sdkRoot);
  1968. struct
  1969. {
  1970. std::string name;
  1971. AppleSDK sdk;
  1972. } const sdkDatabase[]{
  1973. { "appletvos", AppleSDK::AppleTVOS },
  1974. { "appletvsimulator", AppleSDK::AppleTVSimulator },
  1975. { "iphoneos", AppleSDK::IPhoneOS },
  1976. { "iphonesimulator", AppleSDK::IPhoneSimulator },
  1977. { "watchos", AppleSDK::WatchOS },
  1978. { "watchsimulator", AppleSDK::WatchSimulator },
  1979. { "xros", AppleSDK::XROS },
  1980. { "xrsimulator", AppleSDK::XRSimulator },
  1981. };
  1982. for (auto const& entry : sdkDatabase) {
  1983. if (cmHasPrefix(sdkRoot, entry.name) ||
  1984. sdkRoot.find(cmStrCat('/', entry.name)) != std::string::npos) {
  1985. return entry.sdk;
  1986. }
  1987. }
  1988. return AppleSDK::MacOS;
  1989. }
  1990. bool cmMakefile::PlatformIsAppleEmbedded() const
  1991. {
  1992. return this->GetAppleSDKType() != AppleSDK::MacOS;
  1993. }
  1994. bool cmMakefile::PlatformIsAppleSimulator() const
  1995. {
  1996. return std::set<AppleSDK>{
  1997. AppleSDK::AppleTVSimulator,
  1998. AppleSDK::IPhoneSimulator,
  1999. AppleSDK::WatchSimulator,
  2000. AppleSDK::XRSimulator,
  2001. }
  2002. .count(this->GetAppleSDKType());
  2003. }
  2004. bool cmMakefile::PlatformIsAppleCatalyst() const
  2005. {
  2006. std::string systemName;
  2007. systemName = this->GetSafeDefinition("CMAKE_SYSTEM_NAME");
  2008. systemName = cmSystemTools::LowerCase(systemName);
  2009. return systemName == "ios" && this->GetAppleSDKType() == AppleSDK::MacOS;
  2010. }
  2011. bool cmMakefile::PlatformSupportsAppleTextStubs() const
  2012. {
  2013. return this->IsOn("APPLE") && this->IsSet("CMAKE_TAPI");
  2014. }
  2015. char const* cmMakefile::GetSONameFlag(std::string const& language) const
  2016. {
  2017. std::string name = "CMAKE_SHARED_LIBRARY_SONAME";
  2018. if (!language.empty()) {
  2019. name += "_";
  2020. name += language;
  2021. }
  2022. name += "_FLAG";
  2023. return this->GetDefinition(name).GetCStr();
  2024. }
  2025. bool cmMakefile::CanIWriteThisFile(std::string const& fileName) const
  2026. {
  2027. if (!this->IsOn("CMAKE_DISABLE_SOURCE_CHANGES")) {
  2028. return true;
  2029. }
  2030. // If we are doing an in-source build, then the test will always fail
  2031. if (cmSystemTools::SameFile(this->GetHomeDirectory(),
  2032. this->GetHomeOutputDirectory())) {
  2033. return !this->IsOn("CMAKE_DISABLE_IN_SOURCE_BUILD");
  2034. }
  2035. return !cmSystemTools::IsSubDirectory(fileName, this->GetHomeDirectory()) ||
  2036. cmSystemTools::IsSubDirectory(fileName, this->GetHomeOutputDirectory()) ||
  2037. cmSystemTools::SameFile(fileName, this->GetHomeOutputDirectory());
  2038. }
  2039. std::string const& cmMakefile::GetRequiredDefinition(
  2040. std::string const& name) const
  2041. {
  2042. static std::string const empty;
  2043. cmValue def = this->GetDefinition(name);
  2044. if (!def) {
  2045. cmSystemTools::Error("Error required internal CMake variable not "
  2046. "set, cmake may not be built correctly.\n"
  2047. "Missing variable is:\n" +
  2048. name);
  2049. return empty;
  2050. }
  2051. return *def;
  2052. }
  2053. bool cmMakefile::IsDefinitionSet(std::string const& name) const
  2054. {
  2055. cmValue def = this->StateSnapshot.GetDefinition(name);
  2056. if (!def) {
  2057. def = this->GetState()->GetInitializedCacheValue(name);
  2058. }
  2059. #ifndef CMAKE_BOOTSTRAP
  2060. if (cmVariableWatch* vv = this->GetVariableWatch()) {
  2061. if (!def) {
  2062. vv->VariableAccessed(
  2063. name, cmVariableWatch::UNKNOWN_VARIABLE_DEFINED_ACCESS, nullptr, this);
  2064. }
  2065. }
  2066. #endif
  2067. return def != nullptr;
  2068. }
  2069. bool cmMakefile::IsNormalDefinitionSet(std::string const& name) const
  2070. {
  2071. cmValue def = this->StateSnapshot.GetDefinition(name);
  2072. #ifndef CMAKE_BOOTSTRAP
  2073. if (cmVariableWatch* vv = this->GetVariableWatch()) {
  2074. if (!def) {
  2075. vv->VariableAccessed(
  2076. name, cmVariableWatch::UNKNOWN_VARIABLE_DEFINED_ACCESS, nullptr, this);
  2077. }
  2078. }
  2079. #endif
  2080. return def != nullptr;
  2081. }
  2082. cmValue cmMakefile::GetDefinition(std::string const& name) const
  2083. {
  2084. cmValue def = this->StateSnapshot.GetDefinition(name);
  2085. if (!def) {
  2086. def = this->GetState()->GetInitializedCacheValue(name);
  2087. }
  2088. #ifndef CMAKE_BOOTSTRAP
  2089. cmVariableWatch* vv = this->GetVariableWatch();
  2090. if (vv) {
  2091. bool const watch_function_executed =
  2092. vv->VariableAccessed(name,
  2093. def ? cmVariableWatch::VARIABLE_READ_ACCESS
  2094. : cmVariableWatch::UNKNOWN_VARIABLE_READ_ACCESS,
  2095. def.GetCStr(), this);
  2096. if (watch_function_executed) {
  2097. // A callback was executed and may have caused re-allocation of the
  2098. // variable storage. Look it up again for now.
  2099. // FIXME: Refactor variable storage to avoid this problem.
  2100. def = this->StateSnapshot.GetDefinition(name);
  2101. if (!def) {
  2102. def = this->GetState()->GetInitializedCacheValue(name);
  2103. }
  2104. }
  2105. }
  2106. #endif
  2107. return def;
  2108. }
  2109. std::string const& cmMakefile::GetSafeDefinition(std::string const& name) const
  2110. {
  2111. return this->GetDefinition(name);
  2112. }
  2113. std::vector<std::string> cmMakefile::GetDefinitions() const
  2114. {
  2115. std::vector<std::string> res = this->StateSnapshot.ClosureKeys();
  2116. cm::append(res, this->GetState()->GetCacheEntryKeys());
  2117. std::sort(res.begin(), res.end());
  2118. return res;
  2119. }
  2120. std::string const& cmMakefile::ExpandVariablesInString(
  2121. std::string& source) const
  2122. {
  2123. return this->ExpandVariablesInString(source, false, false);
  2124. }
  2125. std::string const& cmMakefile::ExpandVariablesInString(
  2126. std::string& source, bool escapeQuotes, bool noEscapes, bool atOnly,
  2127. char const* filename, long line, bool removeEmpty, bool replaceAt) const
  2128. {
  2129. // Sanity check the @ONLY mode.
  2130. if (atOnly && (!noEscapes || !removeEmpty)) {
  2131. // This case should never be called. At-only is for
  2132. // configure-file/string which always does no escapes.
  2133. this->IssueMessage(MessageType::INTERNAL_ERROR,
  2134. "ExpandVariablesInString @ONLY called "
  2135. "on something with escapes.");
  2136. return source;
  2137. }
  2138. std::string errorstr;
  2139. MessageType mtype = this->ExpandVariablesInStringImpl(
  2140. errorstr, source, escapeQuotes, noEscapes, atOnly, filename, line,
  2141. replaceAt);
  2142. if (mtype != MessageType::LOG) {
  2143. if (mtype == MessageType::FATAL_ERROR) {
  2144. cmSystemTools::SetFatalErrorOccurred();
  2145. }
  2146. this->IssueMessage(mtype, errorstr);
  2147. }
  2148. return source;
  2149. }
  2150. enum t_domain
  2151. {
  2152. NORMAL,
  2153. ENVIRONMENT,
  2154. CACHE
  2155. };
  2156. struct t_lookup
  2157. {
  2158. t_domain domain = NORMAL;
  2159. size_t loc = 0;
  2160. };
  2161. bool cmMakefile::IsProjectFile(char const* filename) const
  2162. {
  2163. return cmSystemTools::IsSubDirectory(filename, this->GetHomeDirectory()) ||
  2164. (cmSystemTools::IsSubDirectory(filename, this->GetHomeOutputDirectory()) &&
  2165. !cmSystemTools::IsSubDirectory(filename, "/CMakeFiles"));
  2166. }
  2167. size_t cmMakefile::GetRecursionDepthLimit() const
  2168. {
  2169. size_t depth = CMake_DEFAULT_RECURSION_LIMIT;
  2170. if (cmValue depthStr =
  2171. this->GetDefinition("CMAKE_MAXIMUM_RECURSION_DEPTH")) {
  2172. unsigned long depthUL;
  2173. if (cmStrToULong(depthStr.GetCStr(), &depthUL)) {
  2174. depth = depthUL;
  2175. }
  2176. } else if (cm::optional<std::string> depthEnv =
  2177. cmSystemTools::GetEnvVar("CMAKE_MAXIMUM_RECURSION_DEPTH")) {
  2178. unsigned long depthUL;
  2179. if (cmStrToULong(*depthEnv, &depthUL)) {
  2180. depth = depthUL;
  2181. }
  2182. }
  2183. return depth;
  2184. }
  2185. size_t cmMakefile::GetRecursionDepth() const
  2186. {
  2187. return this->RecursionDepth;
  2188. }
  2189. void cmMakefile::SetRecursionDepth(size_t recursionDepth)
  2190. {
  2191. this->RecursionDepth = recursionDepth;
  2192. }
  2193. std::string cmMakefile::NewDeferId() const
  2194. {
  2195. return this->GetGlobalGenerator()->NewDeferId();
  2196. }
  2197. bool cmMakefile::DeferCall(std::string id, std::string file,
  2198. cmListFileFunction lff)
  2199. {
  2200. if (!this->Defer) {
  2201. return false;
  2202. }
  2203. this->Defer->Commands.emplace_back(
  2204. DeferCommand{ std::move(id), std::move(file), std::move(lff) });
  2205. return true;
  2206. }
  2207. bool cmMakefile::DeferCancelCall(std::string const& id)
  2208. {
  2209. if (!this->Defer) {
  2210. return false;
  2211. }
  2212. for (DeferCommand& dc : this->Defer->Commands) {
  2213. if (dc.Id == id) {
  2214. dc.Id.clear();
  2215. }
  2216. }
  2217. return true;
  2218. }
  2219. cm::optional<std::string> cmMakefile::DeferGetCallIds() const
  2220. {
  2221. cm::optional<std::string> ids;
  2222. if (this->Defer) {
  2223. ids = cmList::to_string(
  2224. cmMakeRange(this->Defer->Commands)
  2225. .filter([](DeferCommand const& dc) -> bool { return !dc.Id.empty(); })
  2226. .transform(
  2227. [](DeferCommand const& dc) -> std::string const& { return dc.Id; }));
  2228. }
  2229. return ids;
  2230. }
  2231. cm::optional<std::string> cmMakefile::DeferGetCall(std::string const& id) const
  2232. {
  2233. cm::optional<std::string> call;
  2234. if (this->Defer) {
  2235. std::string tmp;
  2236. for (DeferCommand const& dc : this->Defer->Commands) {
  2237. if (dc.Id == id) {
  2238. tmp = dc.Command.OriginalName();
  2239. for (cmListFileArgument const& arg : dc.Command.Arguments()) {
  2240. tmp = cmStrCat(tmp, ';', arg.Value);
  2241. }
  2242. break;
  2243. }
  2244. }
  2245. call = std::move(tmp);
  2246. }
  2247. return call;
  2248. }
  2249. MessageType cmMakefile::ExpandVariablesInStringImpl(
  2250. std::string& errorstr, std::string& source, bool escapeQuotes,
  2251. bool noEscapes, bool atOnly, char const* filename, long line,
  2252. bool replaceAt) const
  2253. {
  2254. // This method replaces ${VAR} and @VAR@ where VAR is looked up
  2255. // with GetDefinition(), if not found in the map, nothing is expanded.
  2256. // It also supports the $ENV{VAR} syntax where VAR is looked up in
  2257. // the current environment variables.
  2258. char const* in = source.c_str();
  2259. char const* last = in;
  2260. std::string result;
  2261. result.reserve(source.size());
  2262. std::vector<t_lookup> openstack;
  2263. bool error = false;
  2264. bool done = false;
  2265. MessageType mtype = MessageType::LOG;
  2266. cmState* state = this->GetCMakeInstance()->GetState();
  2267. static std::string const lineVar = "CMAKE_CURRENT_LIST_LINE";
  2268. do {
  2269. char inc = *in;
  2270. switch (inc) {
  2271. case '}':
  2272. if (!openstack.empty()) {
  2273. t_lookup var = openstack.back();
  2274. openstack.pop_back();
  2275. result.append(last, in - last);
  2276. std::string const& lookup = result.substr(var.loc);
  2277. cmValue value = nullptr;
  2278. std::string varresult;
  2279. std::string svalue;
  2280. switch (var.domain) {
  2281. case NORMAL:
  2282. if (filename && lookup == lineVar) {
  2283. cmListFileContext const& top = this->Backtrace.Top();
  2284. if (top.DeferId) {
  2285. varresult = cmStrCat("DEFERRED:"_s, *top.DeferId);
  2286. } else {
  2287. varresult = std::to_string(line);
  2288. }
  2289. } else {
  2290. value = this->GetDefinition(lookup);
  2291. }
  2292. break;
  2293. case ENVIRONMENT:
  2294. if (cmSystemTools::GetEnv(lookup, svalue)) {
  2295. value = cmValue(svalue);
  2296. }
  2297. break;
  2298. case CACHE:
  2299. value = state->GetCacheEntryValue(lookup);
  2300. break;
  2301. }
  2302. // Get the string we're meant to append to.
  2303. if (value) {
  2304. if (escapeQuotes) {
  2305. varresult = cmEscapeQuotes(*value);
  2306. } else {
  2307. varresult = *value;
  2308. }
  2309. } else {
  2310. this->MaybeWarnUninitialized(lookup, filename);
  2311. }
  2312. result.replace(var.loc, result.size() - var.loc, varresult);
  2313. // Start looking from here on out.
  2314. last = in + 1;
  2315. }
  2316. break;
  2317. case '$':
  2318. if (!atOnly) {
  2319. t_lookup lookup;
  2320. char const* next = in + 1;
  2321. char const* start = nullptr;
  2322. char nextc = *next;
  2323. if (nextc == '{') {
  2324. // Looking for a variable.
  2325. start = in + 2;
  2326. lookup.domain = NORMAL;
  2327. } else if (nextc == '<') {
  2328. } else if (!nextc) {
  2329. result.append(last, next - last);
  2330. last = next;
  2331. } else if (cmHasLiteralPrefix(next, "ENV{")) {
  2332. // Looking for an environment variable.
  2333. start = in + 5;
  2334. lookup.domain = ENVIRONMENT;
  2335. } else if (cmHasLiteralPrefix(next, "CACHE{")) {
  2336. // Looking for a cache variable.
  2337. start = in + 7;
  2338. lookup.domain = CACHE;
  2339. } else {
  2340. if (this->cmNamedCurly.find(next)) {
  2341. errorstr = "Syntax $" +
  2342. std::string(next, this->cmNamedCurly.end()) +
  2343. "{} is not supported. Only ${}, $ENV{}, "
  2344. "and $CACHE{} are allowed.";
  2345. mtype = MessageType::FATAL_ERROR;
  2346. error = true;
  2347. }
  2348. }
  2349. if (start) {
  2350. result.append(last, in - last);
  2351. last = start;
  2352. in = start - 1;
  2353. lookup.loc = result.size();
  2354. openstack.push_back(lookup);
  2355. }
  2356. break;
  2357. }
  2358. CM_FALLTHROUGH;
  2359. case '\\':
  2360. if (!noEscapes) {
  2361. char const* next = in + 1;
  2362. char nextc = *next;
  2363. if (nextc == 't') {
  2364. result.append(last, in - last);
  2365. result.push_back('\t');
  2366. last = next + 1;
  2367. } else if (nextc == 'n') {
  2368. result.append(last, in - last);
  2369. result.push_back('\n');
  2370. last = next + 1;
  2371. } else if (nextc == 'r') {
  2372. result.append(last, in - last);
  2373. result.push_back('\r');
  2374. last = next + 1;
  2375. } else if (nextc == ';' && openstack.empty()) {
  2376. // Handled in ExpandListArgument; pass the backslash literally.
  2377. } else if (isalnum(nextc) || nextc == '\0') {
  2378. errorstr += "Invalid character escape '\\";
  2379. if (nextc) {
  2380. errorstr += nextc;
  2381. errorstr += "'.";
  2382. } else {
  2383. errorstr += "' (at end of input).";
  2384. }
  2385. error = true;
  2386. } else {
  2387. // Take what we've found so far, skipping the escape character.
  2388. result.append(last, in - last);
  2389. // Start tracking from the next character.
  2390. last = in + 1;
  2391. }
  2392. // Skip the next character since it was escaped, but don't read past
  2393. // the end of the string.
  2394. if (*last) {
  2395. ++in;
  2396. }
  2397. }
  2398. break;
  2399. case '\n':
  2400. // Onto the next line.
  2401. ++line;
  2402. break;
  2403. case '\0':
  2404. done = true;
  2405. break;
  2406. case '@':
  2407. if (replaceAt) {
  2408. char const* nextAt = strchr(in + 1, '@');
  2409. if (nextAt && nextAt != in + 1 &&
  2410. nextAt ==
  2411. in + 1 +
  2412. std::strspn(in + 1,
  2413. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  2414. "abcdefghijklmnopqrstuvwxyz"
  2415. "0123456789/_.+-")) {
  2416. std::string variable(in + 1, nextAt - in - 1);
  2417. std::string varresult;
  2418. if (filename && variable == lineVar) {
  2419. varresult = std::to_string(line);
  2420. } else {
  2421. cmValue def = this->GetDefinition(variable);
  2422. if (def) {
  2423. varresult = *def;
  2424. } else {
  2425. this->MaybeWarnUninitialized(variable, filename);
  2426. }
  2427. }
  2428. if (escapeQuotes) {
  2429. varresult = cmEscapeQuotes(varresult);
  2430. }
  2431. // Skip over the variable.
  2432. result.append(last, in - last);
  2433. result.append(varresult);
  2434. in = nextAt;
  2435. last = in + 1;
  2436. break;
  2437. }
  2438. }
  2439. // Failed to find a valid @ expansion; treat it as literal.
  2440. CM_FALLTHROUGH;
  2441. default: {
  2442. if (!openstack.empty() &&
  2443. !(isalnum(inc) || inc == '_' || inc == '/' || inc == '.' ||
  2444. inc == '+' || inc == '-')) {
  2445. errorstr += cmStrCat("Invalid character ('", inc);
  2446. result.append(last, in - last);
  2447. errorstr += cmStrCat("') in a variable name: '",
  2448. result.substr(openstack.back().loc), '\'');
  2449. mtype = MessageType::FATAL_ERROR;
  2450. error = true;
  2451. }
  2452. break;
  2453. }
  2454. }
  2455. // Look at the next character.
  2456. } while (!error && !done && *++in);
  2457. // Check for open variable references yet.
  2458. if (!error && !openstack.empty()) {
  2459. errorstr += "There is an unterminated variable reference.";
  2460. error = true;
  2461. }
  2462. if (error) {
  2463. std::string e = "Syntax error in cmake code ";
  2464. if (filename) {
  2465. // This filename and line number may be more specific than the
  2466. // command context because one command invocation can have
  2467. // arguments on multiple lines.
  2468. e += cmStrCat("at\n ", filename, ':', line, '\n');
  2469. }
  2470. errorstr = cmStrCat(e, "when parsing string\n ", source, '\n', errorstr);
  2471. mtype = MessageType::FATAL_ERROR;
  2472. } else {
  2473. // Append the rest of the unchanged part of the string.
  2474. result.append(last);
  2475. source = result;
  2476. }
  2477. return mtype;
  2478. }
  2479. void cmMakefile::RemoveVariablesInString(std::string& source,
  2480. bool atOnly) const
  2481. {
  2482. if (!atOnly) {
  2483. cmsys::RegularExpression var("(\\${[A-Za-z_0-9]*})");
  2484. while (var.find(source)) {
  2485. source.erase(var.start(), var.end() - var.start());
  2486. }
  2487. }
  2488. if (!atOnly) {
  2489. cmsys::RegularExpression varb("(\\$ENV{[A-Za-z_0-9]*})");
  2490. while (varb.find(source)) {
  2491. source.erase(varb.start(), varb.end() - varb.start());
  2492. }
  2493. }
  2494. cmsys::RegularExpression var2("(@[A-Za-z_0-9]*@)");
  2495. while (var2.find(source)) {
  2496. source.erase(var2.start(), var2.end() - var2.start());
  2497. }
  2498. }
  2499. void cmMakefile::InitCMAKE_CONFIGURATION_TYPES(std::string const& genDefault)
  2500. {
  2501. if (this->GetDefinition("CMAKE_CONFIGURATION_TYPES")) {
  2502. return;
  2503. }
  2504. std::string initConfigs;
  2505. if (this->GetCMakeInstance()->GetIsInTryCompile() ||
  2506. !cmSystemTools::GetEnv("CMAKE_CONFIGURATION_TYPES", initConfigs)) {
  2507. initConfigs = genDefault;
  2508. }
  2509. this->AddCacheDefinition(
  2510. "CMAKE_CONFIGURATION_TYPES", initConfigs,
  2511. "Semicolon separated list of supported configuration types, "
  2512. "only supports Debug, Release, MinSizeRel, and RelWithDebInfo, "
  2513. "anything else will be ignored.",
  2514. cmStateEnums::STRING);
  2515. }
  2516. std::string cmMakefile::GetDefaultConfiguration() const
  2517. {
  2518. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  2519. return std::string{};
  2520. }
  2521. return this->GetSafeDefinition("CMAKE_BUILD_TYPE");
  2522. }
  2523. std::vector<std::string> cmMakefile::GetGeneratorConfigs(
  2524. GeneratorConfigQuery mode) const
  2525. {
  2526. cmList configs;
  2527. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  2528. configs.assign(this->GetDefinition("CMAKE_CONFIGURATION_TYPES"));
  2529. } else if (mode != cmMakefile::OnlyMultiConfig) {
  2530. std::string const& buildType = this->GetSafeDefinition("CMAKE_BUILD_TYPE");
  2531. if (!buildType.empty()) {
  2532. configs.emplace_back(buildType);
  2533. }
  2534. }
  2535. if (mode == cmMakefile::IncludeEmptyConfig && configs.empty()) {
  2536. configs.emplace_back();
  2537. }
  2538. return std::move(configs.data());
  2539. }
  2540. bool cmMakefile::IsFunctionBlocked(cmListFileFunction const& lff,
  2541. cmExecutionStatus& status)
  2542. {
  2543. // if there are no blockers get out of here
  2544. if (this->FunctionBlockers.empty()) {
  2545. return false;
  2546. }
  2547. return this->FunctionBlockers.top()->IsFunctionBlocked(lff, status);
  2548. }
  2549. void cmMakefile::PushFunctionBlockerBarrier()
  2550. {
  2551. this->FunctionBlockerBarriers.push_back(this->FunctionBlockers.size());
  2552. }
  2553. void cmMakefile::PopFunctionBlockerBarrier(bool reportError)
  2554. {
  2555. // Remove any extra entries pushed on the barrier.
  2556. FunctionBlockersType::size_type barrier =
  2557. this->FunctionBlockerBarriers.back();
  2558. while (this->FunctionBlockers.size() > barrier) {
  2559. std::unique_ptr<cmFunctionBlocker> fb(
  2560. std::move(this->FunctionBlockers.top()));
  2561. this->FunctionBlockers.pop();
  2562. if (reportError) {
  2563. // Report the context in which the unclosed block was opened.
  2564. cmListFileContext const& lfc = fb->GetStartingContext();
  2565. std::ostringstream e;
  2566. /* clang-format off */
  2567. e << "A logical block opening on the line\n"
  2568. " " << lfc << "\n"
  2569. "is not closed.";
  2570. /* clang-format on */
  2571. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  2572. reportError = false;
  2573. }
  2574. }
  2575. // Remove the barrier.
  2576. this->FunctionBlockerBarriers.pop_back();
  2577. }
  2578. void cmMakefile::PushLoopBlock()
  2579. {
  2580. assert(!this->LoopBlockCounter.empty());
  2581. this->LoopBlockCounter.top()++;
  2582. }
  2583. void cmMakefile::PopLoopBlock()
  2584. {
  2585. assert(!this->LoopBlockCounter.empty());
  2586. assert(this->LoopBlockCounter.top() > 0);
  2587. this->LoopBlockCounter.top()--;
  2588. }
  2589. void cmMakefile::PushLoopBlockBarrier()
  2590. {
  2591. this->LoopBlockCounter.push(0);
  2592. }
  2593. void cmMakefile::PopLoopBlockBarrier()
  2594. {
  2595. assert(!this->LoopBlockCounter.empty());
  2596. assert(this->LoopBlockCounter.top() == 0);
  2597. this->LoopBlockCounter.pop();
  2598. }
  2599. bool cmMakefile::IsLoopBlock() const
  2600. {
  2601. assert(!this->LoopBlockCounter.empty());
  2602. return !this->LoopBlockCounter.empty() && this->LoopBlockCounter.top() > 0;
  2603. }
  2604. bool cmMakefile::ExpandArguments(std::vector<cmListFileArgument> const& inArgs,
  2605. std::vector<std::string>& outArgs) const
  2606. {
  2607. std::string const& filename = this->GetBacktrace().Top().FilePath;
  2608. std::string value;
  2609. outArgs.reserve(inArgs.size());
  2610. for (cmListFileArgument const& i : inArgs) {
  2611. // No expansion in a bracket argument.
  2612. if (i.Delim == cmListFileArgument::Bracket) {
  2613. outArgs.push_back(i.Value);
  2614. continue;
  2615. }
  2616. // Expand the variables in the argument.
  2617. value = i.Value;
  2618. this->ExpandVariablesInString(value, false, false, false, filename.c_str(),
  2619. i.Line, false, false);
  2620. // If the argument is quoted, it should be one argument.
  2621. // Otherwise, it may be a list of arguments.
  2622. if (i.Delim == cmListFileArgument::Quoted) {
  2623. outArgs.push_back(value);
  2624. } else {
  2625. cmExpandList(value, outArgs);
  2626. }
  2627. }
  2628. return !cmSystemTools::GetFatalErrorOccurred();
  2629. }
  2630. bool cmMakefile::ExpandArguments(
  2631. std::vector<cmListFileArgument> const& inArgs,
  2632. std::vector<cmExpandedCommandArgument>& outArgs) const
  2633. {
  2634. std::string const& filename = this->GetBacktrace().Top().FilePath;
  2635. std::string value;
  2636. outArgs.reserve(inArgs.size());
  2637. for (cmListFileArgument const& i : inArgs) {
  2638. // No expansion in a bracket argument.
  2639. if (i.Delim == cmListFileArgument::Bracket) {
  2640. outArgs.emplace_back(i.Value, true);
  2641. continue;
  2642. }
  2643. // Expand the variables in the argument.
  2644. value = i.Value;
  2645. this->ExpandVariablesInString(value, false, false, false, filename.c_str(),
  2646. i.Line, false, false);
  2647. // If the argument is quoted, it should be one argument.
  2648. // Otherwise, it may be a list of arguments.
  2649. if (i.Delim == cmListFileArgument::Quoted) {
  2650. outArgs.emplace_back(value, true);
  2651. } else {
  2652. cmList stringArgs{ value };
  2653. for (std::string const& stringArg : stringArgs) {
  2654. outArgs.emplace_back(stringArg, false);
  2655. }
  2656. }
  2657. }
  2658. return !cmSystemTools::GetFatalErrorOccurred();
  2659. }
  2660. void cmMakefile::AddFunctionBlocker(std::unique_ptr<cmFunctionBlocker> fb)
  2661. {
  2662. if (!this->ExecutionStatusStack.empty()) {
  2663. // Record the context in which the blocker is created.
  2664. fb->SetStartingContext(this->Backtrace.Top());
  2665. }
  2666. this->FunctionBlockers.push(std::move(fb));
  2667. }
  2668. std::unique_ptr<cmFunctionBlocker> cmMakefile::RemoveFunctionBlocker()
  2669. {
  2670. assert(!this->FunctionBlockers.empty());
  2671. assert(this->FunctionBlockerBarriers.empty() ||
  2672. this->FunctionBlockers.size() > this->FunctionBlockerBarriers.back());
  2673. auto b = std::move(this->FunctionBlockers.top());
  2674. this->FunctionBlockers.pop();
  2675. return b;
  2676. }
  2677. std::string const& cmMakefile::GetHomeDirectory() const
  2678. {
  2679. return this->GetCMakeInstance()->GetHomeDirectory();
  2680. }
  2681. std::string const& cmMakefile::GetHomeOutputDirectory() const
  2682. {
  2683. return this->GetCMakeInstance()->GetHomeOutputDirectory();
  2684. }
  2685. void cmMakefile::SetScriptModeFile(std::string const& scriptfile)
  2686. {
  2687. this->AddDefinition("CMAKE_SCRIPT_MODE_FILE", scriptfile);
  2688. }
  2689. void cmMakefile::SetArgcArgv(std::vector<std::string> const& args)
  2690. {
  2691. this->AddDefinition("CMAKE_ARGC", std::to_string(args.size()));
  2692. for (auto i = 0u; i < args.size(); ++i) {
  2693. this->AddDefinition(cmStrCat("CMAKE_ARGV", i), args[i]);
  2694. }
  2695. }
  2696. cmSourceFile* cmMakefile::GetSource(std::string const& sourceName,
  2697. cmSourceFileLocationKind kind) const
  2698. {
  2699. // First check "Known" paths (avoids the creation of cmSourceFileLocation)
  2700. if (kind == cmSourceFileLocationKind::Known) {
  2701. auto sfsi = this->KnownFileSearchIndex.find(sourceName);
  2702. if (sfsi != this->KnownFileSearchIndex.end()) {
  2703. return sfsi->second;
  2704. }
  2705. }
  2706. cmSourceFileLocation sfl(this, sourceName, kind);
  2707. auto name = this->GetCMakeInstance()->StripExtension(sfl.GetName());
  2708. #if defined(_WIN32) || defined(__APPLE__)
  2709. name = cmSystemTools::LowerCase(name);
  2710. #endif
  2711. auto sfsi = this->SourceFileSearchIndex.find(name);
  2712. if (sfsi != this->SourceFileSearchIndex.end()) {
  2713. for (auto* sf : sfsi->second) {
  2714. if (sf->Matches(sfl)) {
  2715. return sf;
  2716. }
  2717. }
  2718. }
  2719. return nullptr;
  2720. }
  2721. cmSourceFile* cmMakefile::CreateSource(std::string const& sourceName,
  2722. bool generated,
  2723. cmSourceFileLocationKind kind)
  2724. {
  2725. auto sf = cm::make_unique<cmSourceFile>(this, sourceName, generated, kind);
  2726. auto name =
  2727. this->GetCMakeInstance()->StripExtension(sf->GetLocation().GetName());
  2728. #if defined(_WIN32) || defined(__APPLE__)
  2729. name = cmSystemTools::LowerCase(name);
  2730. #endif
  2731. this->SourceFileSearchIndex[name].push_back(sf.get());
  2732. // for "Known" paths add direct lookup (used for faster lookup in GetSource)
  2733. if (kind == cmSourceFileLocationKind::Known) {
  2734. this->KnownFileSearchIndex[sourceName] = sf.get();
  2735. }
  2736. this->SourceFiles.push_back(std::move(sf));
  2737. return this->SourceFiles.back().get();
  2738. }
  2739. cmSourceFile* cmMakefile::GetOrCreateSource(std::string const& sourceName,
  2740. bool generated,
  2741. cmSourceFileLocationKind kind)
  2742. {
  2743. if (cmSourceFile* esf = this->GetSource(sourceName, kind)) {
  2744. return esf;
  2745. }
  2746. return this->CreateSource(sourceName, generated, kind);
  2747. }
  2748. cmSourceFile* cmMakefile::GetOrCreateGeneratedSource(
  2749. std::string const& sourceName)
  2750. {
  2751. cmSourceFile* sf =
  2752. this->GetOrCreateSource(sourceName, true, cmSourceFileLocationKind::Known);
  2753. sf->MarkAsGenerated(); // In case we did not create the source file.
  2754. return sf;
  2755. }
  2756. void cmMakefile::CreateGeneratedOutputs(
  2757. std::vector<std::string> const& outputs)
  2758. {
  2759. for (std::string const& o : outputs) {
  2760. if (cmGeneratorExpression::Find(o) == std::string::npos) {
  2761. this->GetOrCreateGeneratedSource(o);
  2762. }
  2763. }
  2764. }
  2765. void cmMakefile::AddTargetObject(std::string const& tgtName,
  2766. std::string const& objFile)
  2767. {
  2768. cmSourceFile* sf =
  2769. this->GetOrCreateSource(objFile, true, cmSourceFileLocationKind::Known);
  2770. sf->SetSpecialSourceType(cmSourceFile::SpecialSourceType::Object);
  2771. sf->SetObjectLibrary(tgtName);
  2772. sf->SetProperty("EXTERNAL_OBJECT", "1");
  2773. // TODO: Compute a language for this object based on the associated source
  2774. // file that compiles to it. Needs a policy as it likely affects link
  2775. // language selection if done unconditionally.
  2776. #if !defined(CMAKE_BOOTSTRAP)
  2777. this->SourceGroups[this->ObjectLibrariesSourceGroupIndex].AddGroupFile(
  2778. sf->ResolveFullPath());
  2779. #endif
  2780. }
  2781. void cmMakefile::EnableLanguage(std::vector<std::string> const& languages,
  2782. bool optional)
  2783. {
  2784. if (this->DeferRunning) {
  2785. this->IssueMessage(
  2786. MessageType::FATAL_ERROR,
  2787. "Languages may not be enabled during deferred execution.");
  2788. return;
  2789. }
  2790. if (char const* def = this->GetGlobalGenerator()->GetCMakeCFGIntDir()) {
  2791. this->AddDefinition("CMAKE_CFG_INTDIR", def);
  2792. }
  2793. std::vector<std::string> unique_languages;
  2794. {
  2795. std::vector<std::string> duplicate_languages;
  2796. for (std::string const& language : languages) {
  2797. if (!cm::contains(unique_languages, language)) {
  2798. unique_languages.push_back(language);
  2799. } else if (!cm::contains(duplicate_languages, language)) {
  2800. duplicate_languages.push_back(language);
  2801. }
  2802. }
  2803. if (!duplicate_languages.empty()) {
  2804. auto quantity = duplicate_languages.size() == 1 ? " has"_s : "s have"_s;
  2805. this->IssueMessage(
  2806. MessageType::AUTHOR_WARNING,
  2807. cmStrCat("Languages to be enabled may not be specified more "
  2808. "than once at the same time. The following language",
  2809. quantity, " been specified multiple times: ",
  2810. cmJoin(duplicate_languages, ", ")));
  2811. }
  2812. }
  2813. // If RC is explicitly listed we need to do it after other languages.
  2814. // On some platforms we enable RC implicitly while enabling others.
  2815. // Do not let that look like recursive enable_language(RC).
  2816. std::vector<std::string> languages_without_RC;
  2817. std::vector<std::string> languages_for_RC;
  2818. languages_without_RC.reserve(unique_languages.size());
  2819. for (std::string const& language : unique_languages) {
  2820. if (language == "RC"_s) {
  2821. languages_for_RC.push_back(language);
  2822. } else {
  2823. languages_without_RC.push_back(language);
  2824. }
  2825. }
  2826. if (!languages_without_RC.empty()) {
  2827. this->GetGlobalGenerator()->EnableLanguage(languages_without_RC, this,
  2828. optional);
  2829. }
  2830. if (!languages_for_RC.empty()) {
  2831. this->GetGlobalGenerator()->EnableLanguage(languages_for_RC, this,
  2832. optional);
  2833. }
  2834. }
  2835. int cmMakefile::TryCompile(std::string const& srcdir,
  2836. std::string const& bindir,
  2837. std::string const& projectName,
  2838. std::string const& targetName, bool fast, int jobs,
  2839. std::vector<std::string> const* cmakeArgs,
  2840. std::string& output)
  2841. {
  2842. this->IsSourceFileTryCompile = fast;
  2843. // does the binary directory exist ? If not create it...
  2844. if (!cmSystemTools::FileIsDirectory(bindir)) {
  2845. cmSystemTools::MakeDirectory(bindir);
  2846. }
  2847. // change to the tests directory and run cmake
  2848. // use the cmake object instead of calling cmake
  2849. cmWorkingDirectory workdir(bindir);
  2850. if (workdir.Failed()) {
  2851. this->IssueMessage(MessageType::FATAL_ERROR, workdir.GetError());
  2852. cmSystemTools::SetFatalErrorOccurred();
  2853. this->IsSourceFileTryCompile = false;
  2854. return 1;
  2855. }
  2856. // make sure the same generator is used
  2857. // use this program as the cmake to be run, it should not
  2858. // be run that way but the cmake object requires a valid path
  2859. cmake cm(cmake::RoleProject, cmState::Project,
  2860. cmState::ProjectKind::TryCompile);
  2861. auto gg = cm.CreateGlobalGenerator(this->GetGlobalGenerator()->GetName());
  2862. if (!gg) {
  2863. this->IssueMessage(MessageType::INTERNAL_ERROR,
  2864. "Global generator '" +
  2865. this->GetGlobalGenerator()->GetName() +
  2866. "' could not be created.");
  2867. cmSystemTools::SetFatalErrorOccurred();
  2868. this->IsSourceFileTryCompile = false;
  2869. return 1;
  2870. }
  2871. gg->RecursionDepth = this->RecursionDepth;
  2872. cm.SetGlobalGenerator(std::move(gg));
  2873. // copy trace state
  2874. cm.SetTraceRedirect(this->GetCMakeInstance());
  2875. // do a configure
  2876. cm.SetHomeDirectory(srcdir);
  2877. cm.SetHomeOutputDirectory(bindir);
  2878. cm.SetGeneratorInstance(this->GetSafeDefinition("CMAKE_GENERATOR_INSTANCE"));
  2879. cm.SetGeneratorPlatform(this->GetSafeDefinition("CMAKE_GENERATOR_PLATFORM"));
  2880. cm.SetGeneratorToolset(this->GetSafeDefinition("CMAKE_GENERATOR_TOOLSET"));
  2881. cm.LoadCache();
  2882. if (!cm.GetGlobalGenerator()->IsMultiConfig()) {
  2883. if (cmValue config =
  2884. this->GetDefinition("CMAKE_TRY_COMPILE_CONFIGURATION")) {
  2885. // Tell the single-configuration generator which one to use.
  2886. // Add this before the user-provided CMake arguments in case
  2887. // one of the arguments is -DCMAKE_BUILD_TYPE=...
  2888. cm.AddCacheEntry("CMAKE_BUILD_TYPE", config, "Build configuration",
  2889. cmStateEnums::STRING);
  2890. }
  2891. }
  2892. cmValue recursionDepth =
  2893. this->GetDefinition("CMAKE_MAXIMUM_RECURSION_DEPTH");
  2894. if (recursionDepth) {
  2895. cm.AddCacheEntry("CMAKE_MAXIMUM_RECURSION_DEPTH", recursionDepth,
  2896. "Maximum recursion depth", cmStateEnums::STRING);
  2897. }
  2898. // if cmake args were provided then pass them in
  2899. if (cmakeArgs) {
  2900. // FIXME: Workaround to ignore unused CLI variables in try-compile.
  2901. //
  2902. // Ideally we should use SetArgs for options like --no-warn-unused-cli.
  2903. // However, there is a subtle problem when certain arguments are passed to
  2904. // a macro wrapping around try_compile or try_run that does not escape
  2905. // semicolons in its parameters but just passes ${ARGV} or ${ARGN}. In
  2906. // this case a list argument like "-DVAR=a;b" gets split into multiple
  2907. // cmake arguments "-DVAR=a" and "b". Currently SetCacheArgs ignores
  2908. // argument "b" and uses just "-DVAR=a", leading to a subtle bug in that
  2909. // the try_compile or try_run does not get the proper value of VAR. If we
  2910. // call SetArgs here then it would treat "b" as the source directory and
  2911. // cause an error such as "The source directory .../CMakeFiles/CMakeTmp/b
  2912. // does not exist", thus breaking the try_compile or try_run completely.
  2913. //
  2914. // Strictly speaking the bug is in the wrapper macro because the CMake
  2915. // language has always flattened nested lists and the macro should escape
  2916. // the semicolons in its arguments before forwarding them. However, this
  2917. // bug is so subtle that projects typically work anyway, usually because
  2918. // the value VAR=a is sufficient for the try_compile or try_run to get the
  2919. // correct result. Calling SetArgs here would break such projects that
  2920. // previously built. Instead we work around the issue by never reporting
  2921. // unused arguments and ignoring options such as --no-warn-unused-cli.
  2922. cm.SetWarnUnusedCli(false);
  2923. // cm.SetArgs(*cmakeArgs, true);
  2924. cm.SetCacheArgs(*cmakeArgs);
  2925. }
  2926. // to save time we pass the EnableLanguage info directly
  2927. cm.GetGlobalGenerator()->EnableLanguagesFromGenerator(
  2928. this->GetGlobalGenerator(), this);
  2929. if (this->IsOn("CMAKE_SUPPRESS_DEVELOPER_WARNINGS")) {
  2930. cm.AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_WARNINGS", "TRUE", "",
  2931. cmStateEnums::INTERNAL);
  2932. } else {
  2933. cm.AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_WARNINGS", "FALSE", "",
  2934. cmStateEnums::INTERNAL);
  2935. }
  2936. if (cm.Configure() != 0) {
  2937. this->IssueMessage(MessageType::FATAL_ERROR,
  2938. "Failed to configure test project build system.");
  2939. cmSystemTools::SetFatalErrorOccurred();
  2940. this->IsSourceFileTryCompile = false;
  2941. return 1;
  2942. }
  2943. if (cm.Generate() != 0) {
  2944. this->IssueMessage(MessageType::FATAL_ERROR,
  2945. "Failed to generate test project build system.");
  2946. cmSystemTools::SetFatalErrorOccurred();
  2947. this->IsSourceFileTryCompile = false;
  2948. return 1;
  2949. }
  2950. // finally call the generator to actually build the resulting project
  2951. int ret = this->GetGlobalGenerator()->TryCompile(
  2952. jobs, srcdir, bindir, projectName, targetName, fast, output, this);
  2953. this->IsSourceFileTryCompile = false;
  2954. return ret;
  2955. }
  2956. bool cmMakefile::GetIsSourceFileTryCompile() const
  2957. {
  2958. return this->IsSourceFileTryCompile;
  2959. }
  2960. cmake* cmMakefile::GetCMakeInstance() const
  2961. {
  2962. return this->GlobalGenerator->GetCMakeInstance();
  2963. }
  2964. cmMessenger* cmMakefile::GetMessenger() const
  2965. {
  2966. return this->GetCMakeInstance()->GetMessenger();
  2967. }
  2968. cmGlobalGenerator* cmMakefile::GetGlobalGenerator() const
  2969. {
  2970. return this->GlobalGenerator;
  2971. }
  2972. #ifndef CMAKE_BOOTSTRAP
  2973. cmVariableWatch* cmMakefile::GetVariableWatch() const
  2974. {
  2975. if (this->GetCMakeInstance() &&
  2976. this->GetCMakeInstance()->GetVariableWatch()) {
  2977. return this->GetCMakeInstance()->GetVariableWatch();
  2978. }
  2979. return nullptr;
  2980. }
  2981. #endif
  2982. cmState* cmMakefile::GetState() const
  2983. {
  2984. return this->GetCMakeInstance()->GetState();
  2985. }
  2986. void cmMakefile::DisplayStatus(std::string const& message, float s) const
  2987. {
  2988. cmake* cm = this->GetCMakeInstance();
  2989. if (cm->GetWorkingMode() == cmake::FIND_PACKAGE_MODE) {
  2990. // don't output any STATUS message in FIND_PACKAGE_MODE, since they will
  2991. // directly be fed to the compiler, which will be confused.
  2992. return;
  2993. }
  2994. cm->UpdateProgress(message, s);
  2995. #ifdef CMake_ENABLE_DEBUGGER
  2996. if (cm->GetDebugAdapter()) {
  2997. cm->GetDebugAdapter()->OnMessageOutput(MessageType::MESSAGE, message);
  2998. }
  2999. #endif
  3000. }
  3001. std::string cmMakefile::GetModulesFile(cm::string_view filename, bool& system,
  3002. bool debug,
  3003. std::string& debugBuffer) const
  3004. {
  3005. std::string result;
  3006. std::string moduleInCMakeRoot;
  3007. std::string moduleInCMakeModulePath;
  3008. // Always search in CMAKE_MODULE_PATH:
  3009. cmValue cmakeModulePath = this->GetDefinition("CMAKE_MODULE_PATH");
  3010. if (cmakeModulePath) {
  3011. cmList modulePath{ *cmakeModulePath };
  3012. // Look through the possible module directories.
  3013. for (std::string itempl : modulePath) {
  3014. cmSystemTools::ConvertToUnixSlashes(itempl);
  3015. itempl += "/";
  3016. itempl += filename;
  3017. if (cmSystemTools::FileExists(itempl)) {
  3018. moduleInCMakeModulePath = itempl;
  3019. break;
  3020. }
  3021. if (debug) {
  3022. debugBuffer = cmStrCat(debugBuffer, " ", itempl, '\n');
  3023. }
  3024. }
  3025. }
  3026. // Always search in the standard modules location.
  3027. moduleInCMakeRoot =
  3028. cmStrCat(cmSystemTools::GetCMakeRoot(), "/Modules/", filename);
  3029. cmSystemTools::ConvertToUnixSlashes(moduleInCMakeRoot);
  3030. if (!cmSystemTools::FileExists(moduleInCMakeRoot)) {
  3031. if (debug) {
  3032. debugBuffer = cmStrCat(debugBuffer, " ", moduleInCMakeRoot, '\n');
  3033. }
  3034. moduleInCMakeRoot.clear();
  3035. }
  3036. // Normally, prefer the files found in CMAKE_MODULE_PATH. Only when the file
  3037. // from which we are being called is located itself in CMAKE_ROOT, then
  3038. // prefer results from CMAKE_ROOT depending on the policy setting.
  3039. if (!moduleInCMakeModulePath.empty() && !moduleInCMakeRoot.empty()) {
  3040. cmValue currentFile = this->GetDefinition(kCMAKE_CURRENT_LIST_FILE);
  3041. std::string mods = cmStrCat(cmSystemTools::GetCMakeRoot(), "/Modules/");
  3042. if (currentFile && cmSystemTools::IsSubDirectory(*currentFile, mods)) {
  3043. system = true;
  3044. result = moduleInCMakeRoot;
  3045. } else {
  3046. system = false;
  3047. result = moduleInCMakeModulePath;
  3048. }
  3049. } else if (!moduleInCMakeModulePath.empty()) {
  3050. system = false;
  3051. result = moduleInCMakeModulePath;
  3052. } else {
  3053. system = true;
  3054. result = moduleInCMakeRoot;
  3055. }
  3056. return result;
  3057. }
  3058. void cmMakefile::ConfigureString(std::string const& input, std::string& output,
  3059. bool atOnly, bool escapeQuotes) const
  3060. {
  3061. // Split input to handle one line at a time.
  3062. std::string::const_iterator lineStart = input.begin();
  3063. while (lineStart != input.end()) {
  3064. // Find the end of this line.
  3065. std::string::const_iterator lineEnd = lineStart;
  3066. while (lineEnd != input.end() && *lineEnd != '\n') {
  3067. ++lineEnd;
  3068. }
  3069. // Copy the line.
  3070. std::string line(lineStart, lineEnd);
  3071. // Skip the newline character.
  3072. bool haveNewline = (lineEnd != input.end());
  3073. if (haveNewline) {
  3074. ++lineEnd;
  3075. }
  3076. // Replace #cmakedefine instances.
  3077. if (this->cmDefineRegex.find(line)) {
  3078. cmValue def = this->GetDefinition(this->cmDefineRegex.match(2));
  3079. if (!def.IsOff()) {
  3080. std::string const indentation = this->cmDefineRegex.match(1);
  3081. cmSystemTools::ReplaceString(line,
  3082. cmStrCat('#', indentation, "cmakedefine"),
  3083. cmStrCat('#', indentation, "define"));
  3084. output += line;
  3085. } else {
  3086. output += "/* #undef ";
  3087. output += this->cmDefineRegex.match(2);
  3088. output += " */";
  3089. }
  3090. } else if (this->cmDefine01Regex.find(line)) {
  3091. std::string const indentation = this->cmDefine01Regex.match(1);
  3092. cmValue def = this->GetDefinition(this->cmDefine01Regex.match(2));
  3093. cmSystemTools::ReplaceString(line,
  3094. cmStrCat('#', indentation, "cmakedefine01"),
  3095. cmStrCat('#', indentation, "define"));
  3096. output += line;
  3097. if (!def.IsOff()) {
  3098. output += " 1";
  3099. } else {
  3100. output += " 0";
  3101. }
  3102. } else {
  3103. output += line;
  3104. }
  3105. if (haveNewline) {
  3106. output += '\n';
  3107. }
  3108. // Move to the next line.
  3109. lineStart = lineEnd;
  3110. }
  3111. // Perform variable replacements.
  3112. char const* filename = nullptr;
  3113. long lineNumber = -1;
  3114. if (!this->Backtrace.Empty()) {
  3115. auto const& currentTrace = this->Backtrace.Top();
  3116. filename = currentTrace.FilePath.c_str();
  3117. lineNumber = currentTrace.Line;
  3118. }
  3119. this->ExpandVariablesInString(output, escapeQuotes, true, atOnly, filename,
  3120. lineNumber, true, true);
  3121. }
  3122. int cmMakefile::ConfigureFile(std::string const& infile,
  3123. std::string const& outfile, bool copyonly,
  3124. bool atOnly, bool escapeQuotes,
  3125. mode_t permissions, cmNewLineStyle newLine)
  3126. {
  3127. int res = 1;
  3128. if (!this->CanIWriteThisFile(outfile)) {
  3129. cmSystemTools::Error(cmStrCat("Attempt to write file: ", outfile,
  3130. " into a source directory."));
  3131. return 0;
  3132. }
  3133. if (!cmSystemTools::FileExists(infile)) {
  3134. cmSystemTools::Error(cmStrCat("File ", infile, " does not exist."));
  3135. return 0;
  3136. }
  3137. std::string soutfile = outfile;
  3138. std::string const& sinfile = infile;
  3139. this->AddCMakeDependFile(sinfile);
  3140. cmSystemTools::ConvertToUnixSlashes(soutfile);
  3141. // Re-generate if non-temporary outputs are missing.
  3142. // when we finalize the configuration we will remove all
  3143. // output files that now don't exist.
  3144. this->AddCMakeOutputFile(soutfile);
  3145. if (permissions == 0) {
  3146. cmSystemTools::GetPermissions(sinfile, permissions);
  3147. }
  3148. std::string::size_type pos = soutfile.rfind('/');
  3149. if (pos != std::string::npos) {
  3150. std::string path = soutfile.substr(0, pos);
  3151. cmSystemTools::MakeDirectory(path);
  3152. }
  3153. if (copyonly) {
  3154. auto const copy_status =
  3155. cmSystemTools::CopyFileIfDifferent(sinfile, soutfile);
  3156. if (!copy_status) {
  3157. this->IssueMessage(
  3158. MessageType::FATAL_ERROR,
  3159. cmStrCat("Fail to copy ",
  3160. copy_status.Path == cmsys::SystemTools::CopyStatus::SourcePath
  3161. ? "source"
  3162. : "destination",
  3163. "file: ", copy_status.GetString()));
  3164. res = 0;
  3165. } else {
  3166. auto const status = cmSystemTools::SetPermissions(soutfile, permissions);
  3167. if (!status) {
  3168. this->IssueMessage(MessageType::FATAL_ERROR, status.GetString());
  3169. res = 0;
  3170. }
  3171. }
  3172. return res;
  3173. }
  3174. std::string newLineCharacters;
  3175. std::ios::openmode omode = std::ios::out | std::ios::trunc;
  3176. if (newLine.IsValid()) {
  3177. newLineCharacters = newLine.GetCharacters();
  3178. omode |= std::ios::binary;
  3179. } else {
  3180. newLineCharacters = "\n";
  3181. }
  3182. std::string tempOutputFile = cmStrCat(soutfile, ".tmp");
  3183. cmsys::ofstream fout(tempOutputFile.c_str(), omode);
  3184. if (!fout) {
  3185. cmSystemTools::Error("Could not open file for write in copy operation " +
  3186. tempOutputFile);
  3187. cmSystemTools::ReportLastSystemError("");
  3188. return 0;
  3189. }
  3190. cmsys::ifstream fin(sinfile.c_str());
  3191. if (!fin) {
  3192. cmSystemTools::Error("Could not open file for read in copy operation " +
  3193. sinfile);
  3194. return 0;
  3195. }
  3196. cmsys::FStream::BOM bom = cmsys::FStream::ReadBOM(fin);
  3197. if (bom != cmsys::FStream::BOM_None && bom != cmsys::FStream::BOM_UTF8) {
  3198. this->IssueMessage(
  3199. MessageType::FATAL_ERROR,
  3200. cmStrCat("File starts with a Byte-Order-Mark that is not UTF-8:\n ",
  3201. sinfile));
  3202. return 0;
  3203. }
  3204. // rewind to copy BOM to output file
  3205. fin.seekg(0);
  3206. // now copy input to output and expand variables in the
  3207. // input file at the same time
  3208. std::string inLine;
  3209. std::string outLine;
  3210. while (cmSystemTools::GetLineFromStream(fin, inLine)) {
  3211. outLine.clear();
  3212. this->ConfigureString(inLine, outLine, atOnly, escapeQuotes);
  3213. fout << outLine << newLineCharacters;
  3214. }
  3215. // close the files before attempting to copy
  3216. fin.close();
  3217. fout.close();
  3218. auto status = cmSystemTools::MoveFileIfDifferent(tempOutputFile, soutfile);
  3219. if (!status) {
  3220. this->IssueMessage(MessageType::FATAL_ERROR, status.GetString());
  3221. res = 0;
  3222. } else {
  3223. status = cmSystemTools::SetPermissions(soutfile, permissions);
  3224. if (!status) {
  3225. this->IssueMessage(MessageType::FATAL_ERROR, status.GetString());
  3226. res = 0;
  3227. }
  3228. }
  3229. return res;
  3230. }
  3231. void cmMakefile::SetProperty(std::string const& prop, cmValue value)
  3232. {
  3233. this->StateSnapshot.GetDirectory().SetProperty(prop, value, this->Backtrace);
  3234. }
  3235. void cmMakefile::AppendProperty(std::string const& prop,
  3236. std::string const& value, bool asString)
  3237. {
  3238. this->StateSnapshot.GetDirectory().AppendProperty(prop, value, asString,
  3239. this->Backtrace);
  3240. }
  3241. cmValue cmMakefile::GetProperty(std::string const& prop) const
  3242. {
  3243. // Check for computed properties.
  3244. static std::string output;
  3245. if (prop == "TESTS"_s) {
  3246. std::vector<std::string> keys;
  3247. // get list of keys
  3248. auto const* t = this;
  3249. std::transform(
  3250. t->Tests.begin(), t->Tests.end(), std::back_inserter(keys),
  3251. [](decltype(t->Tests)::value_type const& pair) { return pair.first; });
  3252. output = cmList::to_string(keys);
  3253. return cmValue(output);
  3254. }
  3255. return this->StateSnapshot.GetDirectory().GetProperty(prop);
  3256. }
  3257. cmValue cmMakefile::GetProperty(std::string const& prop, bool chain) const
  3258. {
  3259. return this->StateSnapshot.GetDirectory().GetProperty(prop, chain);
  3260. }
  3261. bool cmMakefile::GetPropertyAsBool(std::string const& prop) const
  3262. {
  3263. return this->GetProperty(prop).IsOn();
  3264. }
  3265. std::vector<std::string> cmMakefile::GetPropertyKeys() const
  3266. {
  3267. return this->StateSnapshot.GetDirectory().GetPropertyKeys();
  3268. }
  3269. cmTarget* cmMakefile::FindLocalNonAliasTarget(std::string const& name) const
  3270. {
  3271. auto i = this->Targets.find(name);
  3272. if (i != this->Targets.end()) {
  3273. return &i->second;
  3274. }
  3275. return nullptr;
  3276. }
  3277. cmTest* cmMakefile::CreateTest(std::string const& testName)
  3278. {
  3279. cmTest* test = this->GetTest(testName);
  3280. if (test) {
  3281. return test;
  3282. }
  3283. auto newTest = cm::make_unique<cmTest>(this);
  3284. test = newTest.get();
  3285. newTest->SetName(testName);
  3286. this->Tests[testName] = std::move(newTest);
  3287. return test;
  3288. }
  3289. cmTest* cmMakefile::GetTest(std::string const& testName) const
  3290. {
  3291. auto mi = this->Tests.find(testName);
  3292. if (mi != this->Tests.end()) {
  3293. return mi->second.get();
  3294. }
  3295. return nullptr;
  3296. }
  3297. void cmMakefile::GetTests(std::string const& config,
  3298. std::vector<cmTest*>& tests) const
  3299. {
  3300. for (auto const& generator : this->GetTestGenerators()) {
  3301. if (generator->TestsForConfig(config)) {
  3302. tests.push_back(generator->GetTest());
  3303. }
  3304. }
  3305. }
  3306. void cmMakefile::AddCMakeDependFilesFromUser()
  3307. {
  3308. cmList deps;
  3309. if (cmValue deps_str = this->GetProperty("CMAKE_CONFIGURE_DEPENDS")) {
  3310. deps.assign(*deps_str);
  3311. }
  3312. for (auto const& dep : deps) {
  3313. if (cmSystemTools::FileIsFullPath(dep)) {
  3314. this->AddCMakeDependFile(dep);
  3315. } else {
  3316. std::string f = cmStrCat(this->GetCurrentSourceDirectory(), '/', dep);
  3317. this->AddCMakeDependFile(f);
  3318. }
  3319. }
  3320. }
  3321. std::string cmMakefile::FormatListFileStack() const
  3322. {
  3323. std::vector<std::string> listFiles;
  3324. for (auto snp = this->StateSnapshot; snp.IsValid();
  3325. snp = snp.GetCallStackParent()) {
  3326. listFiles.emplace_back(snp.GetExecutionListFile());
  3327. }
  3328. if (listFiles.empty()) {
  3329. return {};
  3330. }
  3331. auto depth = 1;
  3332. std::transform(listFiles.begin(), listFiles.end(), listFiles.begin(),
  3333. [&depth](std::string const& file) {
  3334. return cmStrCat('[', depth++, "]\t", file);
  3335. });
  3336. return cmJoinStrings(cmMakeRange(listFiles.rbegin(), listFiles.rend()),
  3337. "\n "_s, {});
  3338. }
  3339. void cmMakefile::PushScope()
  3340. {
  3341. this->StateSnapshot =
  3342. this->GetState()->CreateVariableScopeSnapshot(this->StateSnapshot);
  3343. this->PushLoopBlockBarrier();
  3344. #if !defined(CMAKE_BOOTSTRAP)
  3345. this->GetGlobalGenerator()->GetFileLockPool().PushFunctionScope();
  3346. #endif
  3347. }
  3348. void cmMakefile::PopScope()
  3349. {
  3350. #if !defined(CMAKE_BOOTSTRAP)
  3351. this->GetGlobalGenerator()->GetFileLockPool().PopFunctionScope();
  3352. #endif
  3353. this->PopLoopBlockBarrier();
  3354. this->PopSnapshot();
  3355. }
  3356. void cmMakefile::RaiseScope(std::string const& var, char const* varDef)
  3357. {
  3358. if (var.empty()) {
  3359. return;
  3360. }
  3361. if (!this->StateSnapshot.RaiseScope(var, varDef)) {
  3362. this->IssueMessage(
  3363. MessageType::AUTHOR_WARNING,
  3364. cmStrCat("Cannot set \"", var, "\": current scope has no parent."));
  3365. return;
  3366. }
  3367. #ifndef CMAKE_BOOTSTRAP
  3368. cmVariableWatch* vv = this->GetVariableWatch();
  3369. if (vv) {
  3370. vv->VariableAccessed(var, cmVariableWatch::VARIABLE_MODIFIED_ACCESS,
  3371. varDef, this);
  3372. }
  3373. #endif
  3374. }
  3375. void cmMakefile::RaiseScope(std::vector<std::string> const& variables)
  3376. {
  3377. for (auto const& varName : variables) {
  3378. if (this->IsNormalDefinitionSet(varName)) {
  3379. this->RaiseScope(varName, this->GetDefinition(varName));
  3380. } else {
  3381. // unset variable in parent scope
  3382. this->RaiseScope(varName, nullptr);
  3383. }
  3384. }
  3385. }
  3386. cmTarget* cmMakefile::AddImportedTarget(std::string const& name,
  3387. cmStateEnums::TargetType type,
  3388. bool global)
  3389. {
  3390. // Create the target.
  3391. std::unique_ptr<cmTarget> target(
  3392. new cmTarget(name, type,
  3393. global ? cmTarget::Visibility::ImportedGlobally
  3394. : cmTarget::Visibility::Imported,
  3395. this, cmTarget::PerConfig::Yes));
  3396. // Add to the set of available imported targets.
  3397. this->ImportedTargets[name] = target.get();
  3398. this->GetGlobalGenerator()->IndexTarget(target.get());
  3399. this->GetStateSnapshot().GetDirectory().AddImportedTargetName(name);
  3400. // Transfer ownership to this cmMakefile object.
  3401. this->ImportedTargetsOwned.push_back(std::move(target));
  3402. return this->ImportedTargetsOwned.back().get();
  3403. }
  3404. cmTarget* cmMakefile::AddForeignTarget(std::string const& origin,
  3405. std::string const& name)
  3406. {
  3407. auto foreign_name = cmStrCat("@foreign_", origin, "::", name);
  3408. std::unique_ptr<cmTarget> target(new cmTarget(
  3409. foreign_name, cmStateEnums::TargetType::INTERFACE_LIBRARY,
  3410. cmTarget::Visibility::Foreign, this, cmTarget::PerConfig::Yes));
  3411. this->ImportedTargets[foreign_name] = target.get();
  3412. this->GetGlobalGenerator()->IndexTarget(target.get());
  3413. this->GetStateSnapshot().GetDirectory().AddImportedTargetName(foreign_name);
  3414. this->ImportedTargetsOwned.push_back(std::move(target));
  3415. return this->ImportedTargetsOwned.back().get();
  3416. }
  3417. cmTarget* cmMakefile::FindTargetToUse(
  3418. std::string const& name, cmStateEnums::TargetDomainSet domains) const
  3419. {
  3420. // Look for an imported target. These take priority because they
  3421. // are more local in scope and do not have to be globally unique.
  3422. auto targetName = name;
  3423. if (domains.contains(cmStateEnums::TargetDomain::ALIAS)) {
  3424. // Look for local alias targets.
  3425. auto alias = this->AliasTargets.find(name);
  3426. if (alias != this->AliasTargets.end()) {
  3427. targetName = alias->second;
  3428. }
  3429. }
  3430. auto const imported = this->ImportedTargets.find(targetName);
  3431. bool const useForeign =
  3432. domains.contains(cmStateEnums::TargetDomain::FOREIGN);
  3433. bool const useNative = domains.contains(cmStateEnums::TargetDomain::NATIVE);
  3434. if (imported != this->ImportedTargets.end()) {
  3435. if (imported->second->IsForeign() ? useForeign : useNative) {
  3436. return imported->second;
  3437. }
  3438. }
  3439. // Look for a target built in this directory.
  3440. if (cmTarget* t = this->FindLocalNonAliasTarget(name)) {
  3441. if (t->IsForeign() ? useForeign : useNative) {
  3442. return t;
  3443. }
  3444. }
  3445. // Look for a target built in this project.
  3446. return this->GetGlobalGenerator()->FindTarget(name, domains);
  3447. }
  3448. bool cmMakefile::IsAlias(std::string const& name) const
  3449. {
  3450. if (cm::contains(this->AliasTargets, name)) {
  3451. return true;
  3452. }
  3453. return this->GetGlobalGenerator()->IsAlias(name);
  3454. }
  3455. bool cmMakefile::EnforceUniqueName(std::string const& name, std::string& msg,
  3456. bool isCustom) const
  3457. {
  3458. if (this->IsAlias(name)) {
  3459. msg = cmStrCat("cannot create target \"", name,
  3460. "\" because an alias with the same name already exists.");
  3461. return false;
  3462. }
  3463. if (cmTarget* existing = this->FindTargetToUse(name)) {
  3464. // The name given conflicts with an existing target. Produce an
  3465. // error in a compatible way.
  3466. if (existing->IsImported()) {
  3467. // Imported targets were not supported in previous versions.
  3468. // This is new code, so we can make it an error.
  3469. msg = cmStrCat(
  3470. "cannot create target \"", name,
  3471. "\" because an imported target with the same name already exists.");
  3472. return false;
  3473. }
  3474. // The conflict is with a non-imported target.
  3475. // Allow this if the user has requested support.
  3476. cmake* cm = this->GetCMakeInstance();
  3477. if (isCustom && existing->GetType() == cmStateEnums::UTILITY &&
  3478. this != existing->GetMakefile() &&
  3479. cm->GetState()->GetGlobalPropertyAsBool(
  3480. "ALLOW_DUPLICATE_CUSTOM_TARGETS")) {
  3481. return true;
  3482. }
  3483. // Produce an error that tells the user how to work around the
  3484. // problem.
  3485. std::ostringstream e;
  3486. e << "cannot create target \"" << name
  3487. << "\" because another target with the same name already exists. "
  3488. "The existing target is ";
  3489. switch (existing->GetType()) {
  3490. case cmStateEnums::EXECUTABLE:
  3491. e << "an executable ";
  3492. break;
  3493. case cmStateEnums::STATIC_LIBRARY:
  3494. e << "a static library ";
  3495. break;
  3496. case cmStateEnums::SHARED_LIBRARY:
  3497. e << "a shared library ";
  3498. break;
  3499. case cmStateEnums::MODULE_LIBRARY:
  3500. e << "a module library ";
  3501. break;
  3502. case cmStateEnums::UTILITY:
  3503. e << "a custom target ";
  3504. break;
  3505. case cmStateEnums::INTERFACE_LIBRARY:
  3506. e << "an interface library ";
  3507. break;
  3508. default:
  3509. break;
  3510. }
  3511. e << "created in source directory \""
  3512. << existing->GetMakefile()->GetCurrentSourceDirectory()
  3513. << "\". "
  3514. "See documentation for policy CMP0002 for more details.";
  3515. msg = e.str();
  3516. return false;
  3517. }
  3518. return true;
  3519. }
  3520. bool cmMakefile::EnforceUniqueDir(std::string const& srcPath,
  3521. std::string const& binPath) const
  3522. {
  3523. // Make sure the binary directory is unique.
  3524. cmGlobalGenerator* gg = this->GetGlobalGenerator();
  3525. if (gg->BinaryDirectoryIsNew(binPath)) {
  3526. return true;
  3527. }
  3528. this->IssueMessage(MessageType::FATAL_ERROR,
  3529. cmStrCat("The binary directory\n"
  3530. " ",
  3531. binPath,
  3532. "\n"
  3533. "is already used to build a source directory. "
  3534. "It cannot be used to build source directory\n"
  3535. " ",
  3536. srcPath,
  3537. "\n"
  3538. "Specify a unique binary directory name."));
  3539. return false;
  3540. }
  3541. static std::string const matchVariables[] = {
  3542. "CMAKE_MATCH_0", "CMAKE_MATCH_1", "CMAKE_MATCH_2", "CMAKE_MATCH_3",
  3543. "CMAKE_MATCH_4", "CMAKE_MATCH_5", "CMAKE_MATCH_6", "CMAKE_MATCH_7",
  3544. "CMAKE_MATCH_8", "CMAKE_MATCH_9"
  3545. };
  3546. static std::string const nMatchesVariable = "CMAKE_MATCH_COUNT";
  3547. void cmMakefile::ClearMatches()
  3548. {
  3549. cmValue nMatchesStr = this->GetDefinition(nMatchesVariable);
  3550. if (!nMatchesStr) {
  3551. return;
  3552. }
  3553. int nMatches = atoi(nMatchesStr->c_str());
  3554. for (int i = 0; i <= nMatches; i++) {
  3555. std::string const& var = matchVariables[i];
  3556. std::string const& s = this->GetSafeDefinition(var);
  3557. if (!s.empty()) {
  3558. this->AddDefinition(var, "");
  3559. this->MarkVariableAsUsed(var);
  3560. }
  3561. }
  3562. this->AddDefinition(nMatchesVariable, "0");
  3563. this->MarkVariableAsUsed(nMatchesVariable);
  3564. }
  3565. void cmMakefile::StoreMatches(cmsys::RegularExpression& re)
  3566. {
  3567. char highest = 0;
  3568. for (int i = 0; i < 10; i++) {
  3569. std::string const& m = re.match(i);
  3570. if (!m.empty()) {
  3571. std::string const& var = matchVariables[i];
  3572. this->AddDefinition(var, m);
  3573. this->MarkVariableAsUsed(var);
  3574. highest = static_cast<char>('0' + i);
  3575. }
  3576. }
  3577. char nMatches[] = { highest, '\0' };
  3578. this->AddDefinition(nMatchesVariable, nMatches);
  3579. this->MarkVariableAsUsed(nMatchesVariable);
  3580. }
  3581. cmStateSnapshot cmMakefile::GetStateSnapshot() const
  3582. {
  3583. return this->StateSnapshot;
  3584. }
  3585. cmPolicies::PolicyStatus cmMakefile::GetPolicyStatus(cmPolicies::PolicyID id,
  3586. bool parent_scope) const
  3587. {
  3588. return this->StateSnapshot.GetPolicy(id, parent_scope);
  3589. }
  3590. bool cmMakefile::PolicyOptionalWarningEnabled(std::string const& var) const
  3591. {
  3592. // Check for an explicit CMAKE_POLICY_WARNING_CMP<NNNN> setting.
  3593. if (cmValue val = this->GetDefinition(var)) {
  3594. return val.IsOn();
  3595. }
  3596. // Enable optional policy warnings with --debug-output, --trace,
  3597. // or --trace-expand.
  3598. cmake* cm = this->GetCMakeInstance();
  3599. return cm->GetDebugOutput() || cm->GetTrace();
  3600. }
  3601. bool cmMakefile::SetPolicy(char const* id, cmPolicies::PolicyStatus status)
  3602. {
  3603. cmPolicies::PolicyID pid;
  3604. if (!cmPolicies::GetPolicyID(id, /* out */ pid)) {
  3605. this->IssueMessage(
  3606. MessageType::FATAL_ERROR,
  3607. cmStrCat("Policy \"", id, "\" is not known to this version of CMake."));
  3608. return false;
  3609. }
  3610. return this->SetPolicy(pid, status);
  3611. }
  3612. bool cmMakefile::SetPolicy(cmPolicies::PolicyID id,
  3613. cmPolicies::PolicyStatus status)
  3614. {
  3615. // A removed policy may be set only to NEW.
  3616. if (cmPolicies::IsRemoved(id) && status != cmPolicies::NEW) {
  3617. std::string msg = cmPolicies::GetRemovedPolicyError(id);
  3618. this->IssueMessage(MessageType::FATAL_ERROR, msg);
  3619. return false;
  3620. }
  3621. // Deprecate old policies.
  3622. if (status == cmPolicies::OLD && id <= cmPolicies::CMP0143 &&
  3623. !(this->GetCMakeInstance()->GetIsInTryCompile() &&
  3624. (
  3625. // Policies set by cmCoreTryCompile::TryCompileCode.
  3626. id == cmPolicies::CMP0083 || id == cmPolicies::CMP0091 ||
  3627. id == cmPolicies::CMP0104 || id == cmPolicies::CMP0123 ||
  3628. id == cmPolicies::CMP0126 || id == cmPolicies::CMP0128 ||
  3629. id == cmPolicies::CMP0136 || id == cmPolicies::CMP0141)) &&
  3630. (!this->IsSet("CMAKE_WARN_DEPRECATED") ||
  3631. this->IsOn("CMAKE_WARN_DEPRECATED"))) {
  3632. this->IssueMessage(MessageType::DEPRECATION_WARNING,
  3633. cmPolicies::GetPolicyDeprecatedWarning(id));
  3634. }
  3635. this->StateSnapshot.SetPolicy(id, status);
  3636. // Handle CMAKE_PARENT_LIST_FILE for CMP0198 policy changes
  3637. if (id == cmPolicies::CMP0198) {
  3638. this->UpdateParentListFileVariable();
  3639. }
  3640. return true;
  3641. }
  3642. cmMakefile::PolicyPushPop::PolicyPushPop(cmMakefile* m)
  3643. : Makefile(m)
  3644. {
  3645. this->Makefile->PushPolicy();
  3646. }
  3647. cmMakefile::PolicyPushPop::~PolicyPushPop()
  3648. {
  3649. this->Makefile->PopPolicy();
  3650. }
  3651. void cmMakefile::PushPolicy(bool weak, cmPolicies::PolicyMap const& pm)
  3652. {
  3653. this->StateSnapshot.PushPolicy(pm, weak);
  3654. }
  3655. void cmMakefile::PopPolicy()
  3656. {
  3657. if (!this->StateSnapshot.PopPolicy()) {
  3658. this->IssueMessage(MessageType::FATAL_ERROR,
  3659. "cmake_policy POP without matching PUSH");
  3660. }
  3661. }
  3662. void cmMakefile::PopSnapshot(bool reportError)
  3663. {
  3664. // cmStateSnapshot manages nested policy scopes within it.
  3665. // Since the scope corresponding to the snapshot is closing,
  3666. // reject any still-open nested policy scopes with an error.
  3667. while (this->StateSnapshot.CanPopPolicyScope()) {
  3668. if (reportError) {
  3669. this->IssueMessage(MessageType::FATAL_ERROR,
  3670. "cmake_policy PUSH without matching POP");
  3671. reportError = false;
  3672. }
  3673. this->PopPolicy();
  3674. }
  3675. this->StateSnapshot = this->GetState()->Pop(this->StateSnapshot);
  3676. assert(this->StateSnapshot.IsValid());
  3677. }
  3678. bool cmMakefile::SetPolicyVersion(std::string const& version_min,
  3679. std::string const& version_max)
  3680. {
  3681. return cmPolicies::ApplyPolicyVersion(this, version_min, version_max,
  3682. cmPolicies::WarnCompat::On);
  3683. }
  3684. void cmMakefile::UpdateParentListFileVariable()
  3685. {
  3686. // CMP0198 determines CMAKE_PARENT_LIST_FILE behavior in CMakeLists.txt
  3687. if (this->GetPolicyStatus(cmPolicies::CMP0198) == cmPolicies::NEW) {
  3688. this->RemoveDefinition(kCMAKE_PARENT_LIST_FILE);
  3689. } else {
  3690. std::string currentSourceDir =
  3691. this->StateSnapshot.GetDirectory().GetCurrentSource();
  3692. std::string currentStart =
  3693. this->GetCMakeInstance()->GetCMakeListFile(currentSourceDir);
  3694. this->AddDefinition(kCMAKE_PARENT_LIST_FILE, currentStart);
  3695. }
  3696. }
  3697. cmMakefile::VariablePushPop::VariablePushPop(cmMakefile* m)
  3698. : Makefile(m)
  3699. {
  3700. this->Makefile->StateSnapshot =
  3701. this->Makefile->GetState()->CreateVariableScopeSnapshot(
  3702. this->Makefile->StateSnapshot);
  3703. }
  3704. cmMakefile::VariablePushPop::~VariablePushPop()
  3705. {
  3706. this->Makefile->PopSnapshot();
  3707. }
  3708. void cmMakefile::RecordPolicies(cmPolicies::PolicyMap& pm) const
  3709. {
  3710. /* Record the setting of every policy. */
  3711. using PolicyID = cmPolicies::PolicyID;
  3712. for (PolicyID pid = cmPolicies::CMP0000; pid != cmPolicies::CMPCOUNT;
  3713. pid = static_cast<PolicyID>(pid + 1)) {
  3714. pm.Set(pid, this->GetPolicyStatus(pid));
  3715. }
  3716. }
  3717. cmMakefile::FunctionPushPop::FunctionPushPop(cmMakefile* mf,
  3718. std::string const& fileName,
  3719. cmPolicies::PolicyMap const& pm)
  3720. : Makefile(mf)
  3721. {
  3722. this->Makefile->PushFunctionScope(fileName, pm);
  3723. }
  3724. cmMakefile::FunctionPushPop::~FunctionPushPop()
  3725. {
  3726. this->Makefile->PopFunctionScope(this->ReportError);
  3727. }
  3728. cmMakefile::MacroPushPop::MacroPushPop(cmMakefile* mf,
  3729. std::string const& fileName,
  3730. cmPolicies::PolicyMap const& pm)
  3731. : Makefile(mf)
  3732. {
  3733. this->Makefile->PushMacroScope(fileName, pm);
  3734. }
  3735. cmMakefile::MacroPushPop::~MacroPushPop()
  3736. {
  3737. this->Makefile->PopMacroScope(this->ReportError);
  3738. }
  3739. cmFindPackageStackRAII::cmFindPackageStackRAII(cmMakefile* mf,
  3740. std::string const& name)
  3741. : Makefile(mf)
  3742. {
  3743. this->Makefile->FindPackageStack =
  3744. this->Makefile->FindPackageStack.Push(cmFindPackageCall{
  3745. name,
  3746. cmPackageInformation(),
  3747. this->Makefile->FindPackageStackNextIndex,
  3748. });
  3749. this->Makefile->FindPackageStackNextIndex++;
  3750. }
  3751. void cmFindPackageStackRAII::BindTop(cmPackageInformation*& value)
  3752. {
  3753. if (this->Value) {
  3754. *this->Value = nullptr;
  3755. }
  3756. this->Value = &value;
  3757. value = &this->Makefile->FindPackageStack.cmStack::Top().PackageInfo;
  3758. }
  3759. cmFindPackageStackRAII::~cmFindPackageStackRAII()
  3760. {
  3761. if (this->Value) {
  3762. *this->Value = nullptr;
  3763. }
  3764. this->Makefile->FindPackageStackNextIndex =
  3765. this->Makefile->FindPackageStack.Top().Index + 1;
  3766. this->Makefile->FindPackageStack = this->Makefile->FindPackageStack.Pop();
  3767. if (!this->Makefile->FindPackageStack.Empty()) {
  3768. auto top = this->Makefile->FindPackageStack.Top();
  3769. this->Makefile->FindPackageStack = this->Makefile->FindPackageStack.Pop();
  3770. top.Index = this->Makefile->FindPackageStackNextIndex;
  3771. this->Makefile->FindPackageStackNextIndex++;
  3772. this->Makefile->FindPackageStack =
  3773. this->Makefile->FindPackageStack.Push(top);
  3774. }
  3775. }
  3776. cmMakefile::DebugFindPkgRAII::DebugFindPkgRAII(cmMakefile* mf,
  3777. std::string const& pkg)
  3778. : Makefile(mf)
  3779. , OldValue(this->Makefile->DebugFindPkg)
  3780. {
  3781. this->Makefile->DebugFindPkg =
  3782. this->Makefile->GetCMakeInstance()->GetDebugFindPkgOutput(pkg);
  3783. }
  3784. cmMakefile::DebugFindPkgRAII::~DebugFindPkgRAII()
  3785. {
  3786. this->Makefile->DebugFindPkg = this->OldValue;
  3787. }
  3788. bool cmMakefile::GetDebugFindPkgMode() const
  3789. {
  3790. return this->DebugFindPkg;
  3791. }