apex.go 136 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744
  1. // Copyright (C) 2018 The Android Open Source Project
  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 apex implements build rules for creating the APEX files which are container for
  15. // lower-level system components. See https://source.android.com/devices/tech/ota/apex
  16. package apex
  17. import (
  18. "fmt"
  19. "path/filepath"
  20. "regexp"
  21. "sort"
  22. "strings"
  23. "android/soong/bazel/cquery"
  24. "github.com/google/blueprint"
  25. "github.com/google/blueprint/bootstrap"
  26. "github.com/google/blueprint/proptools"
  27. "android/soong/android"
  28. "android/soong/bazel"
  29. "android/soong/bpf"
  30. "android/soong/cc"
  31. prebuilt_etc "android/soong/etc"
  32. "android/soong/filesystem"
  33. "android/soong/java"
  34. "android/soong/multitree"
  35. "android/soong/python"
  36. "android/soong/rust"
  37. "android/soong/sh"
  38. )
  39. func init() {
  40. registerApexBuildComponents(android.InitRegistrationContext)
  41. }
  42. func registerApexBuildComponents(ctx android.RegistrationContext) {
  43. ctx.RegisterModuleType("apex", BundleFactory)
  44. ctx.RegisterModuleType("apex_test", TestApexBundleFactory)
  45. ctx.RegisterModuleType("apex_vndk", vndkApexBundleFactory)
  46. ctx.RegisterModuleType("apex_defaults", DefaultsFactory)
  47. ctx.RegisterModuleType("prebuilt_apex", PrebuiltFactory)
  48. ctx.RegisterModuleType("override_apex", OverrideApexFactory)
  49. ctx.RegisterModuleType("apex_set", apexSetFactory)
  50. ctx.PreArchMutators(registerPreArchMutators)
  51. ctx.PreDepsMutators(RegisterPreDepsMutators)
  52. ctx.PostDepsMutators(RegisterPostDepsMutators)
  53. }
  54. func registerPreArchMutators(ctx android.RegisterMutatorsContext) {
  55. ctx.TopDown("prebuilt_apex_module_creator", prebuiltApexModuleCreatorMutator).Parallel()
  56. }
  57. func RegisterPreDepsMutators(ctx android.RegisterMutatorsContext) {
  58. ctx.TopDown("apex_vndk", apexVndkMutator).Parallel()
  59. ctx.BottomUp("apex_vndk_deps", apexVndkDepsMutator).Parallel()
  60. }
  61. func RegisterPostDepsMutators(ctx android.RegisterMutatorsContext) {
  62. ctx.TopDown("apex_info", apexInfoMutator).Parallel()
  63. ctx.BottomUp("apex_unique", apexUniqueVariationsMutator).Parallel()
  64. ctx.BottomUp("apex_test_for_deps", apexTestForDepsMutator).Parallel()
  65. ctx.BottomUp("apex_test_for", apexTestForMutator).Parallel()
  66. // Run mark_platform_availability before the apexMutator as the apexMutator needs to know whether
  67. // it should create a platform variant.
  68. ctx.BottomUp("mark_platform_availability", markPlatformAvailability).Parallel()
  69. ctx.BottomUp("apex", apexMutator).Parallel()
  70. ctx.BottomUp("apex_directly_in_any", apexDirectlyInAnyMutator).Parallel()
  71. ctx.BottomUp("apex_packaging", apexPackagingMutator).Parallel()
  72. ctx.BottomUp("apex_dcla_deps", apexDCLADepsMutator).Parallel()
  73. // Register after apex_info mutator so that it can use ApexVariationName
  74. ctx.TopDown("apex_strict_updatability_lint", apexStrictUpdatibilityLintMutator).Parallel()
  75. }
  76. type apexBundleProperties struct {
  77. // Json manifest file describing meta info of this APEX bundle. Refer to
  78. // system/apex/proto/apex_manifest.proto for the schema. Default: "apex_manifest.json"
  79. Manifest *string `android:"path"`
  80. // AndroidManifest.xml file used for the zip container of this APEX bundle. If unspecified,
  81. // a default one is automatically generated.
  82. AndroidManifest *string `android:"path"`
  83. // Determines the file contexts file for setting the security contexts to files in this APEX
  84. // bundle. For platform APEXes, this should points to a file under /system/sepolicy Default:
  85. // /system/sepolicy/apex/<module_name>_file_contexts.
  86. File_contexts *string `android:"path"`
  87. // By default, file_contexts is amended by force-labelling / and /apex_manifest.pb as system_file
  88. // to avoid mistakes. When set as true, no force-labelling.
  89. Use_file_contexts_as_is *bool
  90. // Path to the canned fs config file for customizing file's
  91. // uid/gid/mod/capabilities. The content of this file is appended to the
  92. // default config, so that the custom entries are preferred. The format is
  93. // /<path_or_glob> <uid> <gid> <mode> [capabilities=0x<cap>], where
  94. // path_or_glob is a path or glob pattern for a file or set of files,
  95. // uid/gid are numerial values of user ID and group ID, mode is octal value
  96. // for the file mode, and cap is hexadecimal value for the capability.
  97. Canned_fs_config *string `android:"path"`
  98. ApexNativeDependencies
  99. Multilib apexMultilibProperties
  100. // List of runtime resource overlays (RROs) that are embedded inside this APEX.
  101. Rros []string
  102. // List of bootclasspath fragments that are embedded inside this APEX bundle.
  103. Bootclasspath_fragments []string
  104. // List of systemserverclasspath fragments that are embedded inside this APEX bundle.
  105. Systemserverclasspath_fragments []string
  106. // List of java libraries that are embedded inside this APEX bundle.
  107. Java_libs []string
  108. // List of sh binaries that are embedded inside this APEX bundle.
  109. Sh_binaries []string
  110. // List of platform_compat_config files that are embedded inside this APEX bundle.
  111. Compat_configs []string
  112. // List of filesystem images that are embedded inside this APEX bundle.
  113. Filesystems []string
  114. // The minimum SDK version that this APEX must support at minimum. This is usually set to
  115. // the SDK version that the APEX was first introduced.
  116. Min_sdk_version *string
  117. // Whether this APEX is considered updatable or not. When set to true, this will enforce
  118. // additional rules for making sure that the APEX is truly updatable. To be updatable,
  119. // min_sdk_version should be set as well. This will also disable the size optimizations like
  120. // symlinking to the system libs. Default is true.
  121. Updatable *bool
  122. // Marks that this APEX is designed to be updatable in the future, although it's not
  123. // updatable yet. This is used to mimic some of the build behaviors that are applied only to
  124. // updatable APEXes. Currently, this disables the size optimization, so that the size of
  125. // APEX will not increase when the APEX is actually marked as truly updatable. Default is
  126. // false.
  127. Future_updatable *bool
  128. // Whether this APEX can use platform APIs or not. Can be set to true only when `updatable:
  129. // false`. Default is false.
  130. Platform_apis *bool
  131. // Whether this APEX is installable to one of the partitions like system, vendor, etc.
  132. // Default: true.
  133. Installable *bool
  134. // If set true, VNDK libs are considered as stable libs and are not included in this APEX.
  135. // Should be only used in non-system apexes (e.g. vendor: true). Default is false.
  136. Use_vndk_as_stable *bool
  137. // The type of APEX to build. Controls what the APEX payload is. Either 'image', 'zip' or
  138. // 'both'. When set to image, contents are stored in a filesystem image inside a zip
  139. // container. When set to zip, contents are stored in a zip container directly. This type is
  140. // mostly for host-side debugging. When set to both, the two types are both built. Default
  141. // is 'image'.
  142. Payload_type *string
  143. // The type of filesystem to use when the payload_type is 'image'. Either 'ext4', 'f2fs'
  144. // or 'erofs'. Default 'ext4'.
  145. Payload_fs_type *string
  146. // For telling the APEX to ignore special handling for system libraries such as bionic.
  147. // Default is false.
  148. Ignore_system_library_special_case *bool
  149. // Whenever apex_payload.img of the APEX should include dm-verity hashtree.
  150. // Default value is true.
  151. Generate_hashtree *bool
  152. // Whenever apex_payload.img of the APEX should not be dm-verity signed. Should be only
  153. // used in tests.
  154. Test_only_unsigned_payload *bool
  155. // Whenever apex should be compressed, regardless of product flag used. Should be only
  156. // used in tests.
  157. Test_only_force_compression *bool
  158. // Put extra tags (signer=<value>) to apexkeys.txt, so that release tools can sign this apex
  159. // with the tool to sign payload contents.
  160. Custom_sign_tool *string
  161. // Whether this is a dynamic common lib apex, if so the native shared libs will be placed
  162. // in a special way that include the digest of the lib file under /lib(64)?
  163. Dynamic_common_lib_apex *bool
  164. // Canonical name of this APEX bundle. Used to determine the path to the
  165. // activated APEX on device (i.e. /apex/<apexVariationName>), and used for the
  166. // apex mutator variations. For override_apex modules, this is the name of the
  167. // overridden base module.
  168. ApexVariationName string `blueprint:"mutated"`
  169. IsCoverageVariant bool `blueprint:"mutated"`
  170. // List of sanitizer names that this APEX is enabled for
  171. SanitizerNames []string `blueprint:"mutated"`
  172. PreventInstall bool `blueprint:"mutated"`
  173. HideFromMake bool `blueprint:"mutated"`
  174. // Internal package method for this APEX.
  175. ApexType apexPackaging `blueprint:"mutated"`
  176. // Name that dependencies can specify in their apex_available properties to refer to this module.
  177. // If not specified, this defaults to Soong module name. This must be the name of a Soong module.
  178. Apex_available_name *string
  179. // Variant version of the mainline module. Must be an integer between 0-9
  180. Variant_version *string
  181. }
  182. type ApexNativeDependencies struct {
  183. // List of native libraries that are embedded inside this APEX.
  184. Native_shared_libs []string
  185. // List of JNI libraries that are embedded inside this APEX.
  186. Jni_libs []string
  187. // List of rust dyn libraries that are embedded inside this APEX.
  188. Rust_dyn_libs []string
  189. // List of native executables that are embedded inside this APEX.
  190. Binaries []string
  191. // List of native tests that are embedded inside this APEX.
  192. Tests []string
  193. // List of filesystem images that are embedded inside this APEX bundle.
  194. Filesystems []string
  195. // List of native libraries to exclude from this APEX.
  196. Exclude_native_shared_libs []string
  197. // List of JNI libraries to exclude from this APEX.
  198. Exclude_jni_libs []string
  199. // List of rust dyn libraries to exclude from this APEX.
  200. Exclude_rust_dyn_libs []string
  201. // List of native executables to exclude from this APEX.
  202. Exclude_binaries []string
  203. // List of native tests to exclude from this APEX.
  204. Exclude_tests []string
  205. // List of filesystem images to exclude from this APEX bundle.
  206. Exclude_filesystems []string
  207. }
  208. // Merge combines another ApexNativeDependencies into this one
  209. func (a *ApexNativeDependencies) Merge(b ApexNativeDependencies) {
  210. a.Native_shared_libs = append(a.Native_shared_libs, b.Native_shared_libs...)
  211. a.Jni_libs = append(a.Jni_libs, b.Jni_libs...)
  212. a.Rust_dyn_libs = append(a.Rust_dyn_libs, b.Rust_dyn_libs...)
  213. a.Binaries = append(a.Binaries, b.Binaries...)
  214. a.Tests = append(a.Tests, b.Tests...)
  215. a.Filesystems = append(a.Filesystems, b.Filesystems...)
  216. a.Exclude_native_shared_libs = append(a.Exclude_native_shared_libs, b.Exclude_native_shared_libs...)
  217. a.Exclude_jni_libs = append(a.Exclude_jni_libs, b.Exclude_jni_libs...)
  218. a.Exclude_rust_dyn_libs = append(a.Exclude_rust_dyn_libs, b.Exclude_rust_dyn_libs...)
  219. a.Exclude_binaries = append(a.Exclude_binaries, b.Exclude_binaries...)
  220. a.Exclude_tests = append(a.Exclude_tests, b.Exclude_tests...)
  221. a.Exclude_filesystems = append(a.Exclude_filesystems, b.Exclude_filesystems...)
  222. }
  223. type apexMultilibProperties struct {
  224. // Native dependencies whose compile_multilib is "first"
  225. First ApexNativeDependencies
  226. // Native dependencies whose compile_multilib is "both"
  227. Both ApexNativeDependencies
  228. // Native dependencies whose compile_multilib is "prefer32"
  229. Prefer32 ApexNativeDependencies
  230. // Native dependencies whose compile_multilib is "32"
  231. Lib32 ApexNativeDependencies
  232. // Native dependencies whose compile_multilib is "64"
  233. Lib64 ApexNativeDependencies
  234. }
  235. type apexTargetBundleProperties struct {
  236. Target struct {
  237. // Multilib properties only for android.
  238. Android struct {
  239. Multilib apexMultilibProperties
  240. }
  241. // Multilib properties only for host.
  242. Host struct {
  243. Multilib apexMultilibProperties
  244. }
  245. // Multilib properties only for host linux_bionic.
  246. Linux_bionic struct {
  247. Multilib apexMultilibProperties
  248. }
  249. // Multilib properties only for host linux_glibc.
  250. Linux_glibc struct {
  251. Multilib apexMultilibProperties
  252. }
  253. }
  254. }
  255. type apexArchBundleProperties struct {
  256. Arch struct {
  257. Arm struct {
  258. ApexNativeDependencies
  259. }
  260. Arm64 struct {
  261. ApexNativeDependencies
  262. }
  263. Riscv64 struct {
  264. ApexNativeDependencies
  265. }
  266. X86 struct {
  267. ApexNativeDependencies
  268. }
  269. X86_64 struct {
  270. ApexNativeDependencies
  271. }
  272. }
  273. }
  274. // These properties can be used in override_apex to override the corresponding properties in the
  275. // base apex.
  276. type overridableProperties struct {
  277. // List of APKs that are embedded inside this APEX.
  278. Apps []string
  279. // List of prebuilt files that are embedded inside this APEX bundle.
  280. Prebuilts []string
  281. // List of BPF programs inside this APEX bundle.
  282. Bpfs []string
  283. // Names of modules to be overridden. Listed modules can only be other binaries (in Make or
  284. // Soong). This does not completely prevent installation of the overridden binaries, but if
  285. // both binaries would be installed by default (in PRODUCT_PACKAGES) the other binary will
  286. // be removed from PRODUCT_PACKAGES.
  287. Overrides []string
  288. // Logging parent value.
  289. Logging_parent string
  290. // Apex Container package name. Override value for attribute package:name in
  291. // AndroidManifest.xml
  292. Package_name string
  293. // A txt file containing list of files that are allowed to be included in this APEX.
  294. Allowed_files *string `android:"path"`
  295. // Name of the apex_key module that provides the private key to sign this APEX bundle.
  296. Key *string
  297. // Specifies the certificate and the private key to sign the zip container of this APEX. If
  298. // this is "foo", foo.x509.pem and foo.pk8 under PRODUCT_DEFAULT_DEV_CERTIFICATE are used
  299. // as the certificate and the private key, respectively. If this is ":module", then the
  300. // certificate and the private key are provided from the android_app_certificate module
  301. // named "module".
  302. Certificate *string
  303. // Whether this APEX can be compressed or not. Setting this property to false means this
  304. // APEX will never be compressed. When set to true, APEX will be compressed if other
  305. // conditions, e.g., target device needs to support APEX compression, are also fulfilled.
  306. // Default: false.
  307. Compressible *bool
  308. // Trim against a specific Dynamic Common Lib APEX
  309. Trim_against *string
  310. }
  311. type apexBundle struct {
  312. // Inherited structs
  313. android.ModuleBase
  314. android.DefaultableModuleBase
  315. android.OverridableModuleBase
  316. android.BazelModuleBase
  317. multitree.ExportableModuleBase
  318. // Properties
  319. properties apexBundleProperties
  320. targetProperties apexTargetBundleProperties
  321. archProperties apexArchBundleProperties
  322. overridableProperties overridableProperties
  323. vndkProperties apexVndkProperties // only for apex_vndk modules
  324. ///////////////////////////////////////////////////////////////////////////////////////////
  325. // Inputs
  326. // Keys for apex_payload.img
  327. publicKeyFile android.Path
  328. privateKeyFile android.Path
  329. // Cert/priv-key for the zip container
  330. containerCertificateFile android.Path
  331. containerPrivateKeyFile android.Path
  332. // Flags for special variants of APEX
  333. testApex bool
  334. vndkApex bool
  335. // Tells whether this variant of the APEX bundle is the primary one or not. Only the primary
  336. // one gets installed to the device.
  337. primaryApexType bool
  338. // Suffix of module name in Android.mk ".apex", ".zipapex", or ""
  339. suffix string
  340. // File system type of apex_payload.img
  341. payloadFsType fsType
  342. // Whether to create symlink to the system file instead of having a file inside the apex or
  343. // not
  344. linkToSystemLib bool
  345. // List of files to be included in this APEX. This is filled in the first part of
  346. // GenerateAndroidBuildActions.
  347. filesInfo []apexFile
  348. // List of other module names that should be installed when this APEX gets installed (LOCAL_REQUIRED_MODULES).
  349. makeModulesToInstall []string
  350. ///////////////////////////////////////////////////////////////////////////////////////////
  351. // Outputs (final and intermediates)
  352. // Processed apex manifest in JSONson format (for Q)
  353. manifestJsonOut android.WritablePath
  354. // Processed apex manifest in PB format (for R+)
  355. manifestPbOut android.WritablePath
  356. // Processed file_contexts files
  357. fileContexts android.WritablePath
  358. // The built APEX file. This is the main product.
  359. // Could be .apex or .capex
  360. outputFile android.WritablePath
  361. // The built uncompressed .apex file.
  362. outputApexFile android.WritablePath
  363. // The built APEX file in app bundle format. This file is not directly installed to the
  364. // device. For an APEX, multiple app bundles are created each of which is for a specific ABI
  365. // like arm, arm64, x86, etc. Then they are processed again (outside of the Android build
  366. // system) to be merged into a single app bundle file that Play accepts. See
  367. // vendor/google/build/build_unbundled_mainline_module.sh for more detail.
  368. bundleModuleFile android.WritablePath
  369. // Target directory to install this APEX. Usually out/target/product/<device>/<partition>/apex.
  370. installDir android.InstallPath
  371. // Path where this APEX was installed.
  372. installedFile android.InstallPath
  373. // Installed locations of symlinks for backward compatibility.
  374. compatSymlinks android.InstallPaths
  375. // Text file having the list of individual files that are included in this APEX. Used for
  376. // debugging purpose.
  377. installedFilesFile android.WritablePath
  378. // List of module names that this APEX is including (to be shown via *-deps-info target).
  379. // Used for debugging purpose.
  380. android.ApexBundleDepsInfo
  381. // Optional list of lint report zip files for apexes that contain java or app modules
  382. lintReports android.Paths
  383. isCompressed bool
  384. // Path of API coverage generate file
  385. nativeApisUsedByModuleFile android.ModuleOutPath
  386. nativeApisBackedByModuleFile android.ModuleOutPath
  387. javaApisUsedByModuleFile android.ModuleOutPath
  388. // Collect the module directory for IDE info in java/jdeps.go.
  389. modulePaths []string
  390. }
  391. // apexFileClass represents a type of file that can be included in APEX.
  392. type apexFileClass int
  393. const (
  394. app apexFileClass = iota
  395. appSet
  396. etc
  397. goBinary
  398. javaSharedLib
  399. nativeExecutable
  400. nativeSharedLib
  401. nativeTest
  402. pyBinary
  403. shBinary
  404. )
  405. var (
  406. classes = map[string]apexFileClass{
  407. "app": app,
  408. "appSet": appSet,
  409. "etc": etc,
  410. "goBinary": goBinary,
  411. "javaSharedLib": javaSharedLib,
  412. "nativeExecutable": nativeExecutable,
  413. "nativeSharedLib": nativeSharedLib,
  414. "nativeTest": nativeTest,
  415. "pyBinary": pyBinary,
  416. "shBinary": shBinary,
  417. }
  418. )
  419. // apexFile represents a file in an APEX bundle. This is created during the first half of
  420. // GenerateAndroidBuildActions by traversing the dependencies of the APEX. Then in the second half
  421. // of the function, this is used to create commands that copies the files into a staging directory,
  422. // where they are packaged into the APEX file.
  423. type apexFile struct {
  424. // buildFile is put in the installDir inside the APEX.
  425. builtFile android.Path
  426. installDir string
  427. partition string
  428. customStem string
  429. symlinks []string // additional symlinks
  430. // Info for Android.mk Module name of `module` in AndroidMk. Note the generated AndroidMk
  431. // module for apexFile is named something like <AndroidMk module name>.<apex name>[<apex
  432. // suffix>]
  433. androidMkModuleName string // becomes LOCAL_MODULE
  434. class apexFileClass // becomes LOCAL_MODULE_CLASS
  435. moduleDir string // becomes LOCAL_PATH
  436. requiredModuleNames []string // becomes LOCAL_REQUIRED_MODULES
  437. targetRequiredModuleNames []string // becomes LOCAL_TARGET_REQUIRED_MODULES
  438. hostRequiredModuleNames []string // becomes LOCAL_HOST_REQUIRED_MODULES
  439. dataPaths []android.DataPath // becomes LOCAL_TEST_DATA
  440. jacocoReportClassesFile android.Path // only for javalibs and apps
  441. lintDepSets java.LintDepSets // only for javalibs and apps
  442. certificate java.Certificate // only for apps
  443. overriddenPackageName string // only for apps
  444. transitiveDep bool
  445. isJniLib bool
  446. multilib string
  447. isBazelPrebuilt bool
  448. unstrippedBuiltFile android.Path
  449. arch string
  450. // TODO(jiyong): remove this
  451. module android.Module
  452. }
  453. // TODO(jiyong): shorten the arglist using an option struct
  454. func newApexFile(ctx android.BaseModuleContext, builtFile android.Path, androidMkModuleName string, installDir string, class apexFileClass, module android.Module) apexFile {
  455. ret := apexFile{
  456. builtFile: builtFile,
  457. installDir: installDir,
  458. androidMkModuleName: androidMkModuleName,
  459. class: class,
  460. module: module,
  461. }
  462. if module != nil {
  463. ret.moduleDir = ctx.OtherModuleDir(module)
  464. ret.partition = module.PartitionTag(ctx.DeviceConfig())
  465. ret.requiredModuleNames = module.RequiredModuleNames()
  466. ret.targetRequiredModuleNames = module.TargetRequiredModuleNames()
  467. ret.hostRequiredModuleNames = module.HostRequiredModuleNames()
  468. ret.multilib = module.Target().Arch.ArchType.Multilib
  469. }
  470. return ret
  471. }
  472. func (af *apexFile) ok() bool {
  473. return af.builtFile != nil && af.builtFile.String() != ""
  474. }
  475. // apexRelativePath returns the relative path of the given path from the install directory of this
  476. // apexFile.
  477. // TODO(jiyong): rename this
  478. func (af *apexFile) apexRelativePath(path string) string {
  479. return filepath.Join(af.installDir, path)
  480. }
  481. // path returns path of this apex file relative to the APEX root
  482. func (af *apexFile) path() string {
  483. return af.apexRelativePath(af.stem())
  484. }
  485. // stem returns the base filename of this apex file
  486. func (af *apexFile) stem() string {
  487. if af.customStem != "" {
  488. return af.customStem
  489. }
  490. return af.builtFile.Base()
  491. }
  492. // symlinkPaths returns paths of the symlinks (if any) relative to the APEX root
  493. func (af *apexFile) symlinkPaths() []string {
  494. var ret []string
  495. for _, symlink := range af.symlinks {
  496. ret = append(ret, af.apexRelativePath(symlink))
  497. }
  498. return ret
  499. }
  500. // availableToPlatform tests whether this apexFile is from a module that can be installed to the
  501. // platform.
  502. func (af *apexFile) availableToPlatform() bool {
  503. if af.module == nil {
  504. return false
  505. }
  506. if am, ok := af.module.(android.ApexModule); ok {
  507. return am.AvailableFor(android.AvailableToPlatform)
  508. }
  509. return false
  510. }
  511. ////////////////////////////////////////////////////////////////////////////////////////////////////
  512. // Mutators
  513. //
  514. // Brief description about mutators for APEX. The following three mutators are the most important
  515. // ones.
  516. //
  517. // 1) DepsMutator: from the properties like native_shared_libs, java_libs, etc., modules are added
  518. // to the (direct) dependencies of this APEX bundle.
  519. //
  520. // 2) apexInfoMutator: this is a post-deps mutator, so runs after DepsMutator. Its goal is to
  521. // collect modules that are direct and transitive dependencies of each APEX bundle. The collected
  522. // modules are marked as being included in the APEX via BuildForApex().
  523. //
  524. // 3) apexMutator: this is a post-deps mutator that runs after apexInfoMutator. For each module that
  525. // are marked by the apexInfoMutator, apex variations are created using CreateApexVariations().
  526. type dependencyTag struct {
  527. blueprint.BaseDependencyTag
  528. name string
  529. // Determines if the dependent will be part of the APEX payload. Can be false for the
  530. // dependencies to the signing key module, etc.
  531. payload bool
  532. // True if the dependent can only be a source module, false if a prebuilt module is a suitable
  533. // replacement. This is needed because some prebuilt modules do not provide all the information
  534. // needed by the apex.
  535. sourceOnly bool
  536. // If not-nil and an APEX is a member of an SDK then dependencies of that APEX with this tag will
  537. // also be added as exported members of that SDK.
  538. memberType android.SdkMemberType
  539. }
  540. func (d *dependencyTag) SdkMemberType(_ android.Module) android.SdkMemberType {
  541. return d.memberType
  542. }
  543. func (d *dependencyTag) ExportMember() bool {
  544. return true
  545. }
  546. func (d *dependencyTag) String() string {
  547. return fmt.Sprintf("apex.dependencyTag{%q}", d.name)
  548. }
  549. func (d *dependencyTag) ReplaceSourceWithPrebuilt() bool {
  550. return !d.sourceOnly
  551. }
  552. var _ android.ReplaceSourceWithPrebuilt = &dependencyTag{}
  553. var _ android.SdkMemberDependencyTag = &dependencyTag{}
  554. var (
  555. androidAppTag = &dependencyTag{name: "androidApp", payload: true}
  556. bpfTag = &dependencyTag{name: "bpf", payload: true}
  557. certificateTag = &dependencyTag{name: "certificate"}
  558. dclaTag = &dependencyTag{name: "dcla"}
  559. executableTag = &dependencyTag{name: "executable", payload: true}
  560. fsTag = &dependencyTag{name: "filesystem", payload: true}
  561. bcpfTag = &dependencyTag{name: "bootclasspathFragment", payload: true, sourceOnly: true, memberType: java.BootclasspathFragmentSdkMemberType}
  562. sscpfTag = &dependencyTag{name: "systemserverclasspathFragment", payload: true, sourceOnly: true, memberType: java.SystemServerClasspathFragmentSdkMemberType}
  563. compatConfigTag = &dependencyTag{name: "compatConfig", payload: true, sourceOnly: true, memberType: java.CompatConfigSdkMemberType}
  564. javaLibTag = &dependencyTag{name: "javaLib", payload: true}
  565. jniLibTag = &dependencyTag{name: "jniLib", payload: true}
  566. keyTag = &dependencyTag{name: "key"}
  567. prebuiltTag = &dependencyTag{name: "prebuilt", payload: true}
  568. rroTag = &dependencyTag{name: "rro", payload: true}
  569. sharedLibTag = &dependencyTag{name: "sharedLib", payload: true}
  570. testForTag = &dependencyTag{name: "test for"}
  571. testTag = &dependencyTag{name: "test", payload: true}
  572. shBinaryTag = &dependencyTag{name: "shBinary", payload: true}
  573. )
  574. // TODO(jiyong): shorten this function signature
  575. func addDependenciesForNativeModules(ctx android.BottomUpMutatorContext, nativeModules ApexNativeDependencies, target android.Target, imageVariation string) {
  576. binVariations := target.Variations()
  577. libVariations := append(target.Variations(), blueprint.Variation{Mutator: "link", Variation: "shared"})
  578. rustLibVariations := append(target.Variations(), blueprint.Variation{Mutator: "rust_libraries", Variation: "dylib"})
  579. if ctx.Device() {
  580. binVariations = append(binVariations, blueprint.Variation{Mutator: "image", Variation: imageVariation})
  581. libVariations = append(libVariations, blueprint.Variation{Mutator: "image", Variation: imageVariation})
  582. rustLibVariations = append(rustLibVariations, blueprint.Variation{Mutator: "image", Variation: imageVariation})
  583. }
  584. // Use *FarVariation* to be able to depend on modules having conflicting variations with
  585. // this module. This is required since arch variant of an APEX bundle is 'common' but it is
  586. // 'arm' or 'arm64' for native shared libs.
  587. ctx.AddFarVariationDependencies(binVariations, executableTag,
  588. android.RemoveListFromList(nativeModules.Binaries, nativeModules.Exclude_binaries)...)
  589. ctx.AddFarVariationDependencies(binVariations, testTag,
  590. android.RemoveListFromList(nativeModules.Tests, nativeModules.Exclude_tests)...)
  591. ctx.AddFarVariationDependencies(libVariations, jniLibTag,
  592. android.RemoveListFromList(nativeModules.Jni_libs, nativeModules.Exclude_jni_libs)...)
  593. ctx.AddFarVariationDependencies(libVariations, sharedLibTag,
  594. android.RemoveListFromList(nativeModules.Native_shared_libs, nativeModules.Exclude_native_shared_libs)...)
  595. ctx.AddFarVariationDependencies(rustLibVariations, sharedLibTag,
  596. android.RemoveListFromList(nativeModules.Rust_dyn_libs, nativeModules.Exclude_rust_dyn_libs)...)
  597. ctx.AddFarVariationDependencies(target.Variations(), fsTag,
  598. android.RemoveListFromList(nativeModules.Filesystems, nativeModules.Exclude_filesystems)...)
  599. }
  600. func (a *apexBundle) combineProperties(ctx android.BottomUpMutatorContext) {
  601. if ctx.Device() {
  602. proptools.AppendProperties(&a.properties.Multilib, &a.targetProperties.Target.Android.Multilib, nil)
  603. } else {
  604. proptools.AppendProperties(&a.properties.Multilib, &a.targetProperties.Target.Host.Multilib, nil)
  605. if ctx.Os().Bionic() {
  606. proptools.AppendProperties(&a.properties.Multilib, &a.targetProperties.Target.Linux_bionic.Multilib, nil)
  607. } else {
  608. proptools.AppendProperties(&a.properties.Multilib, &a.targetProperties.Target.Linux_glibc.Multilib, nil)
  609. }
  610. }
  611. }
  612. // getImageVariationPair returns a pair for the image variation name as its
  613. // prefix and suffix. The prefix indicates whether it's core/vendor/product and the
  614. // suffix indicates the vndk version when it's vendor or product.
  615. // getImageVariation can simply join the result of this function to get the
  616. // image variation name.
  617. func (a *apexBundle) getImageVariationPair(deviceConfig android.DeviceConfig) (string, string) {
  618. if a.vndkApex {
  619. return cc.VendorVariationPrefix, a.vndkVersion(deviceConfig)
  620. }
  621. var prefix string
  622. var vndkVersion string
  623. if deviceConfig.VndkVersion() != "" {
  624. if a.SocSpecific() || a.DeviceSpecific() {
  625. prefix = cc.VendorVariationPrefix
  626. vndkVersion = deviceConfig.VndkVersion()
  627. } else if a.ProductSpecific() {
  628. prefix = cc.ProductVariationPrefix
  629. vndkVersion = deviceConfig.ProductVndkVersion()
  630. }
  631. }
  632. if vndkVersion == "current" {
  633. vndkVersion = deviceConfig.PlatformVndkVersion()
  634. }
  635. if vndkVersion != "" {
  636. return prefix, vndkVersion
  637. }
  638. return android.CoreVariation, "" // The usual case
  639. }
  640. // getImageVariation returns the image variant name for this apexBundle. In most cases, it's simply
  641. // android.CoreVariation, but gets complicated for the vendor APEXes and the VNDK APEX.
  642. func (a *apexBundle) getImageVariation(ctx android.BottomUpMutatorContext) string {
  643. prefix, vndkVersion := a.getImageVariationPair(ctx.DeviceConfig())
  644. return prefix + vndkVersion
  645. }
  646. func (a *apexBundle) DepsMutator(ctx android.BottomUpMutatorContext) {
  647. // apexBundle is a multi-arch targets module. Arch variant of apexBundle is set to 'common'.
  648. // arch-specific targets are enabled by the compile_multilib setting of the apex bundle. For
  649. // each target os/architectures, appropriate dependencies are selected by their
  650. // target.<os>.multilib.<type> groups and are added as (direct) dependencies.
  651. targets := ctx.MultiTargets()
  652. imageVariation := a.getImageVariation(ctx)
  653. a.combineProperties(ctx)
  654. has32BitTarget := false
  655. for _, target := range targets {
  656. if target.Arch.ArchType.Multilib == "lib32" {
  657. has32BitTarget = true
  658. }
  659. }
  660. for i, target := range targets {
  661. // Don't include artifacts for the host cross targets because there is no way for us
  662. // to run those artifacts natively on host
  663. if target.HostCross {
  664. continue
  665. }
  666. var deps ApexNativeDependencies
  667. // Add native modules targeting both ABIs. When multilib.* is omitted for
  668. // native_shared_libs/jni_libs/tests, it implies multilib.both
  669. deps.Merge(a.properties.Multilib.Both)
  670. deps.Merge(ApexNativeDependencies{
  671. Native_shared_libs: a.properties.Native_shared_libs,
  672. Tests: a.properties.Tests,
  673. Jni_libs: a.properties.Jni_libs,
  674. Binaries: nil,
  675. })
  676. // Add native modules targeting the first ABI When multilib.* is omitted for
  677. // binaries, it implies multilib.first
  678. isPrimaryAbi := i == 0
  679. if isPrimaryAbi {
  680. deps.Merge(a.properties.Multilib.First)
  681. deps.Merge(ApexNativeDependencies{
  682. Native_shared_libs: nil,
  683. Tests: nil,
  684. Jni_libs: nil,
  685. Binaries: a.properties.Binaries,
  686. })
  687. }
  688. // Add native modules targeting either 32-bit or 64-bit ABI
  689. switch target.Arch.ArchType.Multilib {
  690. case "lib32":
  691. deps.Merge(a.properties.Multilib.Lib32)
  692. deps.Merge(a.properties.Multilib.Prefer32)
  693. case "lib64":
  694. deps.Merge(a.properties.Multilib.Lib64)
  695. if !has32BitTarget {
  696. deps.Merge(a.properties.Multilib.Prefer32)
  697. }
  698. }
  699. // Add native modules targeting a specific arch variant
  700. switch target.Arch.ArchType {
  701. case android.Arm:
  702. deps.Merge(a.archProperties.Arch.Arm.ApexNativeDependencies)
  703. case android.Arm64:
  704. deps.Merge(a.archProperties.Arch.Arm64.ApexNativeDependencies)
  705. case android.Riscv64:
  706. deps.Merge(a.archProperties.Arch.Riscv64.ApexNativeDependencies)
  707. case android.X86:
  708. deps.Merge(a.archProperties.Arch.X86.ApexNativeDependencies)
  709. case android.X86_64:
  710. deps.Merge(a.archProperties.Arch.X86_64.ApexNativeDependencies)
  711. default:
  712. panic(fmt.Errorf("unsupported arch %v\n", ctx.Arch().ArchType))
  713. }
  714. addDependenciesForNativeModules(ctx, deps, target, imageVariation)
  715. ctx.AddFarVariationDependencies([]blueprint.Variation{
  716. {Mutator: "os", Variation: target.OsVariation()},
  717. {Mutator: "arch", Variation: target.ArchVariation()},
  718. }, shBinaryTag, a.properties.Sh_binaries...)
  719. }
  720. // Common-arch dependencies come next
  721. commonVariation := ctx.Config().AndroidCommonTarget.Variations()
  722. ctx.AddFarVariationDependencies(commonVariation, rroTag, a.properties.Rros...)
  723. ctx.AddFarVariationDependencies(commonVariation, bcpfTag, a.properties.Bootclasspath_fragments...)
  724. ctx.AddFarVariationDependencies(commonVariation, sscpfTag, a.properties.Systemserverclasspath_fragments...)
  725. ctx.AddFarVariationDependencies(commonVariation, javaLibTag, a.properties.Java_libs...)
  726. ctx.AddFarVariationDependencies(commonVariation, fsTag, a.properties.Filesystems...)
  727. ctx.AddFarVariationDependencies(commonVariation, compatConfigTag, a.properties.Compat_configs...)
  728. }
  729. // DepsMutator for the overridden properties.
  730. func (a *apexBundle) OverridablePropertiesDepsMutator(ctx android.BottomUpMutatorContext) {
  731. if a.overridableProperties.Allowed_files != nil {
  732. android.ExtractSourceDeps(ctx, a.overridableProperties.Allowed_files)
  733. }
  734. commonVariation := ctx.Config().AndroidCommonTarget.Variations()
  735. ctx.AddFarVariationDependencies(commonVariation, androidAppTag, a.overridableProperties.Apps...)
  736. ctx.AddFarVariationDependencies(commonVariation, bpfTag, a.overridableProperties.Bpfs...)
  737. if prebuilts := a.overridableProperties.Prebuilts; len(prebuilts) > 0 {
  738. // For prebuilt_etc, use the first variant (64 on 64/32bit device, 32 on 32bit device)
  739. // regardless of the TARGET_PREFER_* setting. See b/144532908
  740. arches := ctx.DeviceConfig().Arches()
  741. if len(arches) != 0 {
  742. archForPrebuiltEtc := arches[0]
  743. for _, arch := range arches {
  744. // Prefer 64-bit arch if there is any
  745. if arch.ArchType.Multilib == "lib64" {
  746. archForPrebuiltEtc = arch
  747. break
  748. }
  749. }
  750. ctx.AddFarVariationDependencies([]blueprint.Variation{
  751. {Mutator: "os", Variation: ctx.Os().String()},
  752. {Mutator: "arch", Variation: archForPrebuiltEtc.String()},
  753. }, prebuiltTag, prebuilts...)
  754. }
  755. }
  756. // Dependencies for signing
  757. if String(a.overridableProperties.Key) == "" {
  758. ctx.PropertyErrorf("key", "missing")
  759. return
  760. }
  761. ctx.AddDependency(ctx.Module(), keyTag, String(a.overridableProperties.Key))
  762. cert := android.SrcIsModule(a.getCertString(ctx))
  763. if cert != "" {
  764. ctx.AddDependency(ctx.Module(), certificateTag, cert)
  765. // empty cert is not an error. Cert and private keys will be directly found under
  766. // PRODUCT_DEFAULT_DEV_CERTIFICATE
  767. }
  768. }
  769. func apexDCLADepsMutator(mctx android.BottomUpMutatorContext) {
  770. if !mctx.Config().ApexTrimEnabled() {
  771. return
  772. }
  773. if a, ok := mctx.Module().(*apexBundle); ok && a.overridableProperties.Trim_against != nil {
  774. commonVariation := mctx.Config().AndroidCommonTarget.Variations()
  775. mctx.AddFarVariationDependencies(commonVariation, dclaTag, String(a.overridableProperties.Trim_against))
  776. } else if o, ok := mctx.Module().(*OverrideApex); ok {
  777. for _, p := range o.GetProperties() {
  778. properties, ok := p.(*overridableProperties)
  779. if !ok {
  780. continue
  781. }
  782. if properties.Trim_against != nil {
  783. commonVariation := mctx.Config().AndroidCommonTarget.Variations()
  784. mctx.AddFarVariationDependencies(commonVariation, dclaTag, String(properties.Trim_against))
  785. }
  786. }
  787. }
  788. }
  789. type DCLAInfo struct {
  790. ProvidedLibs []string
  791. }
  792. var DCLAInfoProvider = blueprint.NewMutatorProvider(DCLAInfo{}, "apex_info")
  793. type ApexBundleInfo struct {
  794. Contents *android.ApexContents
  795. }
  796. var ApexBundleInfoProvider = blueprint.NewMutatorProvider(ApexBundleInfo{}, "apex_info")
  797. var _ ApexInfoMutator = (*apexBundle)(nil)
  798. func (a *apexBundle) ApexVariationName() string {
  799. return a.properties.ApexVariationName
  800. }
  801. // ApexInfoMutator is responsible for collecting modules that need to have apex variants. They are
  802. // identified by doing a graph walk starting from an apexBundle. Basically, all the (direct and
  803. // indirect) dependencies are collected. But a few types of modules that shouldn't be included in
  804. // the apexBundle (e.g. stub libraries) are not collected. Note that a single module can be depended
  805. // on by multiple apexBundles. In that case, the module is collected for all of the apexBundles.
  806. //
  807. // For each dependency between an apex and an ApexModule an ApexInfo object describing the apex
  808. // is passed to that module's BuildForApex(ApexInfo) method which collates them all in a list.
  809. // The apexMutator uses that list to create module variants for the apexes to which it belongs.
  810. // The relationship between module variants and apexes is not one-to-one as variants will be
  811. // shared between compatible apexes.
  812. func (a *apexBundle) ApexInfoMutator(mctx android.TopDownMutatorContext) {
  813. // The VNDK APEX is special. For the APEX, the membership is described in a very different
  814. // way. There is no dependency from the VNDK APEX to the VNDK libraries. Instead, VNDK
  815. // libraries are self-identified by their vndk.enabled properties. There is no need to run
  816. // this mutator for the APEX as nothing will be collected. So, let's return fast.
  817. if a.vndkApex {
  818. return
  819. }
  820. // Special casing for APEXes on non-system (e.g., vendor, odm, etc.) partitions. They are
  821. // provided with a property named use_vndk_as_stable, which when set to true doesn't collect
  822. // VNDK libraries as transitive dependencies. This option is useful for reducing the size of
  823. // the non-system APEXes because the VNDK libraries won't be included (and duped) in the
  824. // APEX, but shared across APEXes via the VNDK APEX.
  825. useVndk := a.SocSpecific() || a.DeviceSpecific() || (a.ProductSpecific() && mctx.Config().EnforceProductPartitionInterface())
  826. excludeVndkLibs := useVndk && proptools.Bool(a.properties.Use_vndk_as_stable)
  827. if proptools.Bool(a.properties.Use_vndk_as_stable) {
  828. if !useVndk {
  829. mctx.PropertyErrorf("use_vndk_as_stable", "not supported for system/system_ext APEXes")
  830. }
  831. if a.minSdkVersionValue(mctx) != "" {
  832. mctx.PropertyErrorf("use_vndk_as_stable", "not supported when min_sdk_version is set")
  833. }
  834. mctx.VisitDirectDepsWithTag(sharedLibTag, func(dep android.Module) {
  835. if c, ok := dep.(*cc.Module); ok && c.IsVndk() {
  836. mctx.PropertyErrorf("use_vndk_as_stable", "Trying to include a VNDK library(%s) while use_vndk_as_stable is true.", dep.Name())
  837. }
  838. })
  839. if mctx.Failed() {
  840. return
  841. }
  842. }
  843. continueApexDepsWalk := func(child, parent android.Module) bool {
  844. am, ok := child.(android.ApexModule)
  845. if !ok || !am.CanHaveApexVariants() {
  846. return false
  847. }
  848. depTag := mctx.OtherModuleDependencyTag(child)
  849. // Check to see if the tag always requires that the child module has an apex variant for every
  850. // apex variant of the parent module. If it does not then it is still possible for something
  851. // else, e.g. the DepIsInSameApex(...) method to decide that a variant is required.
  852. if required, ok := depTag.(android.AlwaysRequireApexVariantTag); ok && required.AlwaysRequireApexVariant() {
  853. return true
  854. }
  855. if !android.IsDepInSameApex(mctx, parent, child) {
  856. return false
  857. }
  858. if excludeVndkLibs {
  859. if c, ok := child.(*cc.Module); ok && c.IsVndk() {
  860. return false
  861. }
  862. }
  863. // By default, all the transitive dependencies are collected, unless filtered out
  864. // above.
  865. return true
  866. }
  867. // Records whether a certain module is included in this apexBundle via direct dependency or
  868. // inndirect dependency.
  869. contents := make(map[string]android.ApexMembership)
  870. mctx.WalkDeps(func(child, parent android.Module) bool {
  871. if !continueApexDepsWalk(child, parent) {
  872. return false
  873. }
  874. // If the parent is apexBundle, this child is directly depended.
  875. _, directDep := parent.(*apexBundle)
  876. depName := mctx.OtherModuleName(child)
  877. contents[depName] = contents[depName].Add(directDep)
  878. return true
  879. })
  880. // The membership information is saved for later access
  881. apexContents := android.NewApexContents(contents)
  882. mctx.SetProvider(ApexBundleInfoProvider, ApexBundleInfo{
  883. Contents: apexContents,
  884. })
  885. minSdkVersion := a.minSdkVersion(mctx)
  886. // When min_sdk_version is not set, the apex is built against FutureApiLevel.
  887. if minSdkVersion.IsNone() {
  888. minSdkVersion = android.FutureApiLevel
  889. }
  890. // This is the main part of this mutator. Mark the collected dependencies that they need to
  891. // be built for this apexBundle.
  892. apexVariationName := mctx.ModuleName() // could be com.android.foo
  893. a.properties.ApexVariationName = apexVariationName
  894. testApexes := []string{}
  895. if a.testApex {
  896. testApexes = []string{apexVariationName}
  897. }
  898. apexInfo := android.ApexInfo{
  899. ApexVariationName: apexVariationName,
  900. MinSdkVersion: minSdkVersion,
  901. Updatable: a.Updatable(),
  902. UsePlatformApis: a.UsePlatformApis(),
  903. InApexVariants: []string{apexVariationName},
  904. InApexModules: []string{a.Name()}, // could be com.mycompany.android.foo
  905. ApexContents: []*android.ApexContents{apexContents},
  906. TestApexes: testApexes,
  907. }
  908. mctx.WalkDeps(func(child, parent android.Module) bool {
  909. if !continueApexDepsWalk(child, parent) {
  910. return false
  911. }
  912. child.(android.ApexModule).BuildForApex(apexInfo) // leave a mark!
  913. return true
  914. })
  915. if a.dynamic_common_lib_apex() {
  916. mctx.SetProvider(DCLAInfoProvider, DCLAInfo{
  917. ProvidedLibs: a.properties.Native_shared_libs,
  918. })
  919. }
  920. }
  921. type ApexInfoMutator interface {
  922. // ApexVariationName returns the name of the APEX variation to use in the apex
  923. // mutator etc. It is the same name as ApexInfo.ApexVariationName.
  924. ApexVariationName() string
  925. // ApexInfoMutator implementations must call BuildForApex(ApexInfo) on any modules that are
  926. // depended upon by an apex and which require an apex specific variant.
  927. ApexInfoMutator(android.TopDownMutatorContext)
  928. }
  929. // apexInfoMutator delegates the work of identifying which modules need an ApexInfo and apex
  930. // specific variant to modules that support the ApexInfoMutator.
  931. // It also propagates updatable=true to apps of updatable apexes
  932. func apexInfoMutator(mctx android.TopDownMutatorContext) {
  933. if !mctx.Module().Enabled() {
  934. return
  935. }
  936. if a, ok := mctx.Module().(ApexInfoMutator); ok {
  937. a.ApexInfoMutator(mctx)
  938. }
  939. enforceAppUpdatability(mctx)
  940. }
  941. // apexStrictUpdatibilityLintMutator propagates strict_updatability_linting to transitive deps of a mainline module
  942. // This check is enforced for updatable modules
  943. func apexStrictUpdatibilityLintMutator(mctx android.TopDownMutatorContext) {
  944. if !mctx.Module().Enabled() {
  945. return
  946. }
  947. if apex, ok := mctx.Module().(*apexBundle); ok && apex.checkStrictUpdatabilityLinting() {
  948. mctx.WalkDeps(func(child, parent android.Module) bool {
  949. // b/208656169 Do not propagate strict updatability linting to libcore/
  950. // These libs are available on the classpath during compilation
  951. // These libs are transitive deps of the sdk. See java/sdk.go:decodeSdkDep
  952. // Only skip libraries defined in libcore root, not subdirectories
  953. if mctx.OtherModuleDir(child) == "libcore" {
  954. // Do not traverse transitive deps of libcore/ libs
  955. return false
  956. }
  957. if android.InList(child.Name(), skipLintJavalibAllowlist) {
  958. return false
  959. }
  960. if lintable, ok := child.(java.LintDepSetsIntf); ok {
  961. lintable.SetStrictUpdatabilityLinting(true)
  962. }
  963. // visit transitive deps
  964. return true
  965. })
  966. }
  967. }
  968. // enforceAppUpdatability propagates updatable=true to apps of updatable apexes
  969. func enforceAppUpdatability(mctx android.TopDownMutatorContext) {
  970. if !mctx.Module().Enabled() {
  971. return
  972. }
  973. if apex, ok := mctx.Module().(*apexBundle); ok && apex.Updatable() {
  974. // checking direct deps is sufficient since apex->apk is a direct edge, even when inherited via apex_defaults
  975. mctx.VisitDirectDeps(func(module android.Module) {
  976. // ignore android_test_app
  977. if app, ok := module.(*java.AndroidApp); ok {
  978. app.SetUpdatable(true)
  979. }
  980. })
  981. }
  982. }
  983. // TODO: b/215736885 Whittle the denylist
  984. // Transitive deps of certain mainline modules baseline NewApi errors
  985. // Skip these mainline modules for now
  986. var (
  987. skipStrictUpdatabilityLintAllowlist = []string{
  988. "com.android.art",
  989. "com.android.art.debug",
  990. "com.android.conscrypt",
  991. "com.android.media",
  992. // test apexes
  993. "test_com.android.art",
  994. "test_com.android.conscrypt",
  995. "test_com.android.media",
  996. "test_jitzygote_com.android.art",
  997. }
  998. // TODO: b/215736885 Remove this list
  999. skipLintJavalibAllowlist = []string{
  1000. "conscrypt.module.platform.api.stubs",
  1001. "conscrypt.module.public.api.stubs",
  1002. "conscrypt.module.public.api.stubs.system",
  1003. "conscrypt.module.public.api.stubs.module_lib",
  1004. "framework-media.stubs",
  1005. "framework-media.stubs.system",
  1006. "framework-media.stubs.module_lib",
  1007. }
  1008. )
  1009. func (a *apexBundle) checkStrictUpdatabilityLinting() bool {
  1010. return a.Updatable() && !android.InList(a.ApexVariationName(), skipStrictUpdatabilityLintAllowlist)
  1011. }
  1012. // apexUniqueVariationsMutator checks if any dependencies use unique apex variations. If so, use
  1013. // unique apex variations for this module. See android/apex.go for more about unique apex variant.
  1014. // TODO(jiyong): move this to android/apex.go?
  1015. func apexUniqueVariationsMutator(mctx android.BottomUpMutatorContext) {
  1016. if !mctx.Module().Enabled() {
  1017. return
  1018. }
  1019. if am, ok := mctx.Module().(android.ApexModule); ok {
  1020. android.UpdateUniqueApexVariationsForDeps(mctx, am)
  1021. }
  1022. }
  1023. // apexTestForDepsMutator checks if this module is a test for an apex. If so, add a dependency on
  1024. // the apex in order to retrieve its contents later.
  1025. // TODO(jiyong): move this to android/apex.go?
  1026. func apexTestForDepsMutator(mctx android.BottomUpMutatorContext) {
  1027. if !mctx.Module().Enabled() {
  1028. return
  1029. }
  1030. if am, ok := mctx.Module().(android.ApexModule); ok {
  1031. if testFor := am.TestFor(); len(testFor) > 0 {
  1032. mctx.AddFarVariationDependencies([]blueprint.Variation{
  1033. {Mutator: "os", Variation: am.Target().OsVariation()},
  1034. {"arch", "common"},
  1035. }, testForTag, testFor...)
  1036. }
  1037. }
  1038. }
  1039. // TODO(jiyong): move this to android/apex.go?
  1040. func apexTestForMutator(mctx android.BottomUpMutatorContext) {
  1041. if !mctx.Module().Enabled() {
  1042. return
  1043. }
  1044. if _, ok := mctx.Module().(android.ApexModule); ok {
  1045. var contents []*android.ApexContents
  1046. for _, testFor := range mctx.GetDirectDepsWithTag(testForTag) {
  1047. abInfo := mctx.OtherModuleProvider(testFor, ApexBundleInfoProvider).(ApexBundleInfo)
  1048. contents = append(contents, abInfo.Contents)
  1049. }
  1050. mctx.SetProvider(android.ApexTestForInfoProvider, android.ApexTestForInfo{
  1051. ApexContents: contents,
  1052. })
  1053. }
  1054. }
  1055. // markPlatformAvailability marks whether or not a module can be available to platform. A module
  1056. // cannot be available to platform if 1) it is explicitly marked as not available (i.e.
  1057. // "//apex_available:platform" is absent) or 2) it depends on another module that isn't (or can't
  1058. // be) available to platform
  1059. // TODO(jiyong): move this to android/apex.go?
  1060. func markPlatformAvailability(mctx android.BottomUpMutatorContext) {
  1061. // Host and recovery are not considered as platform
  1062. if mctx.Host() || mctx.Module().InstallInRecovery() {
  1063. return
  1064. }
  1065. am, ok := mctx.Module().(android.ApexModule)
  1066. if !ok {
  1067. return
  1068. }
  1069. availableToPlatform := am.AvailableFor(android.AvailableToPlatform)
  1070. // If any of the dep is not available to platform, this module is also considered as being
  1071. // not available to platform even if it has "//apex_available:platform"
  1072. mctx.VisitDirectDeps(func(child android.Module) {
  1073. if !android.IsDepInSameApex(mctx, am, child) {
  1074. // if the dependency crosses apex boundary, don't consider it
  1075. return
  1076. }
  1077. if dep, ok := child.(android.ApexModule); ok && dep.NotAvailableForPlatform() {
  1078. availableToPlatform = false
  1079. // TODO(b/154889534) trigger an error when 'am' has
  1080. // "//apex_available:platform"
  1081. }
  1082. })
  1083. // Exception 1: check to see if the module always requires it.
  1084. if am.AlwaysRequiresPlatformApexVariant() {
  1085. availableToPlatform = true
  1086. }
  1087. // Exception 2: bootstrap bionic libraries are also always available to platform
  1088. if cc.InstallToBootstrap(mctx.ModuleName(), mctx.Config()) {
  1089. availableToPlatform = true
  1090. }
  1091. if !availableToPlatform {
  1092. am.SetNotAvailableForPlatform()
  1093. }
  1094. }
  1095. // apexMutator visits each module and creates apex variations if the module was marked in the
  1096. // previous run of apexInfoMutator.
  1097. func apexMutator(mctx android.BottomUpMutatorContext) {
  1098. if !mctx.Module().Enabled() {
  1099. return
  1100. }
  1101. // This is the usual path.
  1102. if am, ok := mctx.Module().(android.ApexModule); ok && am.CanHaveApexVariants() {
  1103. android.CreateApexVariations(mctx, am)
  1104. return
  1105. }
  1106. // apexBundle itself is mutated so that it and its dependencies have the same apex variant.
  1107. if ai, ok := mctx.Module().(ApexInfoMutator); ok && apexModuleTypeRequiresVariant(ai) {
  1108. apexBundleName := ai.ApexVariationName()
  1109. mctx.CreateVariations(apexBundleName)
  1110. if strings.HasPrefix(apexBundleName, "com.android.art") {
  1111. // Create an alias from the platform variant. This is done to make
  1112. // test_for dependencies work for modules that are split by the APEX
  1113. // mutator, since test_for dependencies always go to the platform variant.
  1114. // This doesn't happen for normal APEXes that are disjunct, so only do
  1115. // this for the overlapping ART APEXes.
  1116. // TODO(b/183882457): Remove this if the test_for functionality is
  1117. // refactored to depend on the proper APEX variants instead of platform.
  1118. mctx.CreateAliasVariation("", apexBundleName)
  1119. }
  1120. } else if o, ok := mctx.Module().(*OverrideApex); ok {
  1121. apexBundleName := o.GetOverriddenModuleName()
  1122. if apexBundleName == "" {
  1123. mctx.ModuleErrorf("base property is not set")
  1124. return
  1125. }
  1126. mctx.CreateVariations(apexBundleName)
  1127. if strings.HasPrefix(apexBundleName, "com.android.art") {
  1128. // TODO(b/183882457): See note for CreateAliasVariation above.
  1129. mctx.CreateAliasVariation("", apexBundleName)
  1130. }
  1131. }
  1132. }
  1133. // apexModuleTypeRequiresVariant determines whether the module supplied requires an apex specific
  1134. // variant.
  1135. func apexModuleTypeRequiresVariant(module ApexInfoMutator) bool {
  1136. if a, ok := module.(*apexBundle); ok {
  1137. // TODO(jiyong): document the reason why the VNDK APEX is an exception here.
  1138. return !a.vndkApex
  1139. }
  1140. return true
  1141. }
  1142. // See android.UpdateDirectlyInAnyApex
  1143. // TODO(jiyong): move this to android/apex.go?
  1144. func apexDirectlyInAnyMutator(mctx android.BottomUpMutatorContext) {
  1145. if !mctx.Module().Enabled() {
  1146. return
  1147. }
  1148. if am, ok := mctx.Module().(android.ApexModule); ok {
  1149. android.UpdateDirectlyInAnyApex(mctx, am)
  1150. }
  1151. }
  1152. // apexPackaging represents a specific packaging method for an APEX.
  1153. type apexPackaging int
  1154. const (
  1155. // imageApex is a packaging method where contents are included in a filesystem image which
  1156. // is then included in a zip container. This is the most typical way of packaging.
  1157. imageApex apexPackaging = iota
  1158. // zipApex is a packaging method where contents are directly included in the zip container.
  1159. // This is used for host-side testing - because the contents are easily accessible by
  1160. // unzipping the container.
  1161. // TODO(b/279835185) deprecate zipApex
  1162. zipApex
  1163. )
  1164. const (
  1165. // File extensions of an APEX for different packaging methods
  1166. imageApexSuffix = ".apex"
  1167. imageCapexSuffix = ".capex"
  1168. zipApexSuffix = ".zipapex"
  1169. // variant names each of which is for a packaging method
  1170. imageApexType = "image"
  1171. zipApexType = "zip"
  1172. ext4FsType = "ext4"
  1173. f2fsFsType = "f2fs"
  1174. erofsFsType = "erofs"
  1175. )
  1176. // The suffix for the output "file", not the module
  1177. func (a apexPackaging) suffix() string {
  1178. switch a {
  1179. case imageApex:
  1180. return imageApexSuffix
  1181. case zipApex:
  1182. return zipApexSuffix
  1183. default:
  1184. panic(fmt.Errorf("unknown APEX type %d", a))
  1185. }
  1186. }
  1187. func (a apexPackaging) name() string {
  1188. switch a {
  1189. case imageApex:
  1190. return imageApexType
  1191. case zipApex:
  1192. return zipApexType
  1193. default:
  1194. panic(fmt.Errorf("unknown APEX type %d", a))
  1195. }
  1196. }
  1197. // apexPackagingMutator creates one or more variations each of which is for a packaging method.
  1198. func apexPackagingMutator(mctx android.BottomUpMutatorContext) {
  1199. if !mctx.Module().Enabled() {
  1200. return
  1201. }
  1202. if ab, ok := mctx.Module().(*apexBundle); ok {
  1203. var variants []string
  1204. switch proptools.StringDefault(ab.properties.Payload_type, "image") {
  1205. case "image":
  1206. variants = append(variants, imageApexType)
  1207. case "zip":
  1208. variants = append(variants, zipApexType)
  1209. case "both":
  1210. variants = append(variants, imageApexType, zipApexType)
  1211. default:
  1212. mctx.PropertyErrorf("payload_type", "%q is not one of \"image\", \"zip\", or \"both\".", *ab.properties.Payload_type)
  1213. return
  1214. }
  1215. modules := mctx.CreateLocalVariations(variants...)
  1216. for i, v := range variants {
  1217. switch v {
  1218. case imageApexType:
  1219. modules[i].(*apexBundle).properties.ApexType = imageApex
  1220. case zipApexType:
  1221. modules[i].(*apexBundle).properties.ApexType = zipApex
  1222. }
  1223. }
  1224. } else if _, ok := mctx.Module().(*OverrideApex); ok {
  1225. // payload_type is forcibly overridden to "image"
  1226. // TODO(jiyong): is this the right decision?
  1227. mctx.CreateVariations(imageApexType)
  1228. }
  1229. }
  1230. var _ android.DepIsInSameApex = (*apexBundle)(nil)
  1231. // Implements android.DepInInSameApex
  1232. func (a *apexBundle) DepIsInSameApex(_ android.BaseModuleContext, _ android.Module) bool {
  1233. // direct deps of an APEX bundle are all part of the APEX bundle
  1234. // TODO(jiyong): shouldn't we look into the payload field of the dependencyTag?
  1235. return true
  1236. }
  1237. var _ android.OutputFileProducer = (*apexBundle)(nil)
  1238. // Implements android.OutputFileProducer
  1239. func (a *apexBundle) OutputFiles(tag string) (android.Paths, error) {
  1240. switch tag {
  1241. case "", android.DefaultDistTag:
  1242. // This is the default dist path.
  1243. return android.Paths{a.outputFile}, nil
  1244. case imageApexSuffix:
  1245. // uncompressed one
  1246. if a.outputApexFile != nil {
  1247. return android.Paths{a.outputApexFile}, nil
  1248. }
  1249. fallthrough
  1250. default:
  1251. return nil, fmt.Errorf("unsupported module reference tag %q", tag)
  1252. }
  1253. }
  1254. var _ multitree.Exportable = (*apexBundle)(nil)
  1255. func (a *apexBundle) Exportable() bool {
  1256. return true
  1257. }
  1258. func (a *apexBundle) TaggedOutputs() map[string]android.Paths {
  1259. ret := make(map[string]android.Paths)
  1260. ret["apex"] = android.Paths{a.outputFile}
  1261. return ret
  1262. }
  1263. var _ cc.Coverage = (*apexBundle)(nil)
  1264. // Implements cc.Coverage
  1265. func (a *apexBundle) IsNativeCoverageNeeded(ctx android.BaseModuleContext) bool {
  1266. return ctx.Device() && ctx.DeviceConfig().NativeCoverageEnabled()
  1267. }
  1268. // Implements cc.Coverage
  1269. func (a *apexBundle) SetPreventInstall() {
  1270. a.properties.PreventInstall = true
  1271. }
  1272. // Implements cc.Coverage
  1273. func (a *apexBundle) HideFromMake() {
  1274. a.properties.HideFromMake = true
  1275. // This HideFromMake is shadowing the ModuleBase one, call through to it for now.
  1276. // TODO(ccross): untangle these
  1277. a.ModuleBase.HideFromMake()
  1278. }
  1279. // Implements cc.Coverage
  1280. func (a *apexBundle) MarkAsCoverageVariant(coverage bool) {
  1281. a.properties.IsCoverageVariant = coverage
  1282. }
  1283. // Implements cc.Coverage
  1284. func (a *apexBundle) EnableCoverageIfNeeded() {}
  1285. var _ android.ApexBundleDepsInfoIntf = (*apexBundle)(nil)
  1286. // Implements android.ApexBundleDepsInfoIntf
  1287. func (a *apexBundle) Updatable() bool {
  1288. return proptools.BoolDefault(a.properties.Updatable, true)
  1289. }
  1290. func (a *apexBundle) FutureUpdatable() bool {
  1291. return proptools.BoolDefault(a.properties.Future_updatable, false)
  1292. }
  1293. func (a *apexBundle) UsePlatformApis() bool {
  1294. return proptools.BoolDefault(a.properties.Platform_apis, false)
  1295. }
  1296. // getCertString returns the name of the cert that should be used to sign this APEX. This is
  1297. // basically from the "certificate" property, but could be overridden by the device config.
  1298. func (a *apexBundle) getCertString(ctx android.BaseModuleContext) string {
  1299. moduleName := ctx.ModuleName()
  1300. // VNDK APEXes share the same certificate. To avoid adding a new VNDK version to the
  1301. // OVERRIDE_* list, we check with the pseudo module name to see if its certificate is
  1302. // overridden.
  1303. if a.vndkApex {
  1304. moduleName = vndkApexName
  1305. }
  1306. certificate, overridden := ctx.DeviceConfig().OverrideCertificateFor(moduleName)
  1307. if overridden {
  1308. return ":" + certificate
  1309. }
  1310. return String(a.overridableProperties.Certificate)
  1311. }
  1312. // See the installable property
  1313. func (a *apexBundle) installable() bool {
  1314. return !a.properties.PreventInstall && (a.properties.Installable == nil || proptools.Bool(a.properties.Installable))
  1315. }
  1316. // See the generate_hashtree property
  1317. func (a *apexBundle) shouldGenerateHashtree() bool {
  1318. return proptools.BoolDefault(a.properties.Generate_hashtree, true)
  1319. }
  1320. // See the test_only_unsigned_payload property
  1321. func (a *apexBundle) testOnlyShouldSkipPayloadSign() bool {
  1322. return proptools.Bool(a.properties.Test_only_unsigned_payload)
  1323. }
  1324. // See the test_only_force_compression property
  1325. func (a *apexBundle) testOnlyShouldForceCompression() bool {
  1326. return proptools.Bool(a.properties.Test_only_force_compression)
  1327. }
  1328. // See the dynamic_common_lib_apex property
  1329. func (a *apexBundle) dynamic_common_lib_apex() bool {
  1330. return proptools.BoolDefault(a.properties.Dynamic_common_lib_apex, false)
  1331. }
  1332. // See the list of libs to trim
  1333. func (a *apexBundle) libs_to_trim(ctx android.ModuleContext) []string {
  1334. dclaModules := ctx.GetDirectDepsWithTag(dclaTag)
  1335. if len(dclaModules) > 1 {
  1336. panic(fmt.Errorf("expected exactly at most one dcla dependency, got %d", len(dclaModules)))
  1337. }
  1338. if len(dclaModules) > 0 {
  1339. DCLAInfo := ctx.OtherModuleProvider(dclaModules[0], DCLAInfoProvider).(DCLAInfo)
  1340. return DCLAInfo.ProvidedLibs
  1341. }
  1342. return []string{}
  1343. }
  1344. // These functions are interfacing with cc/sanitizer.go. The entire APEX (along with all of its
  1345. // members) can be sanitized, either forcibly, or by the global configuration. For some of the
  1346. // sanitizers, extra dependencies can be forcibly added as well.
  1347. func (a *apexBundle) EnableSanitizer(sanitizerName string) {
  1348. if !android.InList(sanitizerName, a.properties.SanitizerNames) {
  1349. a.properties.SanitizerNames = append(a.properties.SanitizerNames, sanitizerName)
  1350. }
  1351. }
  1352. func (a *apexBundle) IsSanitizerEnabled(config android.Config, sanitizerName string) bool {
  1353. if android.InList(sanitizerName, a.properties.SanitizerNames) {
  1354. return true
  1355. }
  1356. // Then follow the global setting
  1357. var globalSanitizerNames []string
  1358. if a.Host() {
  1359. globalSanitizerNames = config.SanitizeHost()
  1360. } else {
  1361. arches := config.SanitizeDeviceArch()
  1362. if len(arches) == 0 || android.InList(a.Arch().ArchType.Name, arches) {
  1363. globalSanitizerNames = config.SanitizeDevice()
  1364. }
  1365. }
  1366. return android.InList(sanitizerName, globalSanitizerNames)
  1367. }
  1368. func (a *apexBundle) AddSanitizerDependencies(ctx android.BottomUpMutatorContext, sanitizerName string) {
  1369. // TODO(jiyong): move this info (the sanitizer name, the lib name, etc.) to cc/sanitize.go
  1370. // Keep only the mechanism here.
  1371. if ctx.Device() && sanitizerName == "hwaddress" && strings.HasPrefix(a.Name(), "com.android.runtime") {
  1372. imageVariation := a.getImageVariation(ctx)
  1373. for _, target := range ctx.MultiTargets() {
  1374. if target.Arch.ArchType.Multilib == "lib64" {
  1375. addDependenciesForNativeModules(ctx, ApexNativeDependencies{
  1376. Native_shared_libs: []string{"libclang_rt.hwasan"},
  1377. Tests: nil,
  1378. Jni_libs: nil,
  1379. Binaries: nil,
  1380. }, target, imageVariation)
  1381. break
  1382. }
  1383. }
  1384. }
  1385. }
  1386. // apexFileFor<Type> functions below create an apexFile struct for a given Soong module. The
  1387. // returned apexFile saves information about the Soong module that will be used for creating the
  1388. // build rules.
  1389. func apexFileForNativeLibrary(ctx android.BaseModuleContext, ccMod *cc.Module, handleSpecialLibs bool) apexFile {
  1390. // Decide the APEX-local directory by the multilib of the library In the future, we may
  1391. // query this to the module.
  1392. // TODO(jiyong): use the new PackagingSpec
  1393. var dirInApex string
  1394. switch ccMod.Arch().ArchType.Multilib {
  1395. case "lib32":
  1396. dirInApex = "lib"
  1397. case "lib64":
  1398. dirInApex = "lib64"
  1399. }
  1400. if ccMod.Target().NativeBridge == android.NativeBridgeEnabled {
  1401. dirInApex = filepath.Join(dirInApex, ccMod.Target().NativeBridgeRelativePath)
  1402. }
  1403. if handleSpecialLibs && cc.InstallToBootstrap(ccMod.BaseModuleName(), ctx.Config()) {
  1404. // Special case for Bionic libs and other libs installed with them. This is to
  1405. // prevent those libs from being included in the search path
  1406. // /apex/com.android.runtime/${LIB}. This exclusion is required because those libs
  1407. // in the Runtime APEX are available via the legacy paths in /system/lib/. By the
  1408. // init process, the libs in the APEX are bind-mounted to the legacy paths and thus
  1409. // will be loaded into the default linker namespace (aka "platform" namespace). If
  1410. // the libs are directly in /apex/com.android.runtime/${LIB} then the same libs will
  1411. // be loaded again into the runtime linker namespace, which will result in double
  1412. // loading of them, which isn't supported.
  1413. dirInApex = filepath.Join(dirInApex, "bionic")
  1414. }
  1415. // This needs to go after the runtime APEX handling because otherwise we would get
  1416. // weird paths like lib64/rel_install_path/bionic rather than
  1417. // lib64/bionic/rel_install_path.
  1418. dirInApex = filepath.Join(dirInApex, ccMod.RelativeInstallPath())
  1419. fileToCopy := android.OutputFileForModule(ctx, ccMod, "")
  1420. androidMkModuleName := ccMod.BaseModuleName() + ccMod.Properties.SubName
  1421. return newApexFile(ctx, fileToCopy, androidMkModuleName, dirInApex, nativeSharedLib, ccMod)
  1422. }
  1423. func apexFileForExecutable(ctx android.BaseModuleContext, cc *cc.Module) apexFile {
  1424. dirInApex := "bin"
  1425. if cc.Target().NativeBridge == android.NativeBridgeEnabled {
  1426. dirInApex = filepath.Join(dirInApex, cc.Target().NativeBridgeRelativePath)
  1427. }
  1428. dirInApex = filepath.Join(dirInApex, cc.RelativeInstallPath())
  1429. fileToCopy := android.OutputFileForModule(ctx, cc, "")
  1430. androidMkModuleName := cc.BaseModuleName() + cc.Properties.SubName
  1431. af := newApexFile(ctx, fileToCopy, androidMkModuleName, dirInApex, nativeExecutable, cc)
  1432. af.symlinks = cc.Symlinks()
  1433. af.dataPaths = cc.DataPaths()
  1434. return af
  1435. }
  1436. func apexFileForRustExecutable(ctx android.BaseModuleContext, rustm *rust.Module) apexFile {
  1437. dirInApex := "bin"
  1438. if rustm.Target().NativeBridge == android.NativeBridgeEnabled {
  1439. dirInApex = filepath.Join(dirInApex, rustm.Target().NativeBridgeRelativePath)
  1440. }
  1441. fileToCopy := android.OutputFileForModule(ctx, rustm, "")
  1442. androidMkModuleName := rustm.BaseModuleName() + rustm.Properties.SubName
  1443. af := newApexFile(ctx, fileToCopy, androidMkModuleName, dirInApex, nativeExecutable, rustm)
  1444. return af
  1445. }
  1446. func apexFileForRustLibrary(ctx android.BaseModuleContext, rustm *rust.Module) apexFile {
  1447. // Decide the APEX-local directory by the multilib of the library
  1448. // In the future, we may query this to the module.
  1449. var dirInApex string
  1450. switch rustm.Arch().ArchType.Multilib {
  1451. case "lib32":
  1452. dirInApex = "lib"
  1453. case "lib64":
  1454. dirInApex = "lib64"
  1455. }
  1456. if rustm.Target().NativeBridge == android.NativeBridgeEnabled {
  1457. dirInApex = filepath.Join(dirInApex, rustm.Target().NativeBridgeRelativePath)
  1458. }
  1459. fileToCopy := android.OutputFileForModule(ctx, rustm, "")
  1460. androidMkModuleName := rustm.BaseModuleName() + rustm.Properties.SubName
  1461. return newApexFile(ctx, fileToCopy, androidMkModuleName, dirInApex, nativeSharedLib, rustm)
  1462. }
  1463. func apexFileForPyBinary(ctx android.BaseModuleContext, py *python.PythonBinaryModule) apexFile {
  1464. dirInApex := "bin"
  1465. fileToCopy := py.HostToolPath().Path()
  1466. return newApexFile(ctx, fileToCopy, py.BaseModuleName(), dirInApex, pyBinary, py)
  1467. }
  1468. func apexFileForGoBinary(ctx android.BaseModuleContext, depName string, gb bootstrap.GoBinaryTool) apexFile {
  1469. dirInApex := "bin"
  1470. fileToCopy := android.PathForGoBinary(ctx, gb)
  1471. // NB: Since go binaries are static we don't need the module for anything here, which is
  1472. // good since the go tool is a blueprint.Module not an android.Module like we would
  1473. // normally use.
  1474. //
  1475. return newApexFile(ctx, fileToCopy, depName, dirInApex, goBinary, nil)
  1476. }
  1477. func apexFileForShBinary(ctx android.BaseModuleContext, sh *sh.ShBinary) apexFile {
  1478. dirInApex := filepath.Join("bin", sh.SubDir())
  1479. if sh.Target().NativeBridge == android.NativeBridgeEnabled {
  1480. dirInApex = filepath.Join(dirInApex, sh.Target().NativeBridgeRelativePath)
  1481. }
  1482. fileToCopy := sh.OutputFile()
  1483. af := newApexFile(ctx, fileToCopy, sh.BaseModuleName(), dirInApex, shBinary, sh)
  1484. af.symlinks = sh.Symlinks()
  1485. return af
  1486. }
  1487. func apexFileForPrebuiltEtc(ctx android.BaseModuleContext, prebuilt prebuilt_etc.PrebuiltEtcModule, depName string) apexFile {
  1488. dirInApex := filepath.Join(prebuilt.BaseDir(), prebuilt.SubDir())
  1489. fileToCopy := prebuilt.OutputFile()
  1490. return newApexFile(ctx, fileToCopy, depName, dirInApex, etc, prebuilt)
  1491. }
  1492. func apexFileForCompatConfig(ctx android.BaseModuleContext, config java.PlatformCompatConfigIntf, depName string) apexFile {
  1493. dirInApex := filepath.Join("etc", config.SubDir())
  1494. fileToCopy := config.CompatConfig()
  1495. return newApexFile(ctx, fileToCopy, depName, dirInApex, etc, config)
  1496. }
  1497. // javaModule is an interface to handle all Java modules (java_library, dex_import, etc) in the same
  1498. // way.
  1499. type javaModule interface {
  1500. android.Module
  1501. BaseModuleName() string
  1502. DexJarBuildPath() java.OptionalDexJarPath
  1503. JacocoReportClassesFile() android.Path
  1504. LintDepSets() java.LintDepSets
  1505. Stem() string
  1506. }
  1507. var _ javaModule = (*java.Library)(nil)
  1508. var _ javaModule = (*java.Import)(nil)
  1509. var _ javaModule = (*java.SdkLibrary)(nil)
  1510. var _ javaModule = (*java.DexImport)(nil)
  1511. var _ javaModule = (*java.SdkLibraryImport)(nil)
  1512. // apexFileForJavaModule creates an apexFile for a java module's dex implementation jar.
  1513. func apexFileForJavaModule(ctx android.BaseModuleContext, module javaModule) apexFile {
  1514. return apexFileForJavaModuleWithFile(ctx, module, module.DexJarBuildPath().PathOrNil())
  1515. }
  1516. // apexFileForJavaModuleWithFile creates an apexFile for a java module with the supplied file.
  1517. func apexFileForJavaModuleWithFile(ctx android.BaseModuleContext, module javaModule, dexImplementationJar android.Path) apexFile {
  1518. dirInApex := "javalib"
  1519. af := newApexFile(ctx, dexImplementationJar, module.BaseModuleName(), dirInApex, javaSharedLib, module)
  1520. af.jacocoReportClassesFile = module.JacocoReportClassesFile()
  1521. af.lintDepSets = module.LintDepSets()
  1522. af.customStem = module.Stem() + ".jar"
  1523. if dexpreopter, ok := module.(java.DexpreopterInterface); ok {
  1524. for _, install := range dexpreopter.DexpreoptBuiltInstalledForApex() {
  1525. af.requiredModuleNames = append(af.requiredModuleNames, install.FullModuleName())
  1526. }
  1527. }
  1528. return af
  1529. }
  1530. func apexFileForJavaModuleProfile(ctx android.BaseModuleContext, module javaModule) *apexFile {
  1531. if dexpreopter, ok := module.(java.DexpreopterInterface); ok {
  1532. if profilePathOnHost := dexpreopter.OutputProfilePathOnHost(); profilePathOnHost != nil {
  1533. dirInApex := "javalib"
  1534. af := newApexFile(ctx, profilePathOnHost, module.BaseModuleName()+"-profile", dirInApex, etc, nil)
  1535. af.customStem = module.Stem() + ".jar.prof"
  1536. return &af
  1537. }
  1538. }
  1539. return nil
  1540. }
  1541. // androidApp is an interface to handle all app modules (android_app, android_app_import, etc.) in
  1542. // the same way.
  1543. type androidApp interface {
  1544. android.Module
  1545. Privileged() bool
  1546. InstallApkName() string
  1547. OutputFile() android.Path
  1548. JacocoReportClassesFile() android.Path
  1549. Certificate() java.Certificate
  1550. BaseModuleName() string
  1551. LintDepSets() java.LintDepSets
  1552. PrivAppAllowlist() android.OptionalPath
  1553. }
  1554. var _ androidApp = (*java.AndroidApp)(nil)
  1555. var _ androidApp = (*java.AndroidAppImport)(nil)
  1556. func sanitizedBuildIdForPath(ctx android.BaseModuleContext) string {
  1557. buildId := ctx.Config().BuildId()
  1558. // The build ID is used as a suffix for a filename, so ensure that
  1559. // the set of characters being used are sanitized.
  1560. // - any word character: [a-zA-Z0-9_]
  1561. // - dots: .
  1562. // - dashes: -
  1563. validRegex := regexp.MustCompile(`^[\w\.\-\_]+$`)
  1564. if !validRegex.MatchString(buildId) {
  1565. ctx.ModuleErrorf("Unable to use build id %s as filename suffix, valid characters are [a-z A-Z 0-9 _ . -].", buildId)
  1566. }
  1567. return buildId
  1568. }
  1569. func apexFilesForAndroidApp(ctx android.BaseModuleContext, aapp androidApp) []apexFile {
  1570. appDir := "app"
  1571. if aapp.Privileged() {
  1572. appDir = "priv-app"
  1573. }
  1574. // TODO(b/224589412, b/226559955): Ensure that the subdirname is suffixed
  1575. // so that PackageManager correctly invalidates the existing installed apk
  1576. // in favour of the new APK-in-APEX. See bugs for more information.
  1577. dirInApex := filepath.Join(appDir, aapp.InstallApkName()+"@"+sanitizedBuildIdForPath(ctx))
  1578. fileToCopy := aapp.OutputFile()
  1579. af := newApexFile(ctx, fileToCopy, aapp.BaseModuleName(), dirInApex, app, aapp)
  1580. af.jacocoReportClassesFile = aapp.JacocoReportClassesFile()
  1581. af.lintDepSets = aapp.LintDepSets()
  1582. af.certificate = aapp.Certificate()
  1583. if app, ok := aapp.(interface {
  1584. OverriddenManifestPackageName() string
  1585. }); ok {
  1586. af.overriddenPackageName = app.OverriddenManifestPackageName()
  1587. }
  1588. apexFiles := []apexFile{}
  1589. if allowlist := aapp.PrivAppAllowlist(); allowlist.Valid() {
  1590. dirInApex := filepath.Join("etc", "permissions")
  1591. privAppAllowlist := newApexFile(ctx, allowlist.Path(), aapp.BaseModuleName()+"_privapp", dirInApex, etc, aapp)
  1592. apexFiles = append(apexFiles, privAppAllowlist)
  1593. }
  1594. apexFiles = append(apexFiles, af)
  1595. return apexFiles
  1596. }
  1597. func apexFileForRuntimeResourceOverlay(ctx android.BaseModuleContext, rro java.RuntimeResourceOverlayModule) apexFile {
  1598. rroDir := "overlay"
  1599. dirInApex := filepath.Join(rroDir, rro.Theme())
  1600. fileToCopy := rro.OutputFile()
  1601. af := newApexFile(ctx, fileToCopy, rro.Name(), dirInApex, app, rro)
  1602. af.certificate = rro.Certificate()
  1603. if a, ok := rro.(interface {
  1604. OverriddenManifestPackageName() string
  1605. }); ok {
  1606. af.overriddenPackageName = a.OverriddenManifestPackageName()
  1607. }
  1608. return af
  1609. }
  1610. func apexFileForBpfProgram(ctx android.BaseModuleContext, builtFile android.Path, apex_sub_dir string, bpfProgram bpf.BpfModule) apexFile {
  1611. dirInApex := filepath.Join("etc", "bpf", apex_sub_dir)
  1612. return newApexFile(ctx, builtFile, builtFile.Base(), dirInApex, etc, bpfProgram)
  1613. }
  1614. func apexFileForFilesystem(ctx android.BaseModuleContext, buildFile android.Path, fs filesystem.Filesystem) apexFile {
  1615. dirInApex := filepath.Join("etc", "fs")
  1616. return newApexFile(ctx, buildFile, buildFile.Base(), dirInApex, etc, fs)
  1617. }
  1618. // WalkPayloadDeps visits dependencies that contributes to the payload of this APEX. For each of the
  1619. // visited module, the `do` callback is executed. Returning true in the callback continues the visit
  1620. // to the child modules. Returning false makes the visit to continue in the sibling or the parent
  1621. // modules. This is used in check* functions below.
  1622. func (a *apexBundle) WalkPayloadDeps(ctx android.ModuleContext, do android.PayloadDepsCallback) {
  1623. ctx.WalkDeps(func(child, parent android.Module) bool {
  1624. am, ok := child.(android.ApexModule)
  1625. if !ok || !am.CanHaveApexVariants() {
  1626. return false
  1627. }
  1628. // Filter-out unwanted depedendencies
  1629. depTag := ctx.OtherModuleDependencyTag(child)
  1630. if _, ok := depTag.(android.ExcludeFromApexContentsTag); ok {
  1631. return false
  1632. }
  1633. if dt, ok := depTag.(*dependencyTag); ok && !dt.payload {
  1634. return false
  1635. }
  1636. ai := ctx.OtherModuleProvider(child, android.ApexInfoProvider).(android.ApexInfo)
  1637. externalDep := !android.InList(ctx.ModuleName(), ai.InApexVariants)
  1638. // Visit actually
  1639. return do(ctx, parent, am, externalDep)
  1640. })
  1641. }
  1642. // filesystem type of the apex_payload.img inside the APEX. Currently, ext4 and f2fs are supported.
  1643. type fsType int
  1644. const (
  1645. ext4 fsType = iota
  1646. f2fs
  1647. erofs
  1648. )
  1649. func (f fsType) string() string {
  1650. switch f {
  1651. case ext4:
  1652. return ext4FsType
  1653. case f2fs:
  1654. return f2fsFsType
  1655. case erofs:
  1656. return erofsFsType
  1657. default:
  1658. panic(fmt.Errorf("unknown APEX payload type %d", f))
  1659. }
  1660. }
  1661. var _ android.MixedBuildBuildable = (*apexBundle)(nil)
  1662. func (a *apexBundle) IsMixedBuildSupported(ctx android.BaseModuleContext) bool {
  1663. return a.properties.ApexType == imageApex
  1664. }
  1665. func (a *apexBundle) QueueBazelCall(ctx android.BaseModuleContext) {
  1666. bazelCtx := ctx.Config().BazelContext
  1667. bazelCtx.QueueBazelRequest(a.GetBazelLabel(ctx, a), cquery.GetApexInfo, android.GetConfigKey(ctx))
  1668. }
  1669. // GetBazelLabel returns the bazel label of this apexBundle, or the label of the
  1670. // override_apex module overriding this apexBundle. An apexBundle can be
  1671. // overridden by different override_apex modules (e.g. Google or Go variants),
  1672. // which is handled by the overrides mutators.
  1673. func (a *apexBundle) GetBazelLabel(ctx android.BazelConversionPathContext, module blueprint.Module) string {
  1674. return a.BazelModuleBase.GetBazelLabel(ctx, a)
  1675. }
  1676. func (a *apexBundle) ProcessBazelQueryResponse(ctx android.ModuleContext) {
  1677. if !a.commonBuildActions(ctx) {
  1678. return
  1679. }
  1680. a.setApexTypeAndSuffix(ctx)
  1681. a.setPayloadFsType(ctx)
  1682. a.setSystemLibLink(ctx)
  1683. if a.properties.ApexType != zipApex {
  1684. a.compatSymlinks = makeCompatSymlinks(a.BaseModuleName(), ctx, a.primaryApexType)
  1685. }
  1686. bazelCtx := ctx.Config().BazelContext
  1687. outputs, err := bazelCtx.GetApexInfo(a.GetBazelLabel(ctx, a), android.GetConfigKey(ctx))
  1688. if err != nil {
  1689. ctx.ModuleErrorf(err.Error())
  1690. return
  1691. }
  1692. a.installDir = android.PathForModuleInstall(ctx, "apex")
  1693. // Set the output file to .apex or .capex depending on the compression configuration.
  1694. a.setCompression(ctx)
  1695. if a.isCompressed {
  1696. a.outputApexFile = android.PathForBazelOutRelative(ctx, ctx.ModuleDir(), outputs.SignedCompressedOutput)
  1697. } else {
  1698. a.outputApexFile = android.PathForBazelOutRelative(ctx, ctx.ModuleDir(), outputs.SignedOutput)
  1699. }
  1700. a.outputFile = a.outputApexFile
  1701. if len(outputs.TidyFiles) > 0 {
  1702. tidyFiles := android.PathsForBazelOut(ctx, outputs.TidyFiles)
  1703. a.outputFile = android.AttachValidationActions(ctx, a.outputFile, tidyFiles)
  1704. }
  1705. // TODO(b/257829940): These are used by the apex_keys_text singleton; would probably be a clearer
  1706. // interface if these were set in a provider rather than the module itself
  1707. a.publicKeyFile = android.PathForBazelOut(ctx, outputs.BundleKeyInfo[0])
  1708. a.privateKeyFile = android.PathForBazelOut(ctx, outputs.BundleKeyInfo[1])
  1709. a.containerCertificateFile = android.PathForBazelOut(ctx, outputs.ContainerKeyInfo[0])
  1710. a.containerPrivateKeyFile = android.PathForBazelOut(ctx, outputs.ContainerKeyInfo[1])
  1711. // Ensure ApexMkInfo.install_to_system make module names are installed as
  1712. // part of a bundled build.
  1713. a.makeModulesToInstall = append(a.makeModulesToInstall, outputs.MakeModulesToInstall...)
  1714. apexType := a.properties.ApexType
  1715. switch apexType {
  1716. case imageApex:
  1717. a.bundleModuleFile = android.PathForBazelOut(ctx, outputs.BundleFile)
  1718. a.nativeApisUsedByModuleFile = android.ModuleOutPath(android.PathForBazelOut(ctx, outputs.SymbolsUsedByApex))
  1719. a.nativeApisBackedByModuleFile = android.ModuleOutPath(android.PathForBazelOut(ctx, outputs.BackingLibs))
  1720. // TODO(b/239084755): Generate the java api using.xml file from Bazel.
  1721. a.javaApisUsedByModuleFile = android.ModuleOutPath(android.PathForBazelOut(ctx, outputs.JavaSymbolsUsedByApex))
  1722. a.installedFilesFile = android.ModuleOutPath(android.PathForBazelOut(ctx, outputs.InstalledFiles))
  1723. installSuffix := imageApexSuffix
  1724. if a.isCompressed {
  1725. installSuffix = imageCapexSuffix
  1726. }
  1727. a.installedFile = ctx.InstallFile(a.installDir, a.Name()+installSuffix, a.outputFile,
  1728. a.compatSymlinks.Paths()...)
  1729. default:
  1730. panic(fmt.Errorf("internal error: unexpected apex_type for the ProcessBazelQueryResponse: %v", a.properties.ApexType))
  1731. }
  1732. // filesInfo in mixed mode must retrieve all information about the apex's
  1733. // contents completely from the Starlark providers. It should never rely on
  1734. // Android.bp information, as they might not exist for fully migrated
  1735. // dependencies.
  1736. //
  1737. // Prevent accidental writes to filesInfo in the earlier parts Soong by
  1738. // asserting it to be nil.
  1739. if a.filesInfo != nil {
  1740. panic(
  1741. fmt.Errorf("internal error: filesInfo must be nil for an apex handled by Bazel. " +
  1742. "Did something else set filesInfo before this line of code?"))
  1743. }
  1744. for _, f := range outputs.PayloadFilesInfo {
  1745. fileInfo := apexFile{
  1746. isBazelPrebuilt: true,
  1747. builtFile: android.PathForBazelOut(ctx, f["built_file"]),
  1748. unstrippedBuiltFile: android.PathForBazelOut(ctx, f["unstripped_built_file"]),
  1749. androidMkModuleName: f["make_module_name"],
  1750. installDir: f["install_dir"],
  1751. class: classes[f["class"]],
  1752. customStem: f["basename"],
  1753. moduleDir: f["package"],
  1754. }
  1755. arch := f["arch"]
  1756. fileInfo.arch = arch
  1757. if len(arch) > 0 {
  1758. fileInfo.multilib = "lib32"
  1759. if strings.HasSuffix(arch, "64") {
  1760. fileInfo.multilib = "lib64"
  1761. }
  1762. }
  1763. a.filesInfo = append(a.filesInfo, fileInfo)
  1764. }
  1765. }
  1766. func (a *apexBundle) setCompression(ctx android.ModuleContext) {
  1767. if a.properties.ApexType != imageApex {
  1768. a.isCompressed = false
  1769. } else if a.testOnlyShouldForceCompression() {
  1770. a.isCompressed = true
  1771. } else {
  1772. a.isCompressed = ctx.Config().ApexCompressionEnabled() && a.isCompressable()
  1773. }
  1774. }
  1775. func (a *apexBundle) setSystemLibLink(ctx android.ModuleContext) {
  1776. // Optimization. If we are building bundled APEX, for the files that are gathered due to the
  1777. // transitive dependencies, don't place them inside the APEX, but place a symlink pointing
  1778. // the same library in the system partition, thus effectively sharing the same libraries
  1779. // across the APEX boundary. For unbundled APEX, all the gathered files are actually placed
  1780. // in the APEX.
  1781. a.linkToSystemLib = !ctx.Config().UnbundledBuild() && a.installable()
  1782. // APEXes targeting other than system/system_ext partitions use vendor/product variants.
  1783. // So we can't link them to /system/lib libs which are core variants.
  1784. if a.SocSpecific() || a.DeviceSpecific() || (a.ProductSpecific() && ctx.Config().EnforceProductPartitionInterface()) {
  1785. a.linkToSystemLib = false
  1786. }
  1787. forced := ctx.Config().ForceApexSymlinkOptimization()
  1788. updatable := a.Updatable() || a.FutureUpdatable()
  1789. // We don't need the optimization for updatable APEXes, as it might give false signal
  1790. // to the system health when the APEXes are still bundled (b/149805758).
  1791. if !forced && updatable && a.properties.ApexType == imageApex {
  1792. a.linkToSystemLib = false
  1793. }
  1794. // We also don't want the optimization for host APEXes, because it doesn't make sense.
  1795. if ctx.Host() {
  1796. a.linkToSystemLib = false
  1797. }
  1798. }
  1799. func (a *apexBundle) setPayloadFsType(ctx android.ModuleContext) {
  1800. switch proptools.StringDefault(a.properties.Payload_fs_type, ext4FsType) {
  1801. case ext4FsType:
  1802. a.payloadFsType = ext4
  1803. case f2fsFsType:
  1804. a.payloadFsType = f2fs
  1805. case erofsFsType:
  1806. a.payloadFsType = erofs
  1807. default:
  1808. ctx.PropertyErrorf("payload_fs_type", "%q is not a valid filesystem for apex [ext4, f2fs, erofs]", *a.properties.Payload_fs_type)
  1809. }
  1810. }
  1811. func (a *apexBundle) setApexTypeAndSuffix(ctx android.ModuleContext) {
  1812. // Set suffix and primaryApexType depending on the ApexType
  1813. switch a.properties.ApexType {
  1814. case imageApex:
  1815. a.suffix = ""
  1816. a.primaryApexType = true
  1817. case zipApex:
  1818. if proptools.String(a.properties.Payload_type) == "zip" {
  1819. a.suffix = ""
  1820. a.primaryApexType = true
  1821. } else {
  1822. a.suffix = zipApexSuffix
  1823. }
  1824. }
  1825. }
  1826. func (a *apexBundle) isCompressable() bool {
  1827. return proptools.BoolDefault(a.overridableProperties.Compressible, false) && !a.testApex
  1828. }
  1829. func (a *apexBundle) commonBuildActions(ctx android.ModuleContext) bool {
  1830. a.checkApexAvailability(ctx)
  1831. a.checkUpdatable(ctx)
  1832. a.CheckMinSdkVersion(ctx)
  1833. a.checkStaticLinkingToStubLibraries(ctx)
  1834. a.checkStaticExecutables(ctx)
  1835. if len(a.properties.Tests) > 0 && !a.testApex {
  1836. ctx.PropertyErrorf("tests", "property allowed only in apex_test module type")
  1837. return false
  1838. }
  1839. return true
  1840. }
  1841. type visitorContext struct {
  1842. // all the files that will be included in this APEX
  1843. filesInfo []apexFile
  1844. // native lib dependencies
  1845. provideNativeLibs []string
  1846. requireNativeLibs []string
  1847. handleSpecialLibs bool
  1848. // if true, raise error on duplicate apexFile
  1849. checkDuplicate bool
  1850. }
  1851. func (vctx *visitorContext) normalizeFileInfo(mctx android.ModuleContext) {
  1852. encountered := make(map[string]apexFile)
  1853. for _, f := range vctx.filesInfo {
  1854. dest := filepath.Join(f.installDir, f.builtFile.Base())
  1855. if e, ok := encountered[dest]; !ok {
  1856. encountered[dest] = f
  1857. } else {
  1858. if vctx.checkDuplicate && f.builtFile.String() != e.builtFile.String() {
  1859. mctx.ModuleErrorf("apex file %v is provided by two different files %v and %v",
  1860. dest, e.builtFile, f.builtFile)
  1861. return
  1862. }
  1863. // If a module is directly included and also transitively depended on
  1864. // consider it as directly included.
  1865. e.transitiveDep = e.transitiveDep && f.transitiveDep
  1866. encountered[dest] = e
  1867. }
  1868. }
  1869. vctx.filesInfo = vctx.filesInfo[:0]
  1870. for _, v := range encountered {
  1871. vctx.filesInfo = append(vctx.filesInfo, v)
  1872. }
  1873. sort.Slice(vctx.filesInfo, func(i, j int) bool {
  1874. // Sort by destination path so as to ensure consistent ordering even if the source of the files
  1875. // changes.
  1876. return vctx.filesInfo[i].path() < vctx.filesInfo[j].path()
  1877. })
  1878. }
  1879. func (a *apexBundle) depVisitor(vctx *visitorContext, ctx android.ModuleContext, child, parent blueprint.Module) bool {
  1880. depTag := ctx.OtherModuleDependencyTag(child)
  1881. if _, ok := depTag.(android.ExcludeFromApexContentsTag); ok {
  1882. return false
  1883. }
  1884. if mod, ok := child.(android.Module); ok && !mod.Enabled() {
  1885. return false
  1886. }
  1887. depName := ctx.OtherModuleName(child)
  1888. if _, isDirectDep := parent.(*apexBundle); isDirectDep {
  1889. switch depTag {
  1890. case sharedLibTag, jniLibTag:
  1891. isJniLib := depTag == jniLibTag
  1892. switch ch := child.(type) {
  1893. case *cc.Module:
  1894. fi := apexFileForNativeLibrary(ctx, ch, vctx.handleSpecialLibs)
  1895. fi.isJniLib = isJniLib
  1896. vctx.filesInfo = append(vctx.filesInfo, fi)
  1897. // Collect the list of stub-providing libs except:
  1898. // - VNDK libs are only for vendors
  1899. // - bootstrap bionic libs are treated as provided by system
  1900. if ch.HasStubsVariants() && !a.vndkApex && !cc.InstallToBootstrap(ch.BaseModuleName(), ctx.Config()) {
  1901. vctx.provideNativeLibs = append(vctx.provideNativeLibs, fi.stem())
  1902. }
  1903. return true // track transitive dependencies
  1904. case *rust.Module:
  1905. fi := apexFileForRustLibrary(ctx, ch)
  1906. fi.isJniLib = isJniLib
  1907. vctx.filesInfo = append(vctx.filesInfo, fi)
  1908. return true // track transitive dependencies
  1909. default:
  1910. propertyName := "native_shared_libs"
  1911. if isJniLib {
  1912. propertyName = "jni_libs"
  1913. }
  1914. ctx.PropertyErrorf(propertyName, "%q is not a cc_library or cc_library_shared module", depName)
  1915. }
  1916. case executableTag:
  1917. switch ch := child.(type) {
  1918. case *cc.Module:
  1919. vctx.filesInfo = append(vctx.filesInfo, apexFileForExecutable(ctx, ch))
  1920. return true // track transitive dependencies
  1921. case *python.PythonBinaryModule:
  1922. if ch.HostToolPath().Valid() {
  1923. vctx.filesInfo = append(vctx.filesInfo, apexFileForPyBinary(ctx, ch))
  1924. }
  1925. case bootstrap.GoBinaryTool:
  1926. if a.Host() {
  1927. vctx.filesInfo = append(vctx.filesInfo, apexFileForGoBinary(ctx, depName, ch))
  1928. }
  1929. case *rust.Module:
  1930. vctx.filesInfo = append(vctx.filesInfo, apexFileForRustExecutable(ctx, ch))
  1931. return true // track transitive dependencies
  1932. default:
  1933. ctx.PropertyErrorf("binaries",
  1934. "%q is neither cc_binary, rust_binary, (embedded) py_binary, (host) blueprint_go_binary, nor (host) bootstrap_go_binary", depName)
  1935. }
  1936. case shBinaryTag:
  1937. if csh, ok := child.(*sh.ShBinary); ok {
  1938. vctx.filesInfo = append(vctx.filesInfo, apexFileForShBinary(ctx, csh))
  1939. } else {
  1940. ctx.PropertyErrorf("sh_binaries", "%q is not a sh_binary module", depName)
  1941. }
  1942. case bcpfTag:
  1943. _, ok := child.(*java.BootclasspathFragmentModule)
  1944. if !ok {
  1945. ctx.PropertyErrorf("bootclasspath_fragments", "%q is not a bootclasspath_fragment module", depName)
  1946. return false
  1947. }
  1948. vctx.filesInfo = append(vctx.filesInfo, apexBootclasspathFragmentFiles(ctx, child)...)
  1949. return true
  1950. case sscpfTag:
  1951. if _, ok := child.(*java.SystemServerClasspathModule); !ok {
  1952. ctx.PropertyErrorf("systemserverclasspath_fragments",
  1953. "%q is not a systemserverclasspath_fragment module", depName)
  1954. return false
  1955. }
  1956. if af := apexClasspathFragmentProtoFile(ctx, child); af != nil {
  1957. vctx.filesInfo = append(vctx.filesInfo, *af)
  1958. }
  1959. return true
  1960. case javaLibTag:
  1961. switch child.(type) {
  1962. case *java.Library, *java.SdkLibrary, *java.DexImport, *java.SdkLibraryImport, *java.Import:
  1963. af := apexFileForJavaModule(ctx, child.(javaModule))
  1964. if !af.ok() {
  1965. ctx.PropertyErrorf("java_libs", "%q is not configured to be compiled into dex", depName)
  1966. return false
  1967. }
  1968. vctx.filesInfo = append(vctx.filesInfo, af)
  1969. return true // track transitive dependencies
  1970. default:
  1971. ctx.PropertyErrorf("java_libs", "%q of type %q is not supported", depName, ctx.OtherModuleType(child))
  1972. }
  1973. case androidAppTag:
  1974. switch ap := child.(type) {
  1975. case *java.AndroidApp:
  1976. vctx.filesInfo = append(vctx.filesInfo, apexFilesForAndroidApp(ctx, ap)...)
  1977. return true // track transitive dependencies
  1978. case *java.AndroidAppImport:
  1979. vctx.filesInfo = append(vctx.filesInfo, apexFilesForAndroidApp(ctx, ap)...)
  1980. case *java.AndroidTestHelperApp:
  1981. vctx.filesInfo = append(vctx.filesInfo, apexFilesForAndroidApp(ctx, ap)...)
  1982. case *java.AndroidAppSet:
  1983. appDir := "app"
  1984. if ap.Privileged() {
  1985. appDir = "priv-app"
  1986. }
  1987. // TODO(b/224589412, b/226559955): Ensure that the dirname is
  1988. // suffixed so that PackageManager correctly invalidates the
  1989. // existing installed apk in favour of the new APK-in-APEX.
  1990. // See bugs for more information.
  1991. appDirName := filepath.Join(appDir, ap.BaseModuleName()+"@"+sanitizedBuildIdForPath(ctx))
  1992. af := newApexFile(ctx, ap.OutputFile(), ap.BaseModuleName(), appDirName, appSet, ap)
  1993. af.certificate = java.PresignedCertificate
  1994. vctx.filesInfo = append(vctx.filesInfo, af)
  1995. default:
  1996. ctx.PropertyErrorf("apps", "%q is not an android_app module", depName)
  1997. }
  1998. case rroTag:
  1999. if rro, ok := child.(java.RuntimeResourceOverlayModule); ok {
  2000. vctx.filesInfo = append(vctx.filesInfo, apexFileForRuntimeResourceOverlay(ctx, rro))
  2001. } else {
  2002. ctx.PropertyErrorf("rros", "%q is not an runtime_resource_overlay module", depName)
  2003. }
  2004. case bpfTag:
  2005. if bpfProgram, ok := child.(bpf.BpfModule); ok {
  2006. filesToCopy, _ := bpfProgram.OutputFiles("")
  2007. apex_sub_dir := bpfProgram.SubDir()
  2008. for _, bpfFile := range filesToCopy {
  2009. vctx.filesInfo = append(vctx.filesInfo, apexFileForBpfProgram(ctx, bpfFile, apex_sub_dir, bpfProgram))
  2010. }
  2011. } else {
  2012. ctx.PropertyErrorf("bpfs", "%q is not a bpf module", depName)
  2013. }
  2014. case fsTag:
  2015. if fs, ok := child.(filesystem.Filesystem); ok {
  2016. vctx.filesInfo = append(vctx.filesInfo, apexFileForFilesystem(ctx, fs.OutputPath(), fs))
  2017. } else {
  2018. ctx.PropertyErrorf("filesystems", "%q is not a filesystem module", depName)
  2019. }
  2020. case prebuiltTag:
  2021. if prebuilt, ok := child.(prebuilt_etc.PrebuiltEtcModule); ok {
  2022. vctx.filesInfo = append(vctx.filesInfo, apexFileForPrebuiltEtc(ctx, prebuilt, depName))
  2023. } else {
  2024. ctx.PropertyErrorf("prebuilts", "%q is not a prebuilt_etc module", depName)
  2025. }
  2026. case compatConfigTag:
  2027. if compatConfig, ok := child.(java.PlatformCompatConfigIntf); ok {
  2028. vctx.filesInfo = append(vctx.filesInfo, apexFileForCompatConfig(ctx, compatConfig, depName))
  2029. } else {
  2030. ctx.PropertyErrorf("compat_configs", "%q is not a platform_compat_config module", depName)
  2031. }
  2032. case testTag:
  2033. if ccTest, ok := child.(*cc.Module); ok {
  2034. if ccTest.IsTestPerSrcAllTestsVariation() {
  2035. // Multiple-output test module (where `test_per_src: true`).
  2036. //
  2037. // `ccTest` is the "" ("all tests") variation of a `test_per_src` module.
  2038. // We do not add this variation to `filesInfo`, as it has no output;
  2039. // however, we do add the other variations of this module as indirect
  2040. // dependencies (see below).
  2041. } else {
  2042. // Single-output test module (where `test_per_src: false`).
  2043. af := apexFileForExecutable(ctx, ccTest)
  2044. af.class = nativeTest
  2045. vctx.filesInfo = append(vctx.filesInfo, af)
  2046. }
  2047. return true // track transitive dependencies
  2048. } else {
  2049. ctx.PropertyErrorf("tests", "%q is not a cc module", depName)
  2050. }
  2051. case keyTag:
  2052. if key, ok := child.(*apexKey); ok {
  2053. a.privateKeyFile = key.privateKeyFile
  2054. a.publicKeyFile = key.publicKeyFile
  2055. } else {
  2056. ctx.PropertyErrorf("key", "%q is not an apex_key module", depName)
  2057. }
  2058. case certificateTag:
  2059. if dep, ok := child.(*java.AndroidAppCertificate); ok {
  2060. a.containerCertificateFile = dep.Certificate.Pem
  2061. a.containerPrivateKeyFile = dep.Certificate.Key
  2062. } else {
  2063. ctx.ModuleErrorf("certificate dependency %q must be an android_app_certificate module", depName)
  2064. }
  2065. }
  2066. return false
  2067. }
  2068. if a.vndkApex {
  2069. return false
  2070. }
  2071. // indirect dependencies
  2072. am, ok := child.(android.ApexModule)
  2073. if !ok {
  2074. return false
  2075. }
  2076. // We cannot use a switch statement on `depTag` here as the checked
  2077. // tags used below are private (e.g. `cc.sharedDepTag`).
  2078. if cc.IsSharedDepTag(depTag) || cc.IsRuntimeDepTag(depTag) {
  2079. if ch, ok := child.(*cc.Module); ok {
  2080. if ch.UseVndk() && proptools.Bool(a.properties.Use_vndk_as_stable) && ch.IsVndk() {
  2081. vctx.requireNativeLibs = append(vctx.requireNativeLibs, ":vndk")
  2082. return false
  2083. }
  2084. af := apexFileForNativeLibrary(ctx, ch, vctx.handleSpecialLibs)
  2085. af.transitiveDep = true
  2086. // Always track transitive dependencies for host.
  2087. if a.Host() {
  2088. vctx.filesInfo = append(vctx.filesInfo, af)
  2089. return true
  2090. }
  2091. abInfo := ctx.Provider(ApexBundleInfoProvider).(ApexBundleInfo)
  2092. if !abInfo.Contents.DirectlyInApex(depName) && (ch.IsStubs() || ch.HasStubsVariants()) {
  2093. // If the dependency is a stubs lib, don't include it in this APEX,
  2094. // but make sure that the lib is installed on the device.
  2095. // In case no APEX is having the lib, the lib is installed to the system
  2096. // partition.
  2097. //
  2098. // Always include if we are a host-apex however since those won't have any
  2099. // system libraries.
  2100. //
  2101. // Skip the dependency in unbundled builds where the device image is not
  2102. // being built.
  2103. if ch.IsStubsImplementationRequired() && !am.DirectlyInAnyApex() && !ctx.Config().UnbundledBuild() {
  2104. // we need a module name for Make
  2105. name := ch.ImplementationModuleNameForMake(ctx) + ch.Properties.SubName
  2106. if !android.InList(name, a.makeModulesToInstall) {
  2107. a.makeModulesToInstall = append(a.makeModulesToInstall, name)
  2108. }
  2109. }
  2110. vctx.requireNativeLibs = append(vctx.requireNativeLibs, af.stem())
  2111. // Don't track further
  2112. return false
  2113. }
  2114. // If the dep is not considered to be in the same
  2115. // apex, don't add it to filesInfo so that it is not
  2116. // included in this APEX.
  2117. // TODO(jiyong): move this to at the top of the
  2118. // else-if clause for the indirect dependencies.
  2119. // Currently, that's impossible because we would
  2120. // like to record requiredNativeLibs even when
  2121. // DepIsInSameAPex is false. We also shouldn't do
  2122. // this for host.
  2123. //
  2124. // TODO(jiyong): explain why the same module is passed in twice.
  2125. // Switching the first am to parent breaks lots of tests.
  2126. if !android.IsDepInSameApex(ctx, am, am) {
  2127. return false
  2128. }
  2129. vctx.filesInfo = append(vctx.filesInfo, af)
  2130. return true // track transitive dependencies
  2131. } else if rm, ok := child.(*rust.Module); ok {
  2132. af := apexFileForRustLibrary(ctx, rm)
  2133. af.transitiveDep = true
  2134. vctx.filesInfo = append(vctx.filesInfo, af)
  2135. return true // track transitive dependencies
  2136. }
  2137. } else if cc.IsTestPerSrcDepTag(depTag) {
  2138. if ch, ok := child.(*cc.Module); ok {
  2139. af := apexFileForExecutable(ctx, ch)
  2140. // Handle modules created as `test_per_src` variations of a single test module:
  2141. // use the name of the generated test binary (`fileToCopy`) instead of the name
  2142. // of the original test module (`depName`, shared by all `test_per_src`
  2143. // variations of that module).
  2144. af.androidMkModuleName = filepath.Base(af.builtFile.String())
  2145. // these are not considered transitive dep
  2146. af.transitiveDep = false
  2147. vctx.filesInfo = append(vctx.filesInfo, af)
  2148. return true // track transitive dependencies
  2149. }
  2150. } else if cc.IsHeaderDepTag(depTag) {
  2151. // nothing
  2152. } else if java.IsJniDepTag(depTag) {
  2153. // Because APK-in-APEX embeds jni_libs transitively, we don't need to track transitive deps
  2154. } else if java.IsXmlPermissionsFileDepTag(depTag) {
  2155. if prebuilt, ok := child.(prebuilt_etc.PrebuiltEtcModule); ok {
  2156. vctx.filesInfo = append(vctx.filesInfo, apexFileForPrebuiltEtc(ctx, prebuilt, depName))
  2157. }
  2158. } else if rust.IsDylibDepTag(depTag) {
  2159. if rustm, ok := child.(*rust.Module); ok && rustm.IsInstallableToApex() {
  2160. af := apexFileForRustLibrary(ctx, rustm)
  2161. af.transitiveDep = true
  2162. vctx.filesInfo = append(vctx.filesInfo, af)
  2163. return true // track transitive dependencies
  2164. }
  2165. } else if rust.IsRlibDepTag(depTag) {
  2166. // Rlib is statically linked, but it might have shared lib
  2167. // dependencies. Track them.
  2168. return true
  2169. } else if java.IsBootclasspathFragmentContentDepTag(depTag) {
  2170. // Add the contents of the bootclasspath fragment to the apex.
  2171. switch child.(type) {
  2172. case *java.Library, *java.SdkLibrary:
  2173. javaModule := child.(javaModule)
  2174. af := apexFileForBootclasspathFragmentContentModule(ctx, parent, javaModule)
  2175. if !af.ok() {
  2176. ctx.PropertyErrorf("bootclasspath_fragments",
  2177. "bootclasspath_fragment content %q is not configured to be compiled into dex", depName)
  2178. return false
  2179. }
  2180. vctx.filesInfo = append(vctx.filesInfo, af)
  2181. return true // track transitive dependencies
  2182. default:
  2183. ctx.PropertyErrorf("bootclasspath_fragments",
  2184. "bootclasspath_fragment content %q of type %q is not supported", depName, ctx.OtherModuleType(child))
  2185. }
  2186. } else if java.IsSystemServerClasspathFragmentContentDepTag(depTag) {
  2187. // Add the contents of the systemserverclasspath fragment to the apex.
  2188. switch child.(type) {
  2189. case *java.Library, *java.SdkLibrary:
  2190. af := apexFileForJavaModule(ctx, child.(javaModule))
  2191. vctx.filesInfo = append(vctx.filesInfo, af)
  2192. if profileAf := apexFileForJavaModuleProfile(ctx, child.(javaModule)); profileAf != nil {
  2193. vctx.filesInfo = append(vctx.filesInfo, *profileAf)
  2194. }
  2195. return true // track transitive dependencies
  2196. default:
  2197. ctx.PropertyErrorf("systemserverclasspath_fragments",
  2198. "systemserverclasspath_fragment content %q of type %q is not supported", depName, ctx.OtherModuleType(child))
  2199. }
  2200. } else if _, ok := depTag.(android.CopyDirectlyInAnyApexTag); ok {
  2201. // nothing
  2202. } else if depTag == android.DarwinUniversalVariantTag {
  2203. // nothing
  2204. } else if am.CanHaveApexVariants() && am.IsInstallableToApex() {
  2205. ctx.ModuleErrorf("unexpected tag %s for indirect dependency %q", android.PrettyPrintTag(depTag), depName)
  2206. }
  2207. return false
  2208. }
  2209. func (a *apexBundle) shouldCheckDuplicate(ctx android.ModuleContext) bool {
  2210. // TODO(b/263308293) remove this
  2211. if a.properties.IsCoverageVariant {
  2212. return false
  2213. }
  2214. // TODO(b/263308515) remove this
  2215. if a.testApex {
  2216. return false
  2217. }
  2218. // TODO(b/263309864) remove this
  2219. if a.Host() {
  2220. return false
  2221. }
  2222. if a.Device() && ctx.DeviceConfig().DeviceArch() == "" {
  2223. return false
  2224. }
  2225. return true
  2226. }
  2227. // Creates build rules for an APEX. It consists of the following major steps:
  2228. //
  2229. // 1) do some validity checks such as apex_available, min_sdk_version, etc.
  2230. // 2) traverse the dependency tree to collect apexFile structs from them.
  2231. // 3) some fields in apexBundle struct are configured
  2232. // 4) generate the build rules to create the APEX. This is mostly done in builder.go.
  2233. func (a *apexBundle) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  2234. ////////////////////////////////////////////////////////////////////////////////////////////
  2235. // 1) do some validity checks such as apex_available, min_sdk_version, etc.
  2236. if !a.commonBuildActions(ctx) {
  2237. return
  2238. }
  2239. ////////////////////////////////////////////////////////////////////////////////////////////
  2240. // 2) traverse the dependency tree to collect apexFile structs from them.
  2241. // Collect the module directory for IDE info in java/jdeps.go.
  2242. a.modulePaths = append(a.modulePaths, ctx.ModuleDir())
  2243. // TODO(jiyong): do this using WalkPayloadDeps
  2244. // TODO(jiyong): make this clean!!!
  2245. vctx := visitorContext{
  2246. handleSpecialLibs: !android.Bool(a.properties.Ignore_system_library_special_case),
  2247. checkDuplicate: a.shouldCheckDuplicate(ctx),
  2248. }
  2249. ctx.WalkDepsBlueprint(func(child, parent blueprint.Module) bool { return a.depVisitor(&vctx, ctx, child, parent) })
  2250. vctx.normalizeFileInfo(ctx)
  2251. if a.privateKeyFile == nil {
  2252. if ctx.Config().AllowMissingDependencies() {
  2253. // TODO(b/266099037): a better approach for slim manifests.
  2254. ctx.AddMissingDependencies([]string{String(a.overridableProperties.Key)})
  2255. // Create placeholder paths for later stages that expect to see those paths,
  2256. // though they won't be used.
  2257. var unusedPath = android.PathForModuleOut(ctx, "nonexistentprivatekey")
  2258. ctx.Build(pctx, android.BuildParams{
  2259. Rule: android.ErrorRule,
  2260. Output: unusedPath,
  2261. Args: map[string]string{
  2262. "error": "Private key not available",
  2263. },
  2264. })
  2265. a.privateKeyFile = unusedPath
  2266. } else {
  2267. ctx.PropertyErrorf("key", "private_key for %q could not be found", String(a.overridableProperties.Key))
  2268. return
  2269. }
  2270. }
  2271. if a.publicKeyFile == nil {
  2272. if ctx.Config().AllowMissingDependencies() {
  2273. // TODO(b/266099037): a better approach for slim manifests.
  2274. ctx.AddMissingDependencies([]string{String(a.overridableProperties.Key)})
  2275. // Create placeholder paths for later stages that expect to see those paths,
  2276. // though they won't be used.
  2277. var unusedPath = android.PathForModuleOut(ctx, "nonexistentpublickey")
  2278. ctx.Build(pctx, android.BuildParams{
  2279. Rule: android.ErrorRule,
  2280. Output: unusedPath,
  2281. Args: map[string]string{
  2282. "error": "Public key not available",
  2283. },
  2284. })
  2285. a.publicKeyFile = unusedPath
  2286. } else {
  2287. ctx.PropertyErrorf("key", "public_key for %q could not be found", String(a.overridableProperties.Key))
  2288. return
  2289. }
  2290. }
  2291. ////////////////////////////////////////////////////////////////////////////////////////////
  2292. // 3) some fields in apexBundle struct are configured
  2293. a.installDir = android.PathForModuleInstall(ctx, "apex")
  2294. a.filesInfo = vctx.filesInfo
  2295. a.setApexTypeAndSuffix(ctx)
  2296. a.setPayloadFsType(ctx)
  2297. a.setSystemLibLink(ctx)
  2298. if a.properties.ApexType != zipApex {
  2299. a.compatSymlinks = makeCompatSymlinks(a.BaseModuleName(), ctx, a.primaryApexType)
  2300. }
  2301. ////////////////////////////////////////////////////////////////////////////////////////////
  2302. // 4) generate the build rules to create the APEX. This is done in builder.go.
  2303. a.buildManifest(ctx, vctx.provideNativeLibs, vctx.requireNativeLibs)
  2304. a.buildApex(ctx)
  2305. a.buildApexDependencyInfo(ctx)
  2306. a.buildLintReports(ctx)
  2307. }
  2308. // apexBootclasspathFragmentFiles returns the list of apexFile structures defining the files that
  2309. // the bootclasspath_fragment contributes to the apex.
  2310. func apexBootclasspathFragmentFiles(ctx android.ModuleContext, module blueprint.Module) []apexFile {
  2311. bootclasspathFragmentInfo := ctx.OtherModuleProvider(module, java.BootclasspathFragmentApexContentInfoProvider).(java.BootclasspathFragmentApexContentInfo)
  2312. var filesToAdd []apexFile
  2313. // Add classpaths.proto config.
  2314. if af := apexClasspathFragmentProtoFile(ctx, module); af != nil {
  2315. filesToAdd = append(filesToAdd, *af)
  2316. }
  2317. pathInApex := bootclasspathFragmentInfo.ProfileInstallPathInApex()
  2318. if pathInApex != "" {
  2319. pathOnHost := bootclasspathFragmentInfo.ProfilePathOnHost()
  2320. tempPath := android.PathForModuleOut(ctx, "boot_image_profile", pathInApex)
  2321. if pathOnHost != nil {
  2322. // We need to copy the profile to a temporary path with the right filename because the apexer
  2323. // will take the filename as is.
  2324. ctx.Build(pctx, android.BuildParams{
  2325. Rule: android.Cp,
  2326. Input: pathOnHost,
  2327. Output: tempPath,
  2328. })
  2329. } else {
  2330. // At this point, the boot image profile cannot be generated. It is probably because the boot
  2331. // image profile source file does not exist on the branch, or it is not available for the
  2332. // current build target.
  2333. // However, we cannot enforce the boot image profile to be generated because some build
  2334. // targets (such as module SDK) do not need it. It is only needed when the APEX is being
  2335. // built. Therefore, we create an error rule so that an error will occur at the ninja phase
  2336. // only if the APEX is being built.
  2337. ctx.Build(pctx, android.BuildParams{
  2338. Rule: android.ErrorRule,
  2339. Output: tempPath,
  2340. Args: map[string]string{
  2341. "error": "Boot image profile cannot be generated",
  2342. },
  2343. })
  2344. }
  2345. androidMkModuleName := filepath.Base(pathInApex)
  2346. af := newApexFile(ctx, tempPath, androidMkModuleName, filepath.Dir(pathInApex), etc, nil)
  2347. filesToAdd = append(filesToAdd, af)
  2348. }
  2349. return filesToAdd
  2350. }
  2351. // apexClasspathFragmentProtoFile returns *apexFile structure defining the classpath.proto config that
  2352. // the module contributes to the apex; or nil if the proto config was not generated.
  2353. func apexClasspathFragmentProtoFile(ctx android.ModuleContext, module blueprint.Module) *apexFile {
  2354. info := ctx.OtherModuleProvider(module, java.ClasspathFragmentProtoContentInfoProvider).(java.ClasspathFragmentProtoContentInfo)
  2355. if !info.ClasspathFragmentProtoGenerated {
  2356. return nil
  2357. }
  2358. classpathProtoOutput := info.ClasspathFragmentProtoOutput
  2359. af := newApexFile(ctx, classpathProtoOutput, classpathProtoOutput.Base(), info.ClasspathFragmentProtoInstallDir.Rel(), etc, nil)
  2360. return &af
  2361. }
  2362. // apexFileForBootclasspathFragmentContentModule creates an apexFile for a bootclasspath_fragment
  2363. // content module, i.e. a library that is part of the bootclasspath.
  2364. func apexFileForBootclasspathFragmentContentModule(ctx android.ModuleContext, fragmentModule blueprint.Module, javaModule javaModule) apexFile {
  2365. bootclasspathFragmentInfo := ctx.OtherModuleProvider(fragmentModule, java.BootclasspathFragmentApexContentInfoProvider).(java.BootclasspathFragmentApexContentInfo)
  2366. // Get the dexBootJar from the bootclasspath_fragment as that is responsible for performing the
  2367. // hidden API encpding.
  2368. dexBootJar, err := bootclasspathFragmentInfo.DexBootJarPathForContentModule(javaModule)
  2369. if err != nil {
  2370. ctx.ModuleErrorf("%s", err)
  2371. }
  2372. // Create an apexFile as for a normal java module but with the dex boot jar provided by the
  2373. // bootclasspath_fragment.
  2374. af := apexFileForJavaModuleWithFile(ctx, javaModule, dexBootJar)
  2375. return af
  2376. }
  2377. ///////////////////////////////////////////////////////////////////////////////////////////////////
  2378. // Factory functions
  2379. //
  2380. func newApexBundle() *apexBundle {
  2381. module := &apexBundle{}
  2382. module.AddProperties(&module.properties)
  2383. module.AddProperties(&module.targetProperties)
  2384. module.AddProperties(&module.archProperties)
  2385. module.AddProperties(&module.overridableProperties)
  2386. android.InitAndroidMultiTargetsArchModule(module, android.HostAndDeviceSupported, android.MultilibCommon)
  2387. android.InitDefaultableModule(module)
  2388. android.InitOverridableModule(module, &module.overridableProperties.Overrides)
  2389. android.InitBazelModule(module)
  2390. multitree.InitExportableModule(module)
  2391. return module
  2392. }
  2393. func ApexBundleFactory(testApex bool) android.Module {
  2394. bundle := newApexBundle()
  2395. bundle.testApex = testApex
  2396. return bundle
  2397. }
  2398. // apex_test is an APEX for testing. The difference from the ordinary apex module type is that
  2399. // certain compatibility checks such as apex_available are not done for apex_test.
  2400. func TestApexBundleFactory() android.Module {
  2401. bundle := newApexBundle()
  2402. bundle.testApex = true
  2403. return bundle
  2404. }
  2405. // apex packages other modules into an APEX file which is a packaging format for system-level
  2406. // components like binaries, shared libraries, etc.
  2407. func BundleFactory() android.Module {
  2408. return newApexBundle()
  2409. }
  2410. type Defaults struct {
  2411. android.ModuleBase
  2412. android.DefaultsModuleBase
  2413. }
  2414. // apex_defaults provides defaultable properties to other apex modules.
  2415. func DefaultsFactory() android.Module {
  2416. module := &Defaults{}
  2417. module.AddProperties(
  2418. &apexBundleProperties{},
  2419. &apexTargetBundleProperties{},
  2420. &apexArchBundleProperties{},
  2421. &overridableProperties{},
  2422. )
  2423. android.InitDefaultsModule(module)
  2424. return module
  2425. }
  2426. type OverrideApex struct {
  2427. android.ModuleBase
  2428. android.OverrideModuleBase
  2429. android.BazelModuleBase
  2430. }
  2431. func (o *OverrideApex) GenerateAndroidBuildActions(_ android.ModuleContext) {
  2432. // All the overrides happen in the base module.
  2433. }
  2434. // override_apex is used to create an apex module based on another apex module by overriding some of
  2435. // its properties.
  2436. func OverrideApexFactory() android.Module {
  2437. m := &OverrideApex{}
  2438. m.AddProperties(&overridableProperties{})
  2439. android.InitAndroidMultiTargetsArchModule(m, android.DeviceSupported, android.MultilibCommon)
  2440. android.InitOverrideModule(m)
  2441. android.InitBazelModule(m)
  2442. return m
  2443. }
  2444. func (o *OverrideApex) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
  2445. if ctx.ModuleType() != "override_apex" {
  2446. return
  2447. }
  2448. baseApexModuleName := o.OverrideModuleBase.GetOverriddenModuleName()
  2449. baseModule, baseApexExists := ctx.ModuleFromName(baseApexModuleName)
  2450. if !baseApexExists {
  2451. panic(fmt.Errorf("Base apex module doesn't exist: %s", baseApexModuleName))
  2452. }
  2453. a, baseModuleIsApex := baseModule.(*apexBundle)
  2454. if !baseModuleIsApex {
  2455. panic(fmt.Errorf("Base module is not apex module: %s", baseApexModuleName))
  2456. }
  2457. attrs, props, commonAttrs := convertWithBp2build(a, ctx)
  2458. // We just want the name, not module reference.
  2459. baseApexName := strings.TrimPrefix(baseApexModuleName, ":")
  2460. attrs.Base_apex_name = &baseApexName
  2461. for _, p := range o.GetProperties() {
  2462. overridableProperties, ok := p.(*overridableProperties)
  2463. if !ok {
  2464. continue
  2465. }
  2466. // Manifest is either empty or a file in the directory of base APEX and is not overridable.
  2467. // After it is converted in convertWithBp2build(baseApex, ctx),
  2468. // the attrs.Manifest.Value.Label is the file path relative to the directory
  2469. // of base apex. So the following code converts it to a label that looks like
  2470. // <package of base apex>:<path of manifest file> if base apex and override
  2471. // apex are not in the same package.
  2472. baseApexPackage := ctx.OtherModuleDir(a)
  2473. overrideApexPackage := ctx.ModuleDir()
  2474. if baseApexPackage != overrideApexPackage {
  2475. attrs.Manifest.Value.Label = "//" + baseApexPackage + ":" + attrs.Manifest.Value.Label
  2476. }
  2477. // Key
  2478. if overridableProperties.Key != nil {
  2479. attrs.Key = bazel.LabelAttribute{}
  2480. attrs.Key.SetValue(android.BazelLabelForModuleDepSingle(ctx, *overridableProperties.Key))
  2481. }
  2482. // Certificate
  2483. if overridableProperties.Certificate == nil {
  2484. // If overridableProperties.Certificate is nil, clear this out as
  2485. // well with zeroed structs, so the override_apex does not use the
  2486. // base apex's certificate.
  2487. attrs.Certificate = bazel.LabelAttribute{}
  2488. attrs.Certificate_name = bazel.StringAttribute{}
  2489. } else {
  2490. attrs.Certificate, attrs.Certificate_name = android.BazelStringOrLabelFromProp(ctx, overridableProperties.Certificate)
  2491. }
  2492. // Prebuilts
  2493. if overridableProperties.Prebuilts != nil {
  2494. prebuiltsLabelList := android.BazelLabelForModuleDeps(ctx, overridableProperties.Prebuilts)
  2495. attrs.Prebuilts = bazel.MakeLabelListAttribute(prebuiltsLabelList)
  2496. }
  2497. // Compressible
  2498. if overridableProperties.Compressible != nil {
  2499. attrs.Compressible = bazel.BoolAttribute{Value: overridableProperties.Compressible}
  2500. }
  2501. // Package name
  2502. //
  2503. // e.g. com.android.adbd's package name is com.android.adbd, but
  2504. // com.google.android.adbd overrides the package name to com.google.android.adbd
  2505. //
  2506. // TODO: this can be overridden from the product configuration, see
  2507. // getOverrideManifestPackageName and
  2508. // PRODUCT_MANIFEST_PACKAGE_NAME_OVERRIDES.
  2509. //
  2510. // Instead of generating the BUILD files differently based on the product config
  2511. // at the point of conversion, this should be handled by the BUILD file loading
  2512. // from the soong_injection's product_vars, so product config is decoupled from bp2build.
  2513. if overridableProperties.Package_name != "" {
  2514. attrs.Package_name = &overridableProperties.Package_name
  2515. }
  2516. // Logging parent
  2517. if overridableProperties.Logging_parent != "" {
  2518. attrs.Logging_parent = &overridableProperties.Logging_parent
  2519. }
  2520. }
  2521. commonAttrs.Name = o.Name()
  2522. ctx.CreateBazelTargetModule(props, commonAttrs, &attrs)
  2523. }
  2524. ///////////////////////////////////////////////////////////////////////////////////////////////////
  2525. // Vality check routines
  2526. //
  2527. // These are called in at the very beginning of GenerateAndroidBuildActions to flag an error when
  2528. // certain conditions are not met.
  2529. //
  2530. // TODO(jiyong): move these checks to a separate go file.
  2531. var _ android.ModuleWithMinSdkVersionCheck = (*apexBundle)(nil)
  2532. // Ensures that min_sdk_version of the included modules are equal or less than the min_sdk_version
  2533. // of this apexBundle.
  2534. func (a *apexBundle) CheckMinSdkVersion(ctx android.ModuleContext) {
  2535. if a.testApex || a.vndkApex {
  2536. return
  2537. }
  2538. // apexBundle::minSdkVersion reports its own errors.
  2539. minSdkVersion := a.minSdkVersion(ctx)
  2540. android.CheckMinSdkVersion(ctx, minSdkVersion, a.WalkPayloadDeps)
  2541. }
  2542. // Returns apex's min_sdk_version string value, honoring overrides
  2543. func (a *apexBundle) minSdkVersionValue(ctx android.EarlyModuleContext) string {
  2544. // Only override the minSdkVersion value on Apexes which already specify
  2545. // a min_sdk_version (it's optional for non-updatable apexes), and that its
  2546. // min_sdk_version value is lower than the one to override with.
  2547. minApiLevel := minSdkVersionFromValue(ctx, proptools.String(a.properties.Min_sdk_version))
  2548. if minApiLevel.IsNone() {
  2549. return ""
  2550. }
  2551. overrideMinSdkValue := ctx.DeviceConfig().ApexGlobalMinSdkVersionOverride()
  2552. overrideApiLevel := minSdkVersionFromValue(ctx, overrideMinSdkValue)
  2553. if !overrideApiLevel.IsNone() && overrideApiLevel.CompareTo(minApiLevel) > 0 {
  2554. minApiLevel = overrideApiLevel
  2555. }
  2556. return minApiLevel.String()
  2557. }
  2558. // Returns apex's min_sdk_version SdkSpec, honoring overrides
  2559. func (a *apexBundle) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
  2560. return a.minSdkVersion(ctx)
  2561. }
  2562. // Returns apex's min_sdk_version ApiLevel, honoring overrides
  2563. func (a *apexBundle) minSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
  2564. return minSdkVersionFromValue(ctx, a.minSdkVersionValue(ctx))
  2565. }
  2566. // Construct ApiLevel object from min_sdk_version string value
  2567. func minSdkVersionFromValue(ctx android.EarlyModuleContext, value string) android.ApiLevel {
  2568. if value == "" {
  2569. return android.NoneApiLevel
  2570. }
  2571. apiLevel, err := android.ApiLevelFromUser(ctx, value)
  2572. if err != nil {
  2573. ctx.PropertyErrorf("min_sdk_version", "%s", err.Error())
  2574. return android.NoneApiLevel
  2575. }
  2576. return apiLevel
  2577. }
  2578. // Ensures that a lib providing stub isn't statically linked
  2579. func (a *apexBundle) checkStaticLinkingToStubLibraries(ctx android.ModuleContext) {
  2580. // Practically, we only care about regular APEXes on the device.
  2581. if ctx.Host() || a.testApex || a.vndkApex {
  2582. return
  2583. }
  2584. abInfo := ctx.Provider(ApexBundleInfoProvider).(ApexBundleInfo)
  2585. a.WalkPayloadDeps(ctx, func(ctx android.ModuleContext, from blueprint.Module, to android.ApexModule, externalDep bool) bool {
  2586. if ccm, ok := to.(*cc.Module); ok {
  2587. apexName := ctx.ModuleName()
  2588. fromName := ctx.OtherModuleName(from)
  2589. toName := ctx.OtherModuleName(to)
  2590. // If `to` is not actually in the same APEX as `from` then it does not need
  2591. // apex_available and neither do any of its dependencies.
  2592. //
  2593. // It is ok to call DepIsInSameApex() directly from within WalkPayloadDeps().
  2594. if am, ok := from.(android.DepIsInSameApex); ok && !am.DepIsInSameApex(ctx, to) {
  2595. // As soon as the dependency graph crosses the APEX boundary, don't go further.
  2596. return false
  2597. }
  2598. // The dynamic linker and crash_dump tool in the runtime APEX is the only
  2599. // exception to this rule. It can't make the static dependencies dynamic
  2600. // because it can't do the dynamic linking for itself.
  2601. // Same rule should be applied to linkerconfig, because it should be executed
  2602. // only with static linked libraries before linker is available with ld.config.txt
  2603. if apexName == "com.android.runtime" && (fromName == "linker" || fromName == "crash_dump" || fromName == "linkerconfig") {
  2604. return false
  2605. }
  2606. isStubLibraryFromOtherApex := ccm.HasStubsVariants() && !abInfo.Contents.DirectlyInApex(toName)
  2607. if isStubLibraryFromOtherApex && !externalDep {
  2608. ctx.ModuleErrorf("%q required by %q is a native library providing stub. "+
  2609. "It shouldn't be included in this APEX via static linking. Dependency path: %s", to.String(), fromName, ctx.GetPathString(false))
  2610. }
  2611. }
  2612. return true
  2613. })
  2614. }
  2615. // checkUpdatable enforces APEX and its transitive dep properties to have desired values for updatable APEXes.
  2616. func (a *apexBundle) checkUpdatable(ctx android.ModuleContext) {
  2617. if a.Updatable() {
  2618. if a.minSdkVersionValue(ctx) == "" {
  2619. ctx.PropertyErrorf("updatable", "updatable APEXes should set min_sdk_version as well")
  2620. }
  2621. if a.UsePlatformApis() {
  2622. ctx.PropertyErrorf("updatable", "updatable APEXes can't use platform APIs")
  2623. }
  2624. if proptools.Bool(a.properties.Use_vndk_as_stable) {
  2625. ctx.PropertyErrorf("use_vndk_as_stable", "updatable APEXes can't use external VNDK libs")
  2626. }
  2627. if a.FutureUpdatable() {
  2628. ctx.PropertyErrorf("future_updatable", "Already updatable. Remove `future_updatable: true:`")
  2629. }
  2630. a.checkJavaStableSdkVersion(ctx)
  2631. a.checkClasspathFragments(ctx)
  2632. }
  2633. }
  2634. // checkClasspathFragments enforces that all classpath fragments in deps generate classpaths.proto config.
  2635. func (a *apexBundle) checkClasspathFragments(ctx android.ModuleContext) {
  2636. ctx.VisitDirectDeps(func(module android.Module) {
  2637. if tag := ctx.OtherModuleDependencyTag(module); tag == bcpfTag || tag == sscpfTag {
  2638. info := ctx.OtherModuleProvider(module, java.ClasspathFragmentProtoContentInfoProvider).(java.ClasspathFragmentProtoContentInfo)
  2639. if !info.ClasspathFragmentProtoGenerated {
  2640. ctx.OtherModuleErrorf(module, "is included in updatable apex %v, it must not set generate_classpaths_proto to false", ctx.ModuleName())
  2641. }
  2642. }
  2643. })
  2644. }
  2645. // checkJavaStableSdkVersion enforces that all Java deps are using stable SDKs to compile.
  2646. func (a *apexBundle) checkJavaStableSdkVersion(ctx android.ModuleContext) {
  2647. // Visit direct deps only. As long as we guarantee top-level deps are using stable SDKs,
  2648. // java's checkLinkType guarantees correct usage for transitive deps
  2649. ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
  2650. tag := ctx.OtherModuleDependencyTag(module)
  2651. switch tag {
  2652. case javaLibTag, androidAppTag:
  2653. if m, ok := module.(interface {
  2654. CheckStableSdkVersion(ctx android.BaseModuleContext) error
  2655. }); ok {
  2656. if err := m.CheckStableSdkVersion(ctx); err != nil {
  2657. ctx.ModuleErrorf("cannot depend on \"%v\": %v", ctx.OtherModuleName(module), err)
  2658. }
  2659. }
  2660. }
  2661. })
  2662. }
  2663. // checkApexAvailability ensures that the all the dependencies are marked as available for this APEX.
  2664. func (a *apexBundle) checkApexAvailability(ctx android.ModuleContext) {
  2665. // Let's be practical. Availability for test, host, and the VNDK apex isn't important
  2666. if ctx.Host() || a.testApex || a.vndkApex {
  2667. return
  2668. }
  2669. // Because APEXes targeting other than system/system_ext partitions can't set
  2670. // apex_available, we skip checks for these APEXes
  2671. if a.SocSpecific() || a.DeviceSpecific() || (a.ProductSpecific() && ctx.Config().EnforceProductPartitionInterface()) {
  2672. return
  2673. }
  2674. // Coverage build adds additional dependencies for the coverage-only runtime libraries.
  2675. // Requiring them and their transitive depencies with apex_available is not right
  2676. // because they just add noise.
  2677. if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") || a.IsNativeCoverageNeeded(ctx) {
  2678. return
  2679. }
  2680. a.WalkPayloadDeps(ctx, func(ctx android.ModuleContext, from blueprint.Module, to android.ApexModule, externalDep bool) bool {
  2681. // As soon as the dependency graph crosses the APEX boundary, don't go further.
  2682. if externalDep {
  2683. return false
  2684. }
  2685. apexName := ctx.ModuleName()
  2686. for _, props := range ctx.Module().GetProperties() {
  2687. if apexProps, ok := props.(*apexBundleProperties); ok {
  2688. if apexProps.Apex_available_name != nil {
  2689. apexName = *apexProps.Apex_available_name
  2690. }
  2691. }
  2692. }
  2693. fromName := ctx.OtherModuleName(from)
  2694. toName := ctx.OtherModuleName(to)
  2695. // If `to` is not actually in the same APEX as `from` then it does not need
  2696. // apex_available and neither do any of its dependencies.
  2697. //
  2698. // It is ok to call DepIsInSameApex() directly from within WalkPayloadDeps().
  2699. if am, ok := from.(android.DepIsInSameApex); ok && !am.DepIsInSameApex(ctx, to) {
  2700. // As soon as the dependency graph crosses the APEX boundary, don't go
  2701. // further.
  2702. return false
  2703. }
  2704. if to.AvailableFor(apexName) || baselineApexAvailable(apexName, toName) {
  2705. return true
  2706. }
  2707. ctx.ModuleErrorf("%q requires %q that doesn't list the APEX under 'apex_available'."+
  2708. "\n\nDependency path:%s\n\n"+
  2709. "Consider adding %q to 'apex_available' property of %q",
  2710. fromName, toName, ctx.GetPathString(true), apexName, toName)
  2711. // Visit this module's dependencies to check and report any issues with their availability.
  2712. return true
  2713. })
  2714. }
  2715. // checkStaticExecutable ensures that executables in an APEX are not static.
  2716. func (a *apexBundle) checkStaticExecutables(ctx android.ModuleContext) {
  2717. // No need to run this for host APEXes
  2718. if ctx.Host() {
  2719. return
  2720. }
  2721. ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
  2722. if ctx.OtherModuleDependencyTag(module) != executableTag {
  2723. return
  2724. }
  2725. if l, ok := module.(cc.LinkableInterface); ok && l.StaticExecutable() {
  2726. apex := a.ApexVariationName()
  2727. exec := ctx.OtherModuleName(module)
  2728. if isStaticExecutableAllowed(apex, exec) {
  2729. return
  2730. }
  2731. ctx.ModuleErrorf("executable %s is static", ctx.OtherModuleName(module))
  2732. }
  2733. })
  2734. }
  2735. // A small list of exceptions where static executables are allowed in APEXes.
  2736. func isStaticExecutableAllowed(apex string, exec string) bool {
  2737. m := map[string][]string{
  2738. "com.android.runtime": {
  2739. "linker",
  2740. "linkerconfig",
  2741. },
  2742. }
  2743. execNames, ok := m[apex]
  2744. return ok && android.InList(exec, execNames)
  2745. }
  2746. // Collect information for opening IDE project files in java/jdeps.go.
  2747. func (a *apexBundle) IDEInfo(dpInfo *android.IdeInfo) {
  2748. dpInfo.Deps = append(dpInfo.Deps, a.properties.Java_libs...)
  2749. dpInfo.Deps = append(dpInfo.Deps, a.properties.Bootclasspath_fragments...)
  2750. dpInfo.Deps = append(dpInfo.Deps, a.properties.Systemserverclasspath_fragments...)
  2751. dpInfo.Paths = append(dpInfo.Paths, a.modulePaths...)
  2752. }
  2753. var (
  2754. apexAvailBaseline = makeApexAvailableBaseline()
  2755. inverseApexAvailBaseline = invertApexBaseline(apexAvailBaseline)
  2756. )
  2757. func baselineApexAvailable(apex, moduleName string) bool {
  2758. key := apex
  2759. moduleName = normalizeModuleName(moduleName)
  2760. if val, ok := apexAvailBaseline[key]; ok && android.InList(moduleName, val) {
  2761. return true
  2762. }
  2763. key = android.AvailableToAnyApex
  2764. if val, ok := apexAvailBaseline[key]; ok && android.InList(moduleName, val) {
  2765. return true
  2766. }
  2767. return false
  2768. }
  2769. func normalizeModuleName(moduleName string) string {
  2770. // Prebuilt modules (e.g. java_import, etc.) have "prebuilt_" prefix added by the build
  2771. // system. Trim the prefix for the check since they are confusing
  2772. moduleName = android.RemoveOptionalPrebuiltPrefix(moduleName)
  2773. if strings.HasPrefix(moduleName, "libclang_rt.") {
  2774. // This module has many arch variants that depend on the product being built.
  2775. // We don't want to list them all
  2776. moduleName = "libclang_rt"
  2777. }
  2778. if strings.HasPrefix(moduleName, "androidx.") {
  2779. // TODO(b/156996905) Set apex_available/min_sdk_version for androidx support libraries
  2780. moduleName = "androidx"
  2781. }
  2782. return moduleName
  2783. }
  2784. // Transform the map of apex -> modules to module -> apexes.
  2785. func invertApexBaseline(m map[string][]string) map[string][]string {
  2786. r := make(map[string][]string)
  2787. for apex, modules := range m {
  2788. for _, module := range modules {
  2789. r[module] = append(r[module], apex)
  2790. }
  2791. }
  2792. return r
  2793. }
  2794. // Retrieve the baseline of apexes to which the supplied module belongs.
  2795. func BaselineApexAvailable(moduleName string) []string {
  2796. return inverseApexAvailBaseline[normalizeModuleName(moduleName)]
  2797. }
  2798. // This is a map from apex to modules, which overrides the apex_available setting for that
  2799. // particular module to make it available for the apex regardless of its setting.
  2800. // TODO(b/147364041): remove this
  2801. func makeApexAvailableBaseline() map[string][]string {
  2802. // The "Module separator"s below are employed to minimize merge conflicts.
  2803. m := make(map[string][]string)
  2804. //
  2805. // Module separator
  2806. //
  2807. m["com.android.appsearch"] = []string{
  2808. "icing-java-proto-lite",
  2809. }
  2810. //
  2811. // Module separator
  2812. //
  2813. m["com.android.btservices"] = []string{
  2814. // empty
  2815. }
  2816. //
  2817. // Module separator
  2818. //
  2819. m["com.android.cellbroadcast"] = []string{}
  2820. //
  2821. // Module separator
  2822. //
  2823. m["com.android.extservices"] = []string{
  2824. "ExtServices-core",
  2825. "libtextclassifier-java",
  2826. "textclassifier-statsd",
  2827. "TextClassifierNotificationLibNoManifest",
  2828. "TextClassifierServiceLibNoManifest",
  2829. }
  2830. //
  2831. // Module separator
  2832. //
  2833. m["com.android.neuralnetworks"] = []string{
  2834. "android.hardware.neuralnetworks@1.0",
  2835. "android.hardware.neuralnetworks@1.1",
  2836. "android.hardware.neuralnetworks@1.2",
  2837. "android.hardware.neuralnetworks@1.3",
  2838. "android.hidl.allocator@1.0",
  2839. "android.hidl.memory.token@1.0",
  2840. "android.hidl.memory@1.0",
  2841. "android.hidl.safe_union@1.0",
  2842. "libarect",
  2843. "libprocpartition",
  2844. }
  2845. //
  2846. // Module separator
  2847. //
  2848. m["com.android.media"] = []string{
  2849. // empty
  2850. }
  2851. //
  2852. // Module separator
  2853. //
  2854. m["com.android.media.swcodec"] = []string{
  2855. // empty
  2856. }
  2857. //
  2858. // Module separator
  2859. //
  2860. m["com.android.mediaprovider"] = []string{
  2861. "MediaProvider",
  2862. "MediaProviderGoogle",
  2863. "fmtlib_ndk",
  2864. "libbase_ndk",
  2865. "libfuse",
  2866. "libfuse_jni",
  2867. }
  2868. //
  2869. // Module separator
  2870. //
  2871. m["com.android.runtime"] = []string{
  2872. "libc_aeabi",
  2873. "libc_bionic",
  2874. "libc_bionic_ndk",
  2875. "libc_bootstrap",
  2876. "libc_common",
  2877. "libc_common_shared",
  2878. "libc_dns",
  2879. "libc_dynamic_dispatch",
  2880. "libc_fortify",
  2881. "libc_freebsd",
  2882. "libc_freebsd_large_stack",
  2883. "libc_gdtoa",
  2884. "libc_init_dynamic",
  2885. "libc_init_static",
  2886. "libc_jemalloc_wrapper",
  2887. "libc_netbsd",
  2888. "libc_nomalloc",
  2889. "libc_nopthread",
  2890. "libc_openbsd",
  2891. "libc_openbsd_large_stack",
  2892. "libc_openbsd_ndk",
  2893. "libc_pthread",
  2894. "libc_syscalls",
  2895. "libc_tzcode",
  2896. "libc_unwind_static",
  2897. "libdebuggerd",
  2898. "libdebuggerd_common_headers",
  2899. "libdebuggerd_handler_core",
  2900. "libdl_static",
  2901. "libjemalloc5",
  2902. "liblinker_main",
  2903. "liblinker_malloc",
  2904. "liblzma",
  2905. "libprocinfo",
  2906. "libpropertyinfoparser",
  2907. "libscudo",
  2908. "libstdc++",
  2909. "libsystemproperties",
  2910. "libtombstoned_client_static",
  2911. "libunwindstack",
  2912. "libz",
  2913. "libziparchive",
  2914. }
  2915. //
  2916. // Module separator
  2917. //
  2918. m["com.android.tethering"] = []string{
  2919. "android.hardware.tetheroffload.config-V1.0-java",
  2920. "android.hardware.tetheroffload.control-V1.0-java",
  2921. "net-utils-framework-common",
  2922. }
  2923. //
  2924. // Module separator
  2925. //
  2926. m["com.android.wifi"] = []string{
  2927. "PlatformProperties",
  2928. "android.hardware.wifi-V1.0-java",
  2929. "android.hardware.wifi-V1.0-java-constants",
  2930. "android.hardware.wifi-V1.1-java",
  2931. "android.hardware.wifi-V1.2-java",
  2932. "android.hardware.wifi-V1.3-java",
  2933. "android.hardware.wifi-V1.4-java",
  2934. "android.hardware.wifi.hostapd-V1.0-java",
  2935. "android.hardware.wifi.hostapd-V1.1-java",
  2936. "android.hardware.wifi.hostapd-V1.2-java",
  2937. "android.hardware.wifi.supplicant-V1.0-java",
  2938. "android.hardware.wifi.supplicant-V1.1-java",
  2939. "android.hardware.wifi.supplicant-V1.2-java",
  2940. "android.hardware.wifi.supplicant-V1.3-java",
  2941. "bouncycastle-unbundled",
  2942. "framework-wifi-util-lib",
  2943. "ksoap2",
  2944. "libnanohttpd",
  2945. "wifi-lite-protos",
  2946. "wifi-nano-protos",
  2947. "wifi-service-pre-jarjar",
  2948. }
  2949. //
  2950. // Module separator
  2951. //
  2952. m[android.AvailableToAnyApex] = []string{
  2953. "libprofile-clang-extras",
  2954. "libprofile-clang-extras_ndk",
  2955. "libprofile-extras",
  2956. "libprofile-extras_ndk",
  2957. }
  2958. return m
  2959. }
  2960. func init() {
  2961. android.AddNeverAllowRules(createBcpPermittedPackagesRules(qBcpPackages())...)
  2962. android.AddNeverAllowRules(createBcpPermittedPackagesRules(rBcpPackages())...)
  2963. }
  2964. func createBcpPermittedPackagesRules(bcpPermittedPackages map[string][]string) []android.Rule {
  2965. rules := make([]android.Rule, 0, len(bcpPermittedPackages))
  2966. for jar, permittedPackages := range bcpPermittedPackages {
  2967. permittedPackagesRule := android.NeverAllow().
  2968. With("name", jar).
  2969. WithMatcher("permitted_packages", android.NotInList(permittedPackages)).
  2970. Because(jar +
  2971. " bootjar may only use these package prefixes: " + strings.Join(permittedPackages, ",") +
  2972. ". Please consider the following alternatives:\n" +
  2973. " 1. If the offending code is from a statically linked library, consider " +
  2974. "removing that dependency and using an alternative already in the " +
  2975. "bootclasspath, or perhaps a shared library." +
  2976. " 2. Move the offending code into an allowed package.\n" +
  2977. " 3. Jarjar the offending code. Please be mindful of the potential system " +
  2978. "health implications of bundling that code, particularly if the offending jar " +
  2979. "is part of the bootclasspath.")
  2980. rules = append(rules, permittedPackagesRule)
  2981. }
  2982. return rules
  2983. }
  2984. // DO NOT EDIT! These are the package prefixes that are exempted from being AOT'ed by ART.
  2985. // Adding code to the bootclasspath in new packages will cause issues on module update.
  2986. func qBcpPackages() map[string][]string {
  2987. return map[string][]string{
  2988. "conscrypt": {
  2989. "android.net.ssl",
  2990. "com.android.org.conscrypt",
  2991. },
  2992. "updatable-media": {
  2993. "android.media",
  2994. },
  2995. }
  2996. }
  2997. // DO NOT EDIT! These are the package prefixes that are exempted from being AOT'ed by ART.
  2998. // Adding code to the bootclasspath in new packages will cause issues on module update.
  2999. func rBcpPackages() map[string][]string {
  3000. return map[string][]string{
  3001. "framework-mediaprovider": {
  3002. "android.provider",
  3003. },
  3004. "framework-permission": {
  3005. "android.permission",
  3006. "android.app.role",
  3007. "com.android.permission",
  3008. "com.android.role",
  3009. },
  3010. "framework-sdkextensions": {
  3011. "android.os.ext",
  3012. },
  3013. "framework-statsd": {
  3014. "android.app",
  3015. "android.os",
  3016. "android.util",
  3017. "com.android.internal.statsd",
  3018. "com.android.server.stats",
  3019. },
  3020. "framework-wifi": {
  3021. "com.android.server.wifi",
  3022. "com.android.wifi.x",
  3023. "android.hardware.wifi",
  3024. "android.net.wifi",
  3025. },
  3026. "framework-tethering": {
  3027. "android.net",
  3028. },
  3029. }
  3030. }
  3031. // For Bazel / bp2build
  3032. type bazelApexBundleAttributes struct {
  3033. Manifest bazel.LabelAttribute
  3034. Android_manifest bazel.LabelAttribute
  3035. File_contexts bazel.LabelAttribute
  3036. Canned_fs_config bazel.LabelAttribute
  3037. Key bazel.LabelAttribute
  3038. Certificate bazel.LabelAttribute // used when the certificate prop is a module
  3039. Certificate_name bazel.StringAttribute // used when the certificate prop is a string
  3040. Min_sdk_version bazel.StringAttribute
  3041. Updatable bazel.BoolAttribute
  3042. Installable bazel.BoolAttribute
  3043. Binaries bazel.LabelListAttribute
  3044. Prebuilts bazel.LabelListAttribute
  3045. Native_shared_libs_32 bazel.LabelListAttribute
  3046. Native_shared_libs_64 bazel.LabelListAttribute
  3047. Compressible bazel.BoolAttribute
  3048. Package_name *string
  3049. Logging_parent *string
  3050. Tests bazel.LabelListAttribute
  3051. Base_apex_name *string
  3052. Apex_available_name *string
  3053. Variant_version *string
  3054. }
  3055. type convertedNativeSharedLibs struct {
  3056. Native_shared_libs_32 bazel.LabelListAttribute
  3057. Native_shared_libs_64 bazel.LabelListAttribute
  3058. }
  3059. const (
  3060. minSdkVersionPropName = "Min_sdk_version"
  3061. )
  3062. // ConvertWithBp2build performs bp2build conversion of an apex
  3063. func (a *apexBundle) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
  3064. // We only convert apex and apex_test modules at this time
  3065. if ctx.ModuleType() != "apex" && ctx.ModuleType() != "apex_test" {
  3066. return
  3067. }
  3068. attrs, props, commonAttrs := convertWithBp2build(a, ctx)
  3069. commonAttrs.Name = a.Name()
  3070. ctx.CreateBazelTargetModule(props, commonAttrs, &attrs)
  3071. }
  3072. func convertWithBp2build(a *apexBundle, ctx android.TopDownMutatorContext) (bazelApexBundleAttributes, bazel.BazelTargetModuleProperties, android.CommonAttributes) {
  3073. var manifestLabelAttribute bazel.LabelAttribute
  3074. manifestLabelAttribute.SetValue(android.BazelLabelForModuleSrcSingle(ctx, proptools.StringDefault(a.properties.Manifest, "apex_manifest.json")))
  3075. var androidManifestLabelAttribute bazel.LabelAttribute
  3076. if a.properties.AndroidManifest != nil {
  3077. androidManifestLabelAttribute.SetValue(android.BazelLabelForModuleSrcSingle(ctx, *a.properties.AndroidManifest))
  3078. }
  3079. var fileContextsLabelAttribute bazel.LabelAttribute
  3080. if a.properties.File_contexts == nil {
  3081. // See buildFileContexts(), if file_contexts is not specified the default one is used, which is //system/sepolicy/apex:<module name>-file_contexts
  3082. fileContextsLabelAttribute.SetValue(android.BazelLabelForModuleDepSingle(ctx, a.Name()+"-file_contexts"))
  3083. } else if strings.HasPrefix(*a.properties.File_contexts, ":") {
  3084. // File_contexts is a module
  3085. fileContextsLabelAttribute.SetValue(android.BazelLabelForModuleDepSingle(ctx, *a.properties.File_contexts))
  3086. } else {
  3087. // File_contexts is a file
  3088. fileContextsLabelAttribute.SetValue(android.BazelLabelForModuleSrcSingle(ctx, *a.properties.File_contexts))
  3089. }
  3090. var cannedFsConfigAttribute bazel.LabelAttribute
  3091. if a.properties.Canned_fs_config != nil {
  3092. cannedFsConfigAttribute.SetValue(android.BazelLabelForModuleSrcSingle(ctx, *a.properties.Canned_fs_config))
  3093. }
  3094. productVariableProps := android.ProductVariableProperties(ctx, a)
  3095. // TODO(b/219503907) this would need to be set to a.MinSdkVersionValue(ctx) but
  3096. // given it's coming via config, we probably don't want to put it in here.
  3097. var minSdkVersion bazel.StringAttribute
  3098. if a.properties.Min_sdk_version != nil {
  3099. minSdkVersion.SetValue(*a.properties.Min_sdk_version)
  3100. }
  3101. if props, ok := productVariableProps[minSdkVersionPropName]; ok {
  3102. for c, p := range props {
  3103. if val, ok := p.(*string); ok {
  3104. minSdkVersion.SetSelectValue(c.ConfigurationAxis(), c.SelectKey(), val)
  3105. }
  3106. }
  3107. }
  3108. var keyLabelAttribute bazel.LabelAttribute
  3109. if a.overridableProperties.Key != nil {
  3110. keyLabelAttribute.SetValue(android.BazelLabelForModuleDepSingle(ctx, *a.overridableProperties.Key))
  3111. }
  3112. // Certificate
  3113. certificate, certificateName := android.BazelStringOrLabelFromProp(ctx, a.overridableProperties.Certificate)
  3114. nativeSharedLibs := &convertedNativeSharedLibs{
  3115. Native_shared_libs_32: bazel.LabelListAttribute{},
  3116. Native_shared_libs_64: bazel.LabelListAttribute{},
  3117. }
  3118. // https://cs.android.com/android/platform/superproject/+/master:build/soong/android/arch.go;l=698;drc=f05b0d35d2fbe51be9961ce8ce8031f840295c68
  3119. // https://cs.android.com/android/platform/superproject/+/master:build/soong/apex/apex.go;l=2549;drc=ec731a83e3e2d80a1254e32fd4ad7ef85e262669
  3120. // In Soong, decodeMultilib, used to get multilib, return "first" if defaultMultilib is set to "common".
  3121. // Since apex sets defaultMultilib to be "common", equivalent compileMultilib in bp2build for apex should be "first"
  3122. compileMultilib := "first"
  3123. if a.CompileMultilib() != nil {
  3124. compileMultilib = *a.CompileMultilib()
  3125. }
  3126. // properties.Native_shared_libs is treated as "both"
  3127. convertBothLibs(ctx, compileMultilib, a.properties.Native_shared_libs, nativeSharedLibs)
  3128. convertBothLibs(ctx, compileMultilib, a.properties.Multilib.Both.Native_shared_libs, nativeSharedLibs)
  3129. convert32Libs(ctx, compileMultilib, a.properties.Multilib.Lib32.Native_shared_libs, nativeSharedLibs)
  3130. convert64Libs(ctx, compileMultilib, a.properties.Multilib.Lib64.Native_shared_libs, nativeSharedLibs)
  3131. convertFirstLibs(ctx, compileMultilib, a.properties.Multilib.First.Native_shared_libs, nativeSharedLibs)
  3132. prebuilts := a.overridableProperties.Prebuilts
  3133. prebuiltsLabelList := android.BazelLabelForModuleDeps(ctx, prebuilts)
  3134. prebuiltsLabelListAttribute := bazel.MakeLabelListAttribute(prebuiltsLabelList)
  3135. binaries := android.BazelLabelForModuleDeps(ctx, a.properties.ApexNativeDependencies.Binaries)
  3136. binariesLabelListAttribute := bazel.MakeLabelListAttribute(binaries)
  3137. var testsAttrs bazel.LabelListAttribute
  3138. if a.testApex && len(a.properties.ApexNativeDependencies.Tests) > 0 {
  3139. tests := android.BazelLabelForModuleDeps(ctx, a.properties.ApexNativeDependencies.Tests)
  3140. testsAttrs = bazel.MakeLabelListAttribute(tests)
  3141. }
  3142. var updatableAttribute bazel.BoolAttribute
  3143. if a.properties.Updatable != nil {
  3144. updatableAttribute.Value = a.properties.Updatable
  3145. }
  3146. var installableAttribute bazel.BoolAttribute
  3147. if a.properties.Installable != nil {
  3148. installableAttribute.Value = a.properties.Installable
  3149. }
  3150. var compressibleAttribute bazel.BoolAttribute
  3151. if a.overridableProperties.Compressible != nil {
  3152. compressibleAttribute.Value = a.overridableProperties.Compressible
  3153. }
  3154. var packageName *string
  3155. if a.overridableProperties.Package_name != "" {
  3156. packageName = &a.overridableProperties.Package_name
  3157. }
  3158. var loggingParent *string
  3159. if a.overridableProperties.Logging_parent != "" {
  3160. loggingParent = &a.overridableProperties.Logging_parent
  3161. }
  3162. attrs := bazelApexBundleAttributes{
  3163. Manifest: manifestLabelAttribute,
  3164. Android_manifest: androidManifestLabelAttribute,
  3165. File_contexts: fileContextsLabelAttribute,
  3166. Canned_fs_config: cannedFsConfigAttribute,
  3167. Min_sdk_version: minSdkVersion,
  3168. Key: keyLabelAttribute,
  3169. Certificate: certificate,
  3170. Certificate_name: certificateName,
  3171. Updatable: updatableAttribute,
  3172. Installable: installableAttribute,
  3173. Native_shared_libs_32: nativeSharedLibs.Native_shared_libs_32,
  3174. Native_shared_libs_64: nativeSharedLibs.Native_shared_libs_64,
  3175. Binaries: binariesLabelListAttribute,
  3176. Prebuilts: prebuiltsLabelListAttribute,
  3177. Compressible: compressibleAttribute,
  3178. Package_name: packageName,
  3179. Logging_parent: loggingParent,
  3180. Tests: testsAttrs,
  3181. Apex_available_name: a.properties.Apex_available_name,
  3182. Variant_version: a.properties.Variant_version,
  3183. }
  3184. props := bazel.BazelTargetModuleProperties{
  3185. Rule_class: "apex",
  3186. Bzl_load_location: "//build/bazel/rules/apex:apex.bzl",
  3187. }
  3188. commonAttrs := android.CommonAttributes{}
  3189. if a.testApex {
  3190. commonAttrs.Testonly = proptools.BoolPtr(true)
  3191. // Set the api_domain of the test apex
  3192. attrs.Base_apex_name = proptools.StringPtr(cc.GetApiDomain(a.Name()))
  3193. }
  3194. return attrs, props, commonAttrs
  3195. }
  3196. // The following conversions are based on this table where the rows are the compile_multilib
  3197. // values and the columns are the properties.Multilib.*.Native_shared_libs. Each cell
  3198. // represents how the libs should be compiled for a 64-bit/32-bit device: 32 means it
  3199. // should be compiled as 32-bit, 64 means it should be compiled as 64-bit, none means it
  3200. // should not be compiled.
  3201. // multib/compile_multilib, 32, 64, both, first
  3202. // 32, 32/32, none/none, 32/32, none/32
  3203. // 64, none/none, 64/none, 64/none, 64/none
  3204. // both, 32/32, 64/none, 32&64/32, 64/32
  3205. // first, 32/32, 64/none, 64/32, 64/32
  3206. func convert32Libs(ctx android.TopDownMutatorContext, compileMultilb string,
  3207. libs []string, nativeSharedLibs *convertedNativeSharedLibs) {
  3208. libsLabelList := android.BazelLabelForModuleDeps(ctx, libs)
  3209. switch compileMultilb {
  3210. case "both", "32":
  3211. makeNoConfig32SharedLibsAttributes(libsLabelList, nativeSharedLibs)
  3212. case "first":
  3213. make32SharedLibsAttributes(libsLabelList, nativeSharedLibs)
  3214. case "64":
  3215. // Incompatible, ignore
  3216. default:
  3217. invalidCompileMultilib(ctx, compileMultilb)
  3218. }
  3219. }
  3220. func convert64Libs(ctx android.TopDownMutatorContext, compileMultilb string,
  3221. libs []string, nativeSharedLibs *convertedNativeSharedLibs) {
  3222. libsLabelList := android.BazelLabelForModuleDeps(ctx, libs)
  3223. switch compileMultilb {
  3224. case "both", "64", "first":
  3225. make64SharedLibsAttributes(libsLabelList, nativeSharedLibs)
  3226. case "32":
  3227. // Incompatible, ignore
  3228. default:
  3229. invalidCompileMultilib(ctx, compileMultilb)
  3230. }
  3231. }
  3232. func convertBothLibs(ctx android.TopDownMutatorContext, compileMultilb string,
  3233. libs []string, nativeSharedLibs *convertedNativeSharedLibs) {
  3234. libsLabelList := android.BazelLabelForModuleDeps(ctx, libs)
  3235. switch compileMultilb {
  3236. case "both":
  3237. makeNoConfig32SharedLibsAttributes(libsLabelList, nativeSharedLibs)
  3238. make64SharedLibsAttributes(libsLabelList, nativeSharedLibs)
  3239. case "first":
  3240. makeFirstSharedLibsAttributes(libsLabelList, nativeSharedLibs)
  3241. case "32":
  3242. makeNoConfig32SharedLibsAttributes(libsLabelList, nativeSharedLibs)
  3243. case "64":
  3244. make64SharedLibsAttributes(libsLabelList, nativeSharedLibs)
  3245. default:
  3246. invalidCompileMultilib(ctx, compileMultilb)
  3247. }
  3248. }
  3249. func convertFirstLibs(ctx android.TopDownMutatorContext, compileMultilb string,
  3250. libs []string, nativeSharedLibs *convertedNativeSharedLibs) {
  3251. libsLabelList := android.BazelLabelForModuleDeps(ctx, libs)
  3252. switch compileMultilb {
  3253. case "both", "first":
  3254. makeFirstSharedLibsAttributes(libsLabelList, nativeSharedLibs)
  3255. case "32":
  3256. make32SharedLibsAttributes(libsLabelList, nativeSharedLibs)
  3257. case "64":
  3258. make64SharedLibsAttributes(libsLabelList, nativeSharedLibs)
  3259. default:
  3260. invalidCompileMultilib(ctx, compileMultilb)
  3261. }
  3262. }
  3263. func makeFirstSharedLibsAttributes(libsLabelList bazel.LabelList, nativeSharedLibs *convertedNativeSharedLibs) {
  3264. make32SharedLibsAttributes(libsLabelList, nativeSharedLibs)
  3265. make64SharedLibsAttributes(libsLabelList, nativeSharedLibs)
  3266. }
  3267. func makeNoConfig32SharedLibsAttributes(libsLabelList bazel.LabelList, nativeSharedLibs *convertedNativeSharedLibs) {
  3268. list := bazel.LabelListAttribute{}
  3269. list.SetSelectValue(bazel.NoConfigAxis, "", libsLabelList)
  3270. nativeSharedLibs.Native_shared_libs_32.Append(list)
  3271. }
  3272. func make32SharedLibsAttributes(libsLabelList bazel.LabelList, nativeSharedLibs *convertedNativeSharedLibs) {
  3273. makeSharedLibsAttributes("x86", libsLabelList, &nativeSharedLibs.Native_shared_libs_32)
  3274. makeSharedLibsAttributes("arm", libsLabelList, &nativeSharedLibs.Native_shared_libs_32)
  3275. }
  3276. func make64SharedLibsAttributes(libsLabelList bazel.LabelList, nativeSharedLibs *convertedNativeSharedLibs) {
  3277. makeSharedLibsAttributes("x86_64", libsLabelList, &nativeSharedLibs.Native_shared_libs_64)
  3278. makeSharedLibsAttributes("arm64", libsLabelList, &nativeSharedLibs.Native_shared_libs_64)
  3279. }
  3280. func makeSharedLibsAttributes(config string, libsLabelList bazel.LabelList,
  3281. labelListAttr *bazel.LabelListAttribute) {
  3282. list := bazel.LabelListAttribute{}
  3283. list.SetSelectValue(bazel.ArchConfigurationAxis, config, libsLabelList)
  3284. labelListAttr.Append(list)
  3285. }
  3286. func invalidCompileMultilib(ctx android.TopDownMutatorContext, value string) {
  3287. ctx.PropertyErrorf("compile_multilib", "Invalid value: %s", value)
  3288. }
  3289. func (a *apexBundle) IsTestApex() bool {
  3290. return a.testApex
  3291. }