cmLocalGenerator.cxx 178 KB

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