cmLocalGenerator.cxx 174 KB

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