apex.go 139 KB

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