cmLocalGenerator.cxx 175 KB

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