cmMakefile.cxx 149 KB

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