cmLocalGenerator.cxx 168 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785
  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 "cmLocalGenerator.h"
  4. #include <algorithm>
  5. #include <array>
  6. #include <cassert>
  7. #include <cstdio>
  8. #include <cstdlib>
  9. #include <initializer_list>
  10. #include <iterator>
  11. #include <sstream>
  12. #include <type_traits>
  13. #include <unordered_set>
  14. #include <utility>
  15. #include <vector>
  16. #include <cm/memory>
  17. #include <cm/optional>
  18. #include <cm/string_view>
  19. #include <cmext/algorithm>
  20. #include <cmext/string_view>
  21. #include "cmsys/RegularExpression.hxx"
  22. #include "cmAlgorithms.h"
  23. #include "cmComputeLinkInformation.h"
  24. #include "cmCryptoHash.h"
  25. #include "cmCustomCommand.h"
  26. #include "cmCustomCommandGenerator.h"
  27. #include "cmCustomCommandLines.h"
  28. #include "cmCustomCommandTypes.h"
  29. #include "cmGeneratedFileStream.h"
  30. #include "cmGeneratorExpression.h"
  31. #include "cmGeneratorExpressionEvaluationFile.h"
  32. #include "cmGeneratorTarget.h"
  33. #include "cmGlobalGenerator.h"
  34. #include "cmInstallGenerator.h"
  35. #include "cmInstallScriptGenerator.h"
  36. #include "cmInstallTargetGenerator.h"
  37. #include "cmLinkLineComputer.h"
  38. #include "cmLinkLineDeviceComputer.h"
  39. #include "cmList.h"
  40. #include "cmMakefile.h"
  41. #include "cmMessageType.h"
  42. #include "cmRange.h"
  43. #include "cmRulePlaceholderExpander.h"
  44. #include "cmSourceFile.h"
  45. #include "cmSourceFileLocation.h"
  46. #include "cmSourceFileLocationKind.h"
  47. #include "cmStandardLevelResolver.h"
  48. #include "cmState.h"
  49. #include "cmStateDirectory.h"
  50. #include "cmStateTypes.h"
  51. #include "cmStringAlgorithms.h"
  52. #include "cmSystemTools.h"
  53. #include "cmTarget.h"
  54. #include "cmTestGenerator.h"
  55. #include "cmValue.h"
  56. #include "cmVersion.h"
  57. #include "cmake.h"
  58. #if defined(__HAIKU__)
  59. # include <FindDirectory.h>
  60. # include <StorageDefs.h>
  61. #endif
  62. // List of variables that are replaced when
  63. // rules are expanded. These variables are
  64. // replaced in the form <var> with GetSafeDefinition(var).
  65. // ${LANG} is replaced in the variable first with all enabled
  66. // languages.
  67. static auto ruleReplaceVars = { "CMAKE_${LANG}_COMPILER",
  68. "CMAKE_SHARED_LIBRARY_CREATE_${LANG}_FLAGS",
  69. "CMAKE_SHARED_MODULE_CREATE_${LANG}_FLAGS",
  70. "CMAKE_SHARED_MODULE_${LANG}_FLAGS",
  71. "CMAKE_SHARED_LIBRARY_${LANG}_FLAGS",
  72. "CMAKE_${LANG}_LINK_FLAGS",
  73. "CMAKE_SHARED_LIBRARY_SONAME_${LANG}_FLAG",
  74. "CMAKE_${LANG}_ARCHIVE",
  75. "CMAKE_AR",
  76. "CMAKE_CURRENT_SOURCE_DIR",
  77. "CMAKE_CURRENT_BINARY_DIR",
  78. "CMAKE_RANLIB",
  79. "CMAKE_LINKER",
  80. "CMAKE_MT",
  81. "CMAKE_TAPI",
  82. "CMAKE_CUDA_HOST_COMPILER",
  83. "CMAKE_CUDA_HOST_LINK_LAUNCHER",
  84. "CMAKE_HIP_HOST_COMPILER",
  85. "CMAKE_HIP_HOST_LINK_LAUNCHER",
  86. "CMAKE_CL_SHOWINCLUDES_PREFIX" };
  87. cmLocalGenerator::cmLocalGenerator(cmGlobalGenerator* gg, cmMakefile* makefile)
  88. : cmOutputConverter(makefile->GetStateSnapshot())
  89. , DirectoryBacktrace(makefile->GetBacktrace())
  90. {
  91. this->GlobalGenerator = gg;
  92. this->Makefile = makefile;
  93. this->AliasTargets = makefile->GetAliasTargets();
  94. this->EmitUniversalBinaryFlags = true;
  95. this->BackwardsCompatibility = 0;
  96. this->BackwardsCompatibilityFinal = false;
  97. this->ComputeObjectMaxPath();
  98. // Canonicalize entries of the CPATH environment variable the same
  99. // way detection of CMAKE_<LANG>_IMPLICIT_INCLUDE_DIRECTORIES does.
  100. {
  101. std::vector<std::string> cpath;
  102. cmSystemTools::GetPath(cpath, "CPATH");
  103. for (std::string const& cp : cpath) {
  104. if (cmSystemTools::FileIsFullPath(cp)) {
  105. this->EnvCPATH.emplace_back(cmSystemTools::CollapseFullPath(cp));
  106. }
  107. }
  108. }
  109. std::vector<std::string> enabledLanguages =
  110. this->GetState()->GetEnabledLanguages();
  111. if (cmValue sysrootCompile =
  112. this->Makefile->GetDefinition("CMAKE_SYSROOT_COMPILE")) {
  113. this->CompilerSysroot = *sysrootCompile;
  114. } else {
  115. this->CompilerSysroot = this->Makefile->GetSafeDefinition("CMAKE_SYSROOT");
  116. }
  117. if (cmValue sysrootLink =
  118. this->Makefile->GetDefinition("CMAKE_SYSROOT_LINK")) {
  119. this->LinkerSysroot = *sysrootLink;
  120. } else {
  121. this->LinkerSysroot = this->Makefile->GetSafeDefinition("CMAKE_SYSROOT");
  122. }
  123. // OSX SYSROOT can be required by some tools, like tapi
  124. {
  125. cmValue osxSysroot = this->Makefile->GetDefinition("CMAKE_OSX_SYSROOT");
  126. this->VariableMappings["CMAKE_OSX_SYSROOT"] =
  127. osxSysroot.IsEmpty() ? "/" : this->EscapeForShell(*osxSysroot, true);
  128. }
  129. if (cmValue appleArchSysroots =
  130. this->Makefile->GetDefinition("CMAKE_APPLE_ARCH_SYSROOTS")) {
  131. std::string const& appleArchs =
  132. this->Makefile->GetSafeDefinition("CMAKE_OSX_ARCHITECTURES");
  133. cmList archs(appleArchs);
  134. cmList sysroots{ appleArchSysroots, cmList::EmptyElements::Yes };
  135. if (archs.size() == sysroots.size()) {
  136. for (cmList::size_type i = 0; i < archs.size(); ++i) {
  137. this->AppleArchSysroots[archs[i]] = sysroots[i];
  138. }
  139. } else {
  140. std::string const e =
  141. cmStrCat("CMAKE_APPLE_ARCH_SYSROOTS:\n ", *appleArchSysroots,
  142. "\n"
  143. "is not the same length as CMAKE_OSX_ARCHITECTURES:\n ",
  144. appleArchs);
  145. this->IssueMessage(MessageType::FATAL_ERROR, e);
  146. }
  147. }
  148. for (std::string const& lang : enabledLanguages) {
  149. if (lang == "NONE") {
  150. continue;
  151. }
  152. this->Compilers["CMAKE_" + lang + "_COMPILER"] = lang;
  153. this->VariableMappings["CMAKE_" + lang + "_COMPILER"] =
  154. this->Makefile->GetSafeDefinition("CMAKE_" + lang + "_COMPILER");
  155. std::string const& compilerArg1 = "CMAKE_" + lang + "_COMPILER_ARG1";
  156. std::string const& compilerTarget = "CMAKE_" + lang + "_COMPILER_TARGET";
  157. std::string const& compilerOptionTarget =
  158. "CMAKE_" + lang + "_COMPILE_OPTIONS_TARGET";
  159. std::string const& compilerExternalToolchain =
  160. "CMAKE_" + lang + "_COMPILER_EXTERNAL_TOOLCHAIN";
  161. std::string const& compilerOptionExternalToolchain =
  162. "CMAKE_" + lang + "_COMPILE_OPTIONS_EXTERNAL_TOOLCHAIN";
  163. std::string const& compilerOptionSysroot =
  164. "CMAKE_" + lang + "_COMPILE_OPTIONS_SYSROOT";
  165. this->VariableMappings[compilerArg1] =
  166. this->Makefile->GetSafeDefinition(compilerArg1);
  167. this->VariableMappings[compilerTarget] =
  168. this->Makefile->GetSafeDefinition(compilerTarget);
  169. this->VariableMappings[compilerOptionTarget] =
  170. this->Makefile->GetSafeDefinition(compilerOptionTarget);
  171. this->VariableMappings[compilerExternalToolchain] =
  172. this->Makefile->GetSafeDefinition(compilerExternalToolchain);
  173. this->VariableMappings[compilerOptionExternalToolchain] =
  174. this->Makefile->GetSafeDefinition(compilerOptionExternalToolchain);
  175. this->VariableMappings[compilerOptionSysroot] =
  176. this->Makefile->GetSafeDefinition(compilerOptionSysroot);
  177. for (std::string replaceVar : ruleReplaceVars) {
  178. if (replaceVar.find("${LANG}") != std::string::npos) {
  179. cmSystemTools::ReplaceString(replaceVar, "${LANG}", lang);
  180. }
  181. this->VariableMappings[replaceVar] =
  182. this->Makefile->GetSafeDefinition(replaceVar);
  183. }
  184. }
  185. }
  186. std::unique_ptr<cmRulePlaceholderExpander>
  187. cmLocalGenerator::CreateRulePlaceholderExpander() const
  188. {
  189. return cm::make_unique<cmRulePlaceholderExpander>(
  190. this->Compilers, this->VariableMappings, this->CompilerSysroot,
  191. this->LinkerSysroot);
  192. }
  193. cmLocalGenerator::~cmLocalGenerator() = default;
  194. void cmLocalGenerator::IssueMessage(MessageType t,
  195. std::string const& text) const
  196. {
  197. this->GetCMakeInstance()->IssueMessage(t, text, this->DirectoryBacktrace);
  198. }
  199. void cmLocalGenerator::ComputeObjectMaxPath()
  200. {
  201. // Choose a maximum object file name length.
  202. #if defined(_WIN32) || defined(__CYGWIN__)
  203. this->ObjectPathMax = 250;
  204. #else
  205. this->ObjectPathMax = 1000;
  206. #endif
  207. cmValue plen = this->Makefile->GetDefinition("CMAKE_OBJECT_PATH_MAX");
  208. if (cmNonempty(plen)) {
  209. unsigned int pmax;
  210. if (sscanf(plen->c_str(), "%u", &pmax) == 1) {
  211. if (pmax >= 128) {
  212. this->ObjectPathMax = pmax;
  213. } else {
  214. std::ostringstream w;
  215. w << "CMAKE_OBJECT_PATH_MAX is set to " << pmax
  216. << ", which is less than the minimum of 128. "
  217. << "The value will be ignored.";
  218. this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  219. }
  220. } else {
  221. std::ostringstream w;
  222. w << "CMAKE_OBJECT_PATH_MAX is set to \"" << *plen
  223. << "\", which fails to parse as a positive integer. "
  224. << "The value will be ignored.";
  225. this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  226. }
  227. }
  228. this->ObjectMaxPathViolations.clear();
  229. }
  230. static void MoveSystemIncludesToEnd(std::vector<std::string>& includeDirs,
  231. const std::string& config,
  232. const std::string& lang,
  233. const cmGeneratorTarget* target)
  234. {
  235. if (!target) {
  236. return;
  237. }
  238. std::stable_sort(
  239. includeDirs.begin(), includeDirs.end(),
  240. [&target, &config, &lang](std::string const& a, std::string const& b) {
  241. return !target->IsSystemIncludeDirectory(a, config, lang) &&
  242. target->IsSystemIncludeDirectory(b, config, lang);
  243. });
  244. }
  245. static void MoveSystemIncludesToEnd(std::vector<BT<std::string>>& includeDirs,
  246. const std::string& config,
  247. const std::string& lang,
  248. const cmGeneratorTarget* target)
  249. {
  250. if (!target) {
  251. return;
  252. }
  253. std::stable_sort(includeDirs.begin(), includeDirs.end(),
  254. [target, &config, &lang](BT<std::string> const& a,
  255. BT<std::string> const& b) {
  256. return !target->IsSystemIncludeDirectory(a.Value, config,
  257. lang) &&
  258. target->IsSystemIncludeDirectory(b.Value, config, lang);
  259. });
  260. }
  261. void cmLocalGenerator::TraceDependencies() const
  262. {
  263. // Generate the rule files for each target.
  264. const auto& targets = this->GetGeneratorTargets();
  265. for (const auto& target : targets) {
  266. if (!target->IsInBuildSystem()) {
  267. continue;
  268. }
  269. target->TraceDependencies();
  270. }
  271. }
  272. void cmLocalGenerator::GenerateTestFiles()
  273. {
  274. if (!this->Makefile->IsOn("CMAKE_TESTING_ENABLED")) {
  275. return;
  276. }
  277. // Compute the set of configurations.
  278. std::vector<std::string> configurationTypes =
  279. this->Makefile->GetGeneratorConfigs(cmMakefile::OnlyMultiConfig);
  280. std::string config = this->Makefile->GetDefaultConfiguration();
  281. std::string file =
  282. cmStrCat(this->StateSnapshot.GetDirectory().GetCurrentBinary(),
  283. "/CTestTestfile.cmake");
  284. cmGeneratedFileStream fout(file);
  285. fout.SetCopyIfDifferent(true);
  286. fout << "# CMake generated Testfile for \n"
  287. "# Source directory: "
  288. << this->StateSnapshot.GetDirectory().GetCurrentSource()
  289. << "\n"
  290. "# Build directory: "
  291. << this->StateSnapshot.GetDirectory().GetCurrentBinary()
  292. << "\n"
  293. "# \n"
  294. "# This file includes the relevant testing commands "
  295. "required for \n"
  296. "# testing this directory and lists subdirectories to "
  297. "be tested as well.\n";
  298. std::string resourceSpecFile =
  299. this->Makefile->GetSafeDefinition("CTEST_RESOURCE_SPEC_FILE");
  300. if (!resourceSpecFile.empty()) {
  301. fout << "set(CTEST_RESOURCE_SPEC_FILE \"" << resourceSpecFile << "\")\n";
  302. }
  303. cmValue testIncludeFile = this->Makefile->GetProperty("TEST_INCLUDE_FILE");
  304. if (testIncludeFile) {
  305. fout << "include(\"" << *testIncludeFile << "\")\n";
  306. }
  307. cmValue testIncludeFiles = this->Makefile->GetProperty("TEST_INCLUDE_FILES");
  308. if (testIncludeFiles) {
  309. cmList includesList{ *testIncludeFiles };
  310. for (std::string const& i : includesList) {
  311. fout << "include(\"" << i << "\")\n";
  312. }
  313. }
  314. // Ask each test generator to write its code.
  315. for (const auto& tester : this->Makefile->GetTestGenerators()) {
  316. tester->Compute(this);
  317. tester->Generate(fout, config, configurationTypes);
  318. }
  319. using vec_t = std::vector<cmStateSnapshot>;
  320. vec_t const& children = this->Makefile->GetStateSnapshot().GetChildren();
  321. for (cmStateSnapshot const& i : children) {
  322. // TODO: Use add_subdirectory instead?
  323. std::string outP = i.GetDirectory().GetCurrentBinary();
  324. outP = this->MaybeRelativeToCurBinDir(outP);
  325. outP = cmOutputConverter::EscapeForCMake(outP);
  326. fout << "subdirs(" << outP << ")\n";
  327. }
  328. // Add directory labels property
  329. cmValue directoryLabels =
  330. this->Makefile->GetDefinition("CMAKE_DIRECTORY_LABELS");
  331. cmValue labels = this->Makefile->GetProperty("LABELS");
  332. if (labels || directoryLabels) {
  333. fout << "set_directory_properties(PROPERTIES LABELS ";
  334. if (labels) {
  335. fout << cmOutputConverter::EscapeForCMake(*labels);
  336. }
  337. if (labels && directoryLabels) {
  338. fout << ";";
  339. }
  340. if (directoryLabels) {
  341. fout << cmOutputConverter::EscapeForCMake(*directoryLabels);
  342. }
  343. fout << ")\n";
  344. }
  345. }
  346. void cmLocalGenerator::CreateEvaluationFileOutputs()
  347. {
  348. std::vector<std::string> const& configs =
  349. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  350. for (std::string const& c : configs) {
  351. this->CreateEvaluationFileOutputs(c);
  352. }
  353. }
  354. void cmLocalGenerator::CreateEvaluationFileOutputs(std::string const& config)
  355. {
  356. for (const auto& geef : this->Makefile->GetEvaluationFiles()) {
  357. geef->CreateOutputFile(this, config);
  358. }
  359. }
  360. void cmLocalGenerator::ProcessEvaluationFiles(
  361. std::vector<std::string>& generatedFiles)
  362. {
  363. for (const auto& geef : this->Makefile->GetEvaluationFiles()) {
  364. geef->Generate(this);
  365. if (cmSystemTools::GetFatalErrorOccurred()) {
  366. return;
  367. }
  368. std::vector<std::string> files = geef->GetFiles();
  369. std::sort(files.begin(), files.end());
  370. std::vector<std::string> intersection;
  371. std::set_intersection(files.begin(), files.end(), generatedFiles.begin(),
  372. generatedFiles.end(),
  373. std::back_inserter(intersection));
  374. if (!intersection.empty()) {
  375. cmSystemTools::Error("Files to be generated by multiple different "
  376. "commands: " +
  377. cmWrap('"', intersection, '"', " "));
  378. return;
  379. }
  380. cm::append(generatedFiles, files);
  381. std::inplace_merge(generatedFiles.begin(),
  382. generatedFiles.end() - files.size(),
  383. generatedFiles.end());
  384. }
  385. }
  386. void cmLocalGenerator::GenerateInstallRules()
  387. {
  388. // Compute the install prefix.
  389. cmValue installPrefix =
  390. this->Makefile->GetDefinition("CMAKE_INSTALL_PREFIX");
  391. std::string prefix = *installPrefix;
  392. #if defined(_WIN32) && !defined(__CYGWIN__)
  393. if (!installPrefix) {
  394. if (!cmSystemTools::GetEnv("SystemDrive", prefix)) {
  395. prefix = "C:";
  396. }
  397. cmValue project_name = this->Makefile->GetDefinition("PROJECT_NAME");
  398. if (cmNonempty(project_name)) {
  399. prefix += "/Program Files/";
  400. prefix += *project_name;
  401. } else {
  402. prefix += "/InstalledCMakeProject";
  403. }
  404. }
  405. #elif defined(__HAIKU__)
  406. char dir[B_PATH_NAME_LENGTH];
  407. if (!installPrefix) {
  408. if (find_directory(B_SYSTEM_DIRECTORY, -1, false, dir, sizeof(dir)) ==
  409. B_OK) {
  410. prefix = dir;
  411. } else {
  412. prefix = "/boot/system";
  413. }
  414. }
  415. #else
  416. if (!installPrefix) {
  417. prefix = "/usr/local";
  418. }
  419. #endif
  420. if (cmValue stagingPrefix =
  421. this->Makefile->GetDefinition("CMAKE_STAGING_PREFIX")) {
  422. prefix = *stagingPrefix;
  423. }
  424. // Compute the set of configurations.
  425. std::vector<std::string> configurationTypes =
  426. this->Makefile->GetGeneratorConfigs(cmMakefile::OnlyMultiConfig);
  427. std::string config = this->Makefile->GetDefaultConfiguration();
  428. // Choose a default install configuration.
  429. std::string default_config = config;
  430. const char* default_order[] = { "RELEASE", "MINSIZEREL", "RELWITHDEBINFO",
  431. "DEBUG", nullptr };
  432. for (const char** c = default_order; *c && default_config.empty(); ++c) {
  433. for (std::string const& configurationType : configurationTypes) {
  434. if (cmSystemTools::UpperCase(configurationType) == *c) {
  435. default_config = configurationType;
  436. }
  437. }
  438. }
  439. if (default_config.empty() && !configurationTypes.empty()) {
  440. default_config = configurationTypes[0];
  441. }
  442. // Create the install script file.
  443. std::string file = this->StateSnapshot.GetDirectory().GetCurrentBinary();
  444. std::string homedir = this->GetState()->GetBinaryDirectory();
  445. int toplevel_install = 0;
  446. if (file == homedir) {
  447. toplevel_install = 1;
  448. }
  449. file += "/cmake_install.cmake";
  450. cmGeneratedFileStream fout(file);
  451. fout.SetCopyIfDifferent(true);
  452. // Write the header.
  453. /* clang-format off */
  454. fout << "# Install script for directory: "
  455. << this->StateSnapshot.GetDirectory().GetCurrentSource()
  456. << "\n\n"
  457. "# Set the install prefix\n"
  458. "if(NOT DEFINED CMAKE_INSTALL_PREFIX)\n"
  459. " set(CMAKE_INSTALL_PREFIX \"" << prefix << "\")\n"
  460. "endif()\n"
  461. << R"(string(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX )"
  462. << "\"${CMAKE_INSTALL_PREFIX}\")\n\n";
  463. /* clang-format on */
  464. // Write support code for generating per-configuration install rules.
  465. /* clang-format off */
  466. fout <<
  467. "# Set the install configuration name.\n"
  468. "if(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME)\n"
  469. " if(BUILD_TYPE)\n"
  470. " string(REGEX REPLACE \"^[^A-Za-z0-9_]+\" \"\"\n"
  471. " CMAKE_INSTALL_CONFIG_NAME \"${BUILD_TYPE}\")\n"
  472. " else()\n"
  473. " set(CMAKE_INSTALL_CONFIG_NAME \"" << default_config << "\")\n"
  474. " endif()\n"
  475. " message(STATUS \"Install configuration: "
  476. "\\\"${CMAKE_INSTALL_CONFIG_NAME}\\\"\")\n"
  477. "endif()\n"
  478. "\n";
  479. /* clang-format on */
  480. // Write support code for dealing with component-specific installs.
  481. /* clang-format off */
  482. fout <<
  483. "# Set the component getting installed.\n"
  484. "if(NOT CMAKE_INSTALL_COMPONENT)\n"
  485. " if(COMPONENT)\n"
  486. " message(STATUS \"Install component: \\\"${COMPONENT}\\\"\")\n"
  487. " set(CMAKE_INSTALL_COMPONENT \"${COMPONENT}\")\n"
  488. " else()\n"
  489. " set(CMAKE_INSTALL_COMPONENT)\n"
  490. " endif()\n"
  491. "endif()\n"
  492. "\n";
  493. /* clang-format on */
  494. // Copy user-specified install options to the install code.
  495. if (cmValue so_no_exe =
  496. this->Makefile->GetDefinition("CMAKE_INSTALL_SO_NO_EXE")) {
  497. /* clang-format off */
  498. fout <<
  499. "# Install shared libraries without execute permission?\n"
  500. "if(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE)\n"
  501. " set(CMAKE_INSTALL_SO_NO_EXE \"" << *so_no_exe << "\")\n"
  502. "endif()\n"
  503. "\n";
  504. /* clang-format on */
  505. }
  506. // Copy cmake cross compile state to install code.
  507. if (cmValue crosscompiling =
  508. this->Makefile->GetDefinition("CMAKE_CROSSCOMPILING")) {
  509. /* clang-format off */
  510. fout <<
  511. "# Is this installation the result of a crosscompile?\n"
  512. "if(NOT DEFINED CMAKE_CROSSCOMPILING)\n"
  513. " set(CMAKE_CROSSCOMPILING \"" << *crosscompiling << "\")\n"
  514. "endif()\n"
  515. "\n";
  516. /* clang-format on */
  517. }
  518. // Write default directory permissions.
  519. if (cmValue defaultDirPermissions = this->Makefile->GetDefinition(
  520. "CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS")) {
  521. /* clang-format off */
  522. fout <<
  523. "# Set default install directory permissions.\n"
  524. "if(NOT DEFINED CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS)\n"
  525. " set(CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS \""
  526. << *defaultDirPermissions << "\")\n"
  527. "endif()\n"
  528. "\n";
  529. /* clang-format on */
  530. }
  531. // Write out CMAKE_GET_RUNTIME_DEPENDENCIES_PLATFORM so that
  532. // installed code that uses `file(GET_RUNTIME_DEPENDENCIES)`
  533. // has same platform variable as when running cmake
  534. if (cmValue platform = this->Makefile->GetDefinition(
  535. "CMAKE_GET_RUNTIME_DEPENDENCIES_PLATFORM")) {
  536. /* clang-format off */
  537. fout <<
  538. "# Set default install directory permissions.\n"
  539. "if(NOT DEFINED CMAKE_GET_RUNTIME_DEPENDENCIES_PLATFORM)\n"
  540. " set(CMAKE_GET_RUNTIME_DEPENDENCIES_PLATFORM \""
  541. << *platform << "\")\n"
  542. "endif()\n"
  543. "\n";
  544. /* clang-format on */
  545. }
  546. // Write out CMAKE_GET_RUNTIME_DEPENDENCIES_TOOL so that
  547. // installed code that uses `file(GET_RUNTIME_DEPENDENCIES)`
  548. // has same tool selected as when running cmake
  549. if (cmValue command =
  550. this->Makefile->GetDefinition("CMAKE_GET_RUNTIME_DEPENDENCIES_TOOL")) {
  551. /* clang-format off */
  552. fout <<
  553. "# Set default install directory permissions.\n"
  554. "if(NOT DEFINED CMAKE_GET_RUNTIME_DEPENDENCIES_TOOL)\n"
  555. " set(CMAKE_GET_RUNTIME_DEPENDENCIES_TOOL \""
  556. << *command << "\")\n"
  557. "endif()\n"
  558. "\n";
  559. /* clang-format on */
  560. }
  561. // Write out CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND so that
  562. // installed code that uses `file(GET_RUNTIME_DEPENDENCIES)`
  563. // has same path to the tool as when running cmake
  564. if (cmValue command = this->Makefile->GetDefinition(
  565. "CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND")) {
  566. /* clang-format off */
  567. fout <<
  568. "# Set default install directory permissions.\n"
  569. "if(NOT DEFINED CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND)\n"
  570. " set(CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND \""
  571. << *command << "\")\n"
  572. "endif()\n"
  573. "\n";
  574. /* clang-format on */
  575. }
  576. // Write out CMAKE_OBJDUMP so that installed code that uses
  577. // `file(GET_RUNTIME_DEPENDENCIES)` and hasn't specified
  578. // CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND has consistent
  579. // logic to fallback to CMAKE_OBJDUMP when `objdump` is
  580. // not on the path
  581. if (cmValue command = this->Makefile->GetDefinition("CMAKE_OBJDUMP")) {
  582. /* clang-format off */
  583. fout <<
  584. "# Set default install directory permissions.\n"
  585. "if(NOT DEFINED CMAKE_OBJDUMP)\n"
  586. " set(CMAKE_OBJDUMP \""
  587. << *command << "\")\n"
  588. "endif()\n"
  589. "\n";
  590. /* clang-format on */
  591. }
  592. this->AddGeneratorSpecificInstallSetup(fout);
  593. // Ask each install generator to write its code.
  594. cmPolicies::PolicyStatus status = this->GetPolicyStatus(cmPolicies::CMP0082);
  595. auto const& installers = this->Makefile->GetInstallGenerators();
  596. bool haveSubdirectoryInstall = false;
  597. bool haveInstallAfterSubdirectory = false;
  598. if (status == cmPolicies::WARN) {
  599. for (const auto& installer : installers) {
  600. installer->CheckCMP0082(haveSubdirectoryInstall,
  601. haveInstallAfterSubdirectory);
  602. installer->Generate(fout, config, configurationTypes);
  603. }
  604. } else {
  605. for (const auto& installer : installers) {
  606. installer->Generate(fout, config, configurationTypes);
  607. }
  608. }
  609. // Write rules from old-style specification stored in targets.
  610. this->GenerateTargetInstallRules(fout, config, configurationTypes);
  611. // Include install scripts from subdirectories.
  612. switch (status) {
  613. case cmPolicies::WARN:
  614. if (haveInstallAfterSubdirectory &&
  615. this->Makefile->PolicyOptionalWarningEnabled(
  616. "CMAKE_POLICY_WARNING_CMP0082")) {
  617. std::ostringstream e;
  618. e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0082) << "\n";
  619. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  620. }
  621. CM_FALLTHROUGH;
  622. case cmPolicies::OLD: {
  623. std::vector<cmStateSnapshot> children =
  624. this->Makefile->GetStateSnapshot().GetChildren();
  625. if (!children.empty()) {
  626. fout << "if(NOT CMAKE_INSTALL_LOCAL_ONLY)\n";
  627. fout << " # Include the install script for each subdirectory.\n";
  628. for (cmStateSnapshot const& c : children) {
  629. if (!c.GetDirectory().GetPropertyAsBool("EXCLUDE_FROM_ALL")) {
  630. std::string odir = c.GetDirectory().GetCurrentBinary();
  631. cmSystemTools::ConvertToUnixSlashes(odir);
  632. fout << " include(\"" << odir << "/cmake_install.cmake\")\n";
  633. }
  634. }
  635. fout << "\n";
  636. fout << "endif()\n\n";
  637. }
  638. } break;
  639. case cmPolicies::REQUIRED_IF_USED:
  640. case cmPolicies::REQUIRED_ALWAYS:
  641. case cmPolicies::NEW:
  642. // NEW behavior is handled in
  643. // cmInstallSubdirectoryGenerator::GenerateScript()
  644. break;
  645. }
  646. // Record the install manifest.
  647. if (toplevel_install) {
  648. /* clang-format off */
  649. fout <<
  650. "if(CMAKE_INSTALL_COMPONENT)\n"
  651. " set(CMAKE_INSTALL_MANIFEST \"install_manifest_"
  652. "${CMAKE_INSTALL_COMPONENT}.txt\")\n"
  653. "else()\n"
  654. " set(CMAKE_INSTALL_MANIFEST \"install_manifest.txt\")\n"
  655. "endif()\n"
  656. "\n"
  657. "string(REPLACE \";\" \"\\n\" CMAKE_INSTALL_MANIFEST_CONTENT\n"
  658. " \"${CMAKE_INSTALL_MANIFEST_FILES}\")\n"
  659. "file(WRITE \"" << homedir << "/${CMAKE_INSTALL_MANIFEST}\"\n"
  660. " \"${CMAKE_INSTALL_MANIFEST_CONTENT}\")\n";
  661. /* clang-format on */
  662. }
  663. }
  664. void cmLocalGenerator::AddGeneratorTarget(
  665. std::unique_ptr<cmGeneratorTarget> gt)
  666. {
  667. cmGeneratorTarget* gt_ptr = gt.get();
  668. this->GeneratorTargets.push_back(std::move(gt));
  669. this->GeneratorTargetSearchIndex.emplace(gt_ptr->GetName(), gt_ptr);
  670. this->GlobalGenerator->IndexGeneratorTarget(gt_ptr);
  671. }
  672. void cmLocalGenerator::AddImportedGeneratorTarget(cmGeneratorTarget* gt)
  673. {
  674. this->ImportedGeneratorTargets.emplace(gt->GetName(), gt);
  675. this->GlobalGenerator->IndexGeneratorTarget(gt);
  676. }
  677. void cmLocalGenerator::AddOwnedImportedGeneratorTarget(
  678. std::unique_ptr<cmGeneratorTarget> gt)
  679. {
  680. this->OwnedImportedGeneratorTargets.push_back(std::move(gt));
  681. }
  682. cmGeneratorTarget* cmLocalGenerator::FindLocalNonAliasGeneratorTarget(
  683. const std::string& name) const
  684. {
  685. auto ti = this->GeneratorTargetSearchIndex.find(name);
  686. if (ti != this->GeneratorTargetSearchIndex.end()) {
  687. return ti->second;
  688. }
  689. return nullptr;
  690. }
  691. void cmLocalGenerator::ComputeTargetManifest()
  692. {
  693. // Collect the set of configuration types.
  694. std::vector<std::string> configNames =
  695. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  696. // Add our targets to the manifest for each configuration.
  697. const auto& targets = this->GetGeneratorTargets();
  698. for (const auto& target : targets) {
  699. if (!target->IsInBuildSystem()) {
  700. continue;
  701. }
  702. for (std::string const& c : configNames) {
  703. target->ComputeTargetManifest(c);
  704. }
  705. }
  706. }
  707. bool cmLocalGenerator::ComputeTargetCompileFeatures()
  708. {
  709. // Collect the set of configuration types.
  710. std::vector<std::string> configNames =
  711. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  712. using LanguagePair = std::pair<std::string, std::string>;
  713. std::vector<LanguagePair> pairedLanguages{
  714. { "OBJC", "C" }, { "OBJCXX", "CXX" }, { "CUDA", "CXX" }, { "HIP", "CXX" }
  715. };
  716. std::set<LanguagePair> inferredEnabledLanguages;
  717. for (auto const& lang : pairedLanguages) {
  718. if (this->Makefile->GetState()->GetLanguageEnabled(lang.first)) {
  719. inferredEnabledLanguages.insert(lang);
  720. }
  721. }
  722. // Process compile features of all targets.
  723. const auto& targets = this->GetGeneratorTargets();
  724. for (const auto& target : targets) {
  725. for (std::string const& c : configNames) {
  726. if (!target->ComputeCompileFeatures(c)) {
  727. return false;
  728. }
  729. }
  730. // Now that C/C++ _STANDARD values have been computed
  731. // set the values to ObjC/ObjCXX _STANDARD variables
  732. if (target->CanCompileSources()) {
  733. for (std::string const& c : configNames) {
  734. target->ComputeCompileFeatures(c, inferredEnabledLanguages);
  735. }
  736. }
  737. }
  738. return true;
  739. }
  740. bool cmLocalGenerator::IsRootMakefile() const
  741. {
  742. return !this->StateSnapshot.GetBuildsystemDirectoryParent().IsValid();
  743. }
  744. cmState* cmLocalGenerator::GetState() const
  745. {
  746. return this->GlobalGenerator->GetCMakeInstance()->GetState();
  747. }
  748. cmStateSnapshot cmLocalGenerator::GetStateSnapshot() const
  749. {
  750. return this->Makefile->GetStateSnapshot();
  751. }
  752. std::string cmLocalGenerator::GetRuleLauncher(cmGeneratorTarget* target,
  753. const std::string& prop,
  754. const std::string& config)
  755. {
  756. cmValue value = this->Makefile->GetProperty(prop);
  757. if (target) {
  758. value = target->GetProperty(prop);
  759. }
  760. if (value) {
  761. return cmGeneratorExpression::Evaluate(*value, this, config, target);
  762. }
  763. return "";
  764. }
  765. std::string cmLocalGenerator::ConvertToIncludeReference(
  766. std::string const& path, OutputFormat format)
  767. {
  768. return this->ConvertToOutputForExisting(path, format);
  769. }
  770. std::string cmLocalGenerator::GetIncludeFlags(
  771. std::vector<std::string> const& includeDirs, cmGeneratorTarget* target,
  772. std::string const& lang, std::string const& config, bool forResponseFile)
  773. {
  774. if (lang.empty()) {
  775. return "";
  776. }
  777. std::vector<std::string> includes = includeDirs;
  778. MoveSystemIncludesToEnd(includes, config, lang, target);
  779. OutputFormat shellFormat = forResponseFile ? RESPONSE : SHELL;
  780. std::ostringstream includeFlags;
  781. std::string const& includeFlag =
  782. this->Makefile->GetSafeDefinition(cmStrCat("CMAKE_INCLUDE_FLAG_", lang));
  783. bool quotePaths = false;
  784. if (this->Makefile->GetDefinition("CMAKE_QUOTE_INCLUDE_PATHS")) {
  785. quotePaths = true;
  786. }
  787. std::string sep = " ";
  788. bool repeatFlag = true;
  789. // should the include flag be repeated like ie. -IA -IB
  790. if (cmValue incSep = this->Makefile->GetDefinition(
  791. cmStrCat("CMAKE_INCLUDE_FLAG_SEP_", lang))) {
  792. // if there is a separator then the flag is not repeated but is only
  793. // given once i.e. -classpath a:b:c
  794. sep = *incSep;
  795. repeatFlag = false;
  796. }
  797. // Support special system include flag if it is available and the
  798. // normal flag is repeated for each directory.
  799. cmValue sysIncludeFlag = nullptr;
  800. cmValue sysIncludeFlagWarning = nullptr;
  801. if (repeatFlag) {
  802. sysIncludeFlag = this->Makefile->GetDefinition(
  803. cmStrCat("CMAKE_INCLUDE_SYSTEM_FLAG_", lang));
  804. sysIncludeFlagWarning = this->Makefile->GetDefinition(
  805. cmStrCat("_CMAKE_INCLUDE_SYSTEM_FLAG_", lang, "_WARNING"));
  806. }
  807. cmValue fwSearchFlag = this->Makefile->GetDefinition(
  808. cmStrCat("CMAKE_", lang, "_FRAMEWORK_SEARCH_FLAG"));
  809. cmValue sysFwSearchFlag = this->Makefile->GetDefinition(
  810. cmStrCat("CMAKE_", lang, "_SYSTEM_FRAMEWORK_SEARCH_FLAG"));
  811. bool flagUsed = false;
  812. bool sysIncludeFlagUsed = false;
  813. std::set<std::string> emitted;
  814. #ifdef __APPLE__
  815. emitted.insert("/System/Library/Frameworks");
  816. #endif
  817. for (std::string const& i : includes) {
  818. if (cmNonempty(fwSearchFlag) && this->Makefile->IsOn("APPLE") &&
  819. cmSystemTools::IsPathToFramework(i)) {
  820. std::string const frameworkDir =
  821. cmSystemTools::CollapseFullPath(cmStrCat(i, "/../"));
  822. if (emitted.insert(frameworkDir).second) {
  823. if (sysFwSearchFlag && target &&
  824. target->IsSystemIncludeDirectory(frameworkDir, config, lang)) {
  825. includeFlags << *sysFwSearchFlag;
  826. } else {
  827. includeFlags << *fwSearchFlag;
  828. }
  829. includeFlags << this->ConvertToOutputFormat(frameworkDir, shellFormat)
  830. << " ";
  831. }
  832. continue;
  833. }
  834. if (!flagUsed || repeatFlag) {
  835. if (sysIncludeFlag && target &&
  836. target->IsSystemIncludeDirectory(i, config, lang)) {
  837. includeFlags << *sysIncludeFlag;
  838. sysIncludeFlagUsed = true;
  839. } else {
  840. includeFlags << includeFlag;
  841. }
  842. flagUsed = true;
  843. }
  844. std::string includePath = this->ConvertToIncludeReference(i, shellFormat);
  845. if (quotePaths && !includePath.empty() && includePath.front() != '\"') {
  846. includeFlags << "\"";
  847. }
  848. includeFlags << includePath;
  849. if (quotePaths && !includePath.empty() && includePath.front() != '\"') {
  850. includeFlags << "\"";
  851. }
  852. includeFlags << sep;
  853. }
  854. if (sysIncludeFlagUsed && sysIncludeFlagWarning) {
  855. includeFlags << *sysIncludeFlagWarning;
  856. }
  857. std::string flags = includeFlags.str();
  858. // remove trailing separators
  859. if ((sep[0] != ' ') && !flags.empty() && flags.back() == sep[0]) {
  860. flags.back() = ' ';
  861. }
  862. return cmTrimWhitespace(flags);
  863. }
  864. void cmLocalGenerator::AddCompileOptions(std::string& flags,
  865. cmGeneratorTarget* target,
  866. const std::string& lang,
  867. const std::string& config)
  868. {
  869. std::vector<BT<std::string>> tmpFlags;
  870. this->AddCompileOptions(tmpFlags, target, lang, config);
  871. this->AppendFlags(flags, tmpFlags);
  872. }
  873. void cmLocalGenerator::AddCompileOptions(std::vector<BT<std::string>>& flags,
  874. cmGeneratorTarget* target,
  875. const std::string& lang,
  876. const std::string& config)
  877. {
  878. std::string langFlagRegexVar = cmStrCat("CMAKE_", lang, "_FLAG_REGEX");
  879. if (cmValue langFlagRegexStr =
  880. this->Makefile->GetDefinition(langFlagRegexVar)) {
  881. // Filter flags acceptable to this language.
  882. if (cmValue targetFlags = target->GetProperty("COMPILE_FLAGS")) {
  883. std::vector<std::string> opts;
  884. cmSystemTools::ParseWindowsCommandLine(targetFlags->c_str(), opts);
  885. // Re-escape these flags since COMPILE_FLAGS were already parsed
  886. // as a command line above.
  887. std::string compileOpts;
  888. this->AppendCompileOptions(compileOpts, opts, langFlagRegexStr->c_str());
  889. if (!compileOpts.empty()) {
  890. flags.emplace_back(std::move(compileOpts));
  891. }
  892. }
  893. std::vector<BT<std::string>> targetCompileOpts =
  894. target->GetCompileOptions(config, lang);
  895. // COMPILE_OPTIONS are escaped.
  896. this->AppendCompileOptions(flags, targetCompileOpts,
  897. langFlagRegexStr->c_str());
  898. } else {
  899. // Use all flags.
  900. if (cmValue targetFlags = target->GetProperty("COMPILE_FLAGS")) {
  901. // COMPILE_FLAGS are not escaped for historical reasons.
  902. std::string compileFlags;
  903. this->AppendFlags(compileFlags, *targetFlags);
  904. if (!compileFlags.empty()) {
  905. flags.emplace_back(std::move(compileFlags));
  906. }
  907. }
  908. std::vector<BT<std::string>> targetCompileOpts =
  909. target->GetCompileOptions(config, lang);
  910. // COMPILE_OPTIONS are escaped.
  911. this->AppendCompileOptions(flags, targetCompileOpts);
  912. }
  913. cmStandardLevelResolver standardResolver(this->Makefile);
  914. for (auto const& it : target->GetMaxLanguageStandards()) {
  915. cmValue standard = target->GetLanguageStandard(it.first, config);
  916. if (!standard) {
  917. continue;
  918. }
  919. if (standardResolver.IsLaterStandard(it.first, *standard, it.second)) {
  920. std::ostringstream e;
  921. e << "The COMPILE_FEATURES property of target \"" << target->GetName()
  922. << "\" was evaluated when computing the link "
  923. "implementation, and the \""
  924. << it.first << "_STANDARD\" was \"" << it.second
  925. << "\" for that computation. Computing the "
  926. "COMPILE_FEATURES based on the link implementation resulted in a "
  927. "higher \""
  928. << it.first << "_STANDARD\" \"" << *standard
  929. << "\". "
  930. "This is not permitted. The COMPILE_FEATURES may not both depend "
  931. "on "
  932. "and be depended on by the link implementation.\n";
  933. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  934. return;
  935. }
  936. }
  937. // Add Warning as errors flags
  938. if (!this->GetCMakeInstance()->GetIgnoreWarningAsError()) {
  939. const cmValue wError = target->GetProperty("COMPILE_WARNING_AS_ERROR");
  940. const cmValue wErrorOpts = this->Makefile->GetDefinition(
  941. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_WARNING_AS_ERROR"));
  942. if (wError.IsOn() && wErrorOpts.IsSet()) {
  943. std::string wErrorFlags;
  944. this->AppendCompileOptions(wErrorFlags, *wErrorOpts);
  945. if (!wErrorFlags.empty()) {
  946. flags.emplace_back(std::move(wErrorFlags));
  947. }
  948. }
  949. }
  950. // Add compile flag for the MSVC compiler only.
  951. cmMakefile* mf = this->GetMakefile();
  952. if (cmValue jmc =
  953. mf->GetDefinition("CMAKE_" + lang + "_COMPILE_OPTIONS_JMC")) {
  954. // Handle Just My Code debugging flags, /JMC.
  955. // If the target is a Managed C++ one, /JMC is not compatible.
  956. if (target->GetManagedType(config) !=
  957. cmGeneratorTarget::ManagedType::Managed) {
  958. // add /JMC flags if target property VS_JUST_MY_CODE_DEBUGGING is set
  959. // to ON
  960. if (cmValue jmcExprGen =
  961. target->GetProperty("VS_JUST_MY_CODE_DEBUGGING")) {
  962. std::string isJMCEnabled =
  963. cmGeneratorExpression::Evaluate(*jmcExprGen, this, config);
  964. if (cmIsOn(isJMCEnabled)) {
  965. cmList optList{ *jmc };
  966. std::string jmcFlags;
  967. this->AppendCompileOptions(jmcFlags, optList);
  968. if (!jmcFlags.empty()) {
  969. flags.emplace_back(std::move(jmcFlags));
  970. }
  971. }
  972. }
  973. }
  974. }
  975. }
  976. cmTarget* cmLocalGenerator::AddCustomCommandToTarget(
  977. const std::string& target, cmCustomCommandType type,
  978. std::unique_ptr<cmCustomCommand> cc, cmObjectLibraryCommands objLibCommands)
  979. {
  980. cmTarget* t = this->Makefile->GetCustomCommandTarget(
  981. target, objLibCommands, this->DirectoryBacktrace);
  982. if (!t) {
  983. return nullptr;
  984. }
  985. cc->SetBacktrace(this->DirectoryBacktrace);
  986. detail::AddCustomCommandToTarget(*this, cmCommandOrigin::Generator, t, type,
  987. std::move(cc));
  988. return t;
  989. }
  990. cmSourceFile* cmLocalGenerator::AddCustomCommandToOutput(
  991. std::unique_ptr<cmCustomCommand> cc, bool replace)
  992. {
  993. // Make sure there is at least one output.
  994. if (cc->GetOutputs().empty()) {
  995. cmSystemTools::Error("Attempt to add a custom rule with no output!");
  996. return nullptr;
  997. }
  998. cc->SetBacktrace(this->DirectoryBacktrace);
  999. return detail::AddCustomCommandToOutput(*this, cmCommandOrigin::Generator,
  1000. std::move(cc), replace);
  1001. }
  1002. cmTarget* cmLocalGenerator::AddUtilityCommand(
  1003. const std::string& utilityName, bool excludeFromAll,
  1004. std::unique_ptr<cmCustomCommand> cc)
  1005. {
  1006. cmTarget* target =
  1007. this->Makefile->AddNewUtilityTarget(utilityName, excludeFromAll);
  1008. target->SetIsGeneratorProvided(true);
  1009. if (cc->GetCommandLines().empty() && cc->GetDepends().empty()) {
  1010. return target;
  1011. }
  1012. cc->SetBacktrace(this->DirectoryBacktrace);
  1013. detail::AddUtilityCommand(*this, cmCommandOrigin::Generator, target,
  1014. std::move(cc));
  1015. return target;
  1016. }
  1017. std::vector<BT<std::string>> cmLocalGenerator::GetIncludeDirectoriesImplicit(
  1018. cmGeneratorTarget const* target, std::string const& lang,
  1019. std::string const& config, bool stripImplicitDirs,
  1020. bool appendAllImplicitDirs) const
  1021. {
  1022. std::vector<BT<std::string>> result;
  1023. // Do not repeat an include path.
  1024. std::set<std::string> emitted;
  1025. auto emitDir = [&result, &emitted](std::string const& dir) {
  1026. if (emitted.insert(dir).second) {
  1027. result.emplace_back(dir);
  1028. }
  1029. };
  1030. auto emitBT = [&result, &emitted](BT<std::string> const& dir) {
  1031. if (emitted.insert(dir.Value).second) {
  1032. result.emplace_back(dir);
  1033. }
  1034. };
  1035. // When automatic include directories are requested for a build then
  1036. // include the source and binary directories at the beginning of the
  1037. // include path to approximate include file behavior for an
  1038. // in-source build. This does not account for the case of a source
  1039. // file in a subdirectory of the current source directory but we
  1040. // cannot fix this because not all native build tools support
  1041. // per-source-file include paths.
  1042. if (this->Makefile->IsOn("CMAKE_INCLUDE_CURRENT_DIR")) {
  1043. // Current binary directory
  1044. emitDir(this->StateSnapshot.GetDirectory().GetCurrentBinary());
  1045. // Current source directory
  1046. emitDir(this->StateSnapshot.GetDirectory().GetCurrentSource());
  1047. }
  1048. if (!target) {
  1049. return result;
  1050. }
  1051. // Standard include directories to be added unconditionally at the end.
  1052. // These are intended to simulate additional implicit include directories.
  1053. cmList userStandardDirs;
  1054. {
  1055. std::string const value = this->Makefile->GetSafeDefinition(
  1056. cmStrCat("CMAKE_", lang, "_STANDARD_INCLUDE_DIRECTORIES"));
  1057. userStandardDirs.assign(value);
  1058. for (std::string& usd : userStandardDirs) {
  1059. cmSystemTools::ConvertToUnixSlashes(usd);
  1060. }
  1061. }
  1062. // Implicit include directories
  1063. std::vector<std::string> implicitDirs;
  1064. std::set<std::string> implicitSet;
  1065. // Include directories to be excluded as if they were implicit.
  1066. std::set<std::string> implicitExclude;
  1067. {
  1068. // Raw list of implicit include directories
  1069. // Start with "standard" directories that we unconditionally add below.
  1070. std::vector<std::string> impDirVec = userStandardDirs;
  1071. // Load implicit include directories for this language.
  1072. // We ignore this for Fortran because:
  1073. // * There are no standard library headers to avoid overriding.
  1074. // * Compilers like gfortran do not search their own implicit include
  1075. // directories for modules ('.mod' files).
  1076. if (lang != "Fortran") {
  1077. size_t const impDirVecOldSize = impDirVec.size();
  1078. cmList::append(impDirVec,
  1079. this->Makefile->GetDefinition(cmStrCat(
  1080. "CMAKE_", lang, "_IMPLICIT_INCLUDE_DIRECTORIES")));
  1081. // FIXME: Use cmRange with 'advance()' when it supports non-const.
  1082. for (size_t i = impDirVecOldSize; i < impDirVec.size(); ++i) {
  1083. cmSystemTools::ConvertToUnixSlashes(impDirVec[i]);
  1084. }
  1085. // The CMAKE_<LANG>_IMPLICIT_INCLUDE_DIRECTORIES are computed using
  1086. // try_compile in CMAKE_DETERMINE_COMPILER_ABI, but the implicit include
  1087. // directories are not known during that try_compile. This can be a
  1088. // problem when the HIP runtime include path is /usr/include because the
  1089. // runtime include path is always added to the userDirs and the compiler
  1090. // includes standard library headers via "__clang_hip_runtime_wrapper.h".
  1091. if (lang == "HIP" && impDirVec.size() == impDirVecOldSize &&
  1092. !cm::contains(impDirVec, "/usr/include")) {
  1093. implicitExclude.emplace("/usr/include");
  1094. }
  1095. }
  1096. // The Platform/UnixPaths module used to hard-code /usr/include for C, CXX,
  1097. // and CUDA in CMAKE_<LANG>_IMPLICIT_INCLUDE_DIRECTORIES, but those
  1098. // variables are now computed. On macOS the /usr/include directory is
  1099. // inside the platform SDK so the computed value does not contain it
  1100. // directly. In this case adding -I/usr/include can hide SDK headers so we
  1101. // must still exclude it.
  1102. if ((lang == "C" || lang == "CXX" || lang == "CUDA") &&
  1103. !cm::contains(impDirVec, "/usr/include") &&
  1104. std::find_if(impDirVec.begin(), impDirVec.end(),
  1105. [](std::string const& d) {
  1106. return cmHasLiteralSuffix(d, "/usr/include");
  1107. }) != impDirVec.end()) {
  1108. // Only exclude this hard coded path for backwards compatibility.
  1109. implicitExclude.emplace("/usr/include");
  1110. }
  1111. for (std::string const& i : impDirVec) {
  1112. if (implicitSet.insert(this->GlobalGenerator->GetRealPath(i)).second) {
  1113. implicitDirs.emplace_back(i);
  1114. }
  1115. }
  1116. }
  1117. bool const isCorCxx = (lang == "C" || lang == "CXX");
  1118. // Resolve symlinks in CPATH for comparison with resolved include paths.
  1119. // We do this here instead of when EnvCPATH is populated in case symlinks
  1120. // on disk have changed in the meantime.
  1121. std::set<std::string> resolvedEnvCPATH;
  1122. if (isCorCxx) {
  1123. for (std::string const& i : this->EnvCPATH) {
  1124. resolvedEnvCPATH.emplace(this->GlobalGenerator->GetRealPath(i));
  1125. }
  1126. }
  1127. // Checks if this is not an excluded (implicit) include directory.
  1128. auto notExcluded = [this, &implicitSet, &implicitExclude, &resolvedEnvCPATH,
  1129. isCorCxx](std::string const& dir) -> bool {
  1130. std::string const& real_dir = this->GlobalGenerator->GetRealPath(dir);
  1131. return
  1132. // Do not exclude directories that are not in any excluded set.
  1133. !(cm::contains(implicitSet, real_dir) ||
  1134. cm::contains(implicitExclude, dir))
  1135. // Do not exclude entries of the CPATH environment variable even though
  1136. // they are implicitly searched by the compiler. They are meant to be
  1137. // user-specified directories that can be re-ordered or converted to
  1138. // -isystem without breaking real compiler builtin headers.
  1139. || (isCorCxx && cm::contains(resolvedEnvCPATH, real_dir));
  1140. };
  1141. // Get the target-specific include directories.
  1142. std::vector<BT<std::string>> userDirs =
  1143. target->GetIncludeDirectories(config, lang);
  1144. // Support putting all the in-project include directories first if
  1145. // it is requested by the project.
  1146. if (this->Makefile->IsOn("CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE")) {
  1147. std::string const& topSourceDir = this->GetState()->GetSourceDirectory();
  1148. std::string const& topBinaryDir = this->GetState()->GetBinaryDirectory();
  1149. for (BT<std::string> const& udr : userDirs) {
  1150. // Emit this directory only if it is a subdirectory of the
  1151. // top-level source or binary tree.
  1152. if (cmSystemTools::ComparePath(udr.Value, topSourceDir) ||
  1153. cmSystemTools::ComparePath(udr.Value, topBinaryDir) ||
  1154. cmSystemTools::IsSubDirectory(udr.Value, topSourceDir) ||
  1155. cmSystemTools::IsSubDirectory(udr.Value, topBinaryDir)) {
  1156. if (notExcluded(udr.Value)) {
  1157. emitBT(udr);
  1158. }
  1159. }
  1160. }
  1161. }
  1162. // Emit remaining non implicit user directories.
  1163. for (BT<std::string> const& udr : userDirs) {
  1164. if (notExcluded(udr.Value)) {
  1165. emitBT(udr);
  1166. }
  1167. }
  1168. // Sort result
  1169. MoveSystemIncludesToEnd(result, config, lang, target);
  1170. // Append standard include directories for this language.
  1171. userDirs.reserve(userDirs.size() + userStandardDirs.size());
  1172. for (std::string& usd : userStandardDirs) {
  1173. emitDir(usd);
  1174. userDirs.emplace_back(std::move(usd));
  1175. }
  1176. // Append compiler implicit include directories
  1177. if (!stripImplicitDirs) {
  1178. // Append implicit directories that were requested by the user only
  1179. for (BT<std::string> const& udr : userDirs) {
  1180. if (cm::contains(implicitSet, cmSystemTools::GetRealPath(udr.Value))) {
  1181. emitBT(udr);
  1182. }
  1183. }
  1184. // Append remaining implicit directories (on demand)
  1185. if (appendAllImplicitDirs) {
  1186. for (std::string& imd : implicitDirs) {
  1187. emitDir(imd);
  1188. }
  1189. }
  1190. }
  1191. return result;
  1192. }
  1193. void cmLocalGenerator::GetIncludeDirectoriesImplicit(
  1194. std::vector<std::string>& dirs, cmGeneratorTarget const* target,
  1195. const std::string& lang, const std::string& config, bool stripImplicitDirs,
  1196. bool appendAllImplicitDirs) const
  1197. {
  1198. std::vector<BT<std::string>> tmp = this->GetIncludeDirectoriesImplicit(
  1199. target, lang, config, stripImplicitDirs, appendAllImplicitDirs);
  1200. dirs.reserve(dirs.size() + tmp.size());
  1201. for (BT<std::string>& v : tmp) {
  1202. dirs.emplace_back(std::move(v.Value));
  1203. }
  1204. }
  1205. std::vector<BT<std::string>> cmLocalGenerator::GetIncludeDirectories(
  1206. cmGeneratorTarget const* target, std::string const& lang,
  1207. std::string const& config) const
  1208. {
  1209. return this->GetIncludeDirectoriesImplicit(target, lang, config);
  1210. }
  1211. void cmLocalGenerator::GetIncludeDirectories(std::vector<std::string>& dirs,
  1212. cmGeneratorTarget const* target,
  1213. const std::string& lang,
  1214. const std::string& config) const
  1215. {
  1216. this->GetIncludeDirectoriesImplicit(dirs, target, lang, config);
  1217. }
  1218. void cmLocalGenerator::GetStaticLibraryFlags(std::string& flags,
  1219. std::string const& config,
  1220. std::string const& linkLanguage,
  1221. cmGeneratorTarget* target)
  1222. {
  1223. std::vector<BT<std::string>> tmpFlags =
  1224. this->GetStaticLibraryFlags(config, linkLanguage, target);
  1225. this->AppendFlags(flags, tmpFlags);
  1226. }
  1227. std::vector<BT<std::string>> cmLocalGenerator::GetStaticLibraryFlags(
  1228. std::string const& config, std::string const& linkLanguage,
  1229. cmGeneratorTarget* target)
  1230. {
  1231. const std::string configUpper = cmSystemTools::UpperCase(config);
  1232. std::vector<BT<std::string>> flags;
  1233. if (linkLanguage != "Swift") {
  1234. std::string staticLibFlags;
  1235. this->AppendFlags(
  1236. staticLibFlags,
  1237. this->Makefile->GetSafeDefinition("CMAKE_STATIC_LINKER_FLAGS"));
  1238. if (!configUpper.empty()) {
  1239. std::string name = "CMAKE_STATIC_LINKER_FLAGS_" + configUpper;
  1240. this->AppendFlags(staticLibFlags,
  1241. this->Makefile->GetSafeDefinition(name));
  1242. }
  1243. if (!staticLibFlags.empty()) {
  1244. flags.emplace_back(std::move(staticLibFlags));
  1245. }
  1246. }
  1247. std::string staticLibFlags;
  1248. this->AppendFlags(staticLibFlags,
  1249. target->GetSafeProperty("STATIC_LIBRARY_FLAGS"));
  1250. if (!configUpper.empty()) {
  1251. std::string name = "STATIC_LIBRARY_FLAGS_" + configUpper;
  1252. this->AppendFlags(staticLibFlags, target->GetSafeProperty(name));
  1253. }
  1254. if (!staticLibFlags.empty()) {
  1255. flags.emplace_back(std::move(staticLibFlags));
  1256. }
  1257. std::vector<BT<std::string>> staticLibOpts =
  1258. target->GetStaticLibraryLinkOptions(config, linkLanguage);
  1259. // STATIC_LIBRARY_OPTIONS are escaped.
  1260. this->AppendCompileOptions(flags, staticLibOpts);
  1261. return flags;
  1262. }
  1263. void cmLocalGenerator::GetDeviceLinkFlags(
  1264. cmLinkLineDeviceComputer& linkLineComputer, const std::string& config,
  1265. std::string& linkLibs, std::string& linkFlags, std::string& frameworkPath,
  1266. std::string& linkPath, cmGeneratorTarget* target)
  1267. {
  1268. cmGeneratorTarget::DeviceLinkSetter setter(*target);
  1269. cmComputeLinkInformation* pcli = target->GetLinkInformation(config);
  1270. auto linklang = linkLineComputer.GetLinkerLanguage(target, config);
  1271. auto ipoEnabled = target->IsIPOEnabled(linklang, config);
  1272. if (!ipoEnabled) {
  1273. ipoEnabled = linkLineComputer.ComputeRequiresDeviceLinkingIPOFlag(*pcli);
  1274. }
  1275. if (ipoEnabled) {
  1276. if (cmValue cudaIPOFlags = this->Makefile->GetDefinition(
  1277. "CMAKE_CUDA_DEVICE_LINK_OPTIONS_IPO")) {
  1278. linkFlags += *cudaIPOFlags;
  1279. }
  1280. }
  1281. if (pcli) {
  1282. // Compute the required device link libraries when
  1283. // resolving gpu lang device symbols
  1284. this->OutputLinkLibraries(pcli, &linkLineComputer, linkLibs, frameworkPath,
  1285. linkPath);
  1286. }
  1287. this->AddVisibilityPresetFlags(linkFlags, target, "CUDA");
  1288. this->GetGlobalGenerator()->EncodeLiteral(linkFlags);
  1289. std::vector<std::string> linkOpts;
  1290. target->GetLinkOptions(linkOpts, config, "CUDA");
  1291. this->SetLinkScriptShell(this->GetGlobalGenerator()->GetUseLinkScript());
  1292. // LINK_OPTIONS are escaped.
  1293. this->AppendCompileOptions(linkFlags, linkOpts);
  1294. this->SetLinkScriptShell(false);
  1295. }
  1296. void cmLocalGenerator::GetTargetFlags(
  1297. cmLinkLineComputer* linkLineComputer, const std::string& config,
  1298. std::string& linkLibs, std::string& flags, std::string& linkFlags,
  1299. std::string& frameworkPath, std::string& linkPath, cmGeneratorTarget* target)
  1300. {
  1301. std::vector<BT<std::string>> linkFlagsList;
  1302. std::vector<BT<std::string>> linkPathList;
  1303. std::vector<BT<std::string>> linkLibsList;
  1304. this->GetTargetFlags(linkLineComputer, config, linkLibsList, flags,
  1305. linkFlagsList, frameworkPath, linkPathList, target);
  1306. this->AppendFlags(linkFlags, linkFlagsList);
  1307. this->AppendFlags(linkPath, linkPathList);
  1308. this->AppendFlags(linkLibs, linkLibsList);
  1309. }
  1310. void cmLocalGenerator::GetTargetFlags(
  1311. cmLinkLineComputer* linkLineComputer, const std::string& config,
  1312. std::vector<BT<std::string>>& linkLibs, std::string& flags,
  1313. std::vector<BT<std::string>>& linkFlags, std::string& frameworkPath,
  1314. std::vector<BT<std::string>>& linkPath, cmGeneratorTarget* target)
  1315. {
  1316. const std::string configUpper = cmSystemTools::UpperCase(config);
  1317. cmComputeLinkInformation* pcli = target->GetLinkInformation(config);
  1318. const char* libraryLinkVariable =
  1319. "CMAKE_SHARED_LINKER_FLAGS"; // default to shared library
  1320. const std::string linkLanguage =
  1321. linkLineComputer->GetLinkerLanguage(target, config);
  1322. switch (target->GetType()) {
  1323. case cmStateEnums::STATIC_LIBRARY:
  1324. linkFlags = this->GetStaticLibraryFlags(config, linkLanguage, target);
  1325. break;
  1326. case cmStateEnums::MODULE_LIBRARY:
  1327. libraryLinkVariable = "CMAKE_MODULE_LINKER_FLAGS";
  1328. CM_FALLTHROUGH;
  1329. case cmStateEnums::SHARED_LIBRARY: {
  1330. std::string sharedLibFlags;
  1331. if (linkLanguage != "Swift") {
  1332. sharedLibFlags = cmStrCat(
  1333. this->Makefile->GetSafeDefinition(libraryLinkVariable), ' ');
  1334. if (!configUpper.empty()) {
  1335. std::string build = cmStrCat(libraryLinkVariable, '_', configUpper);
  1336. sharedLibFlags += this->Makefile->GetSafeDefinition(build);
  1337. sharedLibFlags += " ";
  1338. }
  1339. }
  1340. cmValue targetLinkFlags = target->GetProperty("LINK_FLAGS");
  1341. if (targetLinkFlags) {
  1342. sharedLibFlags += *targetLinkFlags;
  1343. sharedLibFlags += " ";
  1344. }
  1345. if (!configUpper.empty()) {
  1346. targetLinkFlags =
  1347. target->GetProperty(cmStrCat("LINK_FLAGS_", configUpper));
  1348. if (targetLinkFlags) {
  1349. sharedLibFlags += *targetLinkFlags;
  1350. sharedLibFlags += " ";
  1351. }
  1352. }
  1353. if (!sharedLibFlags.empty()) {
  1354. this->GetGlobalGenerator()->EncodeLiteral(sharedLibFlags);
  1355. linkFlags.emplace_back(std::move(sharedLibFlags));
  1356. }
  1357. std::vector<BT<std::string>> linkOpts =
  1358. target->GetLinkOptions(config, linkLanguage);
  1359. this->SetLinkScriptShell(this->GetGlobalGenerator()->GetUseLinkScript());
  1360. // LINK_OPTIONS are escaped.
  1361. this->AppendCompileOptions(linkFlags, linkOpts);
  1362. this->SetLinkScriptShell(false);
  1363. if (pcli) {
  1364. this->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
  1365. frameworkPath, linkPath);
  1366. }
  1367. } break;
  1368. case cmStateEnums::EXECUTABLE: {
  1369. std::string exeFlags;
  1370. if (linkLanguage != "Swift") {
  1371. exeFlags = this->Makefile->GetSafeDefinition("CMAKE_EXE_LINKER_FLAGS");
  1372. exeFlags += " ";
  1373. if (!configUpper.empty()) {
  1374. exeFlags += this->Makefile->GetSafeDefinition(
  1375. cmStrCat("CMAKE_EXE_LINKER_FLAGS_", configUpper));
  1376. exeFlags += " ";
  1377. }
  1378. if (linkLanguage.empty()) {
  1379. cmSystemTools::Error(
  1380. "CMake can not determine linker language for target: " +
  1381. target->GetName());
  1382. return;
  1383. }
  1384. if (target->IsWin32Executable(config)) {
  1385. exeFlags += this->Makefile->GetSafeDefinition(
  1386. cmStrCat("CMAKE_", linkLanguage, "_CREATE_WIN32_EXE"));
  1387. exeFlags += " ";
  1388. } else {
  1389. exeFlags += this->Makefile->GetSafeDefinition(
  1390. cmStrCat("CMAKE_", linkLanguage, "_CREATE_CONSOLE_EXE"));
  1391. exeFlags += " ";
  1392. }
  1393. if (target->IsExecutableWithExports()) {
  1394. exeFlags += this->Makefile->GetSafeDefinition(
  1395. cmStrCat("CMAKE_EXE_EXPORTS_", linkLanguage, "_FLAG"));
  1396. exeFlags += " ";
  1397. }
  1398. }
  1399. this->AddLanguageFlagsForLinking(flags, target, linkLanguage, config);
  1400. if (pcli) {
  1401. this->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
  1402. frameworkPath, linkPath);
  1403. }
  1404. if (this->Makefile->IsOn("BUILD_SHARED_LIBS")) {
  1405. std::string sFlagVar = "CMAKE_SHARED_BUILD_" + linkLanguage + "_FLAGS";
  1406. exeFlags += this->Makefile->GetSafeDefinition(sFlagVar);
  1407. exeFlags += " ";
  1408. }
  1409. std::string cmp0065Flags =
  1410. this->GetLinkLibsCMP0065(linkLanguage, *target);
  1411. if (!cmp0065Flags.empty()) {
  1412. exeFlags += cmp0065Flags;
  1413. exeFlags += " ";
  1414. }
  1415. cmValue targetLinkFlags = target->GetProperty("LINK_FLAGS");
  1416. if (targetLinkFlags) {
  1417. exeFlags += *targetLinkFlags;
  1418. exeFlags += " ";
  1419. }
  1420. if (!configUpper.empty()) {
  1421. targetLinkFlags =
  1422. target->GetProperty(cmStrCat("LINK_FLAGS_", configUpper));
  1423. if (targetLinkFlags) {
  1424. exeFlags += *targetLinkFlags;
  1425. exeFlags += " ";
  1426. }
  1427. }
  1428. if (!exeFlags.empty()) {
  1429. this->GetGlobalGenerator()->EncodeLiteral(exeFlags);
  1430. linkFlags.emplace_back(std::move(exeFlags));
  1431. }
  1432. std::vector<BT<std::string>> linkOpts =
  1433. target->GetLinkOptions(config, linkLanguage);
  1434. this->SetLinkScriptShell(this->GetGlobalGenerator()->GetUseLinkScript());
  1435. // LINK_OPTIONS are escaped.
  1436. this->AppendCompileOptions(linkFlags, linkOpts);
  1437. this->SetLinkScriptShell(false);
  1438. } break;
  1439. default:
  1440. break;
  1441. }
  1442. std::string extraLinkFlags;
  1443. this->AppendPositionIndependentLinkerFlags(extraLinkFlags, target, config,
  1444. linkLanguage);
  1445. this->AppendIPOLinkerFlags(extraLinkFlags, target, config, linkLanguage);
  1446. this->AppendDependencyInfoLinkerFlags(extraLinkFlags, target, config,
  1447. linkLanguage);
  1448. this->AppendModuleDefinitionFlag(extraLinkFlags, target, linkLineComputer,
  1449. config);
  1450. if (!extraLinkFlags.empty()) {
  1451. this->GetGlobalGenerator()->EncodeLiteral(extraLinkFlags);
  1452. linkFlags.emplace_back(std::move(extraLinkFlags));
  1453. }
  1454. }
  1455. void cmLocalGenerator::GetTargetCompileFlags(cmGeneratorTarget* target,
  1456. std::string const& config,
  1457. std::string const& lang,
  1458. std::string& flags,
  1459. std::string const& arch)
  1460. {
  1461. std::vector<BT<std::string>> tmpFlags =
  1462. this->GetTargetCompileFlags(target, config, lang, arch);
  1463. this->AppendFlags(flags, tmpFlags);
  1464. }
  1465. std::vector<BT<std::string>> cmLocalGenerator::GetTargetCompileFlags(
  1466. cmGeneratorTarget* target, std::string const& config,
  1467. std::string const& lang, std::string const& arch)
  1468. {
  1469. std::vector<BT<std::string>> flags;
  1470. std::string compileFlags;
  1471. cmMakefile* mf = this->GetMakefile();
  1472. // Add language-specific flags.
  1473. this->AddLanguageFlags(compileFlags, target, cmBuildStep::Compile, lang,
  1474. config);
  1475. if (target->IsIPOEnabled(lang, config)) {
  1476. this->AppendFeatureOptions(compileFlags, lang, "IPO");
  1477. }
  1478. this->AddArchitectureFlags(compileFlags, target, lang, config, arch);
  1479. if (lang == "Fortran") {
  1480. this->AppendFlags(compileFlags,
  1481. this->GetTargetFortranFlags(target, config));
  1482. }
  1483. this->AddCMP0018Flags(compileFlags, target, lang, config);
  1484. this->AddVisibilityPresetFlags(compileFlags, target, lang);
  1485. this->AddColorDiagnosticsFlags(compileFlags, lang);
  1486. this->AppendFlags(compileFlags, mf->GetDefineFlags());
  1487. this->AppendFlags(compileFlags,
  1488. this->GetFrameworkFlags(lang, config, target));
  1489. this->AppendFlags(compileFlags,
  1490. this->GetXcFrameworkFlags(lang, config, target));
  1491. if (!compileFlags.empty()) {
  1492. flags.emplace_back(std::move(compileFlags));
  1493. }
  1494. this->AddCompileOptions(flags, target, lang, config);
  1495. return flags;
  1496. }
  1497. std::string cmLocalGenerator::GetFrameworkFlags(std::string const& lang,
  1498. std::string const& config,
  1499. cmGeneratorTarget* target)
  1500. {
  1501. cmLocalGenerator* lg = target->GetLocalGenerator();
  1502. cmMakefile* mf = lg->GetMakefile();
  1503. if (!target->IsApple()) {
  1504. return std::string();
  1505. }
  1506. cmValue fwSearchFlag =
  1507. mf->GetDefinition(cmStrCat("CMAKE_", lang, "_FRAMEWORK_SEARCH_FLAG"));
  1508. cmValue sysFwSearchFlag = mf->GetDefinition(
  1509. cmStrCat("CMAKE_", lang, "_SYSTEM_FRAMEWORK_SEARCH_FLAG"));
  1510. if (!fwSearchFlag && !sysFwSearchFlag) {
  1511. return std::string{};
  1512. }
  1513. std::set<std::string> emitted;
  1514. #ifdef __APPLE__ /* don't insert this when crosscompiling e.g. to iphone */
  1515. emitted.insert("/System/Library/Frameworks");
  1516. #endif
  1517. std::vector<std::string> includes;
  1518. lg->GetIncludeDirectories(includes, target, "C", config);
  1519. // check all include directories for frameworks as this
  1520. // will already have added a -F for the framework
  1521. for (std::string const& include : includes) {
  1522. if (lg->GetGlobalGenerator()->NameResolvesToFramework(include)) {
  1523. std::string frameworkDir = cmStrCat(include, "/../");
  1524. frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir);
  1525. emitted.insert(frameworkDir);
  1526. }
  1527. }
  1528. std::string flags;
  1529. if (cmComputeLinkInformation* cli = target->GetLinkInformation(config)) {
  1530. std::vector<std::string> const& frameworks = cli->GetFrameworkPaths();
  1531. for (std::string const& framework : frameworks) {
  1532. if (emitted.insert(framework).second) {
  1533. if (sysFwSearchFlag &&
  1534. target->IsSystemIncludeDirectory(framework, config, lang)) {
  1535. flags += *sysFwSearchFlag;
  1536. } else {
  1537. flags += *fwSearchFlag;
  1538. }
  1539. flags +=
  1540. lg->ConvertToOutputFormat(framework, cmOutputConverter::SHELL);
  1541. flags += " ";
  1542. }
  1543. }
  1544. }
  1545. return flags;
  1546. }
  1547. std::string cmLocalGenerator::GetXcFrameworkFlags(std::string const& lang,
  1548. std::string const& config,
  1549. cmGeneratorTarget* target)
  1550. {
  1551. cmLocalGenerator* lg = target->GetLocalGenerator();
  1552. cmMakefile* mf = lg->GetMakefile();
  1553. if (!target->IsApple()) {
  1554. return std::string();
  1555. }
  1556. cmValue includeSearchFlag =
  1557. mf->GetDefinition(cmStrCat("CMAKE_INCLUDE_FLAG_", lang));
  1558. cmValue sysIncludeSearchFlag =
  1559. mf->GetDefinition(cmStrCat("CMAKE_INCLUDE_SYSTEM_FLAG_", lang));
  1560. if (!includeSearchFlag && !sysIncludeSearchFlag) {
  1561. return std::string{};
  1562. }
  1563. std::string flags;
  1564. if (cmComputeLinkInformation* cli = target->GetLinkInformation(config)) {
  1565. std::vector<std::string> const& paths = cli->GetXcFrameworkHeaderPaths();
  1566. for (std::string const& path : paths) {
  1567. if (sysIncludeSearchFlag &&
  1568. target->IsSystemIncludeDirectory(path, config, lang)) {
  1569. flags += *sysIncludeSearchFlag;
  1570. } else {
  1571. flags += *includeSearchFlag;
  1572. }
  1573. flags += lg->ConvertToOutputFormat(path, cmOutputConverter::SHELL);
  1574. flags += " ";
  1575. }
  1576. }
  1577. return flags;
  1578. }
  1579. void cmLocalGenerator::GetTargetDefines(cmGeneratorTarget const* target,
  1580. std::string const& config,
  1581. std::string const& lang,
  1582. std::set<std::string>& defines) const
  1583. {
  1584. std::set<BT<std::string>> tmp = this->GetTargetDefines(target, config, lang);
  1585. for (BT<std::string> const& v : tmp) {
  1586. defines.emplace(v.Value);
  1587. }
  1588. }
  1589. std::set<BT<std::string>> cmLocalGenerator::GetTargetDefines(
  1590. cmGeneratorTarget const* target, std::string const& config,
  1591. std::string const& lang) const
  1592. {
  1593. std::set<BT<std::string>> defines;
  1594. // Add the export symbol definition for shared library objects.
  1595. if (const std::string* exportMacro = target->GetExportMacro()) {
  1596. this->AppendDefines(defines, *exportMacro);
  1597. }
  1598. // Add preprocessor definitions for this target and configuration.
  1599. std::vector<BT<std::string>> targetDefines =
  1600. target->GetCompileDefinitions(config, lang);
  1601. this->AppendDefines(defines, targetDefines);
  1602. return defines;
  1603. }
  1604. std::string cmLocalGenerator::GetTargetFortranFlags(
  1605. cmGeneratorTarget const* /*unused*/, std::string const& /*unused*/)
  1606. {
  1607. // Implemented by specific generators that override this.
  1608. return std::string();
  1609. }
  1610. /**
  1611. * Output the linking rules on a command line. For executables,
  1612. * targetLibrary should be a NULL pointer. For libraries, it should point
  1613. * to the name of the library. This will not link a library against itself.
  1614. */
  1615. void cmLocalGenerator::OutputLinkLibraries(
  1616. cmComputeLinkInformation* pcli, cmLinkLineComputer* linkLineComputer,
  1617. std::string& linkLibraries, std::string& frameworkPath,
  1618. std::string& linkPath)
  1619. {
  1620. std::vector<BT<std::string>> linkLibrariesList;
  1621. std::vector<BT<std::string>> linkPathList;
  1622. this->OutputLinkLibraries(pcli, linkLineComputer, linkLibrariesList,
  1623. frameworkPath, linkPathList);
  1624. pcli->AppendValues(linkLibraries, linkLibrariesList);
  1625. pcli->AppendValues(linkPath, linkPathList);
  1626. }
  1627. void cmLocalGenerator::OutputLinkLibraries(
  1628. cmComputeLinkInformation* pcli, cmLinkLineComputer* linkLineComputer,
  1629. std::vector<BT<std::string>>& linkLibraries, std::string& frameworkPath,
  1630. std::vector<BT<std::string>>& linkPath)
  1631. {
  1632. cmComputeLinkInformation& cli = *pcli;
  1633. std::string linkLanguage = cli.GetLinkLanguage();
  1634. std::string libPathFlag;
  1635. if (cmValue value = this->Makefile->GetDefinition(
  1636. "CMAKE_" + cli.GetLinkLanguage() + "_LIBRARY_PATH_FLAG")) {
  1637. libPathFlag = *value;
  1638. } else {
  1639. libPathFlag =
  1640. this->Makefile->GetRequiredDefinition("CMAKE_LIBRARY_PATH_FLAG");
  1641. }
  1642. std::string libPathTerminator;
  1643. if (cmValue value = this->Makefile->GetDefinition(
  1644. "CMAKE_" + cli.GetLinkLanguage() + "_LIBRARY_PATH_TERMINATOR")) {
  1645. libPathTerminator = *value;
  1646. } else {
  1647. libPathTerminator =
  1648. this->Makefile->GetRequiredDefinition("CMAKE_LIBRARY_PATH_TERMINATOR");
  1649. }
  1650. // Add standard libraries for this language.
  1651. std::string stdLibString = this->Makefile->GetSafeDefinition(
  1652. cmStrCat("CMAKE_", cli.GetLinkLanguage(), "_STANDARD_LIBRARIES"));
  1653. // Append the framework search path flags.
  1654. cmValue fwSearchFlag = this->Makefile->GetDefinition(
  1655. cmStrCat("CMAKE_", linkLanguage, "_FRAMEWORK_SEARCH_FLAG"));
  1656. frameworkPath = linkLineComputer->ComputeFrameworkPath(cli, fwSearchFlag);
  1657. linkLineComputer->ComputeLinkPath(cli, libPathFlag, libPathTerminator,
  1658. linkPath);
  1659. linkLineComputer->ComputeLinkLibraries(cli, stdLibString, linkLibraries);
  1660. }
  1661. std::string cmLocalGenerator::GetLinkLibsCMP0065(
  1662. std::string const& linkLanguage, cmGeneratorTarget& tgt) const
  1663. {
  1664. std::string linkFlags;
  1665. // Flags to link an executable to shared libraries.
  1666. if (tgt.GetType() == cmStateEnums::EXECUTABLE &&
  1667. this->StateSnapshot.GetState()->GetGlobalPropertyAsBool(
  1668. "TARGET_SUPPORTS_SHARED_LIBS")) {
  1669. bool add_shlib_flags = false;
  1670. switch (tgt.GetPolicyStatusCMP0065()) {
  1671. case cmPolicies::WARN:
  1672. if (!tgt.GetPropertyAsBool("ENABLE_EXPORTS") &&
  1673. this->Makefile->PolicyOptionalWarningEnabled(
  1674. "CMAKE_POLICY_WARNING_CMP0065")) {
  1675. std::ostringstream w;
  1676. /* clang-format off */
  1677. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0065) << "\n"
  1678. "For compatibility with older versions of CMake, "
  1679. "additional flags may be added to export symbols on all "
  1680. "executables regardless of their ENABLE_EXPORTS property.";
  1681. /* clang-format on */
  1682. this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  1683. }
  1684. CM_FALLTHROUGH;
  1685. case cmPolicies::OLD:
  1686. // OLD behavior is to always add the flags, except on AIX where
  1687. // we compute symbol exports if ENABLE_EXPORTS is on.
  1688. add_shlib_flags =
  1689. !(tgt.IsAIX() && tgt.GetPropertyAsBool("ENABLE_EXPORTS"));
  1690. break;
  1691. case cmPolicies::REQUIRED_IF_USED:
  1692. case cmPolicies::REQUIRED_ALWAYS:
  1693. this->IssueMessage(
  1694. MessageType::FATAL_ERROR,
  1695. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0065));
  1696. CM_FALLTHROUGH;
  1697. case cmPolicies::NEW:
  1698. // NEW behavior is to only add the flags if ENABLE_EXPORTS is on,
  1699. // except on AIX where we compute symbol exports.
  1700. add_shlib_flags =
  1701. !tgt.IsAIX() && tgt.GetPropertyAsBool("ENABLE_EXPORTS");
  1702. break;
  1703. }
  1704. if (add_shlib_flags) {
  1705. linkFlags = this->Makefile->GetSafeDefinition(
  1706. cmStrCat("CMAKE_SHARED_LIBRARY_LINK_", linkLanguage, "_FLAGS"));
  1707. }
  1708. }
  1709. return linkFlags;
  1710. }
  1711. bool cmLocalGenerator::AllAppleArchSysrootsAreTheSame(
  1712. const std::vector<std::string>& archs, cmValue sysroot)
  1713. {
  1714. if (!sysroot) {
  1715. return false;
  1716. }
  1717. return std::all_of(archs.begin(), archs.end(),
  1718. [this, sysroot](std::string const& arch) -> bool {
  1719. std::string const& archSysroot =
  1720. this->AppleArchSysroots[arch];
  1721. return cmIsOff(archSysroot) || *sysroot == archSysroot;
  1722. });
  1723. }
  1724. void cmLocalGenerator::AddArchitectureFlags(std::string& flags,
  1725. cmGeneratorTarget const* target,
  1726. const std::string& lang,
  1727. const std::string& config,
  1728. const std::string& filterArch)
  1729. {
  1730. // Only add Apple specific flags on Apple platforms
  1731. if (target->IsApple() && this->EmitUniversalBinaryFlags) {
  1732. std::vector<std::string> archs = target->GetAppleArchs(config, lang);
  1733. if (!archs.empty() &&
  1734. (lang == "C" || lang == "CXX" || lang == "OBJC" || lang == "OBJCXX" ||
  1735. lang == "ASM")) {
  1736. for (std::string const& arch : archs) {
  1737. if (filterArch.empty() || filterArch == arch) {
  1738. flags += " -arch ";
  1739. flags += arch;
  1740. }
  1741. }
  1742. }
  1743. cmValue sysroot = this->Makefile->GetDefinition("CMAKE_OSX_SYSROOT");
  1744. if (sysroot && *sysroot == "/") {
  1745. sysroot = nullptr;
  1746. }
  1747. std::string sysrootFlagVar = "CMAKE_" + lang + "_SYSROOT_FLAG";
  1748. cmValue sysrootFlag = this->Makefile->GetDefinition(sysrootFlagVar);
  1749. if (cmNonempty(sysrootFlag)) {
  1750. if (!this->AppleArchSysroots.empty() &&
  1751. !this->AllAppleArchSysrootsAreTheSame(archs, sysroot)) {
  1752. for (std::string const& arch : archs) {
  1753. std::string const& archSysroot = this->AppleArchSysroots[arch];
  1754. if (cmIsOff(archSysroot)) {
  1755. continue;
  1756. }
  1757. if (filterArch.empty() || filterArch == arch) {
  1758. flags += " -Xarch_" + arch + " ";
  1759. // Combine sysroot flag and path to work with -Xarch
  1760. std::string arch_sysroot = *sysrootFlag + archSysroot;
  1761. flags += this->ConvertToOutputFormat(arch_sysroot, SHELL);
  1762. }
  1763. }
  1764. } else if (cmNonempty(sysroot)) {
  1765. flags += " ";
  1766. flags += *sysrootFlag;
  1767. flags += " ";
  1768. flags += this->ConvertToOutputFormat(*sysroot, SHELL);
  1769. }
  1770. }
  1771. cmValue deploymentTarget =
  1772. this->Makefile->GetDefinition("CMAKE_OSX_DEPLOYMENT_TARGET");
  1773. if (cmNonempty(deploymentTarget)) {
  1774. std::string deploymentTargetFlagVar =
  1775. "CMAKE_" + lang + "_OSX_DEPLOYMENT_TARGET_FLAG";
  1776. cmValue deploymentTargetFlag =
  1777. this->Makefile->GetDefinition(deploymentTargetFlagVar);
  1778. if (cmNonempty(deploymentTargetFlag)) {
  1779. flags += " ";
  1780. flags += *deploymentTargetFlag;
  1781. flags += *deploymentTarget;
  1782. }
  1783. }
  1784. }
  1785. }
  1786. void cmLocalGenerator::AddLanguageFlags(std::string& flags,
  1787. cmGeneratorTarget const* target,
  1788. cmBuildStep compileOrLink,
  1789. const std::string& lang,
  1790. const std::string& config)
  1791. {
  1792. // Add language-specific flags.
  1793. this->AddConfigVariableFlags(flags, cmStrCat("CMAKE_", lang, "_FLAGS"),
  1794. config);
  1795. // Add the language standard flag for compiling, and sometimes linking.
  1796. if (compileOrLink == cmBuildStep::Compile ||
  1797. (compileOrLink == cmBuildStep::Link &&
  1798. // Some toolchains require use of the language standard flag
  1799. // when linking in order to use the matching standard library.
  1800. // FIXME: If CMake gains an abstraction for standard library
  1801. // selection, this will have to be reconciled with it.
  1802. this->Makefile->IsOn(
  1803. cmStrCat("CMAKE_", lang, "_LINK_WITH_STANDARD_COMPILE_OPTION")))) {
  1804. cmStandardLevelResolver standardResolver(this->Makefile);
  1805. std::string const& optionFlagDef =
  1806. standardResolver.GetCompileOptionDef(target, lang, config);
  1807. if (!optionFlagDef.empty()) {
  1808. cmValue opt =
  1809. target->Target->GetMakefile()->GetDefinition(optionFlagDef);
  1810. if (opt) {
  1811. cmList optList{ *opt };
  1812. for (std::string const& i : optList) {
  1813. this->AppendFlagEscape(flags, i);
  1814. }
  1815. }
  1816. }
  1817. }
  1818. std::string compiler = this->Makefile->GetSafeDefinition(
  1819. cmStrCat("CMAKE_", lang, "_COMPILER_ID"));
  1820. std::string compilerSimulateId = this->Makefile->GetSafeDefinition(
  1821. cmStrCat("CMAKE_", lang, "_SIMULATE_ID"));
  1822. if (lang == "Swift") {
  1823. if (cmValue v = target->GetProperty("Swift_LANGUAGE_VERSION")) {
  1824. if (cmSystemTools::VersionCompare(
  1825. cmSystemTools::OP_GREATER_EQUAL,
  1826. this->Makefile->GetDefinition("CMAKE_Swift_COMPILER_VERSION"),
  1827. "4.2")) {
  1828. this->AppendFlags(flags, "-swift-version " + *v);
  1829. }
  1830. }
  1831. } else if (lang == "CUDA") {
  1832. target->AddCUDAArchitectureFlags(compileOrLink, config, flags);
  1833. target->AddCUDAToolkitFlags(flags);
  1834. } else if (lang == "ISPC") {
  1835. target->AddISPCTargetFlags(flags);
  1836. } else if (lang == "RC" &&
  1837. this->Makefile->GetSafeDefinition("CMAKE_RC_COMPILER")
  1838. .find("llvm-rc") != std::string::npos) {
  1839. compiler = this->Makefile->GetSafeDefinition("CMAKE_C_COMPILER_ID");
  1840. if (!compiler.empty()) {
  1841. compilerSimulateId =
  1842. this->Makefile->GetSafeDefinition("CMAKE_C_SIMULATE_ID");
  1843. } else {
  1844. compiler = this->Makefile->GetSafeDefinition("CMAKE_CXX_COMPILER_ID");
  1845. compilerSimulateId =
  1846. this->Makefile->GetSafeDefinition("CMAKE_CXX_SIMULATE_ID");
  1847. }
  1848. } else if (lang == "HIP") {
  1849. target->AddHIPArchitectureFlags(compileOrLink, config, flags);
  1850. }
  1851. // Add VFS Overlay for Clang compilers
  1852. if (compiler == "Clang") {
  1853. if (cmValue vfsOverlay =
  1854. this->Makefile->GetDefinition("CMAKE_CLANG_VFS_OVERLAY")) {
  1855. if (compilerSimulateId == "MSVC") {
  1856. this->AppendCompileOptions(
  1857. flags,
  1858. std::vector<std::string>{ "-Xclang", "-ivfsoverlay", "-Xclang",
  1859. *vfsOverlay });
  1860. } else {
  1861. this->AppendCompileOptions(
  1862. flags, std::vector<std::string>{ "-ivfsoverlay", *vfsOverlay });
  1863. }
  1864. }
  1865. }
  1866. // Add MSVC runtime library flags. This is activated by the presence
  1867. // of a default selection whether or not it is overridden by a property.
  1868. cmValue msvcRuntimeLibraryDefault =
  1869. this->Makefile->GetDefinition("CMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT");
  1870. if (cmNonempty(msvcRuntimeLibraryDefault)) {
  1871. cmValue msvcRuntimeLibraryValue =
  1872. target->GetProperty("MSVC_RUNTIME_LIBRARY");
  1873. if (!msvcRuntimeLibraryValue) {
  1874. msvcRuntimeLibraryValue = msvcRuntimeLibraryDefault;
  1875. }
  1876. std::string const msvcRuntimeLibrary = cmGeneratorExpression::Evaluate(
  1877. *msvcRuntimeLibraryValue, this, config, target);
  1878. if (!msvcRuntimeLibrary.empty()) {
  1879. if (cmValue msvcRuntimeLibraryOptions = this->Makefile->GetDefinition(
  1880. "CMAKE_" + lang + "_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_" +
  1881. msvcRuntimeLibrary)) {
  1882. this->AppendCompileOptions(flags, *msvcRuntimeLibraryOptions);
  1883. } else if ((this->Makefile->GetSafeDefinition(
  1884. "CMAKE_" + lang + "_COMPILER_ID") == "MSVC" ||
  1885. this->Makefile->GetSafeDefinition(
  1886. "CMAKE_" + lang + "_SIMULATE_ID") == "MSVC") &&
  1887. !cmSystemTools::GetErrorOccurredFlag()) {
  1888. // The compiler uses the MSVC ABI so it needs a known runtime library.
  1889. this->IssueMessage(MessageType::FATAL_ERROR,
  1890. "MSVC_RUNTIME_LIBRARY value '" +
  1891. msvcRuntimeLibrary + "' not known for this " +
  1892. lang + " compiler.");
  1893. }
  1894. }
  1895. }
  1896. // Add Watcom runtime library flags. This is activated by the presence
  1897. // of a default selection whether or not it is overridden by a property.
  1898. cmValue watcomRuntimeLibraryDefault =
  1899. this->Makefile->GetDefinition("CMAKE_WATCOM_RUNTIME_LIBRARY_DEFAULT");
  1900. if (cmNonempty(watcomRuntimeLibraryDefault)) {
  1901. cmValue watcomRuntimeLibraryValue =
  1902. target->GetProperty("WATCOM_RUNTIME_LIBRARY");
  1903. if (!watcomRuntimeLibraryValue) {
  1904. watcomRuntimeLibraryValue = watcomRuntimeLibraryDefault;
  1905. }
  1906. std::string const watcomRuntimeLibrary = cmGeneratorExpression::Evaluate(
  1907. *watcomRuntimeLibraryValue, this, config, target);
  1908. if (!watcomRuntimeLibrary.empty()) {
  1909. if (cmValue watcomRuntimeLibraryOptions = this->Makefile->GetDefinition(
  1910. "CMAKE_" + lang + "_COMPILE_OPTIONS_WATCOM_RUNTIME_LIBRARY_" +
  1911. watcomRuntimeLibrary)) {
  1912. this->AppendCompileOptions(flags, *watcomRuntimeLibraryOptions);
  1913. } else if ((this->Makefile->GetSafeDefinition(
  1914. "CMAKE_" + lang + "_COMPILER_ID") == "OpenWatcom" ||
  1915. this->Makefile->GetSafeDefinition(
  1916. "CMAKE_" + lang + "_SIMULATE_ID") == "OpenWatcom") &&
  1917. !cmSystemTools::GetErrorOccurredFlag()) {
  1918. // The compiler uses the Watcom ABI so it needs a known runtime
  1919. // library.
  1920. this->IssueMessage(MessageType::FATAL_ERROR,
  1921. "WATCOM_RUNTIME_LIBRARY value '" +
  1922. watcomRuntimeLibrary + "' not known for this " +
  1923. lang + " compiler.");
  1924. }
  1925. }
  1926. }
  1927. // Add MSVC debug information format flags if CMP0141 is NEW.
  1928. if (cm::optional<std::string> msvcDebugInformationFormat =
  1929. this->GetMSVCDebugFormatName(config, target)) {
  1930. if (!msvcDebugInformationFormat->empty()) {
  1931. if (cmValue msvcDebugInformationFormatOptions =
  1932. this->Makefile->GetDefinition(
  1933. cmStrCat("CMAKE_", lang,
  1934. "_COMPILE_OPTIONS_MSVC_DEBUG_INFORMATION_FORMAT_",
  1935. *msvcDebugInformationFormat))) {
  1936. this->AppendCompileOptions(flags, *msvcDebugInformationFormatOptions);
  1937. } else if ((this->Makefile->GetSafeDefinition(
  1938. cmStrCat("CMAKE_", lang, "_COMPILER_ID")) == "MSVC"_s ||
  1939. this->Makefile->GetSafeDefinition(
  1940. cmStrCat("CMAKE_", lang, "_SIMULATE_ID")) == "MSVC"_s) &&
  1941. !cmSystemTools::GetErrorOccurredFlag()) {
  1942. // The compiler uses the MSVC ABI so it needs a known runtime library.
  1943. this->IssueMessage(MessageType::FATAL_ERROR,
  1944. cmStrCat("MSVC_DEBUG_INFORMATION_FORMAT value '",
  1945. *msvcDebugInformationFormat,
  1946. "' not known for this ", lang,
  1947. " compiler."));
  1948. }
  1949. }
  1950. }
  1951. }
  1952. void cmLocalGenerator::AddLanguageFlagsForLinking(
  1953. std::string& flags, cmGeneratorTarget const* target, const std::string& lang,
  1954. const std::string& config)
  1955. {
  1956. this->AddLanguageFlags(flags, target, cmBuildStep::Link, lang, config);
  1957. if (target->IsIPOEnabled(lang, config)) {
  1958. this->AppendFeatureOptions(flags, lang, "IPO");
  1959. }
  1960. }
  1961. cmGeneratorTarget* cmLocalGenerator::FindGeneratorTargetToUse(
  1962. const std::string& name) const
  1963. {
  1964. auto imported = this->ImportedGeneratorTargets.find(name);
  1965. if (imported != this->ImportedGeneratorTargets.end()) {
  1966. return imported->second;
  1967. }
  1968. // find local alias to imported target
  1969. auto aliased = this->AliasTargets.find(name);
  1970. if (aliased != this->AliasTargets.end()) {
  1971. imported = this->ImportedGeneratorTargets.find(aliased->second);
  1972. if (imported != this->ImportedGeneratorTargets.end()) {
  1973. return imported->second;
  1974. }
  1975. }
  1976. if (cmGeneratorTarget* t = this->FindLocalNonAliasGeneratorTarget(name)) {
  1977. return t;
  1978. }
  1979. return this->GetGlobalGenerator()->FindGeneratorTarget(name);
  1980. }
  1981. bool cmLocalGenerator::GetRealDependency(const std::string& inName,
  1982. const std::string& config,
  1983. std::string& dep)
  1984. {
  1985. // Older CMake code may specify the dependency using the target
  1986. // output file rather than the target name. Such code would have
  1987. // been written before there was support for target properties that
  1988. // modify the name so stripping down to just the file name should
  1989. // produce the target name in this case.
  1990. std::string name = cmSystemTools::GetFilenameName(inName);
  1991. // If the input name is the empty string, there is no real
  1992. // dependency. Short-circuit the other checks:
  1993. if (name.empty()) {
  1994. return false;
  1995. }
  1996. if (cmSystemTools::GetFilenameLastExtension(name) == ".exe") {
  1997. name = cmSystemTools::GetFilenameWithoutLastExtension(name);
  1998. }
  1999. // Look for a CMake target with the given name.
  2000. if (cmGeneratorTarget* target = this->FindGeneratorTargetToUse(name)) {
  2001. // make sure it is not just a coincidence that the target name
  2002. // found is part of the inName
  2003. if (cmSystemTools::FileIsFullPath(inName)) {
  2004. std::string tLocation;
  2005. if (target->GetType() >= cmStateEnums::EXECUTABLE &&
  2006. target->GetType() <= cmStateEnums::MODULE_LIBRARY) {
  2007. tLocation = target->GetLocation(config);
  2008. tLocation = cmSystemTools::GetFilenamePath(tLocation);
  2009. tLocation = cmSystemTools::CollapseFullPath(tLocation);
  2010. }
  2011. std::string depLocation =
  2012. cmSystemTools::GetFilenamePath(std::string(inName));
  2013. depLocation = cmSystemTools::CollapseFullPath(depLocation);
  2014. if (depLocation != tLocation) {
  2015. // it is a full path to a depend that has the same name
  2016. // as a target but is in a different location so do not use
  2017. // the target as the depend
  2018. dep = inName;
  2019. return true;
  2020. }
  2021. }
  2022. switch (target->GetType()) {
  2023. case cmStateEnums::EXECUTABLE:
  2024. case cmStateEnums::STATIC_LIBRARY:
  2025. case cmStateEnums::SHARED_LIBRARY:
  2026. case cmStateEnums::MODULE_LIBRARY:
  2027. case cmStateEnums::UNKNOWN_LIBRARY:
  2028. dep = target->GetFullPath(config, cmStateEnums::RuntimeBinaryArtifact,
  2029. /*realname=*/true);
  2030. return true;
  2031. case cmStateEnums::OBJECT_LIBRARY:
  2032. // An object library has no single file on which to depend.
  2033. // This was listed to get the target-level dependency.
  2034. case cmStateEnums::INTERFACE_LIBRARY:
  2035. // An interface library has no file on which to depend.
  2036. // This was listed to get the target-level dependency.
  2037. case cmStateEnums::UTILITY:
  2038. case cmStateEnums::GLOBAL_TARGET:
  2039. // A utility target has no file on which to depend. This was listed
  2040. // only to get the target-level dependency.
  2041. return false;
  2042. }
  2043. }
  2044. // The name was not that of a CMake target. It must name a file.
  2045. if (cmSystemTools::FileIsFullPath(inName)) {
  2046. // This is a full path. Return it as given.
  2047. dep = inName;
  2048. return true;
  2049. }
  2050. // Check for a source file in this directory that matches the
  2051. // dependency.
  2052. if (cmSourceFile* sf = this->Makefile->GetSource(inName)) {
  2053. dep = sf->ResolveFullPath();
  2054. return true;
  2055. }
  2056. // Treat the name as relative to the source directory in which it
  2057. // was given.
  2058. dep = cmStrCat(this->GetCurrentSourceDirectory(), '/', inName);
  2059. // If the in-source path does not exist, assume it instead lives in the
  2060. // binary directory.
  2061. if (!cmSystemTools::FileExists(dep)) {
  2062. dep = cmStrCat(this->GetCurrentBinaryDirectory(), '/', inName);
  2063. }
  2064. dep = cmSystemTools::CollapseFullPath(dep, this->GetBinaryDirectory());
  2065. return true;
  2066. }
  2067. void cmLocalGenerator::AddSharedFlags(std::string& flags,
  2068. const std::string& lang, bool shared)
  2069. {
  2070. std::string flagsVar;
  2071. // Add flags for dealing with shared libraries for this language.
  2072. if (shared) {
  2073. this->AppendFlags(flags,
  2074. this->Makefile->GetSafeDefinition(
  2075. cmStrCat("CMAKE_SHARED_LIBRARY_", lang, "_FLAGS")));
  2076. }
  2077. }
  2078. static void AddVisibilityCompileOption(std::string& flags,
  2079. cmGeneratorTarget const* target,
  2080. cmLocalGenerator* lg,
  2081. const std::string& lang,
  2082. std::string* warnCMP0063)
  2083. {
  2084. std::string compileOption = "CMAKE_" + lang + "_COMPILE_OPTIONS_VISIBILITY";
  2085. cmValue opt = lg->GetMakefile()->GetDefinition(compileOption);
  2086. if (!opt) {
  2087. return;
  2088. }
  2089. std::string flagDefine = lang + "_VISIBILITY_PRESET";
  2090. cmValue prop = target->GetProperty(flagDefine);
  2091. if (!prop) {
  2092. return;
  2093. }
  2094. if (warnCMP0063) {
  2095. *warnCMP0063 += " " + flagDefine + "\n";
  2096. return;
  2097. }
  2098. if ((*prop != "hidden") && (*prop != "default") && (*prop != "protected") &&
  2099. (*prop != "internal")) {
  2100. std::ostringstream e;
  2101. e << "Target " << target->GetName() << " uses unsupported value \""
  2102. << *prop << "\" for " << flagDefine << "."
  2103. << " The supported values are: default, hidden, protected, and "
  2104. "internal.";
  2105. cmSystemTools::Error(e.str());
  2106. return;
  2107. }
  2108. std::string option = *opt + *prop;
  2109. lg->AppendFlags(flags, option);
  2110. }
  2111. static void AddInlineVisibilityCompileOption(std::string& flags,
  2112. cmGeneratorTarget const* target,
  2113. cmLocalGenerator* lg,
  2114. std::string* warnCMP0063,
  2115. const std::string& lang)
  2116. {
  2117. std::string compileOption =
  2118. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_VISIBILITY_INLINES_HIDDEN");
  2119. cmValue opt = lg->GetMakefile()->GetDefinition(compileOption);
  2120. if (!opt) {
  2121. return;
  2122. }
  2123. bool prop = target->GetPropertyAsBool("VISIBILITY_INLINES_HIDDEN");
  2124. if (!prop) {
  2125. return;
  2126. }
  2127. if (warnCMP0063) {
  2128. *warnCMP0063 += " VISIBILITY_INLINES_HIDDEN\n";
  2129. return;
  2130. }
  2131. lg->AppendFlags(flags, *opt);
  2132. }
  2133. void cmLocalGenerator::AddVisibilityPresetFlags(
  2134. std::string& flags, cmGeneratorTarget const* target, const std::string& lang)
  2135. {
  2136. if (lang.empty()) {
  2137. return;
  2138. }
  2139. std::string warnCMP0063;
  2140. std::string* pWarnCMP0063 = nullptr;
  2141. if (target->GetType() != cmStateEnums::SHARED_LIBRARY &&
  2142. target->GetType() != cmStateEnums::MODULE_LIBRARY &&
  2143. !target->IsExecutableWithExports()) {
  2144. switch (target->GetPolicyStatusCMP0063()) {
  2145. case cmPolicies::OLD:
  2146. return;
  2147. case cmPolicies::WARN:
  2148. pWarnCMP0063 = &warnCMP0063;
  2149. break;
  2150. default:
  2151. break;
  2152. }
  2153. }
  2154. AddVisibilityCompileOption(flags, target, this, lang, pWarnCMP0063);
  2155. if (lang == "CXX" || lang == "OBJCXX") {
  2156. AddInlineVisibilityCompileOption(flags, target, this, pWarnCMP0063, lang);
  2157. }
  2158. if (!warnCMP0063.empty() && this->WarnCMP0063.insert(target).second) {
  2159. std::ostringstream w;
  2160. /* clang-format off */
  2161. w <<
  2162. cmPolicies::GetPolicyWarning(cmPolicies::CMP0063) << "\n"
  2163. "Target \"" << target->GetName() << "\" of "
  2164. "type \"" << cmState::GetTargetTypeName(target->GetType()) << "\" "
  2165. "has the following visibility properties set for " << lang << ":\n" <<
  2166. warnCMP0063 <<
  2167. "For compatibility CMake is not honoring them for this target.";
  2168. /* clang-format on */
  2169. target->GetLocalGenerator()->GetCMakeInstance()->IssueMessage(
  2170. MessageType::AUTHOR_WARNING, w.str(), target->GetBacktrace());
  2171. }
  2172. }
  2173. void cmLocalGenerator::AddCMP0018Flags(std::string& flags,
  2174. cmGeneratorTarget const* target,
  2175. std::string const& lang,
  2176. const std::string& config)
  2177. {
  2178. int targetType = target->GetType();
  2179. bool shared = ((targetType == cmStateEnums::SHARED_LIBRARY) ||
  2180. (targetType == cmStateEnums::MODULE_LIBRARY));
  2181. if (this->GetShouldUseOldFlags(shared, lang)) {
  2182. this->AddSharedFlags(flags, lang, shared);
  2183. } else {
  2184. if (target->GetLinkInterfaceDependentBoolProperty(
  2185. "POSITION_INDEPENDENT_CODE", config)) {
  2186. this->AddPositionIndependentFlags(flags, lang, targetType);
  2187. }
  2188. if (shared) {
  2189. this->AppendFeatureOptions(flags, lang, "DLL");
  2190. }
  2191. }
  2192. }
  2193. bool cmLocalGenerator::GetShouldUseOldFlags(bool shared,
  2194. const std::string& lang) const
  2195. {
  2196. std::string originalFlags =
  2197. this->GlobalGenerator->GetSharedLibFlagsForLanguage(lang);
  2198. if (shared) {
  2199. std::string flagsVar = cmStrCat("CMAKE_SHARED_LIBRARY_", lang, "_FLAGS");
  2200. std::string const& flags = this->Makefile->GetSafeDefinition(flagsVar);
  2201. if (flags != originalFlags) {
  2202. switch (this->GetPolicyStatus(cmPolicies::CMP0018)) {
  2203. case cmPolicies::WARN: {
  2204. std::ostringstream e;
  2205. e << "Variable " << flagsVar
  2206. << " has been modified. CMake "
  2207. "will ignore the POSITION_INDEPENDENT_CODE target property "
  2208. "for "
  2209. "shared libraries and will use the "
  2210. << flagsVar
  2211. << " variable "
  2212. "instead. This may cause errors if the original content of "
  2213. << flagsVar << " was removed.\n"
  2214. << cmPolicies::GetPolicyWarning(cmPolicies::CMP0018);
  2215. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  2216. CM_FALLTHROUGH;
  2217. }
  2218. case cmPolicies::OLD:
  2219. return true;
  2220. case cmPolicies::REQUIRED_IF_USED:
  2221. case cmPolicies::REQUIRED_ALWAYS:
  2222. case cmPolicies::NEW:
  2223. return false;
  2224. }
  2225. }
  2226. }
  2227. return false;
  2228. }
  2229. void cmLocalGenerator::AddPositionIndependentFlags(std::string& flags,
  2230. std::string const& lang,
  2231. int targetType)
  2232. {
  2233. std::string picFlags;
  2234. if (targetType == cmStateEnums::EXECUTABLE) {
  2235. picFlags = this->Makefile->GetSafeDefinition(
  2236. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_PIE"));
  2237. }
  2238. if (picFlags.empty()) {
  2239. picFlags = this->Makefile->GetSafeDefinition(
  2240. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_PIC"));
  2241. }
  2242. if (!picFlags.empty()) {
  2243. cmList options{ picFlags };
  2244. for (std::string const& o : options) {
  2245. this->AppendFlagEscape(flags, o);
  2246. }
  2247. }
  2248. }
  2249. void cmLocalGenerator::AddColorDiagnosticsFlags(std::string& flags,
  2250. const std::string& lang)
  2251. {
  2252. cmValue diag = this->Makefile->GetDefinition("CMAKE_COLOR_DIAGNOSTICS");
  2253. if (diag.IsSet()) {
  2254. std::string colorFlagName;
  2255. if (diag.IsOn()) {
  2256. colorFlagName =
  2257. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_COLOR_DIAGNOSTICS");
  2258. } else {
  2259. colorFlagName =
  2260. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_COLOR_DIAGNOSTICS_OFF");
  2261. }
  2262. cmList options{ this->Makefile->GetDefinition(colorFlagName) };
  2263. for (auto const& option : options) {
  2264. this->AppendFlagEscape(flags, option);
  2265. }
  2266. }
  2267. }
  2268. void cmLocalGenerator::AddConfigVariableFlags(std::string& flags,
  2269. const std::string& var,
  2270. const std::string& config)
  2271. {
  2272. // Add the flags from the variable itself.
  2273. this->AppendFlags(flags, this->Makefile->GetSafeDefinition(var));
  2274. // Add the flags from the build-type specific variable.
  2275. if (!config.empty()) {
  2276. const std::string flagsVar =
  2277. cmStrCat(var, '_', cmSystemTools::UpperCase(config));
  2278. this->AppendFlags(flags, this->Makefile->GetSafeDefinition(flagsVar));
  2279. }
  2280. }
  2281. void cmLocalGenerator::AppendFlags(std::string& flags,
  2282. const std::string& newFlags) const
  2283. {
  2284. bool allSpaces = std::all_of(newFlags.begin(), newFlags.end(), cmIsSpace);
  2285. if (!newFlags.empty() && !allSpaces) {
  2286. if (!flags.empty()) {
  2287. flags += " ";
  2288. }
  2289. flags += newFlags;
  2290. }
  2291. }
  2292. void cmLocalGenerator::AppendFlags(
  2293. std::string& flags, const std::vector<BT<std::string>>& newFlags) const
  2294. {
  2295. for (BT<std::string> const& flag : newFlags) {
  2296. this->AppendFlags(flags, flag.Value);
  2297. }
  2298. }
  2299. void cmLocalGenerator::AppendFlagEscape(std::string& flags,
  2300. const std::string& rawFlag) const
  2301. {
  2302. this->AppendFlags(
  2303. flags,
  2304. this->EscapeForShell(rawFlag, false, false, false, this->IsNinjaMulti()));
  2305. }
  2306. void cmLocalGenerator::AddISPCDependencies(cmGeneratorTarget* target)
  2307. {
  2308. std::vector<std::string> enabledLanguages =
  2309. this->GetState()->GetEnabledLanguages();
  2310. if (std::find(enabledLanguages.begin(), enabledLanguages.end(), "ISPC") ==
  2311. enabledLanguages.end()) {
  2312. return;
  2313. }
  2314. cmValue ispcHeaderSuffixProp = target->GetProperty("ISPC_HEADER_SUFFIX");
  2315. assert(ispcHeaderSuffixProp);
  2316. std::vector<std::string> ispcArchSuffixes =
  2317. detail::ComputeISPCObjectSuffixes(target);
  2318. const bool extra_objects = (ispcArchSuffixes.size() > 1);
  2319. std::vector<std::string> configsList =
  2320. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  2321. for (std::string const& config : configsList) {
  2322. std::string rootObjectDir = target->GetObjectDirectory(config);
  2323. std::string headerDir = rootObjectDir;
  2324. if (cmValue prop = target->GetProperty("ISPC_HEADER_DIRECTORY")) {
  2325. headerDir = cmSystemTools::CollapseFullPath(
  2326. cmStrCat(this->GetBinaryDirectory(), '/', *prop));
  2327. }
  2328. std::vector<cmSourceFile*> sources;
  2329. target->GetSourceFiles(sources, config);
  2330. // build up the list of ispc headers and extra objects that this target is
  2331. // generating
  2332. for (cmSourceFile const* sf : sources) {
  2333. // Generate this object file's rule file.
  2334. const std::string& lang = sf->GetLanguage();
  2335. if (lang == "ISPC") {
  2336. std::string const& objectName = target->GetObjectName(sf);
  2337. // Drop both ".obj" and the source file extension
  2338. std::string ispcSource =
  2339. cmSystemTools::GetFilenameWithoutLastExtension(objectName);
  2340. ispcSource =
  2341. cmSystemTools::GetFilenameWithoutLastExtension(ispcSource);
  2342. auto headerPath =
  2343. cmStrCat(headerDir, '/', ispcSource, *ispcHeaderSuffixProp);
  2344. target->AddISPCGeneratedHeader(headerPath, config);
  2345. if (extra_objects) {
  2346. std::vector<std::string> objs = detail::ComputeISPCExtraObjects(
  2347. objectName, rootObjectDir, ispcArchSuffixes);
  2348. target->AddISPCGeneratedObject(std::move(objs), config);
  2349. }
  2350. }
  2351. }
  2352. }
  2353. }
  2354. void cmLocalGenerator::AddPchDependencies(cmGeneratorTarget* target)
  2355. {
  2356. std::vector<std::string> configsList =
  2357. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  2358. for (std::string const& config : configsList) {
  2359. // FIXME: Refactor collection of sources to not evaluate object
  2360. // libraries.
  2361. std::vector<cmSourceFile*> sources;
  2362. target->GetSourceFiles(sources, config);
  2363. const std::string configUpper = cmSystemTools::UpperCase(config);
  2364. static const std::array<std::string, 4> langs = { { "C", "CXX", "OBJC",
  2365. "OBJCXX" } };
  2366. std::set<std::string> pchLangSet;
  2367. if (this->GetGlobalGenerator()->IsXcode()) {
  2368. for (const std::string& lang : langs) {
  2369. const std::string pchHeader = target->GetPchHeader(config, lang, "");
  2370. if (!pchHeader.empty()) {
  2371. pchLangSet.emplace(lang);
  2372. }
  2373. }
  2374. }
  2375. for (const std::string& lang : langs) {
  2376. auto langSources = std::count_if(
  2377. sources.begin(), sources.end(), [lang](cmSourceFile* sf) {
  2378. return lang == sf->GetLanguage() &&
  2379. !sf->GetProperty("SKIP_PRECOMPILE_HEADERS");
  2380. });
  2381. if (langSources == 0) {
  2382. continue;
  2383. }
  2384. std::vector<std::string> architectures;
  2385. if (!this->GetGlobalGenerator()->IsXcode()) {
  2386. architectures = target->GetAppleArchs(config, lang);
  2387. }
  2388. if (architectures.empty()) {
  2389. architectures.emplace_back();
  2390. } else {
  2391. std::string useMultiArchPch;
  2392. for (const std::string& arch : architectures) {
  2393. const std::string pchHeader =
  2394. target->GetPchHeader(config, lang, arch);
  2395. if (!pchHeader.empty()) {
  2396. useMultiArchPch = cmStrCat(useMultiArchPch, ";-Xarch_", arch,
  2397. ";-include", pchHeader);
  2398. }
  2399. }
  2400. if (!useMultiArchPch.empty()) {
  2401. target->Target->AppendProperty(
  2402. cmStrCat(lang, "_COMPILE_OPTIONS_USE_PCH"),
  2403. cmStrCat("$<$<CONFIG:", config, ">:", useMultiArchPch, ">"));
  2404. }
  2405. }
  2406. for (const std::string& arch : architectures) {
  2407. const std::string pchSource = target->GetPchSource(config, lang, arch);
  2408. const std::string pchHeader = target->GetPchHeader(config, lang, arch);
  2409. if (pchSource.empty() || pchHeader.empty()) {
  2410. if (this->GetGlobalGenerator()->IsXcode() && !pchLangSet.empty()) {
  2411. for (auto* sf : sources) {
  2412. const auto sourceLanguage = sf->GetLanguage();
  2413. if (!sourceLanguage.empty() &&
  2414. pchLangSet.find(sourceLanguage) == pchLangSet.end()) {
  2415. sf->SetProperty("SKIP_PRECOMPILE_HEADERS", "ON");
  2416. }
  2417. }
  2418. }
  2419. continue;
  2420. }
  2421. cmValue pchExtension =
  2422. this->Makefile->GetDefinition("CMAKE_PCH_EXTENSION");
  2423. if (pchExtension.IsEmpty()) {
  2424. continue;
  2425. }
  2426. cmValue ReuseFrom =
  2427. target->GetProperty("PRECOMPILE_HEADERS_REUSE_FROM");
  2428. auto* pch_sf = this->Makefile->GetOrCreateSource(
  2429. pchSource, false, cmSourceFileLocationKind::Known);
  2430. // PCH sources should never be scanned as they cannot contain C++
  2431. // module references.
  2432. pch_sf->SetProperty("CXX_SCAN_FOR_MODULES", "0");
  2433. if (!this->GetGlobalGenerator()->IsXcode()) {
  2434. if (!ReuseFrom) {
  2435. target->AddSource(pchSource, true);
  2436. }
  2437. const std::string pchFile = target->GetPchFile(config, lang, arch);
  2438. // Exclude the pch files from linking
  2439. if (this->Makefile->IsOn("CMAKE_LINK_PCH")) {
  2440. if (!ReuseFrom) {
  2441. pch_sf->AppendProperty(
  2442. "OBJECT_OUTPUTS",
  2443. cmStrCat("$<$<CONFIG:", config, ">:", pchFile, ">"));
  2444. } else {
  2445. auto* reuseTarget =
  2446. this->GlobalGenerator->FindGeneratorTarget(*ReuseFrom);
  2447. if (this->Makefile->IsOn("CMAKE_PCH_COPY_COMPILE_PDB")) {
  2448. const std::string compilerId =
  2449. this->Makefile->GetSafeDefinition(
  2450. cmStrCat("CMAKE_", lang, "_COMPILER_ID"));
  2451. const std::string compilerVersion =
  2452. this->Makefile->GetSafeDefinition(
  2453. cmStrCat("CMAKE_", lang, "_COMPILER_VERSION"));
  2454. const std::string langFlags =
  2455. this->Makefile->GetSafeDefinition(
  2456. cmStrCat("CMAKE_", lang, "_FLAGS_", configUpper));
  2457. bool editAndContinueDebugInfo = false;
  2458. bool programDatabaseDebugInfo = false;
  2459. cm::optional<std::string> msvcDebugInformationFormat =
  2460. this->GetMSVCDebugFormatName(config, target);
  2461. if (msvcDebugInformationFormat &&
  2462. !msvcDebugInformationFormat->empty()) {
  2463. editAndContinueDebugInfo =
  2464. *msvcDebugInformationFormat == "EditAndContinue";
  2465. programDatabaseDebugInfo =
  2466. *msvcDebugInformationFormat == "ProgramDatabase";
  2467. } else {
  2468. editAndContinueDebugInfo =
  2469. langFlags.find("/ZI") != std::string::npos ||
  2470. langFlags.find("-ZI") != std::string::npos;
  2471. programDatabaseDebugInfo =
  2472. langFlags.find("/Zi") != std::string::npos ||
  2473. langFlags.find("-Zi") != std::string::npos;
  2474. }
  2475. // MSVC 2008 is producing both .pdb and .idb files with /Zi.
  2476. bool msvc2008OrLess =
  2477. cmSystemTools::VersionCompare(cmSystemTools::OP_LESS,
  2478. compilerVersion, "16.0") &&
  2479. compilerId == "MSVC";
  2480. // but not when used via toolset -Tv90
  2481. if (this->Makefile->GetSafeDefinition(
  2482. "CMAKE_VS_PLATFORM_TOOLSET") == "v90") {
  2483. msvc2008OrLess = false;
  2484. }
  2485. if (editAndContinueDebugInfo || msvc2008OrLess) {
  2486. this->CopyPchCompilePdb(config, lang, target, *ReuseFrom,
  2487. reuseTarget, { ".pdb", ".idb" });
  2488. } else if (programDatabaseDebugInfo) {
  2489. this->CopyPchCompilePdb(config, lang, target, *ReuseFrom,
  2490. reuseTarget, { ".pdb" });
  2491. }
  2492. }
  2493. // Link to the pch object file
  2494. std::string pchSourceObj =
  2495. reuseTarget->GetPchFileObject(config, lang, arch);
  2496. if (target->GetType() != cmStateEnums::OBJECT_LIBRARY) {
  2497. std::string linkerProperty = "LINK_FLAGS_";
  2498. if (target->GetType() == cmStateEnums::STATIC_LIBRARY) {
  2499. linkerProperty = "STATIC_LIBRARY_FLAGS_";
  2500. }
  2501. target->Target->AppendProperty(
  2502. cmStrCat(linkerProperty, configUpper),
  2503. cmStrCat(" ",
  2504. this->ConvertToOutputFormat(pchSourceObj, SHELL)),
  2505. cm::nullopt, true);
  2506. } else if (reuseTarget->GetType() ==
  2507. cmStateEnums::OBJECT_LIBRARY) {
  2508. // FIXME: This can propagate more than one level, unlike
  2509. // the rest of the object files in an object library.
  2510. // Find another way to do this.
  2511. target->Target->AppendProperty(
  2512. "INTERFACE_LINK_LIBRARIES",
  2513. cmStrCat("$<$<CONFIG:", config,
  2514. ">:$<LINK_ONLY:", pchSourceObj, ">>"));
  2515. // We updated the link interface, so ensure it is recomputed.
  2516. target->ClearLinkInterfaceCache();
  2517. }
  2518. }
  2519. } else {
  2520. pch_sf->SetProperty("PCH_EXTENSION", pchExtension);
  2521. }
  2522. // Add pchHeader to source files, which will
  2523. // be grouped as "Precompile Header File"
  2524. auto* pchHeader_sf = this->Makefile->GetOrCreateSource(
  2525. pchHeader, false, cmSourceFileLocationKind::Known);
  2526. std::string err;
  2527. pchHeader_sf->ResolveFullPath(&err);
  2528. if (!err.empty()) {
  2529. std::ostringstream msg;
  2530. msg << "Unable to resolve full path of PCH-header '" << pchHeader
  2531. << "' assigned to target " << target->GetName()
  2532. << ", although its path is supposed to be known!";
  2533. this->IssueMessage(MessageType::FATAL_ERROR, msg.str());
  2534. }
  2535. target->AddSource(pchHeader);
  2536. }
  2537. }
  2538. }
  2539. }
  2540. }
  2541. void cmLocalGenerator::CopyPchCompilePdb(
  2542. const std::string& config, const std::string& language,
  2543. cmGeneratorTarget* target, const std::string& ReuseFrom,
  2544. cmGeneratorTarget* reuseTarget, const std::vector<std::string>& extensions)
  2545. {
  2546. const std::string pdb_prefix =
  2547. this->GetGlobalGenerator()->IsMultiConfig() ? cmStrCat(config, "/") : "";
  2548. const std::string target_compile_pdb_dir =
  2549. cmStrCat(target->GetLocalGenerator()->GetCurrentBinaryDirectory(), "/",
  2550. target->GetName(), ".dir/");
  2551. const std::string copy_script = cmStrCat(
  2552. target_compile_pdb_dir, "copy_idb_pdb_", config.c_str(), ".cmake");
  2553. cmGeneratedFileStream file(copy_script);
  2554. file << "# CMake generated file\n";
  2555. file << "# The compiler generated pdb file needs to be written to disk\n"
  2556. << "# by mspdbsrv. The foreach retry loop is needed to make sure\n"
  2557. << "# the pdb file is ready to be copied.\n\n";
  2558. for (auto const& extension : extensions) {
  2559. const std::string from_file =
  2560. cmStrCat(reuseTarget->GetLocalGenerator()->GetCurrentBinaryDirectory(),
  2561. "/", ReuseFrom, ".dir/${PDB_PREFIX}", ReuseFrom, extension);
  2562. const std::string to_dir =
  2563. cmStrCat(target->GetLocalGenerator()->GetCurrentBinaryDirectory(), "/",
  2564. target->GetName(), ".dir/${PDB_PREFIX}");
  2565. const std::string to_file = cmStrCat(to_dir, ReuseFrom, extension);
  2566. std::string dest_file = to_file;
  2567. std::string const& prefix = target->GetSafeProperty("PREFIX");
  2568. if (!prefix.empty()) {
  2569. dest_file = cmStrCat(to_dir, prefix, ReuseFrom, extension);
  2570. }
  2571. file << "foreach(retry RANGE 1 30)\n";
  2572. file << " if (EXISTS \"" << from_file << "\" AND (NOT EXISTS \""
  2573. << dest_file << "\" OR NOT \"" << dest_file << " \" IS_NEWER_THAN \""
  2574. << from_file << "\"))\n";
  2575. file << " execute_process(COMMAND ${CMAKE_COMMAND} -E copy";
  2576. file << " \"" << from_file << "\""
  2577. << " \"" << to_dir << "\" RESULT_VARIABLE result "
  2578. << " ERROR_QUIET)\n";
  2579. file << " if (NOT result EQUAL 0)\n"
  2580. << " execute_process(COMMAND ${CMAKE_COMMAND}"
  2581. << " -E sleep 1)\n"
  2582. << " else()\n";
  2583. if (!prefix.empty()) {
  2584. file << " file(REMOVE \"" << dest_file << "\")\n";
  2585. file << " file(RENAME \"" << to_file << "\" \"" << dest_file << "\")\n";
  2586. }
  2587. file << " break()\n"
  2588. << " endif()\n";
  2589. file << " elseif(NOT EXISTS \"" << from_file << "\")\n"
  2590. << " execute_process(COMMAND ${CMAKE_COMMAND}"
  2591. << " -E sleep 1)\n"
  2592. << " endif()\n";
  2593. file << "endforeach()\n";
  2594. }
  2595. auto configGenex = [&](cm::string_view expr) -> std::string {
  2596. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  2597. return cmStrCat("$<$<CONFIG:", config, ">:", expr, ">");
  2598. }
  2599. return std::string(expr);
  2600. };
  2601. cmCustomCommandLines commandLines = cmMakeSingleCommandLine(
  2602. { configGenex(cmSystemTools::GetCMakeCommand()),
  2603. configGenex(cmStrCat("-DPDB_PREFIX=", pdb_prefix)), configGenex("-P"),
  2604. configGenex(copy_script) });
  2605. const char* no_message = "";
  2606. std::vector<std::string> outputs;
  2607. outputs.push_back(configGenex(
  2608. cmStrCat(target_compile_pdb_dir, pdb_prefix, ReuseFrom, ".pdb")));
  2609. auto cc = cm::make_unique<cmCustomCommand>();
  2610. cc->SetCommandLines(commandLines);
  2611. cc->SetComment(no_message);
  2612. cc->SetStdPipesUTF8(true);
  2613. cc->AppendDepends({ reuseTarget->GetPchFile(config, language) });
  2614. if (this->GetGlobalGenerator()->IsVisualStudio()) {
  2615. cc->SetByproducts(outputs);
  2616. this->AddCustomCommandToTarget(
  2617. target->GetName(), cmCustomCommandType::PRE_BUILD, std::move(cc),
  2618. cmObjectLibraryCommands::Accept);
  2619. } else {
  2620. cc->SetOutputs(outputs);
  2621. cmSourceFile* copy_rule = this->AddCustomCommandToOutput(std::move(cc));
  2622. copy_rule->SetProperty("CXX_SCAN_FOR_MODULES", "0");
  2623. if (copy_rule) {
  2624. target->AddSource(copy_rule->ResolveFullPath());
  2625. }
  2626. }
  2627. target->Target->SetProperty("COMPILE_PDB_OUTPUT_DIRECTORY",
  2628. target_compile_pdb_dir);
  2629. }
  2630. cm::optional<std::string> cmLocalGenerator::GetMSVCDebugFormatName(
  2631. std::string const& config, cmGeneratorTarget const* target)
  2632. {
  2633. // MSVC debug information format selection is activated by the presence
  2634. // of a default whether or not it is overridden by a property.
  2635. cm::optional<std::string> msvcDebugInformationFormat;
  2636. cmValue msvcDebugInformationFormatDefault = this->Makefile->GetDefinition(
  2637. "CMAKE_MSVC_DEBUG_INFORMATION_FORMAT_DEFAULT");
  2638. if (cmNonempty(msvcDebugInformationFormatDefault)) {
  2639. cmValue msvcDebugInformationFormatValue =
  2640. target->GetProperty("MSVC_DEBUG_INFORMATION_FORMAT");
  2641. if (!msvcDebugInformationFormatValue) {
  2642. msvcDebugInformationFormatValue = msvcDebugInformationFormatDefault;
  2643. }
  2644. msvcDebugInformationFormat = cmGeneratorExpression::Evaluate(
  2645. *msvcDebugInformationFormatValue, this, config, target);
  2646. }
  2647. return msvcDebugInformationFormat;
  2648. }
  2649. namespace {
  2650. inline void RegisterUnitySources(cmGeneratorTarget* target, cmSourceFile* sf,
  2651. std::string const& filename)
  2652. {
  2653. target->AddSourceFileToUnityBatch(sf->ResolveFullPath());
  2654. sf->SetProperty("UNITY_SOURCE_FILE", filename);
  2655. }
  2656. }
  2657. cmLocalGenerator::UnitySource cmLocalGenerator::WriteUnitySource(
  2658. cmGeneratorTarget* target, std::vector<std::string> const& configs,
  2659. cmRange<std::vector<UnityBatchedSource>::const_iterator> sources,
  2660. cmValue beforeInclude, cmValue afterInclude, std::string filename) const
  2661. {
  2662. cmValue uniqueIdName = target->GetProperty("UNITY_BUILD_UNIQUE_ID");
  2663. cmGeneratedFileStream file(
  2664. filename, false, target->GetGlobalGenerator()->GetMakefileEncoding());
  2665. file.SetCopyIfDifferent(true);
  2666. file << "/* generated by CMake */\n\n";
  2667. bool perConfig = false;
  2668. for (UnityBatchedSource const& ubs : sources) {
  2669. cm::optional<std::string> cond;
  2670. if (ubs.Configs.size() != configs.size()) {
  2671. perConfig = true;
  2672. cond = std::string();
  2673. cm::string_view sep;
  2674. for (size_t ci : ubs.Configs) {
  2675. cond = cmStrCat(*cond, sep, "defined(CMAKE_UNITY_CONFIG_",
  2676. cmSystemTools::UpperCase(configs[ci]), ")");
  2677. sep = " || "_s;
  2678. }
  2679. }
  2680. RegisterUnitySources(target, ubs.Source, filename);
  2681. WriteUnitySourceInclude(file, cond, ubs.Source->ResolveFullPath(),
  2682. beforeInclude, afterInclude, uniqueIdName);
  2683. }
  2684. return UnitySource(std::move(filename), perConfig);
  2685. }
  2686. void cmLocalGenerator::WriteUnitySourceInclude(
  2687. std::ostream& unity_file, cm::optional<std::string> const& cond,
  2688. std::string const& sf_full_path, cmValue beforeInclude, cmValue afterInclude,
  2689. cmValue uniqueIdName) const
  2690. {
  2691. if (cond) {
  2692. unity_file << "#if " << *cond << "\n";
  2693. }
  2694. if (cmNonempty(uniqueIdName)) {
  2695. std::string pathToHash;
  2696. auto PathEqOrSubDir = [](std::string const& a, std::string const& b) {
  2697. return (cmSystemTools::ComparePath(a, b) ||
  2698. cmSystemTools::IsSubDirectory(a, b));
  2699. };
  2700. const auto path = cmSystemTools::GetFilenamePath(sf_full_path);
  2701. if (PathEqOrSubDir(path, this->GetBinaryDirectory())) {
  2702. pathToHash = "BLD_" +
  2703. cmSystemTools::RelativePath(this->GetBinaryDirectory(), sf_full_path);
  2704. } else if (PathEqOrSubDir(path, this->GetSourceDirectory())) {
  2705. pathToHash = "SRC_" +
  2706. cmSystemTools::RelativePath(this->GetSourceDirectory(), sf_full_path);
  2707. } else {
  2708. pathToHash = "ABS_" + sf_full_path;
  2709. }
  2710. cmCryptoHash hasher(cmCryptoHash::AlgoMD5);
  2711. unity_file << "/* " << pathToHash << " */\n"
  2712. << "#undef " << *uniqueIdName << "\n"
  2713. << "#define " << *uniqueIdName << " unity_"
  2714. << hasher.HashString(pathToHash) << "\n";
  2715. }
  2716. if (beforeInclude) {
  2717. unity_file << *beforeInclude << "\n";
  2718. }
  2719. unity_file << "/* NOLINTNEXTLINE(bugprone-suspicious-include) */\n";
  2720. unity_file << "#include \"" << sf_full_path << "\"\n";
  2721. if (afterInclude) {
  2722. unity_file << *afterInclude << "\n";
  2723. }
  2724. if (cond) {
  2725. unity_file << "#endif\n";
  2726. }
  2727. unity_file << "\n";
  2728. }
  2729. std::vector<cmLocalGenerator::UnitySource>
  2730. cmLocalGenerator::AddUnityFilesModeAuto(
  2731. cmGeneratorTarget* target, std::string const& lang,
  2732. std::vector<std::string> const& configs,
  2733. std::vector<UnityBatchedSource> const& filtered_sources,
  2734. cmValue beforeInclude, cmValue afterInclude,
  2735. std::string const& filename_base, size_t batchSize)
  2736. {
  2737. if (batchSize == 0) {
  2738. batchSize = filtered_sources.size();
  2739. }
  2740. std::vector<UnitySource> unity_files;
  2741. for (size_t itemsLeft = filtered_sources.size(), chunk, batch = 0;
  2742. itemsLeft > 0; itemsLeft -= chunk, ++batch) {
  2743. chunk = std::min(itemsLeft, batchSize);
  2744. std::string filename = cmStrCat(filename_base, "unity_", batch,
  2745. (lang == "C") ? "_c.c" : "_cxx.cxx");
  2746. auto const begin = filtered_sources.begin() + batch * batchSize;
  2747. auto const end = begin + chunk;
  2748. unity_files.emplace_back(this->WriteUnitySource(
  2749. target, configs, cmMakeRange(begin, end), beforeInclude, afterInclude,
  2750. std::move(filename)));
  2751. }
  2752. return unity_files;
  2753. }
  2754. std::vector<cmLocalGenerator::UnitySource>
  2755. cmLocalGenerator::AddUnityFilesModeGroup(
  2756. cmGeneratorTarget* target, std::string const& lang,
  2757. std::vector<std::string> const& configs,
  2758. std::vector<UnityBatchedSource> const& filtered_sources,
  2759. cmValue beforeInclude, cmValue afterInclude,
  2760. std::string const& filename_base)
  2761. {
  2762. std::vector<UnitySource> unity_files;
  2763. // sources organized by group name. Drop any source
  2764. // without a group
  2765. std::unordered_map<std::string, std::vector<UnityBatchedSource>>
  2766. explicit_mapping;
  2767. for (UnityBatchedSource const& ubs : filtered_sources) {
  2768. if (cmValue value = ubs.Source->GetProperty("UNITY_GROUP")) {
  2769. auto i = explicit_mapping.find(*value);
  2770. if (i == explicit_mapping.end()) {
  2771. std::vector<UnityBatchedSource> sources{ ubs };
  2772. explicit_mapping.emplace(*value, std::move(sources));
  2773. } else {
  2774. i->second.emplace_back(ubs);
  2775. }
  2776. }
  2777. }
  2778. for (auto const& item : explicit_mapping) {
  2779. auto const& name = item.first;
  2780. std::string filename = cmStrCat(filename_base, "unity_", name,
  2781. (lang == "C") ? "_c.c" : "_cxx.cxx");
  2782. unity_files.emplace_back(this->WriteUnitySource(
  2783. target, configs, cmMakeRange(item.second), beforeInclude, afterInclude,
  2784. std::move(filename)));
  2785. }
  2786. return unity_files;
  2787. }
  2788. void cmLocalGenerator::AddUnityBuild(cmGeneratorTarget* target)
  2789. {
  2790. if (!target->GetPropertyAsBool("UNITY_BUILD")) {
  2791. return;
  2792. }
  2793. std::vector<UnityBatchedSource> unitySources;
  2794. std::vector<std::string> configs =
  2795. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  2796. std::map<cmSourceFile const*, size_t> index;
  2797. for (size_t ci = 0; ci < configs.size(); ++ci) {
  2798. // FIXME: Refactor collection of sources to not evaluate object libraries.
  2799. // Their final set of object files might be transformed by unity builds.
  2800. std::vector<cmSourceFile*> sources;
  2801. target->GetSourceFiles(sources, configs[ci]);
  2802. for (cmSourceFile* sf : sources) {
  2803. // Files which need C++ scanning cannot participate in unity builds as
  2804. // there is a single place in TUs that may perform module-dependency bits
  2805. // and a unity source cannot `#include` them in-order and represent a
  2806. // valid TU.
  2807. if (sf->GetLanguage() == "CXX"_s &&
  2808. target->NeedDyndepForSource("CXX", configs[ci], sf)) {
  2809. continue;
  2810. }
  2811. auto mi = index.find(sf);
  2812. if (mi == index.end()) {
  2813. unitySources.emplace_back(sf);
  2814. std::map<cmSourceFile const*, size_t>::value_type entry(
  2815. sf, unitySources.size() - 1);
  2816. mi = index.insert(entry).first;
  2817. }
  2818. unitySources[mi->second].Configs.emplace_back(ci);
  2819. }
  2820. }
  2821. std::string filename_base =
  2822. cmStrCat(this->GetCurrentBinaryDirectory(), "/CMakeFiles/",
  2823. target->GetName(), ".dir/Unity/");
  2824. cmValue batchSizeString = target->GetProperty("UNITY_BUILD_BATCH_SIZE");
  2825. const size_t unityBatchSize = batchSizeString
  2826. ? static_cast<size_t>(std::atoi(batchSizeString->c_str()))
  2827. : 0;
  2828. cmValue beforeInclude =
  2829. target->GetProperty("UNITY_BUILD_CODE_BEFORE_INCLUDE");
  2830. cmValue afterInclude = target->GetProperty("UNITY_BUILD_CODE_AFTER_INCLUDE");
  2831. cmValue unityMode = target->GetProperty("UNITY_BUILD_MODE");
  2832. for (std::string lang : { "C", "CXX" }) {
  2833. std::vector<UnityBatchedSource> filtered_sources;
  2834. std::copy_if(unitySources.begin(), unitySources.end(),
  2835. std::back_inserter(filtered_sources),
  2836. [&](UnityBatchedSource const& ubs) -> bool {
  2837. cmSourceFile* sf = ubs.Source;
  2838. return sf->GetLanguage() == lang &&
  2839. !sf->GetPropertyAsBool("SKIP_UNITY_BUILD_INCLUSION") &&
  2840. !sf->GetPropertyAsBool("HEADER_FILE_ONLY") &&
  2841. !sf->GetProperty("COMPILE_OPTIONS") &&
  2842. !sf->GetProperty("COMPILE_DEFINITIONS") &&
  2843. !sf->GetProperty("COMPILE_FLAGS") &&
  2844. !sf->GetProperty("INCLUDE_DIRECTORIES");
  2845. });
  2846. std::vector<UnitySource> unity_files;
  2847. if (!unityMode || *unityMode == "BATCH") {
  2848. unity_files = AddUnityFilesModeAuto(
  2849. target, lang, configs, filtered_sources, beforeInclude, afterInclude,
  2850. filename_base, unityBatchSize);
  2851. } else if (unityMode && *unityMode == "GROUP") {
  2852. unity_files =
  2853. AddUnityFilesModeGroup(target, lang, configs, filtered_sources,
  2854. beforeInclude, afterInclude, filename_base);
  2855. } else {
  2856. // unity mode is set to an unsupported value
  2857. std::string e("Invalid UNITY_BUILD_MODE value of " + *unityMode +
  2858. " assigned to target " + target->GetName() +
  2859. ". Acceptable values are BATCH and GROUP.");
  2860. this->IssueMessage(MessageType::FATAL_ERROR, e);
  2861. }
  2862. for (UnitySource const& file : unity_files) {
  2863. auto* unity = this->GetMakefile()->GetOrCreateSource(file.Path);
  2864. target->AddSource(file.Path, true);
  2865. unity->SetProperty("SKIP_UNITY_BUILD_INCLUSION", "ON");
  2866. unity->SetProperty("UNITY_SOURCE_FILE", file.Path);
  2867. unity->SetProperty("CXX_SCAN_FOR_MODULES", "0");
  2868. if (file.PerConfig) {
  2869. unity->SetProperty("COMPILE_DEFINITIONS",
  2870. "CMAKE_UNITY_CONFIG_$<UPPER_CASE:$<CONFIG>>");
  2871. }
  2872. }
  2873. }
  2874. }
  2875. void cmLocalGenerator::AppendIPOLinkerFlags(std::string& flags,
  2876. cmGeneratorTarget* target,
  2877. const std::string& config,
  2878. const std::string& lang)
  2879. {
  2880. if (!target->IsIPOEnabled(lang, config)) {
  2881. return;
  2882. }
  2883. switch (target->GetType()) {
  2884. case cmStateEnums::EXECUTABLE:
  2885. case cmStateEnums::SHARED_LIBRARY:
  2886. case cmStateEnums::MODULE_LIBRARY:
  2887. break;
  2888. default:
  2889. return;
  2890. }
  2891. const std::string name = "CMAKE_" + lang + "_LINK_OPTIONS_IPO";
  2892. cmValue rawFlagsList = this->Makefile->GetDefinition(name);
  2893. if (!rawFlagsList) {
  2894. return;
  2895. }
  2896. cmList flagsList{ *rawFlagsList };
  2897. for (std::string const& o : flagsList) {
  2898. this->AppendFlagEscape(flags, o);
  2899. }
  2900. }
  2901. void cmLocalGenerator::AppendPositionIndependentLinkerFlags(
  2902. std::string& flags, cmGeneratorTarget* target, const std::string& config,
  2903. const std::string& lang)
  2904. {
  2905. // For now, only EXECUTABLE is concerned
  2906. if (target->GetType() != cmStateEnums::EXECUTABLE) {
  2907. return;
  2908. }
  2909. const char* PICValue = target->GetLinkPIEProperty(config);
  2910. if (PICValue == nullptr) {
  2911. // POSITION_INDEPENDENT_CODE is not set
  2912. return;
  2913. }
  2914. const std::string mode = cmIsOn(PICValue) ? "PIE" : "NO_PIE";
  2915. std::string supported = "CMAKE_" + lang + "_LINK_" + mode + "_SUPPORTED";
  2916. if (cmIsOff(this->Makefile->GetDefinition(supported))) {
  2917. return;
  2918. }
  2919. std::string name = "CMAKE_" + lang + "_LINK_OPTIONS_" + mode;
  2920. auto pieFlags = this->Makefile->GetSafeDefinition(name);
  2921. if (pieFlags.empty()) {
  2922. return;
  2923. }
  2924. cmList flagsList{ pieFlags };
  2925. for (const auto& flag : flagsList) {
  2926. this->AppendFlagEscape(flags, flag);
  2927. }
  2928. }
  2929. void cmLocalGenerator::AppendDependencyInfoLinkerFlags(
  2930. std::string& flags, cmGeneratorTarget* target, const std::string& config,
  2931. const std::string& linkLanguage)
  2932. {
  2933. if (!this->GetGlobalGenerator()->SupportsLinkerDependencyFile() ||
  2934. !target->HasLinkDependencyFile(config)) {
  2935. return;
  2936. }
  2937. auto depFlag = *this->Makefile->GetDefinition(
  2938. cmStrCat("CMAKE_", linkLanguage, "_LINKER_DEPFILE_FLAGS"));
  2939. if (depFlag.empty()) {
  2940. return;
  2941. }
  2942. auto depFile = this->ConvertToOutputFormat(
  2943. this->MaybeRelativeToWorkDir(this->GetLinkDependencyFile(target, config)),
  2944. cmOutputConverter::SHELL);
  2945. auto rulePlaceholderExpander = this->CreateRulePlaceholderExpander();
  2946. cmRulePlaceholderExpander::RuleVariables linkDepsVariables;
  2947. linkDepsVariables.DependencyFile = depFile.c_str();
  2948. rulePlaceholderExpander->ExpandRuleVariables(this, depFlag,
  2949. linkDepsVariables);
  2950. auto depFlags = cmExpandListWithBacktrace(depFlag);
  2951. target->ResolveLinkerWrapper(depFlags, linkLanguage);
  2952. this->AppendFlags(flags, depFlags);
  2953. }
  2954. std::string cmLocalGenerator::GetLinkDependencyFile(
  2955. cmGeneratorTarget* /*target*/, const std::string& /*config*/) const
  2956. {
  2957. return "link.d";
  2958. }
  2959. void cmLocalGenerator::AppendModuleDefinitionFlag(
  2960. std::string& flags, cmGeneratorTarget const* target,
  2961. cmLinkLineComputer* linkLineComputer, std::string const& config)
  2962. {
  2963. cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  2964. target->GetModuleDefinitionInfo(config);
  2965. if (!mdi || mdi->DefFile.empty()) {
  2966. return;
  2967. }
  2968. cmValue defFileFlag =
  2969. this->Makefile->GetDefinition("CMAKE_LINK_DEF_FILE_FLAG");
  2970. if (!defFileFlag) {
  2971. return;
  2972. }
  2973. // Append the flag and value. Use ConvertToLinkReference to help
  2974. // vs6's "cl -link" pass it to the linker.
  2975. std::string flag =
  2976. cmStrCat(*defFileFlag,
  2977. this->ConvertToOutputFormat(
  2978. linkLineComputer->ConvertToLinkReference(mdi->DefFile),
  2979. cmOutputConverter::SHELL));
  2980. this->AppendFlags(flags, flag);
  2981. }
  2982. bool cmLocalGenerator::AppendLWYUFlags(std::string& flags,
  2983. const cmGeneratorTarget* target,
  2984. const std::string& lang)
  2985. {
  2986. auto useLWYU = target->GetPropertyAsBool("LINK_WHAT_YOU_USE") &&
  2987. (target->GetType() == cmStateEnums::TargetType::EXECUTABLE ||
  2988. target->GetType() == cmStateEnums::TargetType::SHARED_LIBRARY ||
  2989. target->GetType() == cmStateEnums::TargetType::MODULE_LIBRARY);
  2990. if (useLWYU) {
  2991. const auto& lwyuFlag = this->GetMakefile()->GetSafeDefinition(
  2992. cmStrCat("CMAKE_", lang, "_LINK_WHAT_YOU_USE_FLAG"));
  2993. useLWYU = !lwyuFlag.empty();
  2994. if (useLWYU) {
  2995. std::vector<BT<std::string>> lwyuOpts;
  2996. lwyuOpts.emplace_back(lwyuFlag);
  2997. this->AppendFlags(flags, target->ResolveLinkerWrapper(lwyuOpts, lang));
  2998. }
  2999. }
  3000. return useLWYU;
  3001. }
  3002. void cmLocalGenerator::AppendCompileOptions(std::string& options,
  3003. std::string const& options_list,
  3004. const char* regex) const
  3005. {
  3006. // Short-circuit if there are no options.
  3007. if (options_list.empty()) {
  3008. return;
  3009. }
  3010. // Expand the list of options.
  3011. cmList options_vec{ options_list };
  3012. this->AppendCompileOptions(options, options_vec, regex);
  3013. }
  3014. void cmLocalGenerator::AppendCompileOptions(
  3015. std::string& options, const std::vector<std::string>& options_vec,
  3016. const char* regex) const
  3017. {
  3018. if (regex != nullptr) {
  3019. // Filter flags upon specified reges.
  3020. cmsys::RegularExpression r(regex);
  3021. for (std::string const& opt : options_vec) {
  3022. if (r.find(opt)) {
  3023. this->AppendFlagEscape(options, opt);
  3024. }
  3025. }
  3026. } else {
  3027. for (std::string const& opt : options_vec) {
  3028. this->AppendFlagEscape(options, opt);
  3029. }
  3030. }
  3031. }
  3032. void cmLocalGenerator::AppendCompileOptions(
  3033. std::vector<BT<std::string>>& options,
  3034. const std::vector<BT<std::string>>& options_vec, const char* regex) const
  3035. {
  3036. if (regex != nullptr) {
  3037. // Filter flags upon specified regular expressions.
  3038. cmsys::RegularExpression r(regex);
  3039. for (BT<std::string> const& opt : options_vec) {
  3040. if (r.find(opt.Value)) {
  3041. std::string flag;
  3042. this->AppendFlagEscape(flag, opt.Value);
  3043. options.emplace_back(std::move(flag), opt.Backtrace);
  3044. }
  3045. }
  3046. } else {
  3047. for (BT<std::string> const& opt : options_vec) {
  3048. std::string flag;
  3049. this->AppendFlagEscape(flag, opt.Value);
  3050. options.emplace_back(std::move(flag), opt.Backtrace);
  3051. }
  3052. }
  3053. }
  3054. void cmLocalGenerator::AppendIncludeDirectories(
  3055. std::vector<std::string>& includes, const std::string& includes_list,
  3056. const cmSourceFile& sourceFile) const
  3057. {
  3058. // Short-circuit if there are no includes.
  3059. if (includes_list.empty()) {
  3060. return;
  3061. }
  3062. // Expand the list of includes.
  3063. cmList includes_vec{ includes_list };
  3064. this->AppendIncludeDirectories(includes, includes_vec, sourceFile);
  3065. }
  3066. void cmLocalGenerator::AppendIncludeDirectories(
  3067. std::vector<std::string>& includes,
  3068. const std::vector<std::string>& includes_vec,
  3069. const cmSourceFile& sourceFile) const
  3070. {
  3071. std::unordered_set<std::string> uniqueIncludes;
  3072. for (const std::string& include : includes_vec) {
  3073. if (!cmSystemTools::FileIsFullPath(include)) {
  3074. std::ostringstream e;
  3075. e << "Found relative path while evaluating include directories of "
  3076. "\""
  3077. << sourceFile.GetLocation().GetName() << "\":\n \"" << include
  3078. << "\"\n";
  3079. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  3080. return;
  3081. }
  3082. std::string inc = include;
  3083. if (!cmIsOff(inc)) {
  3084. cmSystemTools::ConvertToUnixSlashes(inc);
  3085. }
  3086. if (uniqueIncludes.insert(inc).second) {
  3087. includes.push_back(std::move(inc));
  3088. }
  3089. }
  3090. }
  3091. void cmLocalGenerator::AppendDefines(std::set<std::string>& defines,
  3092. std::string const& defines_list) const
  3093. {
  3094. std::set<BT<std::string>> tmp;
  3095. this->AppendDefines(tmp, cmExpandListWithBacktrace(defines_list));
  3096. for (BT<std::string> const& i : tmp) {
  3097. defines.emplace(i.Value);
  3098. }
  3099. }
  3100. void cmLocalGenerator::AppendDefines(std::set<BT<std::string>>& defines,
  3101. std::string const& defines_list) const
  3102. {
  3103. // Short-circuit if there are no definitions.
  3104. if (defines_list.empty()) {
  3105. return;
  3106. }
  3107. // Expand the list of definitions.
  3108. this->AppendDefines(defines, cmExpandListWithBacktrace(defines_list));
  3109. }
  3110. void cmLocalGenerator::AppendDefines(
  3111. std::set<BT<std::string>>& defines,
  3112. const std::vector<BT<std::string>>& defines_vec) const
  3113. {
  3114. for (BT<std::string> const& d : defines_vec) {
  3115. // Skip unsupported definitions.
  3116. if (!this->CheckDefinition(d.Value)) {
  3117. continue;
  3118. }
  3119. // remove any leading -D
  3120. if (cmHasLiteralPrefix(d.Value, "-D")) {
  3121. defines.emplace(d.Value.substr(2), d.Backtrace);
  3122. } else {
  3123. defines.insert(d);
  3124. }
  3125. }
  3126. }
  3127. void cmLocalGenerator::JoinDefines(const std::set<std::string>& defines,
  3128. std::string& definesString,
  3129. const std::string& lang)
  3130. {
  3131. // Lookup the define flag for the current language.
  3132. std::string dflag = "-D";
  3133. if (!lang.empty()) {
  3134. cmValue df =
  3135. this->Makefile->GetDefinition(cmStrCat("CMAKE_", lang, "_DEFINE_FLAG"));
  3136. if (cmNonempty(df)) {
  3137. dflag = *df;
  3138. }
  3139. }
  3140. const char* itemSeparator = definesString.empty() ? "" : " ";
  3141. for (std::string const& define : defines) {
  3142. // Append the definition with proper escaping.
  3143. std::string def = dflag;
  3144. if (this->GetState()->UseWatcomWMake()) {
  3145. // The Watcom compiler does its own command line parsing instead
  3146. // of using the windows shell rules. Definitions are one of
  3147. // -DNAME
  3148. // -DNAME=<cpp-token>
  3149. // -DNAME="c-string with spaces and other characters(?@#$)"
  3150. //
  3151. // Watcom will properly parse each of these cases from the
  3152. // command line without any escapes. However we still have to
  3153. // get the '$' and '#' characters through WMake as '$$' and
  3154. // '$#'.
  3155. for (char c : define) {
  3156. if (c == '$' || c == '#') {
  3157. def += '$';
  3158. }
  3159. def += c;
  3160. }
  3161. } else {
  3162. // Make the definition appear properly on the command line. Use
  3163. // -DNAME="value" instead of -D"NAME=value" for historical reasons.
  3164. std::string::size_type eq = define.find('=');
  3165. def += define.substr(0, eq);
  3166. if (eq != std::string::npos) {
  3167. def += "=";
  3168. def += this->EscapeForShell(define.substr(eq + 1), true);
  3169. }
  3170. }
  3171. definesString += itemSeparator;
  3172. itemSeparator = " ";
  3173. definesString += def;
  3174. }
  3175. }
  3176. void cmLocalGenerator::AppendFeatureOptions(std::string& flags,
  3177. const std::string& lang,
  3178. const char* feature)
  3179. {
  3180. cmValue optionList = this->Makefile->GetDefinition(
  3181. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_", feature));
  3182. if (optionList) {
  3183. cmList options{ *optionList };
  3184. for (std::string const& o : options) {
  3185. this->AppendFlagEscape(flags, o);
  3186. }
  3187. }
  3188. }
  3189. cmValue cmLocalGenerator::GetFeature(const std::string& feature,
  3190. const std::string& config)
  3191. {
  3192. std::string featureName = feature;
  3193. // TODO: Define accumulation policy for features (prepend, append,
  3194. // replace). Currently we always replace.
  3195. if (!config.empty()) {
  3196. featureName += "_";
  3197. featureName += cmSystemTools::UpperCase(config);
  3198. }
  3199. cmStateSnapshot snp = this->StateSnapshot;
  3200. while (snp.IsValid()) {
  3201. if (cmValue value = snp.GetDirectory().GetProperty(featureName)) {
  3202. return value;
  3203. }
  3204. snp = snp.GetBuildsystemDirectoryParent();
  3205. }
  3206. return nullptr;
  3207. }
  3208. std::string cmLocalGenerator::GetProjectName() const
  3209. {
  3210. return this->StateSnapshot.GetProjectName();
  3211. }
  3212. std::string cmLocalGenerator::ConstructComment(
  3213. cmCustomCommandGenerator const& ccg, const char* default_comment) const
  3214. {
  3215. // Check for a comment provided with the command.
  3216. if (cm::optional<std::string> comment = ccg.GetComment()) {
  3217. return *comment;
  3218. }
  3219. // Construct a reasonable default comment if possible.
  3220. if (!ccg.GetOutputs().empty()) {
  3221. std::string comment;
  3222. comment = "Generating ";
  3223. const char* sep = "";
  3224. for (std::string const& o : ccg.GetOutputs()) {
  3225. comment += sep;
  3226. comment += this->MaybeRelativeToCurBinDir(o);
  3227. sep = ", ";
  3228. }
  3229. return comment;
  3230. }
  3231. // Otherwise use the provided default.
  3232. return default_comment;
  3233. }
  3234. class cmInstallTargetGeneratorLocal : public cmInstallTargetGenerator
  3235. {
  3236. public:
  3237. cmInstallTargetGeneratorLocal(cmLocalGenerator* lg, std::string const& t,
  3238. std::string const& dest, bool implib)
  3239. : cmInstallTargetGenerator(
  3240. t, dest, implib, "", std::vector<std::string>(), "Unspecified",
  3241. cmInstallGenerator::SelectMessageLevel(lg->GetMakefile()), false,
  3242. false)
  3243. {
  3244. this->Compute(lg);
  3245. }
  3246. };
  3247. void cmLocalGenerator::GenerateTargetInstallRules(
  3248. std::ostream& os, const std::string& config,
  3249. std::vector<std::string> const& configurationTypes)
  3250. {
  3251. // Convert the old-style install specification from each target to
  3252. // an install generator and run it.
  3253. const auto& tgts = this->GetGeneratorTargets();
  3254. for (const auto& l : tgts) {
  3255. if (l->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  3256. continue;
  3257. }
  3258. // Include the user-specified pre-install script for this target.
  3259. if (cmValue preinstall = l->GetProperty("PRE_INSTALL_SCRIPT")) {
  3260. cmInstallScriptGenerator g(*preinstall, false, "", false, false);
  3261. g.Generate(os, config, configurationTypes);
  3262. }
  3263. // Install this target if a destination is given.
  3264. if (!l->Target->GetInstallPath().empty()) {
  3265. // Compute the full install destination. Note that converting
  3266. // to unix slashes also removes any trailing slash.
  3267. // We also skip over the leading slash given by the user.
  3268. std::string destination = l->Target->GetInstallPath().substr(1);
  3269. cmSystemTools::ConvertToUnixSlashes(destination);
  3270. if (destination.empty()) {
  3271. destination = ".";
  3272. }
  3273. // Generate the proper install generator for this target type.
  3274. switch (l->GetType()) {
  3275. case cmStateEnums::EXECUTABLE:
  3276. case cmStateEnums::STATIC_LIBRARY:
  3277. case cmStateEnums::MODULE_LIBRARY: {
  3278. // Use a target install generator.
  3279. cmInstallTargetGeneratorLocal g(this, l->GetName(), destination,
  3280. false);
  3281. g.Generate(os, config, configurationTypes);
  3282. } break;
  3283. case cmStateEnums::SHARED_LIBRARY: {
  3284. #if defined(_WIN32) || defined(__CYGWIN__)
  3285. // Special code to handle DLL. Install the import library
  3286. // to the normal destination and the DLL to the runtime
  3287. // destination.
  3288. cmInstallTargetGeneratorLocal g1(this, l->GetName(), destination,
  3289. true);
  3290. g1.Generate(os, config, configurationTypes);
  3291. // We also skip over the leading slash given by the user.
  3292. destination = l->Target->GetRuntimeInstallPath().substr(1);
  3293. cmSystemTools::ConvertToUnixSlashes(destination);
  3294. cmInstallTargetGeneratorLocal g2(this, l->GetName(), destination,
  3295. false);
  3296. g2.Generate(os, config, configurationTypes);
  3297. #else
  3298. // Use a target install generator.
  3299. cmInstallTargetGeneratorLocal g(this, l->GetName(), destination,
  3300. false);
  3301. g.Generate(os, config, configurationTypes);
  3302. #endif
  3303. } break;
  3304. default:
  3305. break;
  3306. }
  3307. }
  3308. // Include the user-specified post-install script for this target.
  3309. if (cmValue postinstall = l->GetProperty("POST_INSTALL_SCRIPT")) {
  3310. cmInstallScriptGenerator g(*postinstall, false, "", false, false);
  3311. g.Generate(os, config, configurationTypes);
  3312. }
  3313. }
  3314. }
  3315. namespace {
  3316. bool cmLocalGeneratorShortenObjectName(std::string& objName,
  3317. std::string::size_type max_len)
  3318. {
  3319. // Check if the path can be shortened using an md5 sum replacement for
  3320. // a portion of the path.
  3321. std::string::size_type md5Len = 32;
  3322. std::string::size_type numExtraChars = objName.size() - max_len + md5Len;
  3323. std::string::size_type pos = objName.find('/', numExtraChars);
  3324. if (pos == std::string::npos) {
  3325. pos = objName.rfind('/', numExtraChars);
  3326. if (pos == std::string::npos || pos <= md5Len) {
  3327. return false;
  3328. }
  3329. }
  3330. // Replace the beginning of the path portion of the object name with
  3331. // its own md5 sum.
  3332. cmCryptoHash md5(cmCryptoHash::AlgoMD5);
  3333. std::string md5name = cmStrCat(md5.HashString(objName.substr(0, pos)),
  3334. cm::string_view(objName).substr(pos));
  3335. objName = md5name;
  3336. // The object name is now shorter, check if it is short enough.
  3337. return pos >= numExtraChars;
  3338. }
  3339. bool cmLocalGeneratorCheckObjectName(std::string& objName,
  3340. std::string::size_type dir_len,
  3341. std::string::size_type max_total_len)
  3342. {
  3343. // Enforce the maximum file name length if possible.
  3344. std::string::size_type max_obj_len = max_total_len;
  3345. if (dir_len < max_total_len) {
  3346. max_obj_len = max_total_len - dir_len;
  3347. if (objName.size() > max_obj_len) {
  3348. // The current object file name is too long. Try to shorten it.
  3349. return cmLocalGeneratorShortenObjectName(objName, max_obj_len);
  3350. }
  3351. // The object file name is short enough.
  3352. return true;
  3353. }
  3354. // The build directory in which the object will be stored is
  3355. // already too deep.
  3356. return false;
  3357. }
  3358. }
  3359. std::string& cmLocalGenerator::CreateSafeUniqueObjectFileName(
  3360. const std::string& sin, std::string const& dir_max)
  3361. {
  3362. // Look for an existing mapped name for this object file.
  3363. auto it = this->UniqueObjectNamesMap.find(sin);
  3364. // If no entry exists create one.
  3365. if (it == this->UniqueObjectNamesMap.end()) {
  3366. // Start with the original name.
  3367. std::string ssin = sin;
  3368. // Avoid full paths by removing leading slashes.
  3369. ssin.erase(0, ssin.find_first_not_of('/'));
  3370. // Avoid full paths by removing colons.
  3371. std::replace(ssin.begin(), ssin.end(), ':', '_');
  3372. // Avoid relative paths that go up the tree.
  3373. cmSystemTools::ReplaceString(ssin, "../", "__/");
  3374. // Avoid spaces.
  3375. std::replace(ssin.begin(), ssin.end(), ' ', '_');
  3376. // Mangle the name if necessary.
  3377. if (this->Makefile->IsOn("CMAKE_MANGLE_OBJECT_FILE_NAMES")) {
  3378. bool done;
  3379. int cc = 0;
  3380. char rpstr[100];
  3381. snprintf(rpstr, sizeof(rpstr), "_p_");
  3382. cmSystemTools::ReplaceString(ssin, "+", rpstr);
  3383. std::string sssin = sin;
  3384. do {
  3385. done = true;
  3386. for (it = this->UniqueObjectNamesMap.begin();
  3387. it != this->UniqueObjectNamesMap.end(); ++it) {
  3388. if (it->second == ssin) {
  3389. done = false;
  3390. }
  3391. }
  3392. if (done) {
  3393. break;
  3394. }
  3395. sssin = ssin;
  3396. cmSystemTools::ReplaceString(ssin, "_p_", rpstr);
  3397. snprintf(rpstr, sizeof(rpstr), "_p%d_", cc++);
  3398. } while (!done);
  3399. }
  3400. if (!cmLocalGeneratorCheckObjectName(ssin, dir_max.size(),
  3401. this->ObjectPathMax)) {
  3402. // Warn if this is the first time the path has been seen.
  3403. if (this->ObjectMaxPathViolations.insert(dir_max).second) {
  3404. std::ostringstream m;
  3405. /* clang-format off */
  3406. m << "The object file directory\n"
  3407. << " " << dir_max << "\n"
  3408. << "has " << dir_max.size() << " characters. "
  3409. << "The maximum full path to an object file is "
  3410. << this->ObjectPathMax << " characters "
  3411. << "(see CMAKE_OBJECT_PATH_MAX). "
  3412. << "Object file\n"
  3413. << " " << ssin << "\n"
  3414. << "cannot be safely placed under this directory. "
  3415. << "The build may not work correctly.";
  3416. /* clang-format on */
  3417. this->IssueMessage(MessageType::WARNING, m.str());
  3418. }
  3419. }
  3420. // Insert the newly mapped object file name.
  3421. std::map<std::string, std::string>::value_type e(sin, ssin);
  3422. it = this->UniqueObjectNamesMap.insert(e).first;
  3423. }
  3424. // Return the map entry.
  3425. return it->second;
  3426. }
  3427. void cmLocalGenerator::ComputeObjectFilenames(
  3428. std::map<cmSourceFile const*, std::string>& /*unused*/,
  3429. cmGeneratorTarget const* /*unused*/)
  3430. {
  3431. }
  3432. bool cmLocalGenerator::IsWindowsShell() const
  3433. {
  3434. return this->GetState()->UseWindowsShell();
  3435. }
  3436. bool cmLocalGenerator::IsWatcomWMake() const
  3437. {
  3438. return this->GetState()->UseWatcomWMake();
  3439. }
  3440. bool cmLocalGenerator::IsMinGWMake() const
  3441. {
  3442. return this->GetState()->UseMinGWMake();
  3443. }
  3444. bool cmLocalGenerator::IsNMake() const
  3445. {
  3446. return this->GetState()->UseNMake();
  3447. }
  3448. bool cmLocalGenerator::IsNinjaMulti() const
  3449. {
  3450. return this->GetState()->UseNinjaMulti();
  3451. }
  3452. namespace {
  3453. std::string relativeIfUnder(std::string const& top, std::string const& cur,
  3454. std::string const& path)
  3455. {
  3456. // Use a path relative to 'cur' if it can be expressed without
  3457. // a `../` sequence that leaves 'top'.
  3458. if (cmSystemTools::IsSubDirectory(path, cur) ||
  3459. (cmSystemTools::IsSubDirectory(cur, top) &&
  3460. cmSystemTools::IsSubDirectory(path, top))) {
  3461. return cmSystemTools::ForceToRelativePath(cur, path);
  3462. }
  3463. return path;
  3464. }
  3465. }
  3466. std::string cmLocalGenerator::GetObjectFileNameWithoutTarget(
  3467. const cmSourceFile& source, std::string const& dir_max,
  3468. bool* hasSourceExtension, char const* customOutputExtension)
  3469. {
  3470. // Construct the object file name using the full path to the source
  3471. // file which is its only unique identification.
  3472. std::string const& fullPath = source.GetFullPath();
  3473. // Try referencing the source relative to the source tree.
  3474. std::string relFromSource = relativeIfUnder(
  3475. this->GetSourceDirectory(), this->GetCurrentSourceDirectory(), fullPath);
  3476. assert(!relFromSource.empty());
  3477. bool relSource = !cmSystemTools::FileIsFullPath(relFromSource);
  3478. bool subSource = relSource && relFromSource[0] != '.';
  3479. // Try referencing the source relative to the binary tree.
  3480. std::string relFromBinary = relativeIfUnder(
  3481. this->GetBinaryDirectory(), this->GetCurrentBinaryDirectory(), fullPath);
  3482. assert(!relFromBinary.empty());
  3483. bool relBinary = !cmSystemTools::FileIsFullPath(relFromBinary);
  3484. bool subBinary = relBinary && relFromBinary[0] != '.';
  3485. // Select a nice-looking reference to the source file to construct
  3486. // the object file name.
  3487. std::string objectName;
  3488. // XXX(clang-tidy): https://bugs.llvm.org/show_bug.cgi?id=44165
  3489. // NOLINTNEXTLINE(bugprone-branch-clone)
  3490. if ((relSource && !relBinary) || (subSource && !subBinary)) {
  3491. objectName = relFromSource;
  3492. } else if ((relBinary && !relSource) || (subBinary && !subSource) ||
  3493. relFromBinary.length() < relFromSource.length()) {
  3494. objectName = relFromBinary;
  3495. } else {
  3496. objectName = relFromSource;
  3497. }
  3498. // if it is still a full path check for the try compile case
  3499. // try compile never have in source sources, and should not
  3500. // have conflicting source file names in the same target
  3501. if (cmSystemTools::FileIsFullPath(objectName)) {
  3502. if (this->GetGlobalGenerator()->GetCMakeInstance()->GetIsInTryCompile()) {
  3503. objectName = cmSystemTools::GetFilenameName(source.GetFullPath());
  3504. }
  3505. }
  3506. // Ensure that for the CMakeFiles/<target>.dir/generated_source_file
  3507. // we don't end up having:
  3508. // CMakeFiles/<target>.dir/CMakeFiles/<target>.dir/generated_source_file.obj
  3509. cmValue unitySourceFile = source.GetProperty("UNITY_SOURCE_FILE");
  3510. cmValue pchExtension = source.GetProperty("PCH_EXTENSION");
  3511. const bool isPchObject = objectName.find("cmake_pch") != std::string::npos;
  3512. if (unitySourceFile || pchExtension || isPchObject) {
  3513. if (pchExtension) {
  3514. customOutputExtension = pchExtension->c_str();
  3515. }
  3516. cmsys::RegularExpression var("(CMakeFiles/[^/]+.dir/)");
  3517. if (var.find(objectName)) {
  3518. objectName.erase(var.start(), var.end() - var.start());
  3519. }
  3520. }
  3521. // Replace the original source file extension with the object file
  3522. // extension.
  3523. bool keptSourceExtension = true;
  3524. if (!source.GetPropertyAsBool("KEEP_EXTENSION")) {
  3525. // Decide whether this language wants to replace the source
  3526. // extension with the object extension. For CMake 2.4
  3527. // compatibility do this by default.
  3528. bool replaceExt = this->NeedBackwardsCompatibility_2_4();
  3529. if (!replaceExt) {
  3530. std::string lang = source.GetLanguage();
  3531. if (!lang.empty()) {
  3532. replaceExt = this->Makefile->IsOn(
  3533. cmStrCat("CMAKE_", lang, "_OUTPUT_EXTENSION_REPLACE"));
  3534. }
  3535. }
  3536. // Remove the source extension if it is to be replaced.
  3537. if (replaceExt || customOutputExtension) {
  3538. keptSourceExtension = false;
  3539. std::string::size_type dot_pos = objectName.rfind('.');
  3540. if (dot_pos != std::string::npos) {
  3541. objectName = objectName.substr(0, dot_pos);
  3542. }
  3543. }
  3544. // Store the new extension.
  3545. if (customOutputExtension) {
  3546. objectName += customOutputExtension;
  3547. } else {
  3548. objectName += this->GlobalGenerator->GetLanguageOutputExtension(source);
  3549. }
  3550. }
  3551. if (hasSourceExtension) {
  3552. *hasSourceExtension = keptSourceExtension;
  3553. }
  3554. // Convert to a safe name.
  3555. return this->CreateSafeUniqueObjectFileName(objectName, dir_max);
  3556. }
  3557. std::string cmLocalGenerator::GetSourceFileLanguage(const cmSourceFile& source)
  3558. {
  3559. return source.GetLanguage();
  3560. }
  3561. cmake* cmLocalGenerator::GetCMakeInstance() const
  3562. {
  3563. return this->GlobalGenerator->GetCMakeInstance();
  3564. }
  3565. std::string const& cmLocalGenerator::GetSourceDirectory() const
  3566. {
  3567. return this->GetCMakeInstance()->GetHomeDirectory();
  3568. }
  3569. std::string const& cmLocalGenerator::GetBinaryDirectory() const
  3570. {
  3571. return this->GetCMakeInstance()->GetHomeOutputDirectory();
  3572. }
  3573. std::string const& cmLocalGenerator::GetCurrentBinaryDirectory() const
  3574. {
  3575. return this->StateSnapshot.GetDirectory().GetCurrentBinary();
  3576. }
  3577. std::string const& cmLocalGenerator::GetCurrentSourceDirectory() const
  3578. {
  3579. return this->StateSnapshot.GetDirectory().GetCurrentSource();
  3580. }
  3581. std::string cmLocalGenerator::GetTargetDirectory(
  3582. const cmGeneratorTarget* /*unused*/) const
  3583. {
  3584. cmSystemTools::Error("GetTargetDirectory"
  3585. " called on cmLocalGenerator");
  3586. return "";
  3587. }
  3588. KWIML_INT_uint64_t cmLocalGenerator::GetBackwardsCompatibility()
  3589. {
  3590. // The computed version may change until the project is fully
  3591. // configured.
  3592. if (!this->BackwardsCompatibilityFinal) {
  3593. unsigned int major = 0;
  3594. unsigned int minor = 0;
  3595. unsigned int patch = 0;
  3596. if (cmValue value =
  3597. this->Makefile->GetDefinition("CMAKE_BACKWARDS_COMPATIBILITY")) {
  3598. switch (sscanf(value->c_str(), "%u.%u.%u", &major, &minor, &patch)) {
  3599. case 2:
  3600. patch = 0;
  3601. break;
  3602. case 1:
  3603. minor = 0;
  3604. patch = 0;
  3605. break;
  3606. default:
  3607. break;
  3608. }
  3609. }
  3610. this->BackwardsCompatibility = CMake_VERSION_ENCODE(major, minor, patch);
  3611. this->BackwardsCompatibilityFinal = true;
  3612. }
  3613. return this->BackwardsCompatibility;
  3614. }
  3615. bool cmLocalGenerator::NeedBackwardsCompatibility_2_4()
  3616. {
  3617. // Check the policy to decide whether to pay attention to this
  3618. // variable.
  3619. switch (this->GetPolicyStatus(cmPolicies::CMP0001)) {
  3620. case cmPolicies::WARN:
  3621. // WARN is just OLD without warning because user code does not
  3622. // always affect whether this check is done.
  3623. CM_FALLTHROUGH;
  3624. case cmPolicies::OLD:
  3625. // Old behavior is to check the variable.
  3626. break;
  3627. case cmPolicies::NEW:
  3628. // New behavior is to ignore the variable.
  3629. case cmPolicies::REQUIRED_IF_USED:
  3630. case cmPolicies::REQUIRED_ALWAYS:
  3631. // This will never be the case because the only way to require
  3632. // the setting is to require the user to specify version policy
  3633. // 2.6 or higher. Once we add that requirement then this whole
  3634. // method can be removed anyway.
  3635. return false;
  3636. }
  3637. // Compatibility is needed if CMAKE_BACKWARDS_COMPATIBILITY is set
  3638. // equal to or lower than the given version.
  3639. KWIML_INT_uint64_t actual_compat = this->GetBackwardsCompatibility();
  3640. return (actual_compat && actual_compat <= CMake_VERSION_ENCODE(2, 4, 255));
  3641. }
  3642. cmPolicies::PolicyStatus cmLocalGenerator::GetPolicyStatus(
  3643. cmPolicies::PolicyID id) const
  3644. {
  3645. return this->Makefile->GetPolicyStatus(id);
  3646. }
  3647. bool cmLocalGenerator::CheckDefinition(std::string const& define) const
  3648. {
  3649. // Many compilers do not support -DNAME(arg)=sdf so we disable it.
  3650. std::string::size_type pos = define.find_first_of("(=");
  3651. if (pos != std::string::npos) {
  3652. if (define[pos] == '(') {
  3653. std::ostringstream e;
  3654. /* clang-format off */
  3655. e << "WARNING: Function-style preprocessor definitions may not be "
  3656. << "passed on the compiler command line because many compilers "
  3657. << "do not support it.\n"
  3658. << "CMake is dropping a preprocessor definition: " << define << "\n"
  3659. << "Consider defining the macro in a (configured) header file.\n";
  3660. /* clang-format on */
  3661. cmSystemTools::Message(e.str());
  3662. return false;
  3663. }
  3664. }
  3665. // Many compilers do not support # in the value so we disable it.
  3666. if (define.find_first_of('#') != std::string::npos) {
  3667. std::ostringstream e;
  3668. /* clang-format off */
  3669. e << "WARNING: Preprocessor definitions containing '#' may not be "
  3670. << "passed on the compiler command line because many compilers "
  3671. << "do not support it.\n"
  3672. << "CMake is dropping a preprocessor definition: " << define << "\n"
  3673. << "Consider defining the macro in a (configured) header file.\n";
  3674. /* clang-format on */
  3675. cmSystemTools::Message(e.str());
  3676. return false;
  3677. }
  3678. // Assume it is supported.
  3679. return true;
  3680. }
  3681. static void cmLGInfoProp(cmMakefile* mf, cmGeneratorTarget* target,
  3682. const std::string& prop)
  3683. {
  3684. if (cmValue val = target->GetProperty(prop)) {
  3685. mf->AddDefinition(prop, *val);
  3686. }
  3687. }
  3688. void cmLocalGenerator::GenerateAppleInfoPList(cmGeneratorTarget* target,
  3689. const std::string& targetName,
  3690. const std::string& fname)
  3691. {
  3692. // Find the Info.plist template.
  3693. cmValue in = target->GetProperty("MACOSX_BUNDLE_INFO_PLIST");
  3694. std::string inFile = cmNonempty(in) ? *in : "MacOSXBundleInfo.plist.in";
  3695. if (!cmSystemTools::FileIsFullPath(inFile)) {
  3696. std::string inMod = this->Makefile->GetModulesFile(inFile);
  3697. if (!inMod.empty()) {
  3698. inFile = inMod;
  3699. }
  3700. }
  3701. if (!cmSystemTools::FileExists(inFile, true)) {
  3702. std::ostringstream e;
  3703. e << "Target " << target->GetName() << " Info.plist template \"" << inFile
  3704. << "\" could not be found.";
  3705. cmSystemTools::Error(e.str());
  3706. return;
  3707. }
  3708. // Convert target properties to variables in an isolated makefile
  3709. // scope to configure the file. If properties are set they will
  3710. // override user make variables. If not the configuration will fall
  3711. // back to the directory-level values set by the user.
  3712. cmMakefile* mf = this->Makefile;
  3713. cmMakefile::ScopePushPop varScope(mf);
  3714. mf->AddDefinition("MACOSX_BUNDLE_EXECUTABLE_NAME", targetName);
  3715. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_INFO_STRING");
  3716. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_ICON_FILE");
  3717. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_GUI_IDENTIFIER");
  3718. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_LONG_VERSION_STRING");
  3719. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_BUNDLE_NAME");
  3720. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_SHORT_VERSION_STRING");
  3721. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_BUNDLE_VERSION");
  3722. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_COPYRIGHT");
  3723. mf->ConfigureFile(inFile, fname, false, false, false);
  3724. }
  3725. void cmLocalGenerator::GenerateFrameworkInfoPList(
  3726. cmGeneratorTarget* target, const std::string& targetName,
  3727. const std::string& fname)
  3728. {
  3729. // Find the Info.plist template.
  3730. cmValue in = target->GetProperty("MACOSX_FRAMEWORK_INFO_PLIST");
  3731. std::string inFile = cmNonempty(in) ? *in : "MacOSXFrameworkInfo.plist.in";
  3732. if (!cmSystemTools::FileIsFullPath(inFile)) {
  3733. std::string inMod = this->Makefile->GetModulesFile(inFile);
  3734. if (!inMod.empty()) {
  3735. inFile = inMod;
  3736. }
  3737. }
  3738. if (!cmSystemTools::FileExists(inFile, true)) {
  3739. std::ostringstream e;
  3740. e << "Target " << target->GetName() << " Info.plist template \"" << inFile
  3741. << "\" could not be found.";
  3742. cmSystemTools::Error(e.str());
  3743. return;
  3744. }
  3745. // Convert target properties to variables in an isolated makefile
  3746. // scope to configure the file. If properties are set they will
  3747. // override user make variables. If not the configuration will fall
  3748. // back to the directory-level values set by the user.
  3749. cmMakefile* mf = this->Makefile;
  3750. cmMakefile::ScopePushPop varScope(mf);
  3751. mf->AddDefinition("MACOSX_FRAMEWORK_NAME", targetName);
  3752. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_ICON_FILE");
  3753. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_IDENTIFIER");
  3754. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_SHORT_VERSION_STRING");
  3755. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_BUNDLE_VERSION");
  3756. mf->ConfigureFile(inFile, fname, false, false, false);
  3757. }
  3758. namespace {
  3759. cm::string_view CustomOutputRoleKeyword(cmLocalGenerator::OutputRole role)
  3760. {
  3761. return (role == cmLocalGenerator::OutputRole::Primary ? "OUTPUT"_s
  3762. : "BYPRODUCTS"_s);
  3763. }
  3764. void CreateGeneratedSource(cmLocalGenerator& lg, const std::string& output,
  3765. cmLocalGenerator::OutputRole role,
  3766. cmCommandOrigin origin,
  3767. const cmListFileBacktrace& lfbt)
  3768. {
  3769. if (cmGeneratorExpression::Find(output) != std::string::npos) {
  3770. lg.GetCMakeInstance()->IssueMessage(
  3771. MessageType::FATAL_ERROR,
  3772. "Generator expressions in custom command outputs are not implemented!",
  3773. lfbt);
  3774. return;
  3775. }
  3776. // Make sure the file will not be generated into the source
  3777. // directory during an out of source build.
  3778. if (!lg.GetMakefile()->CanIWriteThisFile(output)) {
  3779. lg.GetCMakeInstance()->IssueMessage(
  3780. MessageType::FATAL_ERROR,
  3781. cmStrCat(CustomOutputRoleKeyword(role), " path\n ", output,
  3782. "\nin a source directory as an output of custom command."),
  3783. lfbt);
  3784. return;
  3785. }
  3786. // Make sure the output file name has no invalid characters.
  3787. std::string::size_type pos = output.find_first_of("#<>");
  3788. if (pos != std::string::npos) {
  3789. lg.GetCMakeInstance()->IssueMessage(
  3790. MessageType::FATAL_ERROR,
  3791. cmStrCat(CustomOutputRoleKeyword(role), " containing a \"", output[pos],
  3792. "\" is not allowed."),
  3793. lfbt);
  3794. return;
  3795. }
  3796. // Outputs without generator expressions from the project are already
  3797. // created and marked as generated. Do not mark them again, because
  3798. // other commands might have overwritten the property.
  3799. if (origin == cmCommandOrigin::Generator) {
  3800. lg.GetMakefile()->GetOrCreateGeneratedSource(output);
  3801. }
  3802. }
  3803. std::string ComputeCustomCommandRuleFileName(cmLocalGenerator& lg,
  3804. cmListFileBacktrace const& bt,
  3805. std::string const& output)
  3806. {
  3807. // If the output path has no generator expressions, use it directly.
  3808. if (cmGeneratorExpression::Find(output) == std::string::npos) {
  3809. return output;
  3810. }
  3811. // The output path contains a generator expression, but we must choose
  3812. // a single source file path to which to attach the custom command.
  3813. // Use some heuristics to provide a nice-looking name when possible.
  3814. // If the only genex is $<CONFIG>, replace that gracefully.
  3815. {
  3816. std::string simple = output;
  3817. cmSystemTools::ReplaceString(simple, "$<CONFIG>", "(CONFIG)");
  3818. if (cmGeneratorExpression::Find(simple) == std::string::npos) {
  3819. return simple;
  3820. }
  3821. }
  3822. // If the genex evaluates to the same value in all configurations, use that.
  3823. {
  3824. std::vector<std::string> allConfigOutputs =
  3825. lg.ExpandCustomCommandOutputGenex(output, bt);
  3826. if (allConfigOutputs.size() == 1) {
  3827. return allConfigOutputs.front();
  3828. }
  3829. }
  3830. // Fall back to a deterministic unique name.
  3831. cmCryptoHash h(cmCryptoHash::AlgoSHA256);
  3832. return cmStrCat(lg.GetCurrentBinaryDirectory(), "/CMakeFiles/",
  3833. h.HashString(output).substr(0, 16));
  3834. }
  3835. cmSourceFile* AddCustomCommand(cmLocalGenerator& lg, cmCommandOrigin origin,
  3836. std::unique_ptr<cmCustomCommand> cc,
  3837. bool replace)
  3838. {
  3839. cmMakefile* mf = lg.GetMakefile();
  3840. const auto& lfbt = cc->GetBacktrace();
  3841. const auto& outputs = cc->GetOutputs();
  3842. const auto& byproducts = cc->GetByproducts();
  3843. const auto& commandLines = cc->GetCommandLines();
  3844. // Choose a source file on which to store the custom command.
  3845. cmSourceFile* file = nullptr;
  3846. if (!commandLines.empty() && cc->HasMainDependency()) {
  3847. const auto& main_dependency = cc->GetMainDependency();
  3848. // The main dependency was specified. Use it unless a different
  3849. // custom command already used it.
  3850. file = mf->GetSource(main_dependency);
  3851. if (file && file->GetCustomCommand() && !replace) {
  3852. // The main dependency already has a custom command.
  3853. if (commandLines == file->GetCustomCommand()->GetCommandLines()) {
  3854. // The existing custom command is identical. Silently ignore
  3855. // the duplicate.
  3856. return file;
  3857. }
  3858. // The existing custom command is different. We need to
  3859. // generate a rule file for this new command.
  3860. file = nullptr;
  3861. } else if (!file) {
  3862. file = mf->CreateSource(main_dependency);
  3863. }
  3864. }
  3865. // Generate a rule file if the main dependency is not available.
  3866. if (!file) {
  3867. cmGlobalGenerator* gg = lg.GetGlobalGenerator();
  3868. // Construct a rule file associated with the first output produced.
  3869. std::string outName = gg->GenerateRuleFile(
  3870. ComputeCustomCommandRuleFileName(lg, lfbt, outputs[0]));
  3871. // Check if the rule file already exists.
  3872. file = mf->GetSource(outName, cmSourceFileLocationKind::Known);
  3873. if (file && file->GetCustomCommand() && !replace) {
  3874. // The rule file already exists.
  3875. if (commandLines != file->GetCustomCommand()->GetCommandLines()) {
  3876. lg.GetCMakeInstance()->IssueMessage(
  3877. MessageType::FATAL_ERROR,
  3878. cmStrCat("Attempt to add a custom rule to output\n ", outName,
  3879. "\nwhich already has a custom rule."),
  3880. lfbt);
  3881. }
  3882. return file;
  3883. }
  3884. // Create a cmSourceFile for the rule file.
  3885. if (!file) {
  3886. file = mf->CreateSource(outName, true, cmSourceFileLocationKind::Known);
  3887. }
  3888. file->SetProperty("__CMAKE_RULE", "1");
  3889. }
  3890. // Attach the custom command to the file.
  3891. if (file) {
  3892. cc->SetEscapeAllowMakeVars(true);
  3893. lg.AddSourceOutputs(file, outputs, cmLocalGenerator::OutputRole::Primary,
  3894. lfbt, origin);
  3895. lg.AddSourceOutputs(file, byproducts,
  3896. cmLocalGenerator::OutputRole::Byproduct, lfbt, origin);
  3897. file->SetCustomCommand(std::move(cc));
  3898. }
  3899. return file;
  3900. }
  3901. bool AnyOutputMatches(const std::string& name,
  3902. const std::vector<std::string>& outputs)
  3903. {
  3904. return std::any_of(outputs.begin(), outputs.end(),
  3905. [&name](std::string const& output) -> bool {
  3906. std::string::size_type pos = output.rfind(name);
  3907. // If the output matches exactly
  3908. return (pos != std::string::npos &&
  3909. pos == output.size() - name.size() &&
  3910. (pos == 0 || output[pos - 1] == '/'));
  3911. });
  3912. }
  3913. bool AnyTargetCommandOutputMatches(
  3914. const std::string& name, const std::vector<cmCustomCommand>& commands)
  3915. {
  3916. return std::any_of(commands.begin(), commands.end(),
  3917. [&name](cmCustomCommand const& command) -> bool {
  3918. return AnyOutputMatches(name, command.GetByproducts());
  3919. });
  3920. }
  3921. }
  3922. namespace detail {
  3923. void AddCustomCommandToTarget(cmLocalGenerator& lg, cmCommandOrigin origin,
  3924. cmTarget* target, cmCustomCommandType type,
  3925. std::unique_ptr<cmCustomCommand> cc)
  3926. {
  3927. // Add the command to the appropriate build step for the target.
  3928. cc->SetEscapeAllowMakeVars(true);
  3929. cc->SetTarget(target->GetName());
  3930. lg.AddTargetByproducts(target, cc->GetByproducts(), cc->GetBacktrace(),
  3931. origin);
  3932. switch (type) {
  3933. case cmCustomCommandType::PRE_BUILD:
  3934. target->AddPreBuildCommand(std::move(*cc));
  3935. break;
  3936. case cmCustomCommandType::PRE_LINK:
  3937. target->AddPreLinkCommand(std::move(*cc));
  3938. break;
  3939. case cmCustomCommandType::POST_BUILD:
  3940. target->AddPostBuildCommand(std::move(*cc));
  3941. break;
  3942. }
  3943. cc.reset();
  3944. }
  3945. cmSourceFile* AddCustomCommandToOutput(cmLocalGenerator& lg,
  3946. cmCommandOrigin origin,
  3947. std::unique_ptr<cmCustomCommand> cc,
  3948. bool replace)
  3949. {
  3950. return AddCustomCommand(lg, origin, std::move(cc), replace);
  3951. }
  3952. void AppendCustomCommandToOutput(cmLocalGenerator& lg,
  3953. const cmListFileBacktrace& lfbt,
  3954. const std::string& output,
  3955. const std::vector<std::string>& depends,
  3956. const cmImplicitDependsList& implicit_depends,
  3957. const cmCustomCommandLines& commandLines)
  3958. {
  3959. // Lookup an existing command.
  3960. cmSourceFile* sf = nullptr;
  3961. if (cmGeneratorExpression::Find(output) == std::string::npos) {
  3962. sf = lg.GetSourceFileWithOutput(output);
  3963. } else {
  3964. // This output path has a generator expression. Evaluate it to
  3965. // find the output for any configurations.
  3966. for (std::string const& out :
  3967. lg.ExpandCustomCommandOutputGenex(output, lfbt)) {
  3968. sf = lg.GetSourceFileWithOutput(out);
  3969. if (sf) {
  3970. break;
  3971. }
  3972. }
  3973. }
  3974. if (sf) {
  3975. if (cmCustomCommand* cc = sf->GetCustomCommand()) {
  3976. cc->AppendCommands(commandLines);
  3977. cc->AppendDepends(depends);
  3978. cc->AppendImplicitDepends(implicit_depends);
  3979. return;
  3980. }
  3981. }
  3982. // No existing command found.
  3983. lg.GetCMakeInstance()->IssueMessage(
  3984. MessageType::FATAL_ERROR,
  3985. cmStrCat("Attempt to APPEND to custom command with output\n ", output,
  3986. "\nwhich is not already a custom command output."),
  3987. lfbt);
  3988. }
  3989. void AddUtilityCommand(cmLocalGenerator& lg, cmCommandOrigin origin,
  3990. cmTarget* target, std::unique_ptr<cmCustomCommand> cc)
  3991. {
  3992. // They might be moved away
  3993. auto byproducts = cc->GetByproducts();
  3994. auto lfbt = cc->GetBacktrace();
  3995. // Use an empty comment to avoid generation of default comment.
  3996. if (!cc->GetComment()) {
  3997. cc->SetComment("");
  3998. }
  3999. // Create the generated symbolic output name of the utility target.
  4000. std::string output =
  4001. lg.CreateUtilityOutput(target->GetName(), byproducts, lfbt);
  4002. cc->SetOutputs(output);
  4003. cmSourceFile* rule = AddCustomCommand(lg, origin, std::move(cc),
  4004. /*replace=*/false);
  4005. if (rule) {
  4006. lg.AddTargetByproducts(target, byproducts, lfbt, origin);
  4007. }
  4008. target->AddSource(output);
  4009. }
  4010. std::vector<std::string> ComputeISPCObjectSuffixes(cmGeneratorTarget* target)
  4011. {
  4012. const cmValue targetProperty = target->GetProperty("ISPC_INSTRUCTION_SETS");
  4013. cmList ispcTargets;
  4014. if (!targetProperty.IsOff()) {
  4015. ispcTargets.assign(targetProperty);
  4016. for (auto& ispcTarget : ispcTargets) {
  4017. // transform targets into the suffixes
  4018. auto pos = ispcTarget.find('-');
  4019. auto target_suffix = ispcTarget.substr(0, pos);
  4020. if (target_suffix ==
  4021. "avx1") { // when targeting avx1 ISPC uses the 'avx' output string
  4022. target_suffix = "avx";
  4023. }
  4024. ispcTarget = target_suffix;
  4025. }
  4026. }
  4027. return std::move(ispcTargets.data());
  4028. }
  4029. std::vector<std::string> ComputeISPCExtraObjects(
  4030. std::string const& objectName, std::string const& buildDirectory,
  4031. std::vector<std::string> const& ispcSuffixes)
  4032. {
  4033. auto normalizedDir = cmSystemTools::CollapseFullPath(buildDirectory);
  4034. std::vector<std::string> computedObjects;
  4035. computedObjects.reserve(ispcSuffixes.size());
  4036. auto extension = cmSystemTools::GetFilenameLastExtension(objectName);
  4037. // We can't use cmSystemTools::GetFilenameWithoutLastExtension as it
  4038. // drops any directories in objectName
  4039. auto objNameNoExt = objectName;
  4040. std::string::size_type dot_pos = objectName.rfind('.');
  4041. if (dot_pos != std::string::npos) {
  4042. objNameNoExt.resize(dot_pos);
  4043. }
  4044. for (const auto& ispcTarget : ispcSuffixes) {
  4045. computedObjects.emplace_back(
  4046. cmStrCat(normalizedDir, "/", objNameNoExt, "_", ispcTarget, extension));
  4047. }
  4048. return computedObjects;
  4049. }
  4050. }
  4051. cmSourcesWithOutput cmLocalGenerator::GetSourcesWithOutput(
  4052. const std::string& name) const
  4053. {
  4054. // Linear search? Also see GetSourceFileWithOutput for detail.
  4055. if (!cmSystemTools::FileIsFullPath(name)) {
  4056. cmSourcesWithOutput sources;
  4057. sources.Target = this->LinearGetTargetWithOutput(name);
  4058. sources.Source = this->LinearGetSourceFileWithOutput(
  4059. name, cmSourceOutputKind::OutputOrByproduct, sources.SourceIsByproduct);
  4060. return sources;
  4061. }
  4062. // Otherwise we use an efficient lookup map.
  4063. auto o = this->OutputToSource.find(name);
  4064. if (o != this->OutputToSource.end()) {
  4065. return o->second.Sources;
  4066. }
  4067. return {};
  4068. }
  4069. cmSourceFile* cmLocalGenerator::GetSourceFileWithOutput(
  4070. const std::string& name, cmSourceOutputKind kind) const
  4071. {
  4072. // If the queried path is not absolute we use the backward compatible
  4073. // linear-time search for an output with a matching suffix.
  4074. if (!cmSystemTools::FileIsFullPath(name)) {
  4075. bool byproduct = false;
  4076. return this->LinearGetSourceFileWithOutput(name, kind, byproduct);
  4077. }
  4078. // Otherwise we use an efficient lookup map.
  4079. auto o = this->OutputToSource.find(name);
  4080. if (o != this->OutputToSource.end() &&
  4081. (!o->second.Sources.SourceIsByproduct ||
  4082. kind == cmSourceOutputKind::OutputOrByproduct)) {
  4083. // Source file could also be null pointer for example if we found the
  4084. // byproduct of a utility target, a PRE_BUILD, PRE_LINK, or POST_BUILD
  4085. // command of a target, or a not yet created custom command.
  4086. return o->second.Sources.Source;
  4087. }
  4088. return nullptr;
  4089. }
  4090. std::string cmLocalGenerator::CreateUtilityOutput(
  4091. std::string const& targetName, std::vector<std::string> const&,
  4092. cmListFileBacktrace const&)
  4093. {
  4094. std::string force =
  4095. cmStrCat(this->GetCurrentBinaryDirectory(), "/CMakeFiles/", targetName);
  4096. // The output is not actually created so mark it symbolic.
  4097. if (cmSourceFile* sf = this->Makefile->GetOrCreateGeneratedSource(force)) {
  4098. sf->SetProperty("SYMBOLIC", "1");
  4099. } else {
  4100. cmSystemTools::Error("Could not get source file entry for " + force);
  4101. }
  4102. return force;
  4103. }
  4104. std::vector<cmCustomCommandGenerator>
  4105. cmLocalGenerator::MakeCustomCommandGenerators(cmCustomCommand const& cc,
  4106. std::string const& config)
  4107. {
  4108. std::vector<cmCustomCommandGenerator> ccgs;
  4109. ccgs.emplace_back(cc, config, this);
  4110. return ccgs;
  4111. }
  4112. std::vector<std::string> cmLocalGenerator::ExpandCustomCommandOutputPaths(
  4113. cmCompiledGeneratorExpression const& cge, std::string const& config)
  4114. {
  4115. cmList paths{ cge.Evaluate(this, config) };
  4116. for (std::string& p : paths) {
  4117. p = cmSystemTools::CollapseFullPath(p, this->GetCurrentBinaryDirectory());
  4118. }
  4119. return std::move(paths.data());
  4120. }
  4121. std::vector<std::string> cmLocalGenerator::ExpandCustomCommandOutputGenex(
  4122. std::string const& o, cmListFileBacktrace const& bt)
  4123. {
  4124. std::vector<std::string> allConfigOutputs;
  4125. cmGeneratorExpression ge(*this->GetCMakeInstance(), bt);
  4126. std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(o);
  4127. std::vector<std::string> configs =
  4128. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  4129. for (std::string const& config : configs) {
  4130. std::vector<std::string> configOutputs =
  4131. this->ExpandCustomCommandOutputPaths(*cge, config);
  4132. allConfigOutputs.reserve(allConfigOutputs.size() + configOutputs.size());
  4133. std::move(configOutputs.begin(), configOutputs.end(),
  4134. std::back_inserter(allConfigOutputs));
  4135. }
  4136. auto endUnique =
  4137. cmRemoveDuplicates(allConfigOutputs.begin(), allConfigOutputs.end());
  4138. allConfigOutputs.erase(endUnique, allConfigOutputs.end());
  4139. return allConfigOutputs;
  4140. }
  4141. void cmLocalGenerator::AddTargetByproducts(
  4142. cmTarget* target, const std::vector<std::string>& byproducts,
  4143. cmListFileBacktrace const& bt, cmCommandOrigin origin)
  4144. {
  4145. for (std::string const& o : byproducts) {
  4146. if (cmGeneratorExpression::Find(o) == std::string::npos) {
  4147. this->UpdateOutputToSourceMap(o, target, bt, origin);
  4148. continue;
  4149. }
  4150. // This byproduct path has a generator expression. Evaluate it to
  4151. // register the byproducts for all configurations.
  4152. for (std::string const& b : this->ExpandCustomCommandOutputGenex(o, bt)) {
  4153. this->UpdateOutputToSourceMap(b, target, bt, cmCommandOrigin::Generator);
  4154. }
  4155. }
  4156. }
  4157. void cmLocalGenerator::AddSourceOutputs(
  4158. cmSourceFile* source, const std::vector<std::string>& outputs,
  4159. OutputRole role, cmListFileBacktrace const& bt, cmCommandOrigin origin)
  4160. {
  4161. for (std::string const& o : outputs) {
  4162. if (cmGeneratorExpression::Find(o) == std::string::npos) {
  4163. this->UpdateOutputToSourceMap(o, source, role, bt, origin);
  4164. continue;
  4165. }
  4166. // This output path has a generator expression. Evaluate it to
  4167. // register the outputs for all configurations.
  4168. for (std::string const& out :
  4169. this->ExpandCustomCommandOutputGenex(o, bt)) {
  4170. this->UpdateOutputToSourceMap(out, source, role, bt,
  4171. cmCommandOrigin::Generator);
  4172. }
  4173. }
  4174. }
  4175. void cmLocalGenerator::UpdateOutputToSourceMap(std::string const& byproduct,
  4176. cmTarget* target,
  4177. cmListFileBacktrace const& bt,
  4178. cmCommandOrigin origin)
  4179. {
  4180. SourceEntry entry;
  4181. entry.Sources.Target = target;
  4182. auto pr = this->OutputToSource.emplace(byproduct, entry);
  4183. if (pr.second) {
  4184. CreateGeneratedSource(*this, byproduct, OutputRole::Byproduct, origin, bt);
  4185. } else {
  4186. SourceEntry& current = pr.first->second;
  4187. // Has the target already been set?
  4188. if (!current.Sources.Target) {
  4189. current.Sources.Target = target;
  4190. } else {
  4191. // Multiple custom commands/targets produce the same output (source file
  4192. // or target). See also comment in other UpdateOutputToSourceMap
  4193. // overload.
  4194. //
  4195. // TODO: Warn the user about this case.
  4196. }
  4197. }
  4198. }
  4199. void cmLocalGenerator::UpdateOutputToSourceMap(std::string const& output,
  4200. cmSourceFile* source,
  4201. OutputRole role,
  4202. cmListFileBacktrace const& bt,
  4203. cmCommandOrigin origin)
  4204. {
  4205. SourceEntry entry;
  4206. entry.Sources.Source = source;
  4207. entry.Sources.SourceIsByproduct = role == OutputRole::Byproduct;
  4208. auto pr = this->OutputToSource.emplace(output, entry);
  4209. if (pr.second) {
  4210. CreateGeneratedSource(*this, output, role, origin, bt);
  4211. } else {
  4212. SourceEntry& current = pr.first->second;
  4213. // Outputs take precedence over byproducts
  4214. if (!current.Sources.Source ||
  4215. (current.Sources.SourceIsByproduct && role == OutputRole::Primary)) {
  4216. current.Sources.Source = source;
  4217. current.Sources.SourceIsByproduct = false;
  4218. } else {
  4219. // Multiple custom commands produce the same output but may
  4220. // be attached to a different source file (MAIN_DEPENDENCY).
  4221. // LinearGetSourceFileWithOutput would return the first one,
  4222. // so keep the mapping for the first one.
  4223. //
  4224. // TODO: Warn the user about this case. However, the VS 8 generator
  4225. // triggers it for separate generate.stamp rules in ZERO_CHECK and
  4226. // individual targets.
  4227. }
  4228. }
  4229. }
  4230. cmTarget* cmLocalGenerator::LinearGetTargetWithOutput(
  4231. const std::string& name) const
  4232. {
  4233. // We go through the ordered vector of targets to get reproducible results
  4234. // should multiple names match.
  4235. for (cmTarget* t : this->Makefile->GetOrderedTargets()) {
  4236. // Does the output of any command match the source file name?
  4237. if (AnyTargetCommandOutputMatches(name, t->GetPreBuildCommands())) {
  4238. return t;
  4239. }
  4240. if (AnyTargetCommandOutputMatches(name, t->GetPreLinkCommands())) {
  4241. return t;
  4242. }
  4243. if (AnyTargetCommandOutputMatches(name, t->GetPostBuildCommands())) {
  4244. return t;
  4245. }
  4246. }
  4247. return nullptr;
  4248. }
  4249. cmSourceFile* cmLocalGenerator::LinearGetSourceFileWithOutput(
  4250. const std::string& name, cmSourceOutputKind kind, bool& byproduct) const
  4251. {
  4252. // Outputs take precedence over byproducts.
  4253. byproduct = false;
  4254. cmSourceFile* fallback = nullptr;
  4255. // Look through all the source files that have custom commands and see if the
  4256. // custom command has the passed source file as an output.
  4257. for (const auto& src : this->Makefile->GetSourceFiles()) {
  4258. // Does this source file have a custom command?
  4259. if (src->GetCustomCommand()) {
  4260. // Does the output of the custom command match the source file name?
  4261. if (AnyOutputMatches(name, src->GetCustomCommand()->GetOutputs())) {
  4262. // Return the first matching output.
  4263. return src.get();
  4264. }
  4265. if (kind == cmSourceOutputKind::OutputOrByproduct) {
  4266. if (AnyOutputMatches(name, src->GetCustomCommand()->GetByproducts())) {
  4267. // Do not return the source yet as there might be a matching output.
  4268. fallback = src.get();
  4269. }
  4270. }
  4271. }
  4272. }
  4273. // Did we find a byproduct?
  4274. byproduct = fallback != nullptr;
  4275. return fallback;
  4276. }