cmMakefile.cxx 142 KB

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