apex.go 135 KB

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