cmMakefile.cxx 141 KB

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