apex.go 137 KB

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