cc.go 136 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281
  1. // Copyright 2015 Google Inc. All rights reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package cc
  15. // This file contains the module types for compiling C/C++ for Android, and converts the properties
  16. // into the flags and filenames necessary to pass to the compiler. The final creation of the rules
  17. // is handled in builder.go
  18. import (
  19. "fmt"
  20. "io"
  21. "strconv"
  22. "strings"
  23. "android/soong/ui/metrics/bp2build_metrics_proto"
  24. "github.com/google/blueprint"
  25. "github.com/google/blueprint/proptools"
  26. "android/soong/aidl_library"
  27. "android/soong/android"
  28. "android/soong/bazel/cquery"
  29. "android/soong/cc/config"
  30. "android/soong/fuzz"
  31. "android/soong/genrule"
  32. "android/soong/multitree"
  33. "android/soong/snapshot"
  34. )
  35. func init() {
  36. RegisterCCBuildComponents(android.InitRegistrationContext)
  37. pctx.Import("android/soong/cc/config")
  38. }
  39. func RegisterCCBuildComponents(ctx android.RegistrationContext) {
  40. ctx.RegisterModuleType("cc_defaults", defaultsFactory)
  41. ctx.PreDepsMutators(func(ctx android.RegisterMutatorsContext) {
  42. ctx.BottomUp("sdk", sdkMutator).Parallel()
  43. ctx.BottomUp("vndk", VndkMutator).Parallel()
  44. ctx.BottomUp("link", LinkageMutator).Parallel()
  45. ctx.BottomUp("test_per_src", TestPerSrcMutator).Parallel()
  46. ctx.BottomUp("version", versionMutator).Parallel()
  47. ctx.BottomUp("begin", BeginMutator).Parallel()
  48. ctx.BottomUp("fdo_profile", fdoProfileMutator)
  49. })
  50. ctx.PostDepsMutators(func(ctx android.RegisterMutatorsContext) {
  51. for _, san := range Sanitizers {
  52. san.registerMutators(ctx)
  53. }
  54. ctx.TopDown("sanitize_runtime_deps", sanitizerRuntimeDepsMutator).Parallel()
  55. ctx.BottomUp("sanitize_runtime", sanitizerRuntimeMutator).Parallel()
  56. ctx.TopDown("fuzz_deps", fuzzMutatorDeps)
  57. ctx.BottomUp("coverage", coverageMutator).Parallel()
  58. ctx.TopDown("afdo_deps", afdoDepsMutator)
  59. ctx.BottomUp("afdo", afdoMutator).Parallel()
  60. ctx.TopDown("lto_deps", ltoDepsMutator)
  61. ctx.BottomUp("lto", ltoMutator).Parallel()
  62. ctx.BottomUp("check_linktype", checkLinkTypeMutator).Parallel()
  63. ctx.TopDown("double_loadable", checkDoubleLoadableLibraries).Parallel()
  64. })
  65. ctx.FinalDepsMutators(func(ctx android.RegisterMutatorsContext) {
  66. // sabi mutator needs to be run after apex mutator finishes.
  67. ctx.TopDown("sabi_deps", sabiDepsMutator)
  68. })
  69. ctx.RegisterParallelSingletonType("kythe_extract_all", kytheExtractAllFactory)
  70. }
  71. // Deps is a struct containing module names of dependencies, separated by the kind of dependency.
  72. // Mutators should use `AddVariationDependencies` or its sibling methods to add actual dependency
  73. // edges to these modules.
  74. // This object is constructed in DepsMutator, by calling to various module delegates to set
  75. // relevant fields. For example, `module.compiler.compilerDeps()` may append type-specific
  76. // dependencies.
  77. // This is then consumed by the same DepsMutator, which will call `ctx.AddVariationDependencies()`
  78. // (or its sibling methods) to set real dependencies on the given modules.
  79. type Deps struct {
  80. SharedLibs, LateSharedLibs []string
  81. StaticLibs, LateStaticLibs, WholeStaticLibs []string
  82. HeaderLibs []string
  83. RuntimeLibs []string
  84. // UnexportedStaticLibs are static libraries that are also passed to -Wl,--exclude-libs= to
  85. // prevent automatically exporting symbols.
  86. UnexportedStaticLibs []string
  87. // Used for data dependencies adjacent to tests
  88. DataLibs []string
  89. DataBins []string
  90. // Used by DepsMutator to pass system_shared_libs information to check_elf_file.py.
  91. SystemSharedLibs []string
  92. // Used by DepMutator to pass aidl_library modules to aidl compiler
  93. AidlLibs []string
  94. // If true, statically link the unwinder into native libraries/binaries.
  95. StaticUnwinderIfLegacy bool
  96. ReexportSharedLibHeaders, ReexportStaticLibHeaders, ReexportHeaderLibHeaders []string
  97. ObjFiles []string
  98. GeneratedSources []string
  99. GeneratedHeaders []string
  100. GeneratedDeps []string
  101. ReexportGeneratedHeaders []string
  102. CrtBegin, CrtEnd []string
  103. // Used for host bionic
  104. DynamicLinker string
  105. // List of libs that need to be excluded for APEX variant
  106. ExcludeLibsForApex []string
  107. }
  108. // PathDeps is a struct containing file paths to dependencies of a module.
  109. // It's constructed in depsToPath() by traversing the direct dependencies of the current module.
  110. // It's used to construct flags for various build statements (such as for compiling and linking).
  111. // It is then passed to module decorator functions responsible for registering build statements
  112. // (such as `module.compiler.compile()`).`
  113. type PathDeps struct {
  114. // Paths to .so files
  115. SharedLibs, EarlySharedLibs, LateSharedLibs android.Paths
  116. // Paths to the dependencies to use for .so files (.so.toc files)
  117. SharedLibsDeps, EarlySharedLibsDeps, LateSharedLibsDeps android.Paths
  118. // Paths to .a files
  119. StaticLibs, LateStaticLibs, WholeStaticLibs android.Paths
  120. // Transitive static library dependencies of static libraries for use in ordering.
  121. TranstiveStaticLibrariesForOrdering *android.DepSet[android.Path]
  122. // Paths to .o files
  123. Objs Objects
  124. // Paths to .o files in dependencies that provide them. Note that these lists
  125. // aren't complete since prebuilt modules don't provide the .o files.
  126. StaticLibObjs Objects
  127. WholeStaticLibObjs Objects
  128. // Paths to .a files in prebuilts. Complements WholeStaticLibObjs to contain
  129. // the libs from all whole_static_lib dependencies.
  130. WholeStaticLibsFromPrebuilts android.Paths
  131. // Paths to generated source files
  132. GeneratedSources android.Paths
  133. GeneratedDeps android.Paths
  134. Flags []string
  135. LdFlags []string
  136. IncludeDirs android.Paths
  137. SystemIncludeDirs android.Paths
  138. ReexportedDirs android.Paths
  139. ReexportedSystemDirs android.Paths
  140. ReexportedFlags []string
  141. ReexportedGeneratedHeaders android.Paths
  142. ReexportedDeps android.Paths
  143. // Paths to crt*.o files
  144. CrtBegin, CrtEnd android.Paths
  145. // Path to the dynamic linker binary
  146. DynamicLinker android.OptionalPath
  147. // For Darwin builds, the path to the second architecture's output that should
  148. // be combined with this architectures's output into a FAT MachO file.
  149. DarwinSecondArchOutput android.OptionalPath
  150. // Paths to direct srcs and transitive include dirs from direct aidl_library deps
  151. AidlLibraryInfos []aidl_library.AidlLibraryInfo
  152. }
  153. // LocalOrGlobalFlags contains flags that need to have values set globally by the build system or locally by the module
  154. // tracked separately, in order to maintain the required ordering (most of the global flags need to go first on the
  155. // command line so they can be overridden by the local module flags).
  156. type LocalOrGlobalFlags struct {
  157. CommonFlags []string // Flags that apply to C, C++, and assembly source files
  158. AsFlags []string // Flags that apply to assembly source files
  159. YasmFlags []string // Flags that apply to yasm assembly source files
  160. CFlags []string // Flags that apply to C and C++ source files
  161. ToolingCFlags []string // Flags that apply to C and C++ source files parsed by clang LibTooling tools
  162. ConlyFlags []string // Flags that apply to C source files
  163. CppFlags []string // Flags that apply to C++ source files
  164. ToolingCppFlags []string // Flags that apply to C++ source files parsed by clang LibTooling tools
  165. LdFlags []string // Flags that apply to linker command lines
  166. }
  167. // Flags contains various types of command line flags (and settings) for use in building build
  168. // statements related to C++.
  169. type Flags struct {
  170. // Local flags (which individual modules are responsible for). These may override global flags.
  171. Local LocalOrGlobalFlags
  172. // Global flags (which build system or toolchain is responsible for).
  173. Global LocalOrGlobalFlags
  174. aidlFlags []string // Flags that apply to aidl source files
  175. rsFlags []string // Flags that apply to renderscript source files
  176. libFlags []string // Flags to add libraries early to the link order
  177. extraLibFlags []string // Flags to add libraries late in the link order after LdFlags
  178. TidyFlags []string // Flags that apply to clang-tidy
  179. SAbiFlags []string // Flags that apply to header-abi-dumper
  180. // Global include flags that apply to C, C++, and assembly source files
  181. // These must be after any module include flags, which will be in CommonFlags.
  182. SystemIncludeFlags []string
  183. Toolchain config.Toolchain
  184. Tidy bool // True if ninja .tidy rules should be generated.
  185. NeedTidyFiles bool // True if module link should depend on .tidy files
  186. GcovCoverage bool // True if coverage files should be generated.
  187. SAbiDump bool // True if header abi dumps should be generated.
  188. EmitXrefs bool // If true, generate Ninja rules to generate emitXrefs input files for Kythe
  189. // The instruction set required for clang ("arm" or "thumb").
  190. RequiredInstructionSet string
  191. // The target-device system path to the dynamic linker.
  192. DynamicLinker string
  193. CFlagsDeps android.Paths // Files depended on by compiler flags
  194. LdFlagsDeps android.Paths // Files depended on by linker flags
  195. // True if .s files should be processed with the c preprocessor.
  196. AssemblerWithCpp bool
  197. proto android.ProtoFlags
  198. protoC bool // Whether to use C instead of C++
  199. protoOptionsFile bool // Whether to look for a .options file next to the .proto
  200. Yacc *YaccProperties
  201. Lex *LexProperties
  202. }
  203. // Properties used to compile all C or C++ modules
  204. type BaseProperties struct {
  205. // Deprecated. true is the default, false is invalid.
  206. Clang *bool `android:"arch_variant"`
  207. // The API level that this module is built against. The APIs of this API level will be
  208. // visible at build time, but use of any APIs newer than min_sdk_version will render the
  209. // module unloadable on older devices. In the future it will be possible to weakly-link new
  210. // APIs, making the behavior match Java: such modules will load on older devices, but
  211. // calling new APIs on devices that do not support them will result in a crash.
  212. //
  213. // This property has the same behavior as sdk_version does for Java modules. For those
  214. // familiar with Android Gradle, the property behaves similarly to how compileSdkVersion
  215. // does for Java code.
  216. //
  217. // In addition, setting this property causes two variants to be built, one for the platform
  218. // and one for apps.
  219. Sdk_version *string
  220. // Minimum OS API level supported by this C or C++ module. This property becomes the value
  221. // of the __ANDROID_API__ macro. When the C or C++ module is included in an APEX or an APK,
  222. // this property is also used to ensure that the min_sdk_version of the containing module is
  223. // not older (i.e. less) than this module's min_sdk_version. When not set, this property
  224. // defaults to the value of sdk_version. When this is set to "apex_inherit", this tracks
  225. // min_sdk_version of the containing APEX. When the module
  226. // is not built for an APEX, "apex_inherit" defaults to sdk_version.
  227. Min_sdk_version *string
  228. // If true, always create an sdk variant and don't create a platform variant.
  229. Sdk_variant_only *bool
  230. AndroidMkSharedLibs []string `blueprint:"mutated"`
  231. AndroidMkStaticLibs []string `blueprint:"mutated"`
  232. AndroidMkRuntimeLibs []string `blueprint:"mutated"`
  233. AndroidMkWholeStaticLibs []string `blueprint:"mutated"`
  234. AndroidMkHeaderLibs []string `blueprint:"mutated"`
  235. HideFromMake bool `blueprint:"mutated"`
  236. PreventInstall bool `blueprint:"mutated"`
  237. ApexesProvidingSharedLibs []string `blueprint:"mutated"`
  238. // Set by DepsMutator.
  239. AndroidMkSystemSharedLibs []string `blueprint:"mutated"`
  240. // The name of the image this module is built for, suffixed with a '.'
  241. ImageVariationPrefix string `blueprint:"mutated"`
  242. // The VNDK version this module is built against. If empty, the module is not
  243. // build against the VNDK.
  244. VndkVersion string `blueprint:"mutated"`
  245. // Suffix for the name of Android.mk entries generated by this module
  246. SubName string `blueprint:"mutated"`
  247. // *.logtags files, to combine together in order to generate the /system/etc/event-log-tags
  248. // file
  249. Logtags []string
  250. // Make this module available when building for ramdisk.
  251. // On device without a dedicated recovery partition, the module is only
  252. // available after switching root into
  253. // /first_stage_ramdisk. To expose the module before switching root, install
  254. // the recovery variant instead.
  255. Ramdisk_available *bool
  256. // Make this module available when building for vendor ramdisk.
  257. // On device without a dedicated recovery partition, the module is only
  258. // available after switching root into
  259. // /first_stage_ramdisk. To expose the module before switching root, install
  260. // the recovery variant instead.
  261. Vendor_ramdisk_available *bool
  262. // Make this module available when building for recovery
  263. Recovery_available *bool
  264. // Used by imageMutator, set by ImageMutatorBegin()
  265. CoreVariantNeeded bool `blueprint:"mutated"`
  266. RamdiskVariantNeeded bool `blueprint:"mutated"`
  267. VendorRamdiskVariantNeeded bool `blueprint:"mutated"`
  268. RecoveryVariantNeeded bool `blueprint:"mutated"`
  269. // A list of variations for the "image" mutator of the form
  270. //<image name> '.' <version char>, for example, 'vendor.S'
  271. ExtraVersionedImageVariations []string `blueprint:"mutated"`
  272. // Allows this module to use non-APEX version of libraries. Useful
  273. // for building binaries that are started before APEXes are activated.
  274. Bootstrap *bool
  275. // Even if DeviceConfig().VndkUseCoreVariant() is set, this module must use vendor variant.
  276. // see soong/cc/config/vndk.go
  277. MustUseVendorVariant bool `blueprint:"mutated"`
  278. // Used by vendor snapshot to record dependencies from snapshot modules.
  279. SnapshotSharedLibs []string `blueprint:"mutated"`
  280. SnapshotStaticLibs []string `blueprint:"mutated"`
  281. SnapshotRuntimeLibs []string `blueprint:"mutated"`
  282. Installable *bool `android:"arch_variant"`
  283. // Set by factories of module types that can only be referenced from variants compiled against
  284. // the SDK.
  285. AlwaysSdk bool `blueprint:"mutated"`
  286. // Variant is an SDK variant created by sdkMutator
  287. IsSdkVariant bool `blueprint:"mutated"`
  288. // Set when both SDK and platform variants are exported to Make to trigger renaming the SDK
  289. // variant to have a ".sdk" suffix.
  290. SdkAndPlatformVariantVisibleToMake bool `blueprint:"mutated"`
  291. // Normally Soong uses the directory structure to decide which modules
  292. // should be included (framework) or excluded (non-framework) from the
  293. // different snapshots (vendor, recovery, etc.), but this property
  294. // allows a partner to exclude a module normally thought of as a
  295. // framework module from the vendor snapshot.
  296. Exclude_from_vendor_snapshot *bool
  297. // Normally Soong uses the directory structure to decide which modules
  298. // should be included (framework) or excluded (non-framework) from the
  299. // different snapshots (vendor, recovery, etc.), but this property
  300. // allows a partner to exclude a module normally thought of as a
  301. // framework module from the recovery snapshot.
  302. Exclude_from_recovery_snapshot *bool
  303. // List of APEXes that this module has private access to for testing purpose. The module
  304. // can depend on libraries that are not exported by the APEXes and use private symbols
  305. // from the exported libraries.
  306. Test_for []string `android:"arch_variant"`
  307. Target struct {
  308. Platform struct {
  309. // List of modules required by the core variant.
  310. Required []string `android:"arch_variant"`
  311. // List of modules not required by the core variant.
  312. Exclude_required []string `android:"arch_variant"`
  313. } `android:"arch_variant"`
  314. Recovery struct {
  315. // List of modules required by the recovery variant.
  316. Required []string `android:"arch_variant"`
  317. // List of modules not required by the recovery variant.
  318. Exclude_required []string `android:"arch_variant"`
  319. } `android:"arch_variant"`
  320. } `android:"arch_variant"`
  321. }
  322. type VendorProperties struct {
  323. // whether this module should be allowed to be directly depended by other
  324. // modules with `vendor: true`, `proprietary: true`, or `vendor_available:true`.
  325. // If set to true, two variants will be built separately, one like
  326. // normal, and the other limited to the set of libraries and headers
  327. // that are exposed to /vendor modules.
  328. //
  329. // The vendor variant may be used with a different (newer) /system,
  330. // so it shouldn't have any unversioned runtime dependencies, or
  331. // make assumptions about the system that may not be true in the
  332. // future.
  333. //
  334. // If set to false, this module becomes inaccessible from /vendor modules.
  335. //
  336. // The modules with vndk: {enabled: true} must define 'vendor_available'
  337. // to 'true'.
  338. //
  339. // Nothing happens if BOARD_VNDK_VERSION isn't set in the BoardConfig.mk
  340. Vendor_available *bool
  341. // This is the same as the "vendor_available" except that the install path
  342. // of the vendor variant is /odm or /vendor/odm.
  343. // By replacing "vendor_available: true" with "odm_available: true", the
  344. // module will install its vendor variant to the /odm partition or /vendor/odm.
  345. // As the modules with "odm_available: true" still create the vendor variants,
  346. // they can link to the other vendor modules as the vendor_available modules do.
  347. // Also, the vendor modules can link to odm_available modules.
  348. //
  349. // It may not be used for VNDK modules.
  350. Odm_available *bool
  351. // whether this module should be allowed to be directly depended by other
  352. // modules with `product_specific: true` or `product_available: true`.
  353. // If set to true, an additional product variant will be built separately
  354. // that is limited to the set of libraries and headers that are exposed to
  355. // /product modules.
  356. //
  357. // The product variant may be used with a different (newer) /system,
  358. // so it shouldn't have any unversioned runtime dependencies, or
  359. // make assumptions about the system that may not be true in the
  360. // future.
  361. //
  362. // If set to false, this module becomes inaccessible from /product modules.
  363. //
  364. // Different from the 'vendor_available' property, the modules with
  365. // vndk: {enabled: true} don't have to define 'product_available'. The VNDK
  366. // library without 'product_available' may not be depended on by any other
  367. // modules that has product variants including the product available VNDKs.
  368. //
  369. // Nothing happens if BOARD_VNDK_VERSION isn't set in the BoardConfig.mk
  370. // and PRODUCT_PRODUCT_VNDK_VERSION isn't set.
  371. Product_available *bool
  372. // whether this module is capable of being loaded with other instance
  373. // (possibly an older version) of the same module in the same process.
  374. // Currently, a shared library that is a member of VNDK (vndk: {enabled: true})
  375. // can be double loaded in a vendor process if the library is also a
  376. // (direct and indirect) dependency of an LLNDK library. Such libraries must be
  377. // explicitly marked as `double_loadable: true` by the owner, or the dependency
  378. // from the LLNDK lib should be cut if the lib is not designed to be double loaded.
  379. Double_loadable *bool
  380. // IsLLNDK is set to true for the vendor variant of a cc_library module that has LLNDK stubs.
  381. IsLLNDK bool `blueprint:"mutated"`
  382. // IsVNDKUsingCoreVariant is true for VNDK modules if the global VndkUseCoreVariant option is
  383. // set and the module is not listed in VndkMustUseVendorVariantList.
  384. IsVNDKUsingCoreVariant bool `blueprint:"mutated"`
  385. // IsVNDKCore is set if a VNDK module does not set the vndk.support_system_process property.
  386. IsVNDKCore bool `blueprint:"mutated"`
  387. // IsVNDKSP is set if a VNDK module sets the vndk.support_system_process property.
  388. IsVNDKSP bool `blueprint:"mutated"`
  389. // IsVNDKPrivate is set if a VNDK module sets the vndk.private property or an LLNDK
  390. // module sets the llndk.private property.
  391. IsVNDKPrivate bool `blueprint:"mutated"`
  392. // IsVNDKProduct is set if a VNDK module sets the product_available property.
  393. IsVNDKProduct bool `blueprint:"mutated"`
  394. // IsVendorPublicLibrary is set for the core and product variants of a library that has
  395. // vendor_public_library stubs.
  396. IsVendorPublicLibrary bool `blueprint:"mutated"`
  397. }
  398. // ModuleContextIntf is an interface (on a module context helper) consisting of functions related
  399. // to understanding details about the type of the current module.
  400. // For example, one might call these functions to determine whether the current module is a static
  401. // library and/or is installed in vendor directories.
  402. type ModuleContextIntf interface {
  403. static() bool
  404. staticBinary() bool
  405. testBinary() bool
  406. testLibrary() bool
  407. header() bool
  408. binary() bool
  409. object() bool
  410. toolchain() config.Toolchain
  411. canUseSdk() bool
  412. useSdk() bool
  413. sdkVersion() string
  414. minSdkVersion() string
  415. isSdkVariant() bool
  416. useVndk() bool
  417. isNdk(config android.Config) bool
  418. IsLlndk() bool
  419. IsLlndkPublic() bool
  420. isImplementationForLLNDKPublic() bool
  421. IsVndkPrivate() bool
  422. isVndk() bool
  423. isVndkSp() bool
  424. IsVndkExt() bool
  425. IsVendorPublicLibrary() bool
  426. inProduct() bool
  427. inVendor() bool
  428. inRamdisk() bool
  429. inVendorRamdisk() bool
  430. inRecovery() bool
  431. selectedStl() string
  432. baseModuleName() string
  433. getVndkExtendsModuleName() string
  434. isAfdoCompile() bool
  435. isPgoCompile() bool
  436. isCfi() bool
  437. isFuzzer() bool
  438. isNDKStubLibrary() bool
  439. useClangLld(actx ModuleContext) bool
  440. isForPlatform() bool
  441. apexVariationName() string
  442. apexSdkVersion() android.ApiLevel
  443. bootstrap() bool
  444. mustUseVendorVariant() bool
  445. nativeCoverage() bool
  446. directlyInAnyApex() bool
  447. isPreventInstall() bool
  448. isCfiAssemblySupportEnabled() bool
  449. getSharedFlags() *SharedFlags
  450. }
  451. type SharedFlags struct {
  452. numSharedFlags int
  453. flagsMap map[string]string
  454. }
  455. type ModuleContext interface {
  456. android.ModuleContext
  457. ModuleContextIntf
  458. }
  459. type BaseModuleContext interface {
  460. android.BaseModuleContext
  461. ModuleContextIntf
  462. }
  463. type DepsContext interface {
  464. android.BottomUpMutatorContext
  465. ModuleContextIntf
  466. }
  467. // feature represents additional (optional) steps to building cc-related modules, such as invocation
  468. // of clang-tidy.
  469. type feature interface {
  470. flags(ctx ModuleContext, flags Flags) Flags
  471. props() []interface{}
  472. }
  473. // compiler is the interface for a compiler helper object. Different module decorators may implement
  474. // this helper differently.
  475. type compiler interface {
  476. compilerInit(ctx BaseModuleContext)
  477. compilerDeps(ctx DepsContext, deps Deps) Deps
  478. compilerFlags(ctx ModuleContext, flags Flags, deps PathDeps) Flags
  479. compilerProps() []interface{}
  480. appendCflags([]string)
  481. appendAsflags([]string)
  482. compile(ctx ModuleContext, flags Flags, deps PathDeps) Objects
  483. }
  484. // linker is the interface for a linker decorator object. Individual module types can provide
  485. // their own implementation for this decorator, and thus specify custom logic regarding build
  486. // statements pertaining to linking.
  487. type linker interface {
  488. linkerInit(ctx BaseModuleContext)
  489. linkerDeps(ctx DepsContext, deps Deps) Deps
  490. linkerFlags(ctx ModuleContext, flags Flags) Flags
  491. linkerProps() []interface{}
  492. useClangLld(actx ModuleContext) bool
  493. link(ctx ModuleContext, flags Flags, deps PathDeps, objs Objects) android.Path
  494. appendLdflags([]string)
  495. unstrippedOutputFilePath() android.Path
  496. nativeCoverage() bool
  497. coverageOutputFilePath() android.OptionalPath
  498. // Get the deps that have been explicitly specified in the properties.
  499. linkerSpecifiedDeps(specifiedDeps specifiedDeps) specifiedDeps
  500. }
  501. // specifiedDeps is a tuple struct representing dependencies of a linked binary owned by the linker.
  502. type specifiedDeps struct {
  503. sharedLibs []string
  504. // Note nil and [] are semantically distinct. [] prevents linking against the defaults (usually
  505. // libc, libm, etc.)
  506. systemSharedLibs []string
  507. }
  508. // installer is the interface for an installer helper object. This helper is responsible for
  509. // copying build outputs to the appropriate locations so that they may be installed on device.
  510. type installer interface {
  511. installerProps() []interface{}
  512. install(ctx ModuleContext, path android.Path)
  513. everInstallable() bool
  514. inData() bool
  515. inSanitizerDir() bool
  516. hostToolPath() android.OptionalPath
  517. relativeInstallPath() string
  518. makeUninstallable(mod *Module)
  519. installInRoot() bool
  520. }
  521. type xref interface {
  522. XrefCcFiles() android.Paths
  523. }
  524. type overridable interface {
  525. overriddenModules() []string
  526. }
  527. type libraryDependencyKind int
  528. const (
  529. headerLibraryDependency = iota
  530. sharedLibraryDependency
  531. staticLibraryDependency
  532. )
  533. func (k libraryDependencyKind) String() string {
  534. switch k {
  535. case headerLibraryDependency:
  536. return "headerLibraryDependency"
  537. case sharedLibraryDependency:
  538. return "sharedLibraryDependency"
  539. case staticLibraryDependency:
  540. return "staticLibraryDependency"
  541. default:
  542. panic(fmt.Errorf("unknown libraryDependencyKind %d", k))
  543. }
  544. }
  545. type libraryDependencyOrder int
  546. const (
  547. earlyLibraryDependency = -1
  548. normalLibraryDependency = 0
  549. lateLibraryDependency = 1
  550. )
  551. func (o libraryDependencyOrder) String() string {
  552. switch o {
  553. case earlyLibraryDependency:
  554. return "earlyLibraryDependency"
  555. case normalLibraryDependency:
  556. return "normalLibraryDependency"
  557. case lateLibraryDependency:
  558. return "lateLibraryDependency"
  559. default:
  560. panic(fmt.Errorf("unknown libraryDependencyOrder %d", o))
  561. }
  562. }
  563. // libraryDependencyTag is used to tag dependencies on libraries. Unlike many dependency
  564. // tags that have a set of predefined tag objects that are reused for each dependency, a
  565. // libraryDependencyTag is designed to contain extra metadata and is constructed as needed.
  566. // That means that comparing a libraryDependencyTag for equality will only be equal if all
  567. // of the metadata is equal. Most usages will want to type assert to libraryDependencyTag and
  568. // then check individual metadata fields instead.
  569. type libraryDependencyTag struct {
  570. blueprint.BaseDependencyTag
  571. // These are exported so that fmt.Printf("%#v") can call their String methods.
  572. Kind libraryDependencyKind
  573. Order libraryDependencyOrder
  574. wholeStatic bool
  575. reexportFlags bool
  576. explicitlyVersioned bool
  577. dataLib bool
  578. ndk bool
  579. staticUnwinder bool
  580. makeSuffix string
  581. // Whether or not this dependency should skip the apex dependency check
  582. skipApexAllowedDependenciesCheck bool
  583. // Whether or not this dependency has to be followed for the apex variants
  584. excludeInApex bool
  585. // If true, don't automatically export symbols from the static library into a shared library.
  586. unexportedSymbols bool
  587. }
  588. // header returns true if the libraryDependencyTag is tagging a header lib dependency.
  589. func (d libraryDependencyTag) header() bool {
  590. return d.Kind == headerLibraryDependency
  591. }
  592. // shared returns true if the libraryDependencyTag is tagging a shared lib dependency.
  593. func (d libraryDependencyTag) shared() bool {
  594. return d.Kind == sharedLibraryDependency
  595. }
  596. // shared returns true if the libraryDependencyTag is tagging a static lib dependency.
  597. func (d libraryDependencyTag) static() bool {
  598. return d.Kind == staticLibraryDependency
  599. }
  600. func (d libraryDependencyTag) LicenseAnnotations() []android.LicenseAnnotation {
  601. if d.shared() {
  602. return []android.LicenseAnnotation{android.LicenseAnnotationSharedDependency}
  603. }
  604. return nil
  605. }
  606. var _ android.LicenseAnnotationsDependencyTag = libraryDependencyTag{}
  607. // InstallDepNeeded returns true for shared libraries so that shared library dependencies of
  608. // binaries or other shared libraries are installed as dependencies.
  609. func (d libraryDependencyTag) InstallDepNeeded() bool {
  610. return d.shared()
  611. }
  612. var _ android.InstallNeededDependencyTag = libraryDependencyTag{}
  613. // dependencyTag is used for tagging miscellaneous dependency types that don't fit into
  614. // libraryDependencyTag. Each tag object is created globally and reused for multiple
  615. // dependencies (although since the object contains no references, assigning a tag to a
  616. // variable and modifying it will not modify the original). Users can compare the tag
  617. // returned by ctx.OtherModuleDependencyTag against the global original
  618. type dependencyTag struct {
  619. blueprint.BaseDependencyTag
  620. name string
  621. }
  622. // installDependencyTag is used for tagging miscellaneous dependency types that don't fit into
  623. // libraryDependencyTag, but where the dependency needs to be installed when the parent is
  624. // installed.
  625. type installDependencyTag struct {
  626. blueprint.BaseDependencyTag
  627. android.InstallAlwaysNeededDependencyTag
  628. name string
  629. }
  630. var (
  631. genSourceDepTag = dependencyTag{name: "gen source"}
  632. genHeaderDepTag = dependencyTag{name: "gen header"}
  633. genHeaderExportDepTag = dependencyTag{name: "gen header export"}
  634. objDepTag = dependencyTag{name: "obj"}
  635. dynamicLinkerDepTag = installDependencyTag{name: "dynamic linker"}
  636. reuseObjTag = dependencyTag{name: "reuse objects"}
  637. staticVariantTag = dependencyTag{name: "static variant"}
  638. vndkExtDepTag = dependencyTag{name: "vndk extends"}
  639. dataLibDepTag = dependencyTag{name: "data lib"}
  640. dataBinDepTag = dependencyTag{name: "data bin"}
  641. runtimeDepTag = installDependencyTag{name: "runtime lib"}
  642. testPerSrcDepTag = dependencyTag{name: "test_per_src"}
  643. stubImplDepTag = dependencyTag{name: "stub_impl"}
  644. JniFuzzLibTag = dependencyTag{name: "jni_fuzz_lib_tag"}
  645. FdoProfileTag = dependencyTag{name: "fdo_profile"}
  646. aidlLibraryTag = dependencyTag{name: "aidl_library"}
  647. )
  648. func IsSharedDepTag(depTag blueprint.DependencyTag) bool {
  649. ccLibDepTag, ok := depTag.(libraryDependencyTag)
  650. return ok && ccLibDepTag.shared()
  651. }
  652. func IsStaticDepTag(depTag blueprint.DependencyTag) bool {
  653. ccLibDepTag, ok := depTag.(libraryDependencyTag)
  654. return ok && ccLibDepTag.static()
  655. }
  656. func IsHeaderDepTag(depTag blueprint.DependencyTag) bool {
  657. ccLibDepTag, ok := depTag.(libraryDependencyTag)
  658. return ok && ccLibDepTag.header()
  659. }
  660. func IsRuntimeDepTag(depTag blueprint.DependencyTag) bool {
  661. return depTag == runtimeDepTag
  662. }
  663. func IsTestPerSrcDepTag(depTag blueprint.DependencyTag) bool {
  664. ccDepTag, ok := depTag.(dependencyTag)
  665. return ok && ccDepTag == testPerSrcDepTag
  666. }
  667. // bazelHandler is the interface for a helper object related to deferring to Bazel for
  668. // processing a cc module (during Bazel mixed builds). Individual module types should define
  669. // their own bazel handler if they support being handled by Bazel.
  670. type BazelHandler interface {
  671. // QueueBazelCall invokes request-queueing functions on the BazelContext
  672. //so that these requests are handled when Bazel's cquery is invoked.
  673. QueueBazelCall(ctx android.BaseModuleContext, label string)
  674. // ProcessBazelQueryResponse uses information retrieved from Bazel to set properties
  675. // on the current module with given label.
  676. ProcessBazelQueryResponse(ctx android.ModuleContext, label string)
  677. }
  678. // Module contains the properties and members used by all C/C++ module types, and implements
  679. // the blueprint.Module interface. It delegates to compiler, linker, and installer interfaces
  680. // to construct the output file. Behavior can be customized with a Customizer, or "decorator",
  681. // interface.
  682. //
  683. // To define a C/C++ related module, construct a new Module object and point its delegates to
  684. // type-specific structs. These delegates will be invoked to register module-specific build
  685. // statements which may be unique to the module type. For example, module.compiler.compile() should
  686. // be defined so as to register build statements which are responsible for compiling the module.
  687. //
  688. // Another example: to construct a cc_binary module, one can create a `cc.binaryDecorator` struct
  689. // which implements the `linker` and `installer` interfaces, and points the `linker` and `installer`
  690. // members of the cc.Module to this decorator. Thus, a cc_binary module has custom linker and
  691. // installer logic.
  692. type Module struct {
  693. fuzz.FuzzModule
  694. android.BazelModuleBase
  695. VendorProperties VendorProperties
  696. Properties BaseProperties
  697. // initialize before calling Init
  698. hod android.HostOrDeviceSupported
  699. multilib android.Multilib
  700. bazelable bool
  701. // Allowable SdkMemberTypes of this module type.
  702. sdkMemberTypes []android.SdkMemberType
  703. // decorator delegates, initialize before calling Init
  704. // these may contain module-specific implementations, and effectively allow for custom
  705. // type-specific logic. These members may reference different objects or the same object.
  706. // Functions of these decorators will be invoked to initialize and register type-specific
  707. // build statements.
  708. compiler compiler
  709. linker linker
  710. installer installer
  711. bazelHandler BazelHandler
  712. features []feature
  713. stl *stl
  714. sanitize *sanitize
  715. coverage *coverage
  716. fuzzer *fuzzer
  717. sabi *sabi
  718. vndkdep *vndkdep
  719. lto *lto
  720. afdo *afdo
  721. pgo *pgo
  722. library libraryInterface
  723. outputFile android.OptionalPath
  724. cachedToolchain config.Toolchain
  725. subAndroidMkOnce map[subAndroidMkProvider]bool
  726. // Flags used to compile this module
  727. flags Flags
  728. // Shared flags among build rules of this module
  729. sharedFlags SharedFlags
  730. // only non-nil when this is a shared library that reuses the objects of a static library
  731. staticAnalogue *StaticLibraryInfo
  732. makeLinkType string
  733. // Kythe (source file indexer) paths for this compilation module
  734. kytheFiles android.Paths
  735. // Object .o file output paths for this compilation module
  736. objFiles android.Paths
  737. // Tidy .tidy file output paths for this compilation module
  738. tidyFiles android.Paths
  739. // For apex variants, this is set as apex.min_sdk_version
  740. apexSdkVersion android.ApiLevel
  741. hideApexVariantFromMake bool
  742. }
  743. func (c *Module) AddJSONData(d *map[string]interface{}) {
  744. var hasAidl, hasLex, hasProto, hasRenderscript, hasSysprop, hasWinMsg, hasYacc bool
  745. if b, ok := c.compiler.(*baseCompiler); ok {
  746. hasAidl = b.hasSrcExt(".aidl")
  747. hasLex = b.hasSrcExt(".l") || b.hasSrcExt(".ll")
  748. hasProto = b.hasSrcExt(".proto")
  749. hasRenderscript = b.hasSrcExt(".rscript") || b.hasSrcExt(".fs")
  750. hasSysprop = b.hasSrcExt(".sysprop")
  751. hasWinMsg = b.hasSrcExt(".mc")
  752. hasYacc = b.hasSrcExt(".y") || b.hasSrcExt(".yy")
  753. }
  754. c.AndroidModuleBase().AddJSONData(d)
  755. (*d)["Cc"] = map[string]interface{}{
  756. "SdkVersion": c.SdkVersion(),
  757. "MinSdkVersion": c.MinSdkVersion(),
  758. "VndkVersion": c.VndkVersion(),
  759. "ProductSpecific": c.ProductSpecific(),
  760. "SocSpecific": c.SocSpecific(),
  761. "DeviceSpecific": c.DeviceSpecific(),
  762. "InProduct": c.InProduct(),
  763. "InVendor": c.InVendor(),
  764. "InRamdisk": c.InRamdisk(),
  765. "InVendorRamdisk": c.InVendorRamdisk(),
  766. "InRecovery": c.InRecovery(),
  767. "VendorAvailable": c.VendorAvailable(),
  768. "ProductAvailable": c.ProductAvailable(),
  769. "RamdiskAvailable": c.RamdiskAvailable(),
  770. "VendorRamdiskAvailable": c.VendorRamdiskAvailable(),
  771. "RecoveryAvailable": c.RecoveryAvailable(),
  772. "OdmAvailable": c.OdmAvailable(),
  773. "InstallInData": c.InstallInData(),
  774. "InstallInRamdisk": c.InstallInRamdisk(),
  775. "InstallInSanitizerDir": c.InstallInSanitizerDir(),
  776. "InstallInVendorRamdisk": c.InstallInVendorRamdisk(),
  777. "InstallInRecovery": c.InstallInRecovery(),
  778. "InstallInRoot": c.InstallInRoot(),
  779. "IsVndk": c.IsVndk(),
  780. "IsVndkExt": c.IsVndkExt(),
  781. "IsVndkPrivate": c.IsVndkPrivate(),
  782. "IsVndkSp": c.IsVndkSp(),
  783. "IsLlndk": c.IsLlndk(),
  784. "IsLlndkPublic": c.IsLlndkPublic(),
  785. "IsSnapshotLibrary": c.IsSnapshotLibrary(),
  786. "IsSnapshotPrebuilt": c.IsSnapshotPrebuilt(),
  787. "IsVendorPublicLibrary": c.IsVendorPublicLibrary(),
  788. "ApexSdkVersion": c.apexSdkVersion,
  789. "TestFor": c.TestFor(),
  790. "AidlSrcs": hasAidl,
  791. "LexSrcs": hasLex,
  792. "ProtoSrcs": hasProto,
  793. "RenderscriptSrcs": hasRenderscript,
  794. "SyspropSrcs": hasSysprop,
  795. "WinMsgSrcs": hasWinMsg,
  796. "YaccSrsc": hasYacc,
  797. "OnlyCSrcs": !(hasAidl || hasLex || hasProto || hasRenderscript || hasSysprop || hasWinMsg || hasYacc),
  798. }
  799. }
  800. func (c *Module) SetPreventInstall() {
  801. c.Properties.PreventInstall = true
  802. }
  803. func (c *Module) SetHideFromMake() {
  804. c.Properties.HideFromMake = true
  805. }
  806. func (c *Module) HiddenFromMake() bool {
  807. return c.Properties.HideFromMake
  808. }
  809. func (c *Module) RequiredModuleNames() []string {
  810. required := android.CopyOf(c.ModuleBase.RequiredModuleNames())
  811. if c.ImageVariation().Variation == android.CoreVariation {
  812. required = append(required, c.Properties.Target.Platform.Required...)
  813. required = removeListFromList(required, c.Properties.Target.Platform.Exclude_required)
  814. } else if c.InRecovery() {
  815. required = append(required, c.Properties.Target.Recovery.Required...)
  816. required = removeListFromList(required, c.Properties.Target.Recovery.Exclude_required)
  817. }
  818. return android.FirstUniqueStrings(required)
  819. }
  820. func (c *Module) Toc() android.OptionalPath {
  821. if c.linker != nil {
  822. if library, ok := c.linker.(libraryInterface); ok {
  823. return library.toc()
  824. }
  825. }
  826. panic(fmt.Errorf("Toc() called on non-library module: %q", c.BaseModuleName()))
  827. }
  828. func (c *Module) ApiLevel() string {
  829. if c.linker != nil {
  830. if stub, ok := c.linker.(*stubDecorator); ok {
  831. return stub.apiLevel.String()
  832. }
  833. }
  834. panic(fmt.Errorf("ApiLevel() called on non-stub library module: %q", c.BaseModuleName()))
  835. }
  836. func (c *Module) Static() bool {
  837. if c.linker != nil {
  838. if library, ok := c.linker.(libraryInterface); ok {
  839. return library.static()
  840. }
  841. }
  842. panic(fmt.Errorf("Static() called on non-library module: %q", c.BaseModuleName()))
  843. }
  844. func (c *Module) Shared() bool {
  845. if c.linker != nil {
  846. if library, ok := c.linker.(libraryInterface); ok {
  847. return library.shared()
  848. }
  849. }
  850. panic(fmt.Errorf("Shared() called on non-library module: %q", c.BaseModuleName()))
  851. }
  852. func (c *Module) SelectedStl() string {
  853. if c.stl != nil {
  854. return c.stl.Properties.SelectedStl
  855. }
  856. return ""
  857. }
  858. func (c *Module) NdkPrebuiltStl() bool {
  859. if _, ok := c.linker.(*ndkPrebuiltStlLinker); ok {
  860. return true
  861. }
  862. return false
  863. }
  864. func (c *Module) StubDecorator() bool {
  865. if _, ok := c.linker.(*stubDecorator); ok {
  866. return true
  867. }
  868. return false
  869. }
  870. func (c *Module) SdkVersion() string {
  871. return String(c.Properties.Sdk_version)
  872. }
  873. func (c *Module) MinSdkVersion() string {
  874. return String(c.Properties.Min_sdk_version)
  875. }
  876. func (c *Module) isCrt() bool {
  877. if linker, ok := c.linker.(*objectLinker); ok {
  878. return linker.isCrt()
  879. }
  880. return false
  881. }
  882. func (c *Module) SplitPerApiLevel() bool {
  883. return c.canUseSdk() && c.isCrt()
  884. }
  885. func (c *Module) AlwaysSdk() bool {
  886. return c.Properties.AlwaysSdk || Bool(c.Properties.Sdk_variant_only)
  887. }
  888. func (c *Module) CcLibrary() bool {
  889. if c.linker != nil {
  890. if _, ok := c.linker.(*libraryDecorator); ok {
  891. return true
  892. }
  893. if _, ok := c.linker.(*prebuiltLibraryLinker); ok {
  894. return true
  895. }
  896. }
  897. return false
  898. }
  899. func (c *Module) CcLibraryInterface() bool {
  900. if _, ok := c.linker.(libraryInterface); ok {
  901. return true
  902. }
  903. return false
  904. }
  905. func (c *Module) RustLibraryInterface() bool {
  906. return false
  907. }
  908. func (c *Module) IsFuzzModule() bool {
  909. if _, ok := c.compiler.(*fuzzBinary); ok {
  910. return true
  911. }
  912. return false
  913. }
  914. func (c *Module) FuzzModuleStruct() fuzz.FuzzModule {
  915. return c.FuzzModule
  916. }
  917. func (c *Module) FuzzPackagedModule() fuzz.FuzzPackagedModule {
  918. if fuzzer, ok := c.compiler.(*fuzzBinary); ok {
  919. return fuzzer.fuzzPackagedModule
  920. }
  921. panic(fmt.Errorf("FuzzPackagedModule called on non-fuzz module: %q", c.BaseModuleName()))
  922. }
  923. func (c *Module) FuzzSharedLibraries() android.RuleBuilderInstalls {
  924. if fuzzer, ok := c.compiler.(*fuzzBinary); ok {
  925. return fuzzer.sharedLibraries
  926. }
  927. panic(fmt.Errorf("FuzzSharedLibraries called on non-fuzz module: %q", c.BaseModuleName()))
  928. }
  929. func (c *Module) NonCcVariants() bool {
  930. return false
  931. }
  932. func (c *Module) SetStatic() {
  933. if c.linker != nil {
  934. if library, ok := c.linker.(libraryInterface); ok {
  935. library.setStatic()
  936. return
  937. }
  938. }
  939. panic(fmt.Errorf("SetStatic called on non-library module: %q", c.BaseModuleName()))
  940. }
  941. func (c *Module) SetShared() {
  942. if c.linker != nil {
  943. if library, ok := c.linker.(libraryInterface); ok {
  944. library.setShared()
  945. return
  946. }
  947. }
  948. panic(fmt.Errorf("SetShared called on non-library module: %q", c.BaseModuleName()))
  949. }
  950. func (c *Module) BuildStaticVariant() bool {
  951. if c.linker != nil {
  952. if library, ok := c.linker.(libraryInterface); ok {
  953. return library.buildStatic()
  954. }
  955. }
  956. panic(fmt.Errorf("BuildStaticVariant called on non-library module: %q", c.BaseModuleName()))
  957. }
  958. func (c *Module) BuildSharedVariant() bool {
  959. if c.linker != nil {
  960. if library, ok := c.linker.(libraryInterface); ok {
  961. return library.buildShared()
  962. }
  963. }
  964. panic(fmt.Errorf("BuildSharedVariant called on non-library module: %q", c.BaseModuleName()))
  965. }
  966. func (c *Module) Module() android.Module {
  967. return c
  968. }
  969. func (c *Module) OutputFile() android.OptionalPath {
  970. return c.outputFile
  971. }
  972. func (c *Module) CoverageFiles() android.Paths {
  973. if c.linker != nil {
  974. if library, ok := c.linker.(libraryInterface); ok {
  975. return library.objs().coverageFiles
  976. }
  977. }
  978. panic(fmt.Errorf("CoverageFiles called on non-library module: %q", c.BaseModuleName()))
  979. }
  980. var _ LinkableInterface = (*Module)(nil)
  981. func (c *Module) UnstrippedOutputFile() android.Path {
  982. if c.linker != nil {
  983. return c.linker.unstrippedOutputFilePath()
  984. }
  985. return nil
  986. }
  987. func (c *Module) CoverageOutputFile() android.OptionalPath {
  988. if c.linker != nil {
  989. return c.linker.coverageOutputFilePath()
  990. }
  991. return android.OptionalPath{}
  992. }
  993. func (c *Module) RelativeInstallPath() string {
  994. if c.installer != nil {
  995. return c.installer.relativeInstallPath()
  996. }
  997. return ""
  998. }
  999. func (c *Module) VndkVersion() string {
  1000. return c.Properties.VndkVersion
  1001. }
  1002. func (c *Module) Init() android.Module {
  1003. c.AddProperties(&c.Properties, &c.VendorProperties)
  1004. if c.compiler != nil {
  1005. c.AddProperties(c.compiler.compilerProps()...)
  1006. }
  1007. if c.linker != nil {
  1008. c.AddProperties(c.linker.linkerProps()...)
  1009. }
  1010. if c.installer != nil {
  1011. c.AddProperties(c.installer.installerProps()...)
  1012. }
  1013. if c.stl != nil {
  1014. c.AddProperties(c.stl.props()...)
  1015. }
  1016. if c.sanitize != nil {
  1017. c.AddProperties(c.sanitize.props()...)
  1018. }
  1019. if c.coverage != nil {
  1020. c.AddProperties(c.coverage.props()...)
  1021. }
  1022. if c.fuzzer != nil {
  1023. c.AddProperties(c.fuzzer.props()...)
  1024. }
  1025. if c.sabi != nil {
  1026. c.AddProperties(c.sabi.props()...)
  1027. }
  1028. if c.vndkdep != nil {
  1029. c.AddProperties(c.vndkdep.props()...)
  1030. }
  1031. if c.lto != nil {
  1032. c.AddProperties(c.lto.props()...)
  1033. }
  1034. if c.afdo != nil {
  1035. c.AddProperties(c.afdo.props()...)
  1036. }
  1037. if c.pgo != nil {
  1038. c.AddProperties(c.pgo.props()...)
  1039. }
  1040. for _, feature := range c.features {
  1041. c.AddProperties(feature.props()...)
  1042. }
  1043. android.InitAndroidArchModule(c, c.hod, c.multilib)
  1044. if c.bazelable {
  1045. android.InitBazelModule(c)
  1046. }
  1047. android.InitApexModule(c)
  1048. android.InitDefaultableModule(c)
  1049. return c
  1050. }
  1051. // UseVndk() returns true if this module is built against VNDK.
  1052. // This means the vendor and product variants of a module.
  1053. func (c *Module) UseVndk() bool {
  1054. return c.Properties.VndkVersion != ""
  1055. }
  1056. func (c *Module) canUseSdk() bool {
  1057. return c.Os() == android.Android && c.Target().NativeBridge == android.NativeBridgeDisabled &&
  1058. !c.UseVndk() && !c.InRamdisk() && !c.InRecovery() && !c.InVendorRamdisk()
  1059. }
  1060. func (c *Module) UseSdk() bool {
  1061. if c.canUseSdk() {
  1062. return String(c.Properties.Sdk_version) != ""
  1063. }
  1064. return false
  1065. }
  1066. func (c *Module) isCoverageVariant() bool {
  1067. return c.coverage.Properties.IsCoverageVariant
  1068. }
  1069. func (c *Module) IsNdk(config android.Config) bool {
  1070. return inList(c.BaseModuleName(), *getNDKKnownLibs(config))
  1071. }
  1072. func (c *Module) IsLlndk() bool {
  1073. return c.VendorProperties.IsLLNDK
  1074. }
  1075. func (c *Module) IsLlndkPublic() bool {
  1076. return c.VendorProperties.IsLLNDK && !c.VendorProperties.IsVNDKPrivate
  1077. }
  1078. func (m *Module) NeedsLlndkVariants() bool {
  1079. lib := moduleLibraryInterface(m)
  1080. return lib != nil && (lib.hasLLNDKStubs() || lib.hasLLNDKHeaders())
  1081. }
  1082. func (m *Module) NeedsVendorPublicLibraryVariants() bool {
  1083. lib := moduleLibraryInterface(m)
  1084. return lib != nil && (lib.hasVendorPublicLibrary())
  1085. }
  1086. // IsVendorPublicLibrary returns true for vendor public libraries.
  1087. func (c *Module) IsVendorPublicLibrary() bool {
  1088. return c.VendorProperties.IsVendorPublicLibrary
  1089. }
  1090. func (c *Module) IsVndkPrebuiltLibrary() bool {
  1091. if _, ok := c.linker.(*vndkPrebuiltLibraryDecorator); ok {
  1092. return true
  1093. }
  1094. return false
  1095. }
  1096. func (c *Module) SdkAndPlatformVariantVisibleToMake() bool {
  1097. return c.Properties.SdkAndPlatformVariantVisibleToMake
  1098. }
  1099. func (c *Module) HasLlndkStubs() bool {
  1100. lib := moduleLibraryInterface(c)
  1101. return lib != nil && lib.hasLLNDKStubs()
  1102. }
  1103. func (c *Module) StubsVersion() string {
  1104. if lib, ok := c.linker.(versionedInterface); ok {
  1105. return lib.stubsVersion()
  1106. }
  1107. panic(fmt.Errorf("StubsVersion called on non-versioned module: %q", c.BaseModuleName()))
  1108. }
  1109. // isImplementationForLLNDKPublic returns true for any variant of a cc_library that has LLNDK stubs
  1110. // and does not set llndk.vendor_available: false.
  1111. func (c *Module) isImplementationForLLNDKPublic() bool {
  1112. library, _ := c.library.(*libraryDecorator)
  1113. return library != nil && library.hasLLNDKStubs() &&
  1114. !Bool(library.Properties.Llndk.Private)
  1115. }
  1116. // Returns true for LLNDK-private, VNDK-SP-private, and VNDK-core-private.
  1117. func (c *Module) IsVndkPrivate() bool {
  1118. // Check if VNDK-core-private or VNDK-SP-private
  1119. if c.IsVndk() {
  1120. return Bool(c.vndkdep.Properties.Vndk.Private)
  1121. }
  1122. // Check if LLNDK-private
  1123. if library, ok := c.library.(*libraryDecorator); ok && c.IsLlndk() {
  1124. return Bool(library.Properties.Llndk.Private)
  1125. }
  1126. return false
  1127. }
  1128. // IsVndk() returns true if this module has a vndk variant.
  1129. // Note that IsVndk() returns true for all variants of vndk-enabled libraries. Not only vendor variant,
  1130. // but also platform and product variants of vndk-enabled libraries return true for IsVndk().
  1131. func (c *Module) IsVndk() bool {
  1132. if vndkdep := c.vndkdep; vndkdep != nil {
  1133. return vndkdep.isVndk()
  1134. }
  1135. return false
  1136. }
  1137. func (c *Module) isAfdoCompile() bool {
  1138. if afdo := c.afdo; afdo != nil {
  1139. return afdo.Properties.FdoProfilePath != nil
  1140. }
  1141. return false
  1142. }
  1143. func (c *Module) isPgoCompile() bool {
  1144. if pgo := c.pgo; pgo != nil {
  1145. return pgo.Properties.PgoCompile
  1146. }
  1147. return false
  1148. }
  1149. func (c *Module) isCfi() bool {
  1150. if sanitize := c.sanitize; sanitize != nil {
  1151. return Bool(sanitize.Properties.Sanitize.Cfi)
  1152. }
  1153. return false
  1154. }
  1155. func (c *Module) isFuzzer() bool {
  1156. if sanitize := c.sanitize; sanitize != nil {
  1157. return Bool(sanitize.Properties.SanitizeMutated.Fuzzer)
  1158. }
  1159. return false
  1160. }
  1161. func (c *Module) isNDKStubLibrary() bool {
  1162. if _, ok := c.compiler.(*stubDecorator); ok {
  1163. return true
  1164. }
  1165. return false
  1166. }
  1167. func (c *Module) IsVndkSp() bool {
  1168. if vndkdep := c.vndkdep; vndkdep != nil {
  1169. return vndkdep.isVndkSp()
  1170. }
  1171. return false
  1172. }
  1173. func (c *Module) IsVndkExt() bool {
  1174. if vndkdep := c.vndkdep; vndkdep != nil {
  1175. return vndkdep.isVndkExt()
  1176. }
  1177. return false
  1178. }
  1179. func (c *Module) SubName() string {
  1180. return c.Properties.SubName
  1181. }
  1182. func (c *Module) MustUseVendorVariant() bool {
  1183. return c.IsVndkSp() || c.Properties.MustUseVendorVariant
  1184. }
  1185. func (c *Module) getVndkExtendsModuleName() string {
  1186. if vndkdep := c.vndkdep; vndkdep != nil {
  1187. return vndkdep.getVndkExtendsModuleName()
  1188. }
  1189. return ""
  1190. }
  1191. func (c *Module) IsStubs() bool {
  1192. if lib := c.library; lib != nil {
  1193. return lib.buildStubs()
  1194. }
  1195. return false
  1196. }
  1197. func (c *Module) HasStubsVariants() bool {
  1198. if lib := c.library; lib != nil {
  1199. return lib.hasStubsVariants()
  1200. }
  1201. return false
  1202. }
  1203. func (c *Module) IsStubsImplementationRequired() bool {
  1204. if lib := c.library; lib != nil {
  1205. return lib.isStubsImplementationRequired()
  1206. }
  1207. return false
  1208. }
  1209. // If this is a stubs library, ImplementationModuleName returns the name of the module that contains
  1210. // the implementation. If it is an implementation library it returns its own name.
  1211. func (c *Module) ImplementationModuleName(ctx android.BaseModuleContext) string {
  1212. name := ctx.OtherModuleName(c)
  1213. if versioned, ok := c.linker.(versionedInterface); ok {
  1214. name = versioned.implementationModuleName(name)
  1215. }
  1216. return name
  1217. }
  1218. // Similar to ImplementationModuleName, but uses the Make variant of the module
  1219. // name as base name, for use in AndroidMk output. E.g. for a prebuilt module
  1220. // where the Soong name is prebuilt_foo, this returns foo (which works in Make
  1221. // under the premise that the prebuilt module overrides its source counterpart
  1222. // if it is exposed to Make).
  1223. func (c *Module) ImplementationModuleNameForMake(ctx android.BaseModuleContext) string {
  1224. name := c.BaseModuleName()
  1225. if versioned, ok := c.linker.(versionedInterface); ok {
  1226. name = versioned.implementationModuleName(name)
  1227. }
  1228. return name
  1229. }
  1230. func (c *Module) Bootstrap() bool {
  1231. return Bool(c.Properties.Bootstrap)
  1232. }
  1233. func (c *Module) nativeCoverage() bool {
  1234. // Bug: http://b/137883967 - native-bridge modules do not currently work with coverage
  1235. if c.Target().NativeBridge == android.NativeBridgeEnabled {
  1236. return false
  1237. }
  1238. return c.linker != nil && c.linker.nativeCoverage()
  1239. }
  1240. func (c *Module) IsSnapshotPrebuilt() bool {
  1241. if p, ok := c.linker.(SnapshotInterface); ok {
  1242. return p.IsSnapshotPrebuilt()
  1243. }
  1244. return false
  1245. }
  1246. func (c *Module) ExcludeFromVendorSnapshot() bool {
  1247. return Bool(c.Properties.Exclude_from_vendor_snapshot)
  1248. }
  1249. func (c *Module) ExcludeFromRecoverySnapshot() bool {
  1250. return Bool(c.Properties.Exclude_from_recovery_snapshot)
  1251. }
  1252. func isBionic(name string) bool {
  1253. switch name {
  1254. case "libc", "libm", "libdl", "libdl_android", "linker":
  1255. return true
  1256. }
  1257. return false
  1258. }
  1259. func InstallToBootstrap(name string, config android.Config) bool {
  1260. // NOTE: also update //build/bazel/rules/apex/cc.bzl#_installed_to_bootstrap
  1261. // if this list is updated.
  1262. if name == "libclang_rt.hwasan" || name == "libc_hwasan" {
  1263. return true
  1264. }
  1265. return isBionic(name)
  1266. }
  1267. func (c *Module) XrefCcFiles() android.Paths {
  1268. return c.kytheFiles
  1269. }
  1270. func (c *Module) isCfiAssemblySupportEnabled() bool {
  1271. return c.sanitize != nil &&
  1272. Bool(c.sanitize.Properties.Sanitize.Config.Cfi_assembly_support)
  1273. }
  1274. func (c *Module) InstallInRoot() bool {
  1275. return c.installer != nil && c.installer.installInRoot()
  1276. }
  1277. type baseModuleContext struct {
  1278. android.BaseModuleContext
  1279. moduleContextImpl
  1280. }
  1281. type depsContext struct {
  1282. android.BottomUpMutatorContext
  1283. moduleContextImpl
  1284. }
  1285. type moduleContext struct {
  1286. android.ModuleContext
  1287. moduleContextImpl
  1288. }
  1289. type moduleContextImpl struct {
  1290. mod *Module
  1291. ctx BaseModuleContext
  1292. }
  1293. func (ctx *moduleContextImpl) toolchain() config.Toolchain {
  1294. return ctx.mod.toolchain(ctx.ctx)
  1295. }
  1296. func (ctx *moduleContextImpl) static() bool {
  1297. return ctx.mod.static()
  1298. }
  1299. func (ctx *moduleContextImpl) staticBinary() bool {
  1300. return ctx.mod.staticBinary()
  1301. }
  1302. func (ctx *moduleContextImpl) testBinary() bool {
  1303. return ctx.mod.testBinary()
  1304. }
  1305. func (ctx *moduleContextImpl) testLibrary() bool {
  1306. return ctx.mod.testLibrary()
  1307. }
  1308. func (ctx *moduleContextImpl) header() bool {
  1309. return ctx.mod.Header()
  1310. }
  1311. func (ctx *moduleContextImpl) binary() bool {
  1312. return ctx.mod.Binary()
  1313. }
  1314. func (ctx *moduleContextImpl) object() bool {
  1315. return ctx.mod.Object()
  1316. }
  1317. func (ctx *moduleContextImpl) canUseSdk() bool {
  1318. return ctx.mod.canUseSdk()
  1319. }
  1320. func (ctx *moduleContextImpl) useSdk() bool {
  1321. return ctx.mod.UseSdk()
  1322. }
  1323. func (ctx *moduleContextImpl) sdkVersion() string {
  1324. if ctx.ctx.Device() {
  1325. if ctx.useVndk() {
  1326. vndkVer := ctx.mod.VndkVersion()
  1327. if inList(vndkVer, ctx.ctx.Config().PlatformVersionActiveCodenames()) {
  1328. return "current"
  1329. }
  1330. return vndkVer
  1331. }
  1332. return String(ctx.mod.Properties.Sdk_version)
  1333. }
  1334. return ""
  1335. }
  1336. func (ctx *moduleContextImpl) minSdkVersion() string {
  1337. ver := ctx.mod.MinSdkVersion()
  1338. if ver == "apex_inherit" && !ctx.isForPlatform() {
  1339. ver = ctx.apexSdkVersion().String()
  1340. }
  1341. if ver == "apex_inherit" || ver == "" {
  1342. ver = ctx.sdkVersion()
  1343. }
  1344. // For crt objects, the meaning of min_sdk_version is very different from other types of
  1345. // module. For them, min_sdk_version defines the oldest version that the build system will
  1346. // create versioned variants for. For example, if min_sdk_version is 16, then sdk variant of
  1347. // the crt object has local variants of 16, 17, ..., up to the latest version. sdk_version
  1348. // and min_sdk_version properties of the variants are set to the corresponding version
  1349. // numbers. However, the non-sdk variant (for apex or platform) of the crt object is left
  1350. // untouched. min_sdk_version: 16 doesn't actually mean that the non-sdk variant has to
  1351. // support such an old version. The version is set to the later version in case when the
  1352. // non-sdk variant is for the platform, or the min_sdk_version of the containing APEX if
  1353. // it's for an APEX.
  1354. if ctx.mod.isCrt() && !ctx.isSdkVariant() {
  1355. if ctx.isForPlatform() {
  1356. ver = strconv.Itoa(android.FutureApiLevelInt)
  1357. } else { // for apex
  1358. ver = ctx.apexSdkVersion().String()
  1359. if ver == "" { // in case when min_sdk_version was not set by the APEX
  1360. ver = ctx.sdkVersion()
  1361. }
  1362. }
  1363. }
  1364. // Also make sure that minSdkVersion is not greater than sdkVersion, if they are both numbers
  1365. sdkVersionInt, err := strconv.Atoi(ctx.sdkVersion())
  1366. minSdkVersionInt, err2 := strconv.Atoi(ver)
  1367. if err == nil && err2 == nil {
  1368. if sdkVersionInt < minSdkVersionInt {
  1369. return strconv.Itoa(sdkVersionInt)
  1370. }
  1371. }
  1372. return ver
  1373. }
  1374. func (ctx *moduleContextImpl) isSdkVariant() bool {
  1375. return ctx.mod.IsSdkVariant()
  1376. }
  1377. func (ctx *moduleContextImpl) useVndk() bool {
  1378. return ctx.mod.UseVndk()
  1379. }
  1380. func (ctx *moduleContextImpl) isNdk(config android.Config) bool {
  1381. return ctx.mod.IsNdk(config)
  1382. }
  1383. func (ctx *moduleContextImpl) IsLlndk() bool {
  1384. return ctx.mod.IsLlndk()
  1385. }
  1386. func (ctx *moduleContextImpl) IsLlndkPublic() bool {
  1387. return ctx.mod.IsLlndkPublic()
  1388. }
  1389. func (ctx *moduleContextImpl) isImplementationForLLNDKPublic() bool {
  1390. return ctx.mod.isImplementationForLLNDKPublic()
  1391. }
  1392. func (ctx *moduleContextImpl) IsVndkPrivate() bool {
  1393. return ctx.mod.IsVndkPrivate()
  1394. }
  1395. func (ctx *moduleContextImpl) isVndk() bool {
  1396. return ctx.mod.IsVndk()
  1397. }
  1398. func (ctx *moduleContextImpl) isAfdoCompile() bool {
  1399. return ctx.mod.isAfdoCompile()
  1400. }
  1401. func (ctx *moduleContextImpl) isPgoCompile() bool {
  1402. return ctx.mod.isPgoCompile()
  1403. }
  1404. func (ctx *moduleContextImpl) isCfi() bool {
  1405. return ctx.mod.isCfi()
  1406. }
  1407. func (ctx *moduleContextImpl) isFuzzer() bool {
  1408. return ctx.mod.isFuzzer()
  1409. }
  1410. func (ctx *moduleContextImpl) isNDKStubLibrary() bool {
  1411. return ctx.mod.isNDKStubLibrary()
  1412. }
  1413. func (ctx *moduleContextImpl) isVndkSp() bool {
  1414. return ctx.mod.IsVndkSp()
  1415. }
  1416. func (ctx *moduleContextImpl) IsVndkExt() bool {
  1417. return ctx.mod.IsVndkExt()
  1418. }
  1419. func (ctx *moduleContextImpl) IsVendorPublicLibrary() bool {
  1420. return ctx.mod.IsVendorPublicLibrary()
  1421. }
  1422. func (ctx *moduleContextImpl) mustUseVendorVariant() bool {
  1423. return ctx.mod.MustUseVendorVariant()
  1424. }
  1425. func (ctx *moduleContextImpl) selectedStl() string {
  1426. if stl := ctx.mod.stl; stl != nil {
  1427. return stl.Properties.SelectedStl
  1428. }
  1429. return ""
  1430. }
  1431. func (ctx *moduleContextImpl) useClangLld(actx ModuleContext) bool {
  1432. return ctx.mod.linker.useClangLld(actx)
  1433. }
  1434. func (ctx *moduleContextImpl) baseModuleName() string {
  1435. return ctx.mod.ModuleBase.BaseModuleName()
  1436. }
  1437. func (ctx *moduleContextImpl) getVndkExtendsModuleName() string {
  1438. return ctx.mod.getVndkExtendsModuleName()
  1439. }
  1440. func (ctx *moduleContextImpl) isForPlatform() bool {
  1441. return ctx.ctx.Provider(android.ApexInfoProvider).(android.ApexInfo).IsForPlatform()
  1442. }
  1443. func (ctx *moduleContextImpl) apexVariationName() string {
  1444. return ctx.ctx.Provider(android.ApexInfoProvider).(android.ApexInfo).ApexVariationName
  1445. }
  1446. func (ctx *moduleContextImpl) apexSdkVersion() android.ApiLevel {
  1447. return ctx.mod.apexSdkVersion
  1448. }
  1449. func (ctx *moduleContextImpl) bootstrap() bool {
  1450. return ctx.mod.Bootstrap()
  1451. }
  1452. func (ctx *moduleContextImpl) nativeCoverage() bool {
  1453. return ctx.mod.nativeCoverage()
  1454. }
  1455. func (ctx *moduleContextImpl) directlyInAnyApex() bool {
  1456. return ctx.mod.DirectlyInAnyApex()
  1457. }
  1458. func (ctx *moduleContextImpl) isPreventInstall() bool {
  1459. return ctx.mod.Properties.PreventInstall
  1460. }
  1461. func (ctx *moduleContextImpl) getSharedFlags() *SharedFlags {
  1462. shared := &ctx.mod.sharedFlags
  1463. if shared.flagsMap == nil {
  1464. shared.numSharedFlags = 0
  1465. shared.flagsMap = make(map[string]string)
  1466. }
  1467. return shared
  1468. }
  1469. func (ctx *moduleContextImpl) isCfiAssemblySupportEnabled() bool {
  1470. return ctx.mod.isCfiAssemblySupportEnabled()
  1471. }
  1472. func newBaseModule(hod android.HostOrDeviceSupported, multilib android.Multilib) *Module {
  1473. return &Module{
  1474. hod: hod,
  1475. multilib: multilib,
  1476. }
  1477. }
  1478. func newModule(hod android.HostOrDeviceSupported, multilib android.Multilib) *Module {
  1479. module := newBaseModule(hod, multilib)
  1480. module.features = []feature{
  1481. &tidyFeature{},
  1482. }
  1483. module.stl = &stl{}
  1484. module.sanitize = &sanitize{}
  1485. module.coverage = &coverage{}
  1486. module.fuzzer = &fuzzer{}
  1487. module.sabi = &sabi{}
  1488. module.vndkdep = &vndkdep{}
  1489. module.lto = &lto{}
  1490. module.afdo = &afdo{}
  1491. module.pgo = &pgo{}
  1492. return module
  1493. }
  1494. func (c *Module) Prebuilt() *android.Prebuilt {
  1495. if p, ok := c.linker.(prebuiltLinkerInterface); ok {
  1496. return p.prebuilt()
  1497. }
  1498. return nil
  1499. }
  1500. func (c *Module) IsPrebuilt() bool {
  1501. return c.Prebuilt() != nil
  1502. }
  1503. func (c *Module) Name() string {
  1504. name := c.ModuleBase.Name()
  1505. if p, ok := c.linker.(interface {
  1506. Name(string) string
  1507. }); ok {
  1508. name = p.Name(name)
  1509. }
  1510. return name
  1511. }
  1512. func (c *Module) Symlinks() []string {
  1513. if p, ok := c.installer.(interface {
  1514. symlinkList() []string
  1515. }); ok {
  1516. return p.symlinkList()
  1517. }
  1518. return nil
  1519. }
  1520. func (c *Module) IsTestPerSrcAllTestsVariation() bool {
  1521. test, ok := c.linker.(testPerSrc)
  1522. return ok && test.isAllTestsVariation()
  1523. }
  1524. func (c *Module) DataPaths() []android.DataPath {
  1525. if p, ok := c.installer.(interface {
  1526. dataPaths() []android.DataPath
  1527. }); ok {
  1528. return p.dataPaths()
  1529. }
  1530. return nil
  1531. }
  1532. func getNameSuffixWithVndkVersion(ctx android.ModuleContext, c LinkableInterface) string {
  1533. // Returns the name suffix for product and vendor variants. If the VNDK version is not
  1534. // "current", it will append the VNDK version to the name suffix.
  1535. var vndkVersion string
  1536. var nameSuffix string
  1537. if c.InProduct() {
  1538. if c.ProductSpecific() {
  1539. // If the module is product specific with 'product_specific: true',
  1540. // do not add a name suffix because it is a base module.
  1541. return ""
  1542. }
  1543. vndkVersion = ctx.DeviceConfig().ProductVndkVersion()
  1544. nameSuffix = ProductSuffix
  1545. } else {
  1546. vndkVersion = ctx.DeviceConfig().VndkVersion()
  1547. nameSuffix = VendorSuffix
  1548. }
  1549. if vndkVersion == "current" {
  1550. vndkVersion = ctx.DeviceConfig().PlatformVndkVersion()
  1551. }
  1552. if c.VndkVersion() != vndkVersion && c.VndkVersion() != "" {
  1553. // add version suffix only if the module is using different vndk version than the
  1554. // version in product or vendor partition.
  1555. nameSuffix += "." + c.VndkVersion()
  1556. }
  1557. return nameSuffix
  1558. }
  1559. func GetSubnameProperty(actx android.ModuleContext, c LinkableInterface) string {
  1560. var subName = ""
  1561. if c.Target().NativeBridge == android.NativeBridgeEnabled {
  1562. subName += NativeBridgeSuffix
  1563. }
  1564. llndk := c.IsLlndk()
  1565. if llndk || (c.UseVndk() && c.HasNonSystemVariants()) {
  1566. // .vendor.{version} suffix is added for vendor variant or .product.{version} suffix is
  1567. // added for product variant only when we have vendor and product variants with core
  1568. // variant. The suffix is not added for vendor-only or product-only module.
  1569. subName += getNameSuffixWithVndkVersion(actx, c)
  1570. } else if c.IsVendorPublicLibrary() {
  1571. subName += vendorPublicLibrarySuffix
  1572. } else if c.IsVndkPrebuiltLibrary() {
  1573. // .vendor suffix is added for backward compatibility with VNDK snapshot whose names with
  1574. // such suffixes are already hard-coded in prebuilts/vndk/.../Android.bp.
  1575. subName += VendorSuffix
  1576. } else if c.InRamdisk() && !c.OnlyInRamdisk() {
  1577. subName += RamdiskSuffix
  1578. } else if c.InVendorRamdisk() && !c.OnlyInVendorRamdisk() {
  1579. subName += VendorRamdiskSuffix
  1580. } else if c.InRecovery() && !c.OnlyInRecovery() {
  1581. subName += RecoverySuffix
  1582. } else if c.IsSdkVariant() && (c.SdkAndPlatformVariantVisibleToMake() || c.SplitPerApiLevel()) {
  1583. subName += sdkSuffix
  1584. if c.SplitPerApiLevel() {
  1585. subName += "." + c.SdkVersion()
  1586. }
  1587. } else if c.IsStubs() && c.IsSdkVariant() {
  1588. // Public API surface (NDK)
  1589. // Add a suffix to this stub variant to distinguish it from the module-lib stub variant.
  1590. subName = sdkSuffix
  1591. }
  1592. return subName
  1593. }
  1594. var _ android.MixedBuildBuildable = (*Module)(nil)
  1595. func (c *Module) getBazelModuleLabel(ctx android.BaseModuleContext) string {
  1596. var bazelModuleLabel string
  1597. if c.typ() == fullLibrary && c.static() {
  1598. // cc_library is a special case in bp2build; two targets are generated -- one for each
  1599. // of the shared and static variants. The shared variant keeps the module name, but the
  1600. // static variant uses a different suffixed name.
  1601. bazelModuleLabel = bazelLabelForStaticModule(ctx, c)
  1602. } else {
  1603. bazelModuleLabel = c.GetBazelLabel(ctx, c)
  1604. }
  1605. labelNoPrebuilt := bazelModuleLabel
  1606. if c.IsPrebuilt() {
  1607. labelNoPrebuilt = android.RemoveOptionalPrebuiltPrefixFromBazelLabel(bazelModuleLabel)
  1608. }
  1609. return labelNoPrebuilt
  1610. }
  1611. func (c *Module) QueueBazelCall(ctx android.BaseModuleContext) {
  1612. c.bazelHandler.QueueBazelCall(ctx, c.getBazelModuleLabel(ctx))
  1613. }
  1614. // IsMixedBuildSupported returns true if the module should be analyzed by Bazel
  1615. // in any of the --bazel-mode(s).
  1616. func (c *Module) IsMixedBuildSupported(ctx android.BaseModuleContext) bool {
  1617. if !allEnabledSanitizersSupportedByBazel(ctx, c) {
  1618. //TODO(b/278772861) support sanitizers in Bazel rules
  1619. return false
  1620. }
  1621. if !imageVariantSupportedByBazel(c) {
  1622. return false
  1623. }
  1624. if c.IsSdkVariant() {
  1625. return false
  1626. }
  1627. return c.bazelHandler != nil
  1628. }
  1629. func imageVariantSupportedByBazel(c *Module) bool {
  1630. if c.IsLlndk() {
  1631. return false
  1632. }
  1633. if c.InVendor() {
  1634. return false
  1635. }
  1636. if c.InProduct() {
  1637. return false
  1638. }
  1639. if c.InRamdisk() {
  1640. return false
  1641. }
  1642. if c.InVendorRamdisk() {
  1643. return false
  1644. }
  1645. if c.InRecovery() {
  1646. return false
  1647. }
  1648. return true
  1649. }
  1650. func allEnabledSanitizersSupportedByBazel(ctx android.BaseModuleContext, c *Module) bool {
  1651. if c.sanitize == nil {
  1652. return true
  1653. }
  1654. sanitizeProps := &c.sanitize.Properties.SanitizeMutated
  1655. unsupportedSanitizers := []*bool{
  1656. sanitizeProps.Safestack,
  1657. sanitizeProps.Scudo,
  1658. BoolPtr(len(c.sanitize.Properties.Sanitize.Recover) > 0),
  1659. }
  1660. for _, san := range unsupportedSanitizers {
  1661. if Bool(san) {
  1662. return false
  1663. }
  1664. }
  1665. for _, san := range Sanitizers {
  1666. if san == intOverflow {
  1667. // TODO(b/261058727): enable mixed builds for all modules with UBSan
  1668. // Currently we can only support ubsan when minimum runtime is used.
  1669. ubsanEnabled := Bool(sanitizeProps.Integer_overflow) || len(sanitizeProps.Misc_undefined) > 0
  1670. if !ubsanEnabled || c.MinimalRuntimeNeeded() {
  1671. continue
  1672. }
  1673. } else if san == cfi {
  1674. apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
  1675. // Only allow cfi if this is an apex variant
  1676. if !apexInfo.IsForPlatform() {
  1677. continue
  1678. }
  1679. }
  1680. if c.sanitize.isSanitizerEnabled(san) {
  1681. return false
  1682. }
  1683. }
  1684. return true
  1685. }
  1686. func GetApexConfigKey(ctx android.BaseModuleContext) *android.ApexConfigKey {
  1687. apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
  1688. if !apexInfo.IsForPlatform() {
  1689. apexKey := android.ApexConfigKey{
  1690. WithinApex: true,
  1691. ApexSdkVersion: findApexSdkVersion(ctx, apexInfo).String(),
  1692. ApiDomain: findApiDomain(apexInfo),
  1693. }
  1694. return &apexKey
  1695. }
  1696. return nil
  1697. }
  1698. // Returns the api domain of a module for an apexInfo group
  1699. // Input:
  1700. // ai.InApexModules: [com.android.foo, test_com.android.foo, com.google.android.foo]
  1701. // Return:
  1702. // com.android.foo
  1703. // If a module is included in multiple api domains (collated by min_sdk_version), it will return
  1704. // the first match. The other matches have the same build actions since they share a min_sdk_version, so returning
  1705. // the first match is fine.
  1706. func findApiDomain(ai android.ApexInfo) string {
  1707. // Remove any test apexes
  1708. matches, _ := android.FilterList(ai.InApexModules, ai.TestApexes)
  1709. // Remove any google apexes. Rely on naming convention.
  1710. pred := func(s string) bool { return !strings.HasPrefix(s, "com.google") }
  1711. matches = android.FilterListPred(matches, pred)
  1712. if len(matches) > 0 {
  1713. // Return the first match
  1714. return android.SortedUniqueStrings(matches)[0]
  1715. } else {
  1716. // No apex in the tree has a dependency on this module
  1717. return ""
  1718. }
  1719. }
  1720. func (c *Module) ProcessBazelQueryResponse(ctx android.ModuleContext) {
  1721. bazelModuleLabel := c.getBazelModuleLabel(ctx)
  1722. c.bazelHandler.ProcessBazelQueryResponse(ctx, bazelModuleLabel)
  1723. c.Properties.SubName = GetSubnameProperty(ctx, c)
  1724. apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
  1725. if !apexInfo.IsForPlatform() {
  1726. c.hideApexVariantFromMake = true
  1727. }
  1728. c.makeLinkType = GetMakeLinkType(ctx, c)
  1729. mctx := &moduleContext{
  1730. ModuleContext: ctx,
  1731. moduleContextImpl: moduleContextImpl{
  1732. mod: c,
  1733. },
  1734. }
  1735. mctx.ctx = mctx
  1736. // TODO(b/244432500): Get the tradefed config from the bazel target instead
  1737. // of generating it with Soong.
  1738. c.maybeInstall(mctx, apexInfo)
  1739. }
  1740. func moduleContextFromAndroidModuleContext(actx android.ModuleContext, c *Module) ModuleContext {
  1741. ctx := &moduleContext{
  1742. ModuleContext: actx,
  1743. moduleContextImpl: moduleContextImpl{
  1744. mod: c,
  1745. },
  1746. }
  1747. ctx.ctx = ctx
  1748. return ctx
  1749. }
  1750. // TODO (b/277651159): Remove this allowlist
  1751. var (
  1752. skipStubLibraryMultipleApexViolation = map[string]bool{
  1753. "libclang_rt.asan": true,
  1754. "libclang_rt.hwasan": true,
  1755. // runtime apex
  1756. "libc": true,
  1757. "libc_hwasan": true,
  1758. "libdl_android": true,
  1759. "libm": true,
  1760. "libdl": true,
  1761. // art apex
  1762. "libandroidio": true,
  1763. "libdexfile": true,
  1764. "libnativebridge": true,
  1765. "libnativehelper": true,
  1766. "libnativeloader": true,
  1767. "libsigchain": true,
  1768. }
  1769. )
  1770. // Returns true if a stub library could be installed in multiple apexes
  1771. func (c *Module) stubLibraryMultipleApexViolation(ctx android.ModuleContext) bool {
  1772. // If this is not an apex variant, no check necessary
  1773. if !c.InAnyApex() {
  1774. return false
  1775. }
  1776. // If this is not a stub library, no check necessary
  1777. if !c.HasStubsVariants() {
  1778. return false
  1779. }
  1780. // Skip the allowlist
  1781. // Use BaseModuleName so that this matches prebuilts.
  1782. if _, exists := skipStubLibraryMultipleApexViolation[c.BaseModuleName()]; exists {
  1783. return false
  1784. }
  1785. _, aaWithoutTestApexes, _ := android.ListSetDifference(c.ApexAvailable(), c.TestApexes())
  1786. // Stub libraries should not have more than one apex_available
  1787. if len(aaWithoutTestApexes) > 1 {
  1788. return true
  1789. }
  1790. // Stub libraries should not use the wildcard
  1791. if aaWithoutTestApexes[0] == android.AvailableToAnyApex {
  1792. return true
  1793. }
  1794. // Default: no violation
  1795. return false
  1796. }
  1797. func (c *Module) GenerateAndroidBuildActions(actx android.ModuleContext) {
  1798. // Handle the case of a test module split by `test_per_src` mutator.
  1799. //
  1800. // The `test_per_src` mutator adds an extra variation named "", depending on all the other
  1801. // `test_per_src` variations of the test module. Set `outputFile` to an empty path for this
  1802. // module and return early, as this module does not produce an output file per se.
  1803. if c.IsTestPerSrcAllTestsVariation() {
  1804. c.outputFile = android.OptionalPath{}
  1805. return
  1806. }
  1807. c.Properties.SubName = GetSubnameProperty(actx, c)
  1808. apexInfo := actx.Provider(android.ApexInfoProvider).(android.ApexInfo)
  1809. if !apexInfo.IsForPlatform() {
  1810. c.hideApexVariantFromMake = true
  1811. }
  1812. c.makeLinkType = GetMakeLinkType(actx, c)
  1813. ctx := moduleContextFromAndroidModuleContext(actx, c)
  1814. deps := c.depsToPaths(ctx)
  1815. if ctx.Failed() {
  1816. return
  1817. }
  1818. if c.stubLibraryMultipleApexViolation(actx) {
  1819. actx.PropertyErrorf("apex_available",
  1820. "Stub libraries should have a single apex_available (test apexes excluded). Got %v", c.ApexAvailable())
  1821. }
  1822. if c.Properties.Clang != nil && *c.Properties.Clang == false {
  1823. ctx.PropertyErrorf("clang", "false (GCC) is no longer supported")
  1824. } else if c.Properties.Clang != nil && !ctx.DeviceConfig().BuildBrokenClangProperty() {
  1825. ctx.PropertyErrorf("clang", "property is deprecated, see Changes.md file")
  1826. }
  1827. flags := Flags{
  1828. Toolchain: c.toolchain(ctx),
  1829. EmitXrefs: ctx.Config().EmitXrefRules(),
  1830. }
  1831. if c.compiler != nil {
  1832. flags = c.compiler.compilerFlags(ctx, flags, deps)
  1833. }
  1834. if c.linker != nil {
  1835. flags = c.linker.linkerFlags(ctx, flags)
  1836. }
  1837. if c.stl != nil {
  1838. flags = c.stl.flags(ctx, flags)
  1839. }
  1840. if c.sanitize != nil {
  1841. flags = c.sanitize.flags(ctx, flags)
  1842. }
  1843. if c.coverage != nil {
  1844. flags, deps = c.coverage.flags(ctx, flags, deps)
  1845. }
  1846. if c.fuzzer != nil {
  1847. flags = c.fuzzer.flags(ctx, flags)
  1848. }
  1849. if c.lto != nil {
  1850. flags = c.lto.flags(ctx, flags)
  1851. }
  1852. if c.afdo != nil {
  1853. flags = c.afdo.flags(ctx, flags)
  1854. }
  1855. if c.pgo != nil {
  1856. flags = c.pgo.flags(ctx, flags)
  1857. }
  1858. for _, feature := range c.features {
  1859. flags = feature.flags(ctx, flags)
  1860. }
  1861. if ctx.Failed() {
  1862. return
  1863. }
  1864. flags.Local.CFlags, _ = filterList(flags.Local.CFlags, config.IllegalFlags)
  1865. flags.Local.CppFlags, _ = filterList(flags.Local.CppFlags, config.IllegalFlags)
  1866. flags.Local.ConlyFlags, _ = filterList(flags.Local.ConlyFlags, config.IllegalFlags)
  1867. flags.Local.CommonFlags = append(flags.Local.CommonFlags, deps.Flags...)
  1868. for _, dir := range deps.IncludeDirs {
  1869. flags.Local.CommonFlags = append(flags.Local.CommonFlags, "-I"+dir.String())
  1870. }
  1871. for _, dir := range deps.SystemIncludeDirs {
  1872. flags.Local.CommonFlags = append(flags.Local.CommonFlags, "-isystem "+dir.String())
  1873. }
  1874. flags.Local.LdFlags = append(flags.Local.LdFlags, deps.LdFlags...)
  1875. c.flags = flags
  1876. // We need access to all the flags seen by a source file.
  1877. if c.sabi != nil {
  1878. flags = c.sabi.flags(ctx, flags)
  1879. }
  1880. flags.AssemblerWithCpp = inList("-xassembler-with-cpp", flags.Local.AsFlags)
  1881. var objs Objects
  1882. if c.compiler != nil {
  1883. objs = c.compiler.compile(ctx, flags, deps)
  1884. if ctx.Failed() {
  1885. return
  1886. }
  1887. c.kytheFiles = objs.kytheFiles
  1888. c.objFiles = objs.objFiles
  1889. c.tidyFiles = objs.tidyFiles
  1890. }
  1891. if c.linker != nil {
  1892. outputFile := c.linker.link(ctx, flags, deps, objs)
  1893. if ctx.Failed() {
  1894. return
  1895. }
  1896. c.outputFile = android.OptionalPathForPath(outputFile)
  1897. c.maybeUnhideFromMake()
  1898. // glob exported headers for snapshot, if BOARD_VNDK_VERSION is current or
  1899. // RECOVERY_SNAPSHOT_VERSION is current.
  1900. if i, ok := c.linker.(snapshotLibraryInterface); ok {
  1901. if ShouldCollectHeadersForSnapshot(ctx, c, apexInfo) {
  1902. i.collectHeadersForSnapshot(ctx)
  1903. }
  1904. }
  1905. }
  1906. c.maybeInstall(ctx, apexInfo)
  1907. }
  1908. func (c *Module) maybeUnhideFromMake() {
  1909. // If a lib is directly included in any of the APEXes or is not available to the
  1910. // platform (which is often the case when the stub is provided as a prebuilt),
  1911. // unhide the stubs variant having the latest version gets visible to make. In
  1912. // addition, the non-stubs variant is renamed to <libname>.bootstrap. This is to
  1913. // force anything in the make world to link against the stubs library. (unless it
  1914. // is explicitly referenced via .bootstrap suffix or the module is marked with
  1915. // 'bootstrap: true').
  1916. if c.HasStubsVariants() && c.NotInPlatform() && !c.InRamdisk() &&
  1917. !c.InRecovery() && !c.UseVndk() && !c.static() && !c.isCoverageVariant() &&
  1918. c.IsStubs() && !c.InVendorRamdisk() {
  1919. c.Properties.HideFromMake = false // unhide
  1920. // Note: this is still non-installable
  1921. }
  1922. }
  1923. // maybeInstall is called at the end of both GenerateAndroidBuildActions and
  1924. // ProcessBazelQueryResponse to run the install hooks for installable modules,
  1925. // like binaries and tests.
  1926. func (c *Module) maybeInstall(ctx ModuleContext, apexInfo android.ApexInfo) {
  1927. if !proptools.BoolDefault(c.Installable(), true) {
  1928. // If the module has been specifically configure to not be installed then
  1929. // hide from make as otherwise it will break when running inside make
  1930. // as the output path to install will not be specified. Not all uninstallable
  1931. // modules can be hidden from make as some are needed for resolving make side
  1932. // dependencies.
  1933. c.HideFromMake()
  1934. } else if !installable(c, apexInfo) {
  1935. c.SkipInstall()
  1936. }
  1937. // Still call c.installer.install though, the installs will be stored as PackageSpecs
  1938. // to allow using the outputs in a genrule.
  1939. if c.installer != nil && c.outputFile.Valid() {
  1940. c.installer.install(ctx, c.outputFile.Path())
  1941. if ctx.Failed() {
  1942. return
  1943. }
  1944. }
  1945. }
  1946. func (c *Module) setAndroidMkVariablesFromCquery(info cquery.CcAndroidMkInfo) {
  1947. c.Properties.AndroidMkSharedLibs = info.LocalSharedLibs
  1948. c.Properties.AndroidMkStaticLibs = info.LocalStaticLibs
  1949. c.Properties.AndroidMkWholeStaticLibs = info.LocalWholeStaticLibs
  1950. }
  1951. func (c *Module) toolchain(ctx android.BaseModuleContext) config.Toolchain {
  1952. if c.cachedToolchain == nil {
  1953. c.cachedToolchain = config.FindToolchainWithContext(ctx)
  1954. }
  1955. return c.cachedToolchain
  1956. }
  1957. func (c *Module) begin(ctx BaseModuleContext) {
  1958. if c.compiler != nil {
  1959. c.compiler.compilerInit(ctx)
  1960. }
  1961. if c.linker != nil {
  1962. c.linker.linkerInit(ctx)
  1963. }
  1964. if c.stl != nil {
  1965. c.stl.begin(ctx)
  1966. }
  1967. if c.sanitize != nil {
  1968. c.sanitize.begin(ctx)
  1969. }
  1970. if c.coverage != nil {
  1971. c.coverage.begin(ctx)
  1972. }
  1973. if c.lto != nil {
  1974. c.lto.begin(ctx)
  1975. }
  1976. if c.pgo != nil {
  1977. c.pgo.begin(ctx)
  1978. }
  1979. if ctx.useSdk() && c.IsSdkVariant() {
  1980. version, err := nativeApiLevelFromUser(ctx, ctx.sdkVersion())
  1981. if err != nil {
  1982. ctx.PropertyErrorf("sdk_version", err.Error())
  1983. c.Properties.Sdk_version = nil
  1984. } else {
  1985. c.Properties.Sdk_version = StringPtr(version.String())
  1986. }
  1987. }
  1988. }
  1989. func (c *Module) deps(ctx DepsContext) Deps {
  1990. deps := Deps{}
  1991. if c.compiler != nil {
  1992. deps = c.compiler.compilerDeps(ctx, deps)
  1993. }
  1994. if c.linker != nil {
  1995. deps = c.linker.linkerDeps(ctx, deps)
  1996. }
  1997. if c.stl != nil {
  1998. deps = c.stl.deps(ctx, deps)
  1999. }
  2000. if c.coverage != nil {
  2001. deps = c.coverage.deps(ctx, deps)
  2002. }
  2003. deps.WholeStaticLibs = android.LastUniqueStrings(deps.WholeStaticLibs)
  2004. deps.StaticLibs = android.LastUniqueStrings(deps.StaticLibs)
  2005. deps.LateStaticLibs = android.LastUniqueStrings(deps.LateStaticLibs)
  2006. deps.SharedLibs = android.LastUniqueStrings(deps.SharedLibs)
  2007. deps.LateSharedLibs = android.LastUniqueStrings(deps.LateSharedLibs)
  2008. deps.HeaderLibs = android.LastUniqueStrings(deps.HeaderLibs)
  2009. deps.RuntimeLibs = android.LastUniqueStrings(deps.RuntimeLibs)
  2010. for _, lib := range deps.ReexportSharedLibHeaders {
  2011. if !inList(lib, deps.SharedLibs) {
  2012. ctx.PropertyErrorf("export_shared_lib_headers", "Shared library not in shared_libs: '%s'", lib)
  2013. }
  2014. }
  2015. for _, lib := range deps.ReexportStaticLibHeaders {
  2016. if !inList(lib, deps.StaticLibs) && !inList(lib, deps.WholeStaticLibs) {
  2017. ctx.PropertyErrorf("export_static_lib_headers", "Static library not in static_libs or whole_static_libs: '%s'", lib)
  2018. }
  2019. }
  2020. for _, lib := range deps.ReexportHeaderLibHeaders {
  2021. if !inList(lib, deps.HeaderLibs) {
  2022. ctx.PropertyErrorf("export_header_lib_headers", "Header library not in header_libs: '%s'", lib)
  2023. }
  2024. }
  2025. for _, gen := range deps.ReexportGeneratedHeaders {
  2026. if !inList(gen, deps.GeneratedHeaders) {
  2027. ctx.PropertyErrorf("export_generated_headers", "Generated header module not in generated_headers: '%s'", gen)
  2028. }
  2029. }
  2030. return deps
  2031. }
  2032. func (c *Module) beginMutator(actx android.BottomUpMutatorContext) {
  2033. ctx := &baseModuleContext{
  2034. BaseModuleContext: actx,
  2035. moduleContextImpl: moduleContextImpl{
  2036. mod: c,
  2037. },
  2038. }
  2039. ctx.ctx = ctx
  2040. if !actx.Host() || !ctx.static() || ctx.staticBinary() {
  2041. c.afdo.addDep(ctx, actx)
  2042. }
  2043. c.begin(ctx)
  2044. }
  2045. // Split name#version into name and version
  2046. func StubsLibNameAndVersion(name string) (string, string) {
  2047. if sharp := strings.LastIndex(name, "#"); sharp != -1 && sharp != len(name)-1 {
  2048. version := name[sharp+1:]
  2049. libname := name[:sharp]
  2050. return libname, version
  2051. }
  2052. return name, ""
  2053. }
  2054. func GetCrtVariations(ctx android.BottomUpMutatorContext,
  2055. m LinkableInterface) []blueprint.Variation {
  2056. if ctx.Os() != android.Android {
  2057. return nil
  2058. }
  2059. if m.UseSdk() {
  2060. // Choose the CRT that best satisfies the min_sdk_version requirement of this module
  2061. minSdkVersion := m.MinSdkVersion()
  2062. if minSdkVersion == "" || minSdkVersion == "apex_inherit" {
  2063. minSdkVersion = m.SdkVersion()
  2064. }
  2065. apiLevel, err := android.ApiLevelFromUser(ctx, minSdkVersion)
  2066. if err != nil {
  2067. ctx.PropertyErrorf("min_sdk_version", err.Error())
  2068. }
  2069. // Raise the minSdkVersion to the minimum supported for the architecture.
  2070. minApiForArch := MinApiForArch(ctx, m.Target().Arch.ArchType)
  2071. if apiLevel.LessThan(minApiForArch) {
  2072. apiLevel = minApiForArch
  2073. }
  2074. return []blueprint.Variation{
  2075. {Mutator: "sdk", Variation: "sdk"},
  2076. {Mutator: "version", Variation: apiLevel.String()},
  2077. }
  2078. }
  2079. return []blueprint.Variation{
  2080. {Mutator: "sdk", Variation: ""},
  2081. }
  2082. }
  2083. func AddSharedLibDependenciesWithVersions(ctx android.BottomUpMutatorContext, mod LinkableInterface,
  2084. variations []blueprint.Variation, depTag blueprint.DependencyTag, name, version string, far bool) {
  2085. variations = append([]blueprint.Variation(nil), variations...)
  2086. if version != "" && canBeOrLinkAgainstVersionVariants(mod) {
  2087. // Version is explicitly specified. i.e. libFoo#30
  2088. variations = append(variations, blueprint.Variation{Mutator: "version", Variation: version})
  2089. if tag, ok := depTag.(libraryDependencyTag); ok {
  2090. tag.explicitlyVersioned = true
  2091. } else {
  2092. panic(fmt.Errorf("Unexpected dependency tag: %T", depTag))
  2093. }
  2094. }
  2095. if far {
  2096. ctx.AddFarVariationDependencies(variations, depTag, name)
  2097. } else {
  2098. ctx.AddVariationDependencies(variations, depTag, name)
  2099. }
  2100. }
  2101. func GetApiImports(c LinkableInterface, actx android.BottomUpMutatorContext) multitree.ApiImportInfo {
  2102. apiImportInfo := multitree.ApiImportInfo{}
  2103. if c.Device() {
  2104. var apiImportModule []blueprint.Module
  2105. if actx.OtherModuleExists("api_imports") {
  2106. apiImportModule = actx.AddDependency(c, nil, "api_imports")
  2107. if len(apiImportModule) > 0 && apiImportModule[0] != nil {
  2108. apiInfo := actx.OtherModuleProvider(apiImportModule[0], multitree.ApiImportsProvider).(multitree.ApiImportInfo)
  2109. apiImportInfo = apiInfo
  2110. actx.SetProvider(multitree.ApiImportsProvider, apiInfo)
  2111. }
  2112. }
  2113. }
  2114. return apiImportInfo
  2115. }
  2116. func GetSnapshot(c LinkableInterface, snapshotInfo **SnapshotInfo, actx android.BottomUpMutatorContext) SnapshotInfo {
  2117. // Only device modules with BOARD_VNDK_VERSION uses snapshot. Others use the zero value of
  2118. // SnapshotInfo, which provides no mappings.
  2119. if *snapshotInfo == nil && c.Device() {
  2120. // Only retrieve the snapshot on demand in order to avoid circular dependencies
  2121. // between the modules in the snapshot and the snapshot itself.
  2122. var snapshotModule []blueprint.Module
  2123. if c.InVendor() && c.VndkVersion() == actx.DeviceConfig().VndkVersion() {
  2124. snapshotModule = actx.AddVariationDependencies(nil, nil, "vendor_snapshot")
  2125. } else if recoverySnapshotVersion := actx.DeviceConfig().RecoverySnapshotVersion(); recoverySnapshotVersion != "current" && recoverySnapshotVersion != "" && c.InRecovery() {
  2126. snapshotModule = actx.AddVariationDependencies(nil, nil, "recovery_snapshot")
  2127. }
  2128. if len(snapshotModule) > 0 && snapshotModule[0] != nil {
  2129. snapshot := actx.OtherModuleProvider(snapshotModule[0], SnapshotInfoProvider).(SnapshotInfo)
  2130. *snapshotInfo = &snapshot
  2131. // republish the snapshot for use in later mutators on this module
  2132. actx.SetProvider(SnapshotInfoProvider, snapshot)
  2133. }
  2134. }
  2135. if *snapshotInfo == nil {
  2136. *snapshotInfo = &SnapshotInfo{}
  2137. }
  2138. return **snapshotInfo
  2139. }
  2140. func GetReplaceModuleName(lib string, replaceMap map[string]string) string {
  2141. if snapshot, ok := replaceMap[lib]; ok {
  2142. return snapshot
  2143. }
  2144. return lib
  2145. }
  2146. // RewriteLibs takes a list of names of shared libraries and scans it for three types
  2147. // of names:
  2148. //
  2149. // 1. Name of an NDK library that refers to a prebuilt module.
  2150. //
  2151. // For each of these, it adds the name of the prebuilt module (which will be in
  2152. // prebuilts/ndk) to the list of nonvariant libs.
  2153. //
  2154. // 2. Name of an NDK library that refers to an ndk_library module.
  2155. //
  2156. // For each of these, it adds the name of the ndk_library module to the list of
  2157. // variant libs.
  2158. //
  2159. // 3. Anything else (so anything that isn't an NDK library).
  2160. //
  2161. // It adds these to the nonvariantLibs list.
  2162. //
  2163. // The caller can then know to add the variantLibs dependencies differently from the
  2164. // nonvariantLibs
  2165. func RewriteLibs(c LinkableInterface, snapshotInfo **SnapshotInfo, actx android.BottomUpMutatorContext, config android.Config, list []string) (nonvariantLibs []string, variantLibs []string) {
  2166. variantLibs = []string{}
  2167. nonvariantLibs = []string{}
  2168. for _, entry := range list {
  2169. // strip #version suffix out
  2170. name, _ := StubsLibNameAndVersion(entry)
  2171. if c.InRecovery() {
  2172. nonvariantLibs = append(nonvariantLibs, GetReplaceModuleName(entry, GetSnapshot(c, snapshotInfo, actx).SharedLibs))
  2173. } else if c.UseSdk() && inList(name, *getNDKKnownLibs(config)) {
  2174. variantLibs = append(variantLibs, name+ndkLibrarySuffix)
  2175. } else if c.UseVndk() {
  2176. nonvariantLibs = append(nonvariantLibs, GetReplaceModuleName(entry, GetSnapshot(c, snapshotInfo, actx).SharedLibs))
  2177. } else {
  2178. // put name#version back
  2179. nonvariantLibs = append(nonvariantLibs, entry)
  2180. }
  2181. }
  2182. return nonvariantLibs, variantLibs
  2183. }
  2184. func rewriteLibsForApiImports(c LinkableInterface, libs []string, replaceList map[string]string, config android.Config) ([]string, []string) {
  2185. nonVariantLibs := []string{}
  2186. variantLibs := []string{}
  2187. for _, lib := range libs {
  2188. replaceLibName := GetReplaceModuleName(lib, replaceList)
  2189. if replaceLibName == lib {
  2190. // Do not handle any libs which are not in API imports
  2191. nonVariantLibs = append(nonVariantLibs, replaceLibName)
  2192. } else if c.UseSdk() && inList(replaceLibName, *getNDKKnownLibs(config)) {
  2193. variantLibs = append(variantLibs, replaceLibName)
  2194. } else {
  2195. nonVariantLibs = append(nonVariantLibs, replaceLibName)
  2196. }
  2197. }
  2198. return nonVariantLibs, variantLibs
  2199. }
  2200. func (c *Module) shouldUseApiSurface() bool {
  2201. if c.Os() == android.Android && c.Target().NativeBridge != android.NativeBridgeEnabled {
  2202. if GetImageVariantType(c) == vendorImageVariant || GetImageVariantType(c) == productImageVariant {
  2203. // LLNDK Variant
  2204. return true
  2205. }
  2206. if c.Properties.IsSdkVariant {
  2207. // NDK Variant
  2208. return true
  2209. }
  2210. if c.isImportedApiLibrary() {
  2211. // API Library should depend on API headers
  2212. return true
  2213. }
  2214. }
  2215. return false
  2216. }
  2217. func (c *Module) DepsMutator(actx android.BottomUpMutatorContext) {
  2218. if !c.Enabled() {
  2219. return
  2220. }
  2221. ctx := &depsContext{
  2222. BottomUpMutatorContext: actx,
  2223. moduleContextImpl: moduleContextImpl{
  2224. mod: c,
  2225. },
  2226. }
  2227. ctx.ctx = ctx
  2228. deps := c.deps(ctx)
  2229. apiImportInfo := GetApiImports(c, actx)
  2230. apiNdkLibs := []string{}
  2231. apiLateNdkLibs := []string{}
  2232. if c.shouldUseApiSurface() {
  2233. deps.SharedLibs, apiNdkLibs = rewriteLibsForApiImports(c, deps.SharedLibs, apiImportInfo.SharedLibs, ctx.Config())
  2234. deps.LateSharedLibs, apiLateNdkLibs = rewriteLibsForApiImports(c, deps.LateSharedLibs, apiImportInfo.SharedLibs, ctx.Config())
  2235. deps.SystemSharedLibs, _ = rewriteLibsForApiImports(c, deps.SystemSharedLibs, apiImportInfo.SharedLibs, ctx.Config())
  2236. deps.ReexportHeaderLibHeaders, _ = rewriteLibsForApiImports(c, deps.ReexportHeaderLibHeaders, apiImportInfo.SharedLibs, ctx.Config())
  2237. deps.ReexportSharedLibHeaders, _ = rewriteLibsForApiImports(c, deps.ReexportSharedLibHeaders, apiImportInfo.SharedLibs, ctx.Config())
  2238. }
  2239. c.Properties.AndroidMkSystemSharedLibs = deps.SystemSharedLibs
  2240. var snapshotInfo *SnapshotInfo
  2241. variantNdkLibs := []string{}
  2242. variantLateNdkLibs := []string{}
  2243. if ctx.Os() == android.Android {
  2244. deps.SharedLibs, variantNdkLibs = RewriteLibs(c, &snapshotInfo, actx, ctx.Config(), deps.SharedLibs)
  2245. deps.LateSharedLibs, variantLateNdkLibs = RewriteLibs(c, &snapshotInfo, actx, ctx.Config(), deps.LateSharedLibs)
  2246. deps.ReexportSharedLibHeaders, _ = RewriteLibs(c, &snapshotInfo, actx, ctx.Config(), deps.ReexportSharedLibHeaders)
  2247. for idx, lib := range deps.RuntimeLibs {
  2248. deps.RuntimeLibs[idx] = GetReplaceModuleName(lib, GetSnapshot(c, &snapshotInfo, actx).SharedLibs)
  2249. }
  2250. }
  2251. for _, lib := range deps.HeaderLibs {
  2252. depTag := libraryDependencyTag{Kind: headerLibraryDependency}
  2253. if inList(lib, deps.ReexportHeaderLibHeaders) {
  2254. depTag.reexportFlags = true
  2255. }
  2256. // Check header lib replacement from API surface first, and then check again with VSDK
  2257. if c.shouldUseApiSurface() {
  2258. lib = GetReplaceModuleName(lib, apiImportInfo.HeaderLibs)
  2259. }
  2260. lib = GetReplaceModuleName(lib, GetSnapshot(c, &snapshotInfo, actx).HeaderLibs)
  2261. if c.isNDKStubLibrary() {
  2262. // ndk_headers do not have any variations
  2263. actx.AddFarVariationDependencies([]blueprint.Variation{}, depTag, lib)
  2264. } else if c.IsStubs() && !c.isImportedApiLibrary() {
  2265. actx.AddFarVariationDependencies(append(ctx.Target().Variations(), c.ImageVariation()),
  2266. depTag, lib)
  2267. } else {
  2268. actx.AddVariationDependencies(nil, depTag, lib)
  2269. }
  2270. }
  2271. if c.isNDKStubLibrary() {
  2272. // NDK stubs depend on their implementation because the ABI dumps are
  2273. // generated from the implementation library.
  2274. actx.AddFarVariationDependencies(append(ctx.Target().Variations(),
  2275. c.ImageVariation(),
  2276. blueprint.Variation{Mutator: "link", Variation: "shared"},
  2277. ), stubImplementation, c.BaseModuleName())
  2278. }
  2279. for _, lib := range deps.WholeStaticLibs {
  2280. depTag := libraryDependencyTag{Kind: staticLibraryDependency, wholeStatic: true, reexportFlags: true}
  2281. lib = GetReplaceModuleName(lib, GetSnapshot(c, &snapshotInfo, actx).StaticLibs)
  2282. actx.AddVariationDependencies([]blueprint.Variation{
  2283. {Mutator: "link", Variation: "static"},
  2284. }, depTag, lib)
  2285. }
  2286. for _, lib := range deps.StaticLibs {
  2287. depTag := libraryDependencyTag{Kind: staticLibraryDependency}
  2288. if inList(lib, deps.ReexportStaticLibHeaders) {
  2289. depTag.reexportFlags = true
  2290. }
  2291. if inList(lib, deps.ExcludeLibsForApex) {
  2292. depTag.excludeInApex = true
  2293. }
  2294. lib = GetReplaceModuleName(lib, GetSnapshot(c, &snapshotInfo, actx).StaticLibs)
  2295. actx.AddVariationDependencies([]blueprint.Variation{
  2296. {Mutator: "link", Variation: "static"},
  2297. }, depTag, lib)
  2298. }
  2299. // staticUnwinderDep is treated as staticDep for Q apexes
  2300. // so that native libraries/binaries are linked with static unwinder
  2301. // because Q libc doesn't have unwinder APIs
  2302. if deps.StaticUnwinderIfLegacy {
  2303. depTag := libraryDependencyTag{Kind: staticLibraryDependency, staticUnwinder: true}
  2304. actx.AddVariationDependencies([]blueprint.Variation{
  2305. {Mutator: "link", Variation: "static"},
  2306. }, depTag, GetReplaceModuleName(staticUnwinder(actx), GetSnapshot(c, &snapshotInfo, actx).StaticLibs))
  2307. }
  2308. // shared lib names without the #version suffix
  2309. var sharedLibNames []string
  2310. for _, lib := range deps.SharedLibs {
  2311. depTag := libraryDependencyTag{Kind: sharedLibraryDependency}
  2312. if inList(lib, deps.ReexportSharedLibHeaders) {
  2313. depTag.reexportFlags = true
  2314. }
  2315. if inList(lib, deps.ExcludeLibsForApex) {
  2316. depTag.excludeInApex = true
  2317. }
  2318. name, version := StubsLibNameAndVersion(lib)
  2319. if apiLibraryName, ok := apiImportInfo.SharedLibs[name]; ok && !ctx.OtherModuleExists(name) {
  2320. name = apiLibraryName
  2321. }
  2322. sharedLibNames = append(sharedLibNames, name)
  2323. variations := []blueprint.Variation{
  2324. {Mutator: "link", Variation: "shared"},
  2325. }
  2326. if _, ok := apiImportInfo.ApexSharedLibs[name]; !ok || ctx.OtherModuleExists(name) {
  2327. AddSharedLibDependenciesWithVersions(ctx, c, variations, depTag, name, version, false)
  2328. }
  2329. if apiLibraryName, ok := apiImportInfo.ApexSharedLibs[name]; ok {
  2330. AddSharedLibDependenciesWithVersions(ctx, c, variations, depTag, apiLibraryName, version, false)
  2331. }
  2332. }
  2333. for _, lib := range deps.LateStaticLibs {
  2334. depTag := libraryDependencyTag{Kind: staticLibraryDependency, Order: lateLibraryDependency}
  2335. actx.AddVariationDependencies([]blueprint.Variation{
  2336. {Mutator: "link", Variation: "static"},
  2337. }, depTag, GetReplaceModuleName(lib, GetSnapshot(c, &snapshotInfo, actx).StaticLibs))
  2338. }
  2339. for _, lib := range deps.UnexportedStaticLibs {
  2340. depTag := libraryDependencyTag{Kind: staticLibraryDependency, Order: lateLibraryDependency, unexportedSymbols: true}
  2341. actx.AddVariationDependencies([]blueprint.Variation{
  2342. {Mutator: "link", Variation: "static"},
  2343. }, depTag, GetReplaceModuleName(lib, GetSnapshot(c, &snapshotInfo, actx).StaticLibs))
  2344. }
  2345. for _, lib := range deps.LateSharedLibs {
  2346. if inList(lib, sharedLibNames) {
  2347. // This is to handle the case that some of the late shared libs (libc, libdl, libm, ...)
  2348. // are added also to SharedLibs with version (e.g., libc#10). If not skipped, we will be
  2349. // linking against both the stubs lib and the non-stubs lib at the same time.
  2350. continue
  2351. }
  2352. depTag := libraryDependencyTag{Kind: sharedLibraryDependency, Order: lateLibraryDependency}
  2353. variations := []blueprint.Variation{
  2354. {Mutator: "link", Variation: "shared"},
  2355. }
  2356. AddSharedLibDependenciesWithVersions(ctx, c, variations, depTag, lib, "", false)
  2357. }
  2358. actx.AddVariationDependencies([]blueprint.Variation{
  2359. {Mutator: "link", Variation: "shared"},
  2360. }, dataLibDepTag, deps.DataLibs...)
  2361. actx.AddVariationDependencies(nil, dataBinDepTag, deps.DataBins...)
  2362. actx.AddVariationDependencies([]blueprint.Variation{
  2363. {Mutator: "link", Variation: "shared"},
  2364. }, runtimeDepTag, deps.RuntimeLibs...)
  2365. actx.AddDependency(c, genSourceDepTag, deps.GeneratedSources...)
  2366. for _, gen := range deps.GeneratedHeaders {
  2367. depTag := genHeaderDepTag
  2368. if inList(gen, deps.ReexportGeneratedHeaders) {
  2369. depTag = genHeaderExportDepTag
  2370. }
  2371. actx.AddDependency(c, depTag, gen)
  2372. }
  2373. crtVariations := GetCrtVariations(ctx, c)
  2374. actx.AddVariationDependencies(crtVariations, objDepTag, deps.ObjFiles...)
  2375. for _, crt := range deps.CrtBegin {
  2376. actx.AddVariationDependencies(crtVariations, CrtBeginDepTag,
  2377. GetReplaceModuleName(crt, GetSnapshot(c, &snapshotInfo, actx).Objects))
  2378. }
  2379. for _, crt := range deps.CrtEnd {
  2380. actx.AddVariationDependencies(crtVariations, CrtEndDepTag,
  2381. GetReplaceModuleName(crt, GetSnapshot(c, &snapshotInfo, actx).Objects))
  2382. }
  2383. if deps.DynamicLinker != "" {
  2384. actx.AddDependency(c, dynamicLinkerDepTag, deps.DynamicLinker)
  2385. }
  2386. version := ctx.sdkVersion()
  2387. ndkStubDepTag := libraryDependencyTag{Kind: sharedLibraryDependency, ndk: true, makeSuffix: "." + version}
  2388. actx.AddVariationDependencies([]blueprint.Variation{
  2389. {Mutator: "version", Variation: version},
  2390. {Mutator: "link", Variation: "shared"},
  2391. }, ndkStubDepTag, variantNdkLibs...)
  2392. actx.AddVariationDependencies([]blueprint.Variation{
  2393. {Mutator: "version", Variation: version},
  2394. {Mutator: "link", Variation: "shared"},
  2395. }, ndkStubDepTag, apiNdkLibs...)
  2396. ndkLateStubDepTag := libraryDependencyTag{Kind: sharedLibraryDependency, Order: lateLibraryDependency, ndk: true, makeSuffix: "." + version}
  2397. actx.AddVariationDependencies([]blueprint.Variation{
  2398. {Mutator: "version", Variation: version},
  2399. {Mutator: "link", Variation: "shared"},
  2400. }, ndkLateStubDepTag, variantLateNdkLibs...)
  2401. actx.AddVariationDependencies([]blueprint.Variation{
  2402. {Mutator: "version", Variation: version},
  2403. {Mutator: "link", Variation: "shared"},
  2404. }, ndkLateStubDepTag, apiLateNdkLibs...)
  2405. if vndkdep := c.vndkdep; vndkdep != nil {
  2406. if vndkdep.isVndkExt() {
  2407. actx.AddVariationDependencies([]blueprint.Variation{
  2408. c.ImageVariation(),
  2409. {Mutator: "link", Variation: "shared"},
  2410. }, vndkExtDepTag, GetReplaceModuleName(vndkdep.getVndkExtendsModuleName(), GetSnapshot(c, &snapshotInfo, actx).SharedLibs))
  2411. }
  2412. }
  2413. if len(deps.AidlLibs) > 0 {
  2414. actx.AddDependency(
  2415. c,
  2416. aidlLibraryTag,
  2417. deps.AidlLibs...,
  2418. )
  2419. }
  2420. updateImportedLibraryDependency(ctx)
  2421. }
  2422. func BeginMutator(ctx android.BottomUpMutatorContext) {
  2423. if c, ok := ctx.Module().(*Module); ok && c.Enabled() {
  2424. c.beginMutator(ctx)
  2425. }
  2426. }
  2427. // Whether a module can link to another module, taking into
  2428. // account NDK linking.
  2429. func checkLinkType(ctx android.BaseModuleContext, from LinkableInterface, to LinkableInterface,
  2430. tag blueprint.DependencyTag) {
  2431. switch t := tag.(type) {
  2432. case dependencyTag:
  2433. if t != vndkExtDepTag {
  2434. return
  2435. }
  2436. case libraryDependencyTag:
  2437. default:
  2438. return
  2439. }
  2440. if from.Target().Os != android.Android {
  2441. // Host code is not restricted
  2442. return
  2443. }
  2444. // VNDK is cc.Module supported only for now.
  2445. if ccFrom, ok := from.(*Module); ok && from.UseVndk() {
  2446. // Though allowed dependency is limited by the image mutator,
  2447. // each vendor and product module needs to check link-type
  2448. // for VNDK.
  2449. if ccTo, ok := to.(*Module); ok {
  2450. if ccFrom.vndkdep != nil {
  2451. ccFrom.vndkdep.vndkCheckLinkType(ctx, ccTo, tag)
  2452. }
  2453. } else if _, ok := to.(LinkableInterface); !ok {
  2454. ctx.ModuleErrorf("Attempting to link VNDK cc.Module with unsupported module type")
  2455. }
  2456. return
  2457. }
  2458. // TODO(b/244244438) : Remove this once all variants are implemented
  2459. if ccFrom, ok := from.(*Module); ok && ccFrom.isImportedApiLibrary() {
  2460. return
  2461. }
  2462. if from.SdkVersion() == "" {
  2463. // Platform code can link to anything
  2464. return
  2465. }
  2466. if from.InRamdisk() {
  2467. // Ramdisk code is not NDK
  2468. return
  2469. }
  2470. if from.InVendorRamdisk() {
  2471. // Vendor ramdisk code is not NDK
  2472. return
  2473. }
  2474. if from.InRecovery() {
  2475. // Recovery code is not NDK
  2476. return
  2477. }
  2478. if c, ok := to.(*Module); ok {
  2479. if c.NdkPrebuiltStl() {
  2480. // These are allowed, but they don't set sdk_version
  2481. return
  2482. }
  2483. if c.StubDecorator() {
  2484. // These aren't real libraries, but are the stub shared libraries that are included in
  2485. // the NDK.
  2486. return
  2487. }
  2488. if c.isImportedApiLibrary() {
  2489. // Imported library from the API surface is a stub library built against interface definition.
  2490. return
  2491. }
  2492. }
  2493. if strings.HasPrefix(ctx.ModuleName(), "libclang_rt.") && to.Module().Name() == "libc++" {
  2494. // Bug: http://b/121358700 - Allow libclang_rt.* shared libraries (with sdk_version)
  2495. // to link to libc++ (non-NDK and without sdk_version).
  2496. return
  2497. }
  2498. if to.SdkVersion() == "" {
  2499. // NDK code linking to platform code is never okay.
  2500. ctx.ModuleErrorf("depends on non-NDK-built library %q",
  2501. ctx.OtherModuleName(to.Module()))
  2502. return
  2503. }
  2504. // At this point we know we have two NDK libraries, but we need to
  2505. // check that we're not linking against anything built against a higher
  2506. // API level, as it is only valid to link against older or equivalent
  2507. // APIs.
  2508. // Current can link against anything.
  2509. if from.SdkVersion() != "current" {
  2510. // Otherwise we need to check.
  2511. if to.SdkVersion() == "current" {
  2512. // Current can't be linked against by anything else.
  2513. ctx.ModuleErrorf("links %q built against newer API version %q",
  2514. ctx.OtherModuleName(to.Module()), "current")
  2515. } else {
  2516. fromApi, err := strconv.Atoi(from.SdkVersion())
  2517. if err != nil {
  2518. ctx.PropertyErrorf("sdk_version",
  2519. "Invalid sdk_version value (must be int or current): %q",
  2520. from.SdkVersion())
  2521. }
  2522. toApi, err := strconv.Atoi(to.SdkVersion())
  2523. if err != nil {
  2524. ctx.PropertyErrorf("sdk_version",
  2525. "Invalid sdk_version value (must be int or current): %q",
  2526. to.SdkVersion())
  2527. }
  2528. if toApi > fromApi {
  2529. ctx.ModuleErrorf("links %q built against newer API version %q",
  2530. ctx.OtherModuleName(to.Module()), to.SdkVersion())
  2531. }
  2532. }
  2533. }
  2534. // Also check that the two STL choices are compatible.
  2535. fromStl := from.SelectedStl()
  2536. toStl := to.SelectedStl()
  2537. if fromStl == "" || toStl == "" {
  2538. // Libraries that don't use the STL are unrestricted.
  2539. } else if fromStl == "ndk_system" || toStl == "ndk_system" {
  2540. // We can be permissive with the system "STL" since it is only the C++
  2541. // ABI layer, but in the future we should make sure that everyone is
  2542. // using either libc++ or nothing.
  2543. } else if getNdkStlFamily(from) != getNdkStlFamily(to) {
  2544. ctx.ModuleErrorf("uses %q and depends on %q which uses incompatible %q",
  2545. from.SelectedStl(), ctx.OtherModuleName(to.Module()),
  2546. to.SelectedStl())
  2547. }
  2548. }
  2549. func checkLinkTypeMutator(ctx android.BottomUpMutatorContext) {
  2550. if c, ok := ctx.Module().(*Module); ok {
  2551. ctx.VisitDirectDeps(func(dep android.Module) {
  2552. depTag := ctx.OtherModuleDependencyTag(dep)
  2553. ccDep, ok := dep.(LinkableInterface)
  2554. if ok {
  2555. checkLinkType(ctx, c, ccDep, depTag)
  2556. }
  2557. })
  2558. }
  2559. }
  2560. // Tests whether the dependent library is okay to be double loaded inside a single process.
  2561. // If a library has a vendor variant and is a (transitive) dependency of an LLNDK library,
  2562. // it is subject to be double loaded. Such lib should be explicitly marked as double_loadable: true
  2563. // or as vndk-sp (vndk: { enabled: true, support_system_process: true}).
  2564. func checkDoubleLoadableLibraries(ctx android.TopDownMutatorContext) {
  2565. check := func(child, parent android.Module) bool {
  2566. to, ok := child.(*Module)
  2567. if !ok {
  2568. return false
  2569. }
  2570. if lib, ok := to.linker.(*libraryDecorator); !ok || !lib.shared() {
  2571. return false
  2572. }
  2573. // These dependencies are not excercised at runtime. Tracking these will give us
  2574. // false negative, so skip.
  2575. depTag := ctx.OtherModuleDependencyTag(child)
  2576. if IsHeaderDepTag(depTag) {
  2577. return false
  2578. }
  2579. if depTag == staticVariantTag {
  2580. return false
  2581. }
  2582. if depTag == stubImplDepTag {
  2583. return false
  2584. }
  2585. // Even if target lib has no vendor variant, keep checking dependency
  2586. // graph in case it depends on vendor_available or product_available
  2587. // but not double_loadable transtively.
  2588. if !to.HasNonSystemVariants() {
  2589. return true
  2590. }
  2591. // The happy path. Keep tracking dependencies until we hit a non double-loadable
  2592. // one.
  2593. if Bool(to.VendorProperties.Double_loadable) {
  2594. return true
  2595. }
  2596. if to.IsVndkSp() || to.IsLlndk() {
  2597. return false
  2598. }
  2599. ctx.ModuleErrorf("links a library %q which is not LL-NDK, "+
  2600. "VNDK-SP, or explicitly marked as 'double_loadable:true'. "+
  2601. "Dependency list: %s", ctx.OtherModuleName(to), ctx.GetPathString(false))
  2602. return false
  2603. }
  2604. if module, ok := ctx.Module().(*Module); ok {
  2605. if lib, ok := module.linker.(*libraryDecorator); ok && lib.shared() {
  2606. if lib.hasLLNDKStubs() {
  2607. ctx.WalkDeps(check)
  2608. }
  2609. }
  2610. }
  2611. }
  2612. func findApexSdkVersion(ctx android.BaseModuleContext, apexInfo android.ApexInfo) android.ApiLevel {
  2613. // For the dependency from platform to apex, use the latest stubs
  2614. apexSdkVersion := android.FutureApiLevel
  2615. if !apexInfo.IsForPlatform() {
  2616. apexSdkVersion = apexInfo.MinSdkVersion
  2617. }
  2618. if android.InList("hwaddress", ctx.Config().SanitizeDevice()) {
  2619. // In hwasan build, we override apexSdkVersion to the FutureApiLevel(10000)
  2620. // so that even Q(29/Android10) apexes could use the dynamic unwinder by linking the newer stubs(e.g libc(R+)).
  2621. // (b/144430859)
  2622. apexSdkVersion = android.FutureApiLevel
  2623. }
  2624. return apexSdkVersion
  2625. }
  2626. // Convert dependencies to paths. Returns a PathDeps containing paths
  2627. func (c *Module) depsToPaths(ctx android.ModuleContext) PathDeps {
  2628. var depPaths PathDeps
  2629. var directStaticDeps []StaticLibraryInfo
  2630. var directSharedDeps []SharedLibraryInfo
  2631. reexportExporter := func(exporter FlagExporterInfo) {
  2632. depPaths.ReexportedDirs = append(depPaths.ReexportedDirs, exporter.IncludeDirs...)
  2633. depPaths.ReexportedSystemDirs = append(depPaths.ReexportedSystemDirs, exporter.SystemIncludeDirs...)
  2634. depPaths.ReexportedFlags = append(depPaths.ReexportedFlags, exporter.Flags...)
  2635. depPaths.ReexportedDeps = append(depPaths.ReexportedDeps, exporter.Deps...)
  2636. depPaths.ReexportedGeneratedHeaders = append(depPaths.ReexportedGeneratedHeaders, exporter.GeneratedHeaders...)
  2637. }
  2638. apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
  2639. c.apexSdkVersion = findApexSdkVersion(ctx, apexInfo)
  2640. skipModuleList := map[string]bool{}
  2641. var apiImportInfo multitree.ApiImportInfo
  2642. hasApiImportInfo := false
  2643. ctx.VisitDirectDeps(func(dep android.Module) {
  2644. if dep.Name() == "api_imports" {
  2645. apiImportInfo = ctx.OtherModuleProvider(dep, multitree.ApiImportsProvider).(multitree.ApiImportInfo)
  2646. hasApiImportInfo = true
  2647. }
  2648. })
  2649. if hasApiImportInfo {
  2650. targetStubModuleList := map[string]string{}
  2651. targetOrigModuleList := map[string]string{}
  2652. // Search for dependency which both original module and API imported library with APEX stub exists
  2653. ctx.VisitDirectDeps(func(dep android.Module) {
  2654. depName := ctx.OtherModuleName(dep)
  2655. if apiLibrary, ok := apiImportInfo.ApexSharedLibs[depName]; ok {
  2656. targetStubModuleList[apiLibrary] = depName
  2657. }
  2658. })
  2659. ctx.VisitDirectDeps(func(dep android.Module) {
  2660. depName := ctx.OtherModuleName(dep)
  2661. if origLibrary, ok := targetStubModuleList[depName]; ok {
  2662. targetOrigModuleList[origLibrary] = depName
  2663. }
  2664. })
  2665. // Decide which library should be used between original and API imported library
  2666. ctx.VisitDirectDeps(func(dep android.Module) {
  2667. depName := ctx.OtherModuleName(dep)
  2668. if apiLibrary, ok := targetOrigModuleList[depName]; ok {
  2669. if ShouldUseStubForApex(ctx, dep) {
  2670. skipModuleList[depName] = true
  2671. } else {
  2672. skipModuleList[apiLibrary] = true
  2673. }
  2674. }
  2675. })
  2676. }
  2677. ctx.VisitDirectDeps(func(dep android.Module) {
  2678. depName := ctx.OtherModuleName(dep)
  2679. depTag := ctx.OtherModuleDependencyTag(dep)
  2680. if _, ok := skipModuleList[depName]; ok {
  2681. // skip this module because original module or API imported module matching with this should be used instead.
  2682. return
  2683. }
  2684. if depTag == android.DarwinUniversalVariantTag {
  2685. depPaths.DarwinSecondArchOutput = dep.(*Module).OutputFile()
  2686. return
  2687. }
  2688. if depTag == aidlLibraryTag {
  2689. if ctx.OtherModuleHasProvider(dep, aidl_library.AidlLibraryProvider) {
  2690. depPaths.AidlLibraryInfos = append(
  2691. depPaths.AidlLibraryInfos,
  2692. ctx.OtherModuleProvider(
  2693. dep,
  2694. aidl_library.AidlLibraryProvider).(aidl_library.AidlLibraryInfo),
  2695. )
  2696. }
  2697. }
  2698. ccDep, ok := dep.(LinkableInterface)
  2699. if !ok {
  2700. // handling for a few module types that aren't cc Module but that are also supported
  2701. switch depTag {
  2702. case genSourceDepTag:
  2703. if genRule, ok := dep.(genrule.SourceFileGenerator); ok {
  2704. depPaths.GeneratedSources = append(depPaths.GeneratedSources,
  2705. genRule.GeneratedSourceFiles()...)
  2706. } else {
  2707. ctx.ModuleErrorf("module %q is not a gensrcs or genrule", depName)
  2708. }
  2709. // Support exported headers from a generated_sources dependency
  2710. fallthrough
  2711. case genHeaderDepTag, genHeaderExportDepTag:
  2712. if genRule, ok := dep.(genrule.SourceFileGenerator); ok {
  2713. depPaths.GeneratedDeps = append(depPaths.GeneratedDeps,
  2714. genRule.GeneratedDeps()...)
  2715. dirs := genRule.GeneratedHeaderDirs()
  2716. depPaths.IncludeDirs = append(depPaths.IncludeDirs, dirs...)
  2717. if depTag == genHeaderExportDepTag {
  2718. depPaths.ReexportedDirs = append(depPaths.ReexportedDirs, dirs...)
  2719. depPaths.ReexportedGeneratedHeaders = append(depPaths.ReexportedGeneratedHeaders,
  2720. genRule.GeneratedSourceFiles()...)
  2721. depPaths.ReexportedDeps = append(depPaths.ReexportedDeps, genRule.GeneratedDeps()...)
  2722. // Add these re-exported flags to help header-abi-dumper to infer the abi exported by a library.
  2723. c.sabi.Properties.ReexportedIncludes = append(c.sabi.Properties.ReexportedIncludes, dirs.Strings()...)
  2724. }
  2725. } else {
  2726. ctx.ModuleErrorf("module %q is not a genrule", depName)
  2727. }
  2728. case CrtBeginDepTag:
  2729. depPaths.CrtBegin = append(depPaths.CrtBegin, android.OutputFileForModule(ctx, dep, ""))
  2730. case CrtEndDepTag:
  2731. depPaths.CrtEnd = append(depPaths.CrtEnd, android.OutputFileForModule(ctx, dep, ""))
  2732. }
  2733. return
  2734. }
  2735. if depTag == android.ProtoPluginDepTag {
  2736. return
  2737. }
  2738. if dep.Target().Os != ctx.Os() {
  2739. ctx.ModuleErrorf("OS mismatch between %q and %q", ctx.ModuleName(), depName)
  2740. return
  2741. }
  2742. if dep.Target().Arch.ArchType != ctx.Arch().ArchType {
  2743. ctx.ModuleErrorf("Arch mismatch between %q(%v) and %q(%v)",
  2744. ctx.ModuleName(), ctx.Arch().ArchType, depName, dep.Target().Arch.ArchType)
  2745. return
  2746. }
  2747. if depTag == reuseObjTag {
  2748. // Skip reused objects for stub libraries, they use their own stub object file instead.
  2749. // The reuseObjTag dependency still exists because the LinkageMutator runs before the
  2750. // version mutator, so the stubs variant is created from the shared variant that
  2751. // already has the reuseObjTag dependency on the static variant.
  2752. if !c.library.buildStubs() {
  2753. staticAnalogue := ctx.OtherModuleProvider(dep, StaticLibraryInfoProvider).(StaticLibraryInfo)
  2754. objs := staticAnalogue.ReuseObjects
  2755. depPaths.Objs = depPaths.Objs.Append(objs)
  2756. depExporterInfo := ctx.OtherModuleProvider(dep, FlagExporterInfoProvider).(FlagExporterInfo)
  2757. reexportExporter(depExporterInfo)
  2758. }
  2759. return
  2760. }
  2761. linkFile := ccDep.OutputFile()
  2762. if libDepTag, ok := depTag.(libraryDependencyTag); ok {
  2763. // Only use static unwinder for legacy (min_sdk_version = 29) apexes (b/144430859)
  2764. if libDepTag.staticUnwinder && c.apexSdkVersion.GreaterThan(android.SdkVersion_Android10) {
  2765. return
  2766. }
  2767. if !apexInfo.IsForPlatform() && libDepTag.excludeInApex {
  2768. return
  2769. }
  2770. depExporterInfo := ctx.OtherModuleProvider(dep, FlagExporterInfoProvider).(FlagExporterInfo)
  2771. var ptr *android.Paths
  2772. var depPtr *android.Paths
  2773. depFile := android.OptionalPath{}
  2774. switch {
  2775. case libDepTag.header():
  2776. if !ctx.OtherModuleHasProvider(dep, HeaderLibraryInfoProvider) {
  2777. if !ctx.Config().AllowMissingDependencies() {
  2778. ctx.ModuleErrorf("module %q is not a header library", depName)
  2779. } else {
  2780. ctx.AddMissingDependencies([]string{depName})
  2781. }
  2782. return
  2783. }
  2784. case libDepTag.shared():
  2785. if !ctx.OtherModuleHasProvider(dep, SharedLibraryInfoProvider) {
  2786. if !ctx.Config().AllowMissingDependencies() {
  2787. ctx.ModuleErrorf("module %q is not a shared library", depName)
  2788. } else {
  2789. ctx.AddMissingDependencies([]string{depName})
  2790. }
  2791. return
  2792. }
  2793. sharedLibraryInfo, returnedDepExporterInfo := ChooseStubOrImpl(ctx, dep)
  2794. depExporterInfo = returnedDepExporterInfo
  2795. // Stubs lib doesn't link to the shared lib dependencies. Don't set
  2796. // linkFile, depFile, and ptr.
  2797. if c.IsStubs() {
  2798. break
  2799. }
  2800. linkFile = android.OptionalPathForPath(sharedLibraryInfo.SharedLibrary)
  2801. depFile = sharedLibraryInfo.TableOfContents
  2802. ptr = &depPaths.SharedLibs
  2803. switch libDepTag.Order {
  2804. case earlyLibraryDependency:
  2805. ptr = &depPaths.EarlySharedLibs
  2806. depPtr = &depPaths.EarlySharedLibsDeps
  2807. case normalLibraryDependency:
  2808. ptr = &depPaths.SharedLibs
  2809. depPtr = &depPaths.SharedLibsDeps
  2810. directSharedDeps = append(directSharedDeps, sharedLibraryInfo)
  2811. case lateLibraryDependency:
  2812. ptr = &depPaths.LateSharedLibs
  2813. depPtr = &depPaths.LateSharedLibsDeps
  2814. default:
  2815. panic(fmt.Errorf("unexpected library dependency order %d", libDepTag.Order))
  2816. }
  2817. case libDepTag.static():
  2818. if !ctx.OtherModuleHasProvider(dep, StaticLibraryInfoProvider) {
  2819. if !ctx.Config().AllowMissingDependencies() {
  2820. ctx.ModuleErrorf("module %q is not a static library", depName)
  2821. } else {
  2822. ctx.AddMissingDependencies([]string{depName})
  2823. }
  2824. return
  2825. }
  2826. // Stubs lib doesn't link to the static lib dependencies. Don't set
  2827. // linkFile, depFile, and ptr.
  2828. if c.IsStubs() {
  2829. break
  2830. }
  2831. staticLibraryInfo := ctx.OtherModuleProvider(dep, StaticLibraryInfoProvider).(StaticLibraryInfo)
  2832. linkFile = android.OptionalPathForPath(staticLibraryInfo.StaticLibrary)
  2833. if libDepTag.wholeStatic {
  2834. ptr = &depPaths.WholeStaticLibs
  2835. if len(staticLibraryInfo.Objects.objFiles) > 0 {
  2836. depPaths.WholeStaticLibObjs = depPaths.WholeStaticLibObjs.Append(staticLibraryInfo.Objects)
  2837. } else {
  2838. // This case normally catches prebuilt static
  2839. // libraries, but it can also occur when
  2840. // AllowMissingDependencies is on and the
  2841. // dependencies has no sources of its own
  2842. // but has a whole_static_libs dependency
  2843. // on a missing library. We want to depend
  2844. // on the .a file so that there is something
  2845. // in the dependency tree that contains the
  2846. // error rule for the missing transitive
  2847. // dependency.
  2848. depPaths.WholeStaticLibsFromPrebuilts = append(depPaths.WholeStaticLibsFromPrebuilts, linkFile.Path())
  2849. }
  2850. depPaths.WholeStaticLibsFromPrebuilts = append(depPaths.WholeStaticLibsFromPrebuilts,
  2851. staticLibraryInfo.WholeStaticLibsFromPrebuilts...)
  2852. } else {
  2853. switch libDepTag.Order {
  2854. case earlyLibraryDependency:
  2855. panic(fmt.Errorf("early static libs not suppported"))
  2856. case normalLibraryDependency:
  2857. // static dependencies will be handled separately so they can be ordered
  2858. // using transitive dependencies.
  2859. ptr = nil
  2860. directStaticDeps = append(directStaticDeps, staticLibraryInfo)
  2861. case lateLibraryDependency:
  2862. ptr = &depPaths.LateStaticLibs
  2863. default:
  2864. panic(fmt.Errorf("unexpected library dependency order %d", libDepTag.Order))
  2865. }
  2866. }
  2867. if libDepTag.unexportedSymbols {
  2868. depPaths.LdFlags = append(depPaths.LdFlags,
  2869. "-Wl,--exclude-libs="+staticLibraryInfo.StaticLibrary.Base())
  2870. }
  2871. }
  2872. if libDepTag.static() && !libDepTag.wholeStatic {
  2873. if !ccDep.CcLibraryInterface() || !ccDep.Static() {
  2874. ctx.ModuleErrorf("module %q not a static library", depName)
  2875. return
  2876. }
  2877. // When combining coverage files for shared libraries and executables, coverage files
  2878. // in static libraries act as if they were whole static libraries. The same goes for
  2879. // source based Abi dump files.
  2880. if c, ok := ccDep.(*Module); ok {
  2881. staticLib := c.linker.(libraryInterface)
  2882. depPaths.StaticLibObjs.coverageFiles = append(depPaths.StaticLibObjs.coverageFiles,
  2883. staticLib.objs().coverageFiles...)
  2884. depPaths.StaticLibObjs.sAbiDumpFiles = append(depPaths.StaticLibObjs.sAbiDumpFiles,
  2885. staticLib.objs().sAbiDumpFiles...)
  2886. } else {
  2887. // Handle non-CC modules here
  2888. depPaths.StaticLibObjs.coverageFiles = append(depPaths.StaticLibObjs.coverageFiles,
  2889. ccDep.CoverageFiles()...)
  2890. }
  2891. }
  2892. if ptr != nil {
  2893. if !linkFile.Valid() {
  2894. if !ctx.Config().AllowMissingDependencies() {
  2895. ctx.ModuleErrorf("module %q missing output file", depName)
  2896. } else {
  2897. ctx.AddMissingDependencies([]string{depName})
  2898. }
  2899. return
  2900. }
  2901. *ptr = append(*ptr, linkFile.Path())
  2902. }
  2903. if depPtr != nil {
  2904. dep := depFile
  2905. if !dep.Valid() {
  2906. dep = linkFile
  2907. }
  2908. *depPtr = append(*depPtr, dep.Path())
  2909. }
  2910. depPaths.IncludeDirs = append(depPaths.IncludeDirs, depExporterInfo.IncludeDirs...)
  2911. depPaths.SystemIncludeDirs = append(depPaths.SystemIncludeDirs, depExporterInfo.SystemIncludeDirs...)
  2912. depPaths.GeneratedDeps = append(depPaths.GeneratedDeps, depExporterInfo.Deps...)
  2913. depPaths.Flags = append(depPaths.Flags, depExporterInfo.Flags...)
  2914. if libDepTag.reexportFlags {
  2915. reexportExporter(depExporterInfo)
  2916. // Add these re-exported flags to help header-abi-dumper to infer the abi exported by a library.
  2917. // Re-exported shared library headers must be included as well since they can help us with type information
  2918. // about template instantiations (instantiated from their headers).
  2919. // -isystem headers are not included since for bionic libraries, abi-filtering is taken care of by version
  2920. // scripts.
  2921. c.sabi.Properties.ReexportedIncludes = append(
  2922. c.sabi.Properties.ReexportedIncludes, depExporterInfo.IncludeDirs.Strings()...)
  2923. }
  2924. makeLibName := MakeLibName(ctx, c, ccDep, depName) + libDepTag.makeSuffix
  2925. switch {
  2926. case libDepTag.header():
  2927. c.Properties.AndroidMkHeaderLibs = append(
  2928. c.Properties.AndroidMkHeaderLibs, makeLibName)
  2929. case libDepTag.shared():
  2930. if lib := moduleLibraryInterface(dep); lib != nil {
  2931. if lib.buildStubs() && dep.(android.ApexModule).InAnyApex() {
  2932. // Add the dependency to the APEX(es) providing the library so that
  2933. // m <module> can trigger building the APEXes as well.
  2934. depApexInfo := ctx.OtherModuleProvider(dep, android.ApexInfoProvider).(android.ApexInfo)
  2935. for _, an := range depApexInfo.InApexVariants {
  2936. c.Properties.ApexesProvidingSharedLibs = append(
  2937. c.Properties.ApexesProvidingSharedLibs, an)
  2938. }
  2939. }
  2940. }
  2941. // Note: the order of libs in this list is not important because
  2942. // they merely serve as Make dependencies and do not affect this lib itself.
  2943. c.Properties.AndroidMkSharedLibs = append(
  2944. c.Properties.AndroidMkSharedLibs, makeLibName)
  2945. // Record BaseLibName for snapshots.
  2946. c.Properties.SnapshotSharedLibs = append(c.Properties.SnapshotSharedLibs, BaseLibName(depName))
  2947. case libDepTag.static():
  2948. if libDepTag.wholeStatic {
  2949. c.Properties.AndroidMkWholeStaticLibs = append(
  2950. c.Properties.AndroidMkWholeStaticLibs, makeLibName)
  2951. } else {
  2952. c.Properties.AndroidMkStaticLibs = append(
  2953. c.Properties.AndroidMkStaticLibs, makeLibName)
  2954. }
  2955. // Record BaseLibName for snapshots.
  2956. c.Properties.SnapshotStaticLibs = append(c.Properties.SnapshotStaticLibs, BaseLibName(depName))
  2957. }
  2958. } else if !c.IsStubs() {
  2959. // Stubs lib doesn't link to the runtime lib, object, crt, etc. dependencies.
  2960. switch depTag {
  2961. case runtimeDepTag:
  2962. c.Properties.AndroidMkRuntimeLibs = append(
  2963. c.Properties.AndroidMkRuntimeLibs, MakeLibName(ctx, c, ccDep, depName)+libDepTag.makeSuffix)
  2964. // Record BaseLibName for snapshots.
  2965. c.Properties.SnapshotRuntimeLibs = append(c.Properties.SnapshotRuntimeLibs, BaseLibName(depName))
  2966. case objDepTag:
  2967. depPaths.Objs.objFiles = append(depPaths.Objs.objFiles, linkFile.Path())
  2968. case CrtBeginDepTag:
  2969. depPaths.CrtBegin = append(depPaths.CrtBegin, linkFile.Path())
  2970. case CrtEndDepTag:
  2971. depPaths.CrtEnd = append(depPaths.CrtEnd, linkFile.Path())
  2972. case dynamicLinkerDepTag:
  2973. depPaths.DynamicLinker = linkFile
  2974. }
  2975. }
  2976. })
  2977. // use the ordered dependencies as this module's dependencies
  2978. orderedStaticPaths, transitiveStaticLibs := orderStaticModuleDeps(directStaticDeps, directSharedDeps)
  2979. depPaths.TranstiveStaticLibrariesForOrdering = transitiveStaticLibs
  2980. depPaths.StaticLibs = append(depPaths.StaticLibs, orderedStaticPaths...)
  2981. // Dedup exported flags from dependencies
  2982. depPaths.Flags = android.FirstUniqueStrings(depPaths.Flags)
  2983. depPaths.IncludeDirs = android.FirstUniquePaths(depPaths.IncludeDirs)
  2984. depPaths.SystemIncludeDirs = android.FirstUniquePaths(depPaths.SystemIncludeDirs)
  2985. depPaths.GeneratedDeps = android.FirstUniquePaths(depPaths.GeneratedDeps)
  2986. depPaths.ReexportedDirs = android.FirstUniquePaths(depPaths.ReexportedDirs)
  2987. depPaths.ReexportedSystemDirs = android.FirstUniquePaths(depPaths.ReexportedSystemDirs)
  2988. depPaths.ReexportedFlags = android.FirstUniqueStrings(depPaths.ReexportedFlags)
  2989. depPaths.ReexportedDeps = android.FirstUniquePaths(depPaths.ReexportedDeps)
  2990. depPaths.ReexportedGeneratedHeaders = android.FirstUniquePaths(depPaths.ReexportedGeneratedHeaders)
  2991. if c.sabi != nil {
  2992. c.sabi.Properties.ReexportedIncludes = android.FirstUniqueStrings(c.sabi.Properties.ReexportedIncludes)
  2993. }
  2994. return depPaths
  2995. }
  2996. func ShouldUseStubForApex(ctx android.ModuleContext, dep android.Module) bool {
  2997. depName := ctx.OtherModuleName(dep)
  2998. thisModule, ok := ctx.Module().(android.ApexModule)
  2999. if !ok {
  3000. panic(fmt.Errorf("Not an APEX module: %q", ctx.ModuleName()))
  3001. }
  3002. useVndk := false
  3003. bootstrap := false
  3004. if linkable, ok := ctx.Module().(LinkableInterface); !ok {
  3005. panic(fmt.Errorf("Not a Linkable module: %q", ctx.ModuleName()))
  3006. } else {
  3007. useVndk = linkable.UseVndk()
  3008. bootstrap = linkable.Bootstrap()
  3009. }
  3010. apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
  3011. useStubs := false
  3012. if lib := moduleLibraryInterface(dep); lib.buildStubs() && useVndk { // LLNDK
  3013. if !apexInfo.IsForPlatform() {
  3014. // For platform libraries, use current version of LLNDK
  3015. // If this is for use_vendor apex we will apply the same rules
  3016. // of apex sdk enforcement below to choose right version.
  3017. useStubs = true
  3018. }
  3019. } else if apexInfo.IsForPlatform() || apexInfo.UsePlatformApis {
  3020. // If not building for APEX or the containing APEX allows the use of
  3021. // platform APIs, use stubs only when it is from an APEX (and not from
  3022. // platform) However, for host, ramdisk, vendor_ramdisk, recovery or
  3023. // bootstrap modules, always link to non-stub variant
  3024. isNotInPlatform := dep.(android.ApexModule).NotInPlatform()
  3025. isApexImportedApiLibrary := false
  3026. if cc, ok := dep.(*Module); ok {
  3027. if apiLibrary, ok := cc.linker.(*apiLibraryDecorator); ok {
  3028. if apiLibrary.hasApexStubs() {
  3029. isApexImportedApiLibrary = true
  3030. }
  3031. }
  3032. }
  3033. useStubs = (isNotInPlatform || isApexImportedApiLibrary) && !bootstrap
  3034. if useStubs {
  3035. // Another exception: if this module is a test for an APEX, then
  3036. // it is linked with the non-stub variant of a module in the APEX
  3037. // as if this is part of the APEX.
  3038. testFor := ctx.Provider(android.ApexTestForInfoProvider).(android.ApexTestForInfo)
  3039. for _, apexContents := range testFor.ApexContents {
  3040. if apexContents.DirectlyInApex(depName) {
  3041. useStubs = false
  3042. break
  3043. }
  3044. }
  3045. }
  3046. if useStubs {
  3047. // Yet another exception: If this module and the dependency are
  3048. // available to the same APEXes then skip stubs between their
  3049. // platform variants. This complements the test_for case above,
  3050. // which avoids the stubs on a direct APEX library dependency, by
  3051. // avoiding stubs for indirect test dependencies as well.
  3052. //
  3053. // TODO(b/183882457): This doesn't work if the two libraries have
  3054. // only partially overlapping apex_available. For that test_for
  3055. // modules would need to be split into APEX variants and resolved
  3056. // separately for each APEX they have access to.
  3057. if !isApexImportedApiLibrary && android.AvailableToSameApexes(thisModule, dep.(android.ApexModule)) {
  3058. useStubs = false
  3059. }
  3060. }
  3061. } else {
  3062. // If building for APEX, use stubs when the parent is in any APEX that
  3063. // the child is not in.
  3064. useStubs = !android.DirectlyInAllApexes(apexInfo, depName)
  3065. }
  3066. return useStubs
  3067. }
  3068. // ChooseStubOrImpl determines whether a given dependency should be redirected to the stub variant
  3069. // of the dependency or not, and returns the SharedLibraryInfo and FlagExporterInfo for the right
  3070. // dependency. The stub variant is selected when the dependency crosses a boundary where each side
  3071. // has different level of updatability. For example, if a library foo in an APEX depends on a
  3072. // library bar which provides stable interface and exists in the platform, foo uses the stub variant
  3073. // of bar. If bar doesn't provide a stable interface (i.e. buildStubs() == false) or is in the
  3074. // same APEX as foo, the non-stub variant of bar is used.
  3075. func ChooseStubOrImpl(ctx android.ModuleContext, dep android.Module) (SharedLibraryInfo, FlagExporterInfo) {
  3076. depTag := ctx.OtherModuleDependencyTag(dep)
  3077. libDepTag, ok := depTag.(libraryDependencyTag)
  3078. if !ok || !libDepTag.shared() {
  3079. panic(fmt.Errorf("Unexpected dependency tag: %T", depTag))
  3080. }
  3081. sharedLibraryInfo := ctx.OtherModuleProvider(dep, SharedLibraryInfoProvider).(SharedLibraryInfo)
  3082. depExporterInfo := ctx.OtherModuleProvider(dep, FlagExporterInfoProvider).(FlagExporterInfo)
  3083. sharedLibraryStubsInfo := ctx.OtherModuleProvider(dep, SharedLibraryStubsProvider).(SharedLibraryStubsInfo)
  3084. if !libDepTag.explicitlyVersioned && len(sharedLibraryStubsInfo.SharedStubLibraries) > 0 {
  3085. // when to use (unspecified) stubs, use the latest one.
  3086. if ShouldUseStubForApex(ctx, dep) {
  3087. stubs := sharedLibraryStubsInfo.SharedStubLibraries
  3088. toUse := stubs[len(stubs)-1]
  3089. sharedLibraryInfo = toUse.SharedLibraryInfo
  3090. depExporterInfo = toUse.FlagExporterInfo
  3091. }
  3092. }
  3093. return sharedLibraryInfo, depExporterInfo
  3094. }
  3095. // orderStaticModuleDeps rearranges the order of the static library dependencies of the module
  3096. // to match the topological order of the dependency tree, including any static analogues of
  3097. // direct shared libraries. It returns the ordered static dependencies, and an android.DepSet
  3098. // of the transitive dependencies.
  3099. func orderStaticModuleDeps(staticDeps []StaticLibraryInfo, sharedDeps []SharedLibraryInfo) (ordered android.Paths, transitive *android.DepSet[android.Path]) {
  3100. transitiveStaticLibsBuilder := android.NewDepSetBuilder[android.Path](android.TOPOLOGICAL)
  3101. var staticPaths android.Paths
  3102. for _, staticDep := range staticDeps {
  3103. staticPaths = append(staticPaths, staticDep.StaticLibrary)
  3104. transitiveStaticLibsBuilder.Transitive(staticDep.TransitiveStaticLibrariesForOrdering)
  3105. }
  3106. for _, sharedDep := range sharedDeps {
  3107. if sharedDep.TransitiveStaticLibrariesForOrdering != nil {
  3108. transitiveStaticLibsBuilder.Transitive(sharedDep.TransitiveStaticLibrariesForOrdering)
  3109. }
  3110. }
  3111. transitiveStaticLibs := transitiveStaticLibsBuilder.Build()
  3112. orderedTransitiveStaticLibs := transitiveStaticLibs.ToList()
  3113. // reorder the dependencies based on transitive dependencies
  3114. staticPaths = android.FirstUniquePaths(staticPaths)
  3115. _, orderedStaticPaths := android.FilterPathList(orderedTransitiveStaticLibs, staticPaths)
  3116. if len(orderedStaticPaths) != len(staticPaths) {
  3117. missing, _ := android.FilterPathList(staticPaths, orderedStaticPaths)
  3118. panic(fmt.Errorf("expected %d ordered static paths , got %d, missing %q %q %q", len(staticPaths), len(orderedStaticPaths), missing, orderedStaticPaths, staticPaths))
  3119. }
  3120. return orderedStaticPaths, transitiveStaticLibs
  3121. }
  3122. // BaseLibName trims known prefixes and suffixes
  3123. func BaseLibName(depName string) string {
  3124. libName := strings.TrimSuffix(depName, llndkLibrarySuffix)
  3125. libName = strings.TrimSuffix(libName, vendorPublicLibrarySuffix)
  3126. libName = android.RemoveOptionalPrebuiltPrefix(libName)
  3127. return libName
  3128. }
  3129. func MakeLibName(ctx android.ModuleContext, c LinkableInterface, ccDep LinkableInterface, depName string) string {
  3130. libName := BaseLibName(depName)
  3131. ccDepModule, _ := ccDep.(*Module)
  3132. isLLndk := ccDepModule != nil && ccDepModule.IsLlndk()
  3133. nonSystemVariantsExist := ccDep.HasNonSystemVariants() || isLLndk
  3134. if ccDepModule != nil {
  3135. // Use base module name for snapshots when exporting to Makefile.
  3136. if snapshotPrebuilt, ok := ccDepModule.linker.(SnapshotInterface); ok {
  3137. baseName := ccDepModule.BaseModuleName()
  3138. return baseName + snapshotPrebuilt.SnapshotAndroidMkSuffix()
  3139. }
  3140. }
  3141. if ctx.DeviceConfig().VndkUseCoreVariant() && ccDep.IsVndk() && !ccDep.MustUseVendorVariant() &&
  3142. !c.InRamdisk() && !c.InVendorRamdisk() && !c.InRecovery() {
  3143. // The vendor module is a no-vendor-variant VNDK library. Depend on the
  3144. // core module instead.
  3145. return libName
  3146. } else if ccDep.UseVndk() && nonSystemVariantsExist {
  3147. // The vendor and product modules in Make will have been renamed to not conflict with the
  3148. // core module, so update the dependency name here accordingly.
  3149. return libName + ccDep.SubName()
  3150. } else if ccDep.InRamdisk() && !ccDep.OnlyInRamdisk() {
  3151. return libName + RamdiskSuffix
  3152. } else if ccDep.InVendorRamdisk() && !ccDep.OnlyInVendorRamdisk() {
  3153. return libName + VendorRamdiskSuffix
  3154. } else if ccDep.InRecovery() && !ccDep.OnlyInRecovery() {
  3155. return libName + RecoverySuffix
  3156. } else if ccDep.Target().NativeBridge == android.NativeBridgeEnabled {
  3157. return libName + NativeBridgeSuffix
  3158. } else {
  3159. return libName
  3160. }
  3161. }
  3162. func (c *Module) InstallInData() bool {
  3163. if c.installer == nil {
  3164. return false
  3165. }
  3166. return c.installer.inData()
  3167. }
  3168. func (c *Module) InstallInSanitizerDir() bool {
  3169. if c.installer == nil {
  3170. return false
  3171. }
  3172. if c.sanitize != nil && c.sanitize.inSanitizerDir() {
  3173. return true
  3174. }
  3175. return c.installer.inSanitizerDir()
  3176. }
  3177. func (c *Module) InstallInRamdisk() bool {
  3178. return c.InRamdisk()
  3179. }
  3180. func (c *Module) InstallInVendorRamdisk() bool {
  3181. return c.InVendorRamdisk()
  3182. }
  3183. func (c *Module) InstallInRecovery() bool {
  3184. return c.InRecovery()
  3185. }
  3186. func (c *Module) MakeUninstallable() {
  3187. if c.installer == nil {
  3188. c.ModuleBase.MakeUninstallable()
  3189. return
  3190. }
  3191. c.installer.makeUninstallable(c)
  3192. }
  3193. func (c *Module) HostToolPath() android.OptionalPath {
  3194. if c.installer == nil {
  3195. return android.OptionalPath{}
  3196. }
  3197. return c.installer.hostToolPath()
  3198. }
  3199. func (c *Module) IntermPathForModuleOut() android.OptionalPath {
  3200. return c.outputFile
  3201. }
  3202. func (c *Module) OutputFiles(tag string) (android.Paths, error) {
  3203. switch tag {
  3204. case "":
  3205. if c.outputFile.Valid() {
  3206. return android.Paths{c.outputFile.Path()}, nil
  3207. }
  3208. return android.Paths{}, nil
  3209. case "unstripped":
  3210. if c.linker != nil {
  3211. return android.PathsIfNonNil(c.linker.unstrippedOutputFilePath()), nil
  3212. }
  3213. return nil, nil
  3214. default:
  3215. return nil, fmt.Errorf("unsupported module reference tag %q", tag)
  3216. }
  3217. }
  3218. func (c *Module) static() bool {
  3219. if static, ok := c.linker.(interface {
  3220. static() bool
  3221. }); ok {
  3222. return static.static()
  3223. }
  3224. return false
  3225. }
  3226. func (c *Module) staticBinary() bool {
  3227. if static, ok := c.linker.(interface {
  3228. staticBinary() bool
  3229. }); ok {
  3230. return static.staticBinary()
  3231. }
  3232. return false
  3233. }
  3234. func (c *Module) testBinary() bool {
  3235. if test, ok := c.linker.(interface {
  3236. testBinary() bool
  3237. }); ok {
  3238. return test.testBinary()
  3239. }
  3240. return false
  3241. }
  3242. func (c *Module) testLibrary() bool {
  3243. if test, ok := c.linker.(interface {
  3244. testLibrary() bool
  3245. }); ok {
  3246. return test.testLibrary()
  3247. }
  3248. return false
  3249. }
  3250. func (c *Module) benchmarkBinary() bool {
  3251. if b, ok := c.linker.(interface {
  3252. benchmarkBinary() bool
  3253. }); ok {
  3254. return b.benchmarkBinary()
  3255. }
  3256. return false
  3257. }
  3258. func (c *Module) fuzzBinary() bool {
  3259. if f, ok := c.linker.(interface {
  3260. fuzzBinary() bool
  3261. }); ok {
  3262. return f.fuzzBinary()
  3263. }
  3264. return false
  3265. }
  3266. // Header returns true if the module is a header-only variant. (See cc/library.go header()).
  3267. func (c *Module) Header() bool {
  3268. if h, ok := c.linker.(interface {
  3269. header() bool
  3270. }); ok {
  3271. return h.header()
  3272. }
  3273. return false
  3274. }
  3275. func (c *Module) Binary() bool {
  3276. if b, ok := c.linker.(interface {
  3277. binary() bool
  3278. }); ok {
  3279. return b.binary()
  3280. }
  3281. return false
  3282. }
  3283. func (c *Module) StaticExecutable() bool {
  3284. if b, ok := c.linker.(*binaryDecorator); ok {
  3285. return b.static()
  3286. }
  3287. return false
  3288. }
  3289. func (c *Module) Object() bool {
  3290. if o, ok := c.linker.(interface {
  3291. object() bool
  3292. }); ok {
  3293. return o.object()
  3294. }
  3295. return false
  3296. }
  3297. func GetMakeLinkType(actx android.ModuleContext, c LinkableInterface) string {
  3298. if c.UseVndk() {
  3299. if c.IsLlndk() {
  3300. if !c.IsLlndkPublic() {
  3301. return "native:vndk_private"
  3302. }
  3303. return "native:vndk"
  3304. }
  3305. if c.IsVndk() && !c.IsVndkExt() {
  3306. if c.IsVndkPrivate() {
  3307. return "native:vndk_private"
  3308. }
  3309. return "native:vndk"
  3310. }
  3311. if c.InProduct() {
  3312. return "native:product"
  3313. }
  3314. return "native:vendor"
  3315. } else if c.InRamdisk() {
  3316. return "native:ramdisk"
  3317. } else if c.InVendorRamdisk() {
  3318. return "native:vendor_ramdisk"
  3319. } else if c.InRecovery() {
  3320. return "native:recovery"
  3321. } else if c.Target().Os == android.Android && c.SdkVersion() != "" {
  3322. return "native:ndk:none:none"
  3323. // TODO(b/114741097): use the correct ndk stl once build errors have been fixed
  3324. //family, link := getNdkStlFamilyAndLinkType(c)
  3325. //return fmt.Sprintf("native:ndk:%s:%s", family, link)
  3326. } else if actx.DeviceConfig().VndkUseCoreVariant() && !c.MustUseVendorVariant() {
  3327. return "native:platform_vndk"
  3328. } else {
  3329. return "native:platform"
  3330. }
  3331. }
  3332. // Overrides ApexModule.IsInstallabeToApex()
  3333. // Only shared/runtime libraries and "test_per_src" tests are installable to APEX.
  3334. func (c *Module) IsInstallableToApex() bool {
  3335. if lib := c.library; lib != nil {
  3336. // Stub libs and prebuilt libs in a versioned SDK are not
  3337. // installable to APEX even though they are shared libs.
  3338. return lib.shared() && !lib.buildStubs()
  3339. } else if _, ok := c.linker.(testPerSrc); ok {
  3340. return true
  3341. }
  3342. return false
  3343. }
  3344. func (c *Module) AvailableFor(what string) bool {
  3345. if linker, ok := c.linker.(interface {
  3346. availableFor(string) bool
  3347. }); ok {
  3348. return c.ApexModuleBase.AvailableFor(what) || linker.availableFor(what)
  3349. } else {
  3350. return c.ApexModuleBase.AvailableFor(what)
  3351. }
  3352. }
  3353. func (c *Module) TestFor() []string {
  3354. return c.Properties.Test_for
  3355. }
  3356. func (c *Module) EverInstallable() bool {
  3357. return c.installer != nil &&
  3358. // Check to see whether the module is actually ever installable.
  3359. c.installer.everInstallable()
  3360. }
  3361. func (c *Module) PreventInstall() bool {
  3362. return c.Properties.PreventInstall
  3363. }
  3364. func (c *Module) Installable() *bool {
  3365. if c.library != nil {
  3366. if i := c.library.installable(); i != nil {
  3367. return i
  3368. }
  3369. }
  3370. return c.Properties.Installable
  3371. }
  3372. func installable(c LinkableInterface, apexInfo android.ApexInfo) bool {
  3373. ret := c.EverInstallable() &&
  3374. // Check to see whether the module has been configured to not be installed.
  3375. proptools.BoolDefault(c.Installable(), true) &&
  3376. !c.PreventInstall() && c.OutputFile().Valid()
  3377. // The platform variant doesn't need further condition. Apex variants however might not
  3378. // be installable because it will likely to be included in the APEX and won't appear
  3379. // in the system partition.
  3380. if apexInfo.IsForPlatform() {
  3381. return ret
  3382. }
  3383. // Special case for modules that are configured to be installed to /data, which includes
  3384. // test modules. For these modules, both APEX and non-APEX variants are considered as
  3385. // installable. This is because even the APEX variants won't be included in the APEX, but
  3386. // will anyway be installed to /data/*.
  3387. // See b/146995717
  3388. if c.InstallInData() {
  3389. return ret
  3390. }
  3391. return false
  3392. }
  3393. func (c *Module) AndroidMkWriteAdditionalDependenciesForSourceAbiDiff(w io.Writer) {
  3394. if c.linker != nil {
  3395. if library, ok := c.linker.(*libraryDecorator); ok {
  3396. library.androidMkWriteAdditionalDependenciesForSourceAbiDiff(w)
  3397. }
  3398. }
  3399. }
  3400. var _ android.ApexModule = (*Module)(nil)
  3401. // Implements android.ApexModule
  3402. func (c *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
  3403. depTag := ctx.OtherModuleDependencyTag(dep)
  3404. libDepTag, isLibDepTag := depTag.(libraryDependencyTag)
  3405. if cc, ok := dep.(*Module); ok {
  3406. if cc.HasStubsVariants() {
  3407. if isLibDepTag && libDepTag.shared() {
  3408. // dynamic dep to a stubs lib crosses APEX boundary
  3409. return false
  3410. }
  3411. if IsRuntimeDepTag(depTag) {
  3412. // runtime dep to a stubs lib also crosses APEX boundary
  3413. return false
  3414. }
  3415. }
  3416. if cc.IsLlndk() {
  3417. return false
  3418. }
  3419. if isLibDepTag && c.static() && libDepTag.shared() {
  3420. // shared_lib dependency from a static lib is considered as crossing
  3421. // the APEX boundary because the dependency doesn't actually is
  3422. // linked; the dependency is used only during the compilation phase.
  3423. return false
  3424. }
  3425. if isLibDepTag && libDepTag.excludeInApex {
  3426. return false
  3427. }
  3428. }
  3429. if depTag == stubImplDepTag {
  3430. // We don't track from an implementation library to its stubs.
  3431. return false
  3432. }
  3433. if depTag == staticVariantTag {
  3434. // This dependency is for optimization (reuse *.o from the static lib). It doesn't
  3435. // actually mean that the static lib (and its dependencies) are copied into the
  3436. // APEX.
  3437. return false
  3438. }
  3439. return true
  3440. }
  3441. // Implements android.ApexModule
  3442. func (c *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
  3443. sdkVersion android.ApiLevel) error {
  3444. // We ignore libclang_rt.* prebuilt libs since they declare sdk_version: 14(b/121358700)
  3445. if strings.HasPrefix(ctx.OtherModuleName(c), "libclang_rt") {
  3446. return nil
  3447. }
  3448. // We don't check for prebuilt modules
  3449. if _, ok := c.linker.(prebuiltLinkerInterface); ok {
  3450. return nil
  3451. }
  3452. minSdkVersion := c.MinSdkVersion()
  3453. if minSdkVersion == "apex_inherit" {
  3454. return nil
  3455. }
  3456. if minSdkVersion == "" {
  3457. // JNI libs within APK-in-APEX fall into here
  3458. // Those are okay to set sdk_version instead
  3459. // We don't have to check if this is a SDK variant because
  3460. // non-SDK variant resets sdk_version, which works too.
  3461. minSdkVersion = c.SdkVersion()
  3462. }
  3463. if minSdkVersion == "" {
  3464. return fmt.Errorf("neither min_sdk_version nor sdk_version specificed")
  3465. }
  3466. // Not using nativeApiLevelFromUser because the context here is not
  3467. // necessarily a native context.
  3468. ver, err := android.ApiLevelFromUser(ctx, minSdkVersion)
  3469. if err != nil {
  3470. return err
  3471. }
  3472. // A dependency only needs to support a min_sdk_version at least
  3473. // as high as the api level that the architecture was introduced in.
  3474. // This allows introducing new architectures in the platform that
  3475. // need to be included in apexes that normally require an older
  3476. // min_sdk_version.
  3477. minApiForArch := MinApiForArch(ctx, c.Target().Arch.ArchType)
  3478. if sdkVersion.LessThan(minApiForArch) {
  3479. sdkVersion = minApiForArch
  3480. }
  3481. if ver.GreaterThan(sdkVersion) {
  3482. return fmt.Errorf("newer SDK(%v)", ver)
  3483. }
  3484. return nil
  3485. }
  3486. // Implements android.ApexModule
  3487. func (c *Module) AlwaysRequiresPlatformApexVariant() bool {
  3488. // stub libraries and native bridge libraries are always available to platform
  3489. return c.IsStubs() || c.Target().NativeBridge == android.NativeBridgeEnabled
  3490. }
  3491. // Overrides android.ApexModuleBase.UniqueApexVariations
  3492. func (c *Module) UniqueApexVariations() bool {
  3493. // When a vendor APEX needs a VNDK lib in it (use_vndk_as_stable: false), it should be a unique
  3494. // APEX variation. Otherwise, another vendor APEX with use_vndk_as_stable:true may use a wrong
  3495. // variation of the VNDK lib because APEX variations are merged/grouped.
  3496. // TODO(b/274401041) Find a way to merge APEX variations for vendor apexes.
  3497. return c.UseVndk() && c.IsVndk()
  3498. }
  3499. func (c *Module) overriddenModules() []string {
  3500. if o, ok := c.linker.(overridable); ok {
  3501. return o.overriddenModules()
  3502. }
  3503. return nil
  3504. }
  3505. var _ snapshot.RelativeInstallPath = (*Module)(nil)
  3506. type moduleType int
  3507. const (
  3508. unknownType moduleType = iota
  3509. binary
  3510. object
  3511. fullLibrary
  3512. staticLibrary
  3513. sharedLibrary
  3514. headerLibrary
  3515. testBin // testBinary already declared
  3516. ndkLibrary
  3517. )
  3518. func (c *Module) typ() moduleType {
  3519. if c.testBinary() {
  3520. // testBinary is also a binary, so this comes before the c.Binary()
  3521. // conditional. A testBinary has additional implicit dependencies and
  3522. // other test-only semantics.
  3523. return testBin
  3524. } else if c.Binary() {
  3525. return binary
  3526. } else if c.Object() {
  3527. return object
  3528. } else if c.testLibrary() {
  3529. // TODO(b/244431896) properly convert cc_test_library to its own macro. This
  3530. // will let them add implicit compile deps on gtest, for example.
  3531. //
  3532. // For now, treat them as regular libraries.
  3533. return fullLibrary
  3534. } else if c.CcLibrary() {
  3535. static := false
  3536. shared := false
  3537. if library, ok := c.linker.(*libraryDecorator); ok {
  3538. static = library.MutatedProperties.BuildStatic
  3539. shared = library.MutatedProperties.BuildShared
  3540. } else if library, ok := c.linker.(*prebuiltLibraryLinker); ok {
  3541. static = library.MutatedProperties.BuildStatic
  3542. shared = library.MutatedProperties.BuildShared
  3543. }
  3544. if static && shared {
  3545. return fullLibrary
  3546. } else if !static && !shared {
  3547. return headerLibrary
  3548. } else if static {
  3549. return staticLibrary
  3550. }
  3551. return sharedLibrary
  3552. } else if c.isNDKStubLibrary() {
  3553. return ndkLibrary
  3554. }
  3555. return unknownType
  3556. }
  3557. // ConvertWithBp2build converts Module to Bazel for bp2build.
  3558. func (c *Module) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
  3559. prebuilt := c.IsPrebuilt()
  3560. switch c.typ() {
  3561. case binary:
  3562. if prebuilt {
  3563. prebuiltBinaryBp2Build(ctx, c)
  3564. } else {
  3565. binaryBp2build(ctx, c)
  3566. }
  3567. case testBin:
  3568. if !prebuilt {
  3569. testBinaryBp2build(ctx, c)
  3570. }
  3571. case object:
  3572. if prebuilt {
  3573. prebuiltObjectBp2Build(ctx, c)
  3574. } else {
  3575. objectBp2Build(ctx, c)
  3576. }
  3577. case fullLibrary:
  3578. if !prebuilt {
  3579. libraryBp2Build(ctx, c)
  3580. } else {
  3581. prebuiltLibraryBp2Build(ctx, c)
  3582. }
  3583. case headerLibrary:
  3584. libraryHeadersBp2Build(ctx, c)
  3585. case staticLibrary:
  3586. if prebuilt {
  3587. prebuiltLibraryStaticBp2Build(ctx, c, false)
  3588. } else {
  3589. sharedOrStaticLibraryBp2Build(ctx, c, true)
  3590. }
  3591. case sharedLibrary:
  3592. if prebuilt {
  3593. prebuiltLibrarySharedBp2Build(ctx, c)
  3594. } else {
  3595. sharedOrStaticLibraryBp2Build(ctx, c, false)
  3596. }
  3597. default:
  3598. ctx.MarkBp2buildUnconvertible(bp2build_metrics_proto.UnconvertedReasonType_TYPE_UNSUPPORTED, "")
  3599. }
  3600. }
  3601. var _ android.ApiProvider = (*Module)(nil)
  3602. func (c *Module) ConvertWithApiBp2build(ctx android.TopDownMutatorContext) {
  3603. if c.IsPrebuilt() {
  3604. return
  3605. }
  3606. switch c.typ() {
  3607. case fullLibrary:
  3608. apiContributionBp2Build(ctx, c)
  3609. case sharedLibrary:
  3610. apiContributionBp2Build(ctx, c)
  3611. case headerLibrary:
  3612. // Aggressively generate api targets for all header modules
  3613. // This is necessary since the header module does not know if it is a dep of API surface stub library
  3614. apiLibraryHeadersBp2Build(ctx, c)
  3615. }
  3616. }
  3617. // Defaults
  3618. type Defaults struct {
  3619. android.ModuleBase
  3620. android.DefaultsModuleBase
  3621. android.ApexModuleBase
  3622. }
  3623. // cc_defaults provides a set of properties that can be inherited by other cc
  3624. // modules. A module can use the properties from a cc_defaults using
  3625. // `defaults: ["<:default_module_name>"]`. Properties of both modules are
  3626. // merged (when possible) by prepending the default module's values to the
  3627. // depending module's values.
  3628. func defaultsFactory() android.Module {
  3629. return DefaultsFactory()
  3630. }
  3631. func DefaultsFactory(props ...interface{}) android.Module {
  3632. module := &Defaults{}
  3633. module.AddProperties(props...)
  3634. module.AddProperties(
  3635. &BaseProperties{},
  3636. &VendorProperties{},
  3637. &BaseCompilerProperties{},
  3638. &BaseLinkerProperties{},
  3639. &ObjectLinkerProperties{},
  3640. &LibraryProperties{},
  3641. &StaticProperties{},
  3642. &SharedProperties{},
  3643. &FlagExporterProperties{},
  3644. &BinaryLinkerProperties{},
  3645. &TestLinkerProperties{},
  3646. &TestInstallerProperties{},
  3647. &TestBinaryProperties{},
  3648. &BenchmarkProperties{},
  3649. &fuzz.FuzzProperties{},
  3650. &StlProperties{},
  3651. &SanitizeProperties{},
  3652. &StripProperties{},
  3653. &InstallerProperties{},
  3654. &TidyProperties{},
  3655. &CoverageProperties{},
  3656. &SAbiProperties{},
  3657. &VndkProperties{},
  3658. &LTOProperties{},
  3659. &AfdoProperties{},
  3660. &PgoProperties{},
  3661. &android.ProtoProperties{},
  3662. // RustBindgenProperties is included here so that cc_defaults can be used for rust_bindgen modules.
  3663. &RustBindgenClangProperties{},
  3664. &prebuiltLinkerProperties{},
  3665. )
  3666. android.InitDefaultsModule(module)
  3667. return module
  3668. }
  3669. func (c *Module) IsSdkVariant() bool {
  3670. return c.Properties.IsSdkVariant
  3671. }
  3672. func (c *Module) isImportedApiLibrary() bool {
  3673. _, ok := c.linker.(*apiLibraryDecorator)
  3674. return ok
  3675. }
  3676. func kytheExtractAllFactory() android.Singleton {
  3677. return &kytheExtractAllSingleton{}
  3678. }
  3679. type kytheExtractAllSingleton struct {
  3680. }
  3681. func (ks *kytheExtractAllSingleton) GenerateBuildActions(ctx android.SingletonContext) {
  3682. var xrefTargets android.Paths
  3683. ctx.VisitAllModules(func(module android.Module) {
  3684. if ccModule, ok := module.(xref); ok {
  3685. xrefTargets = append(xrefTargets, ccModule.XrefCcFiles()...)
  3686. }
  3687. })
  3688. // TODO(asmundak): Perhaps emit a rule to output a warning if there were no xrefTargets
  3689. if len(xrefTargets) > 0 {
  3690. ctx.Phony("xref_cxx", xrefTargets...)
  3691. }
  3692. }
  3693. func (c *Module) Partition() string {
  3694. if p, ok := c.installer.(interface {
  3695. getPartition() string
  3696. }); ok {
  3697. return p.getPartition()
  3698. }
  3699. return ""
  3700. }
  3701. var Bool = proptools.Bool
  3702. var BoolDefault = proptools.BoolDefault
  3703. var BoolPtr = proptools.BoolPtr
  3704. var String = proptools.String
  3705. var StringPtr = proptools.StringPtr