cmMakefile.cxx 149 KB

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