cmLocalGenerator.cxx 158 KB

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