cmLocalGenerator.cxx 181 KB

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