cmLocalGenerator.cxx 175 KB

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