cmLocalGenerator.cxx 175 KB

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