cmMakefile.cxx 148 KB

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