cmLocalGenerator.cxx 166 KB

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