apex.go 137 KB

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