cmMakefile.cxx 143 KB

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