java.go 108 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217
  1. // Copyright 2015 Google Inc. All rights reserved.
  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 java
  15. // This file contains the module types for compiling Java for Android, and converts the properties
  16. // into the flags and filenames necessary to pass to the Module. The final creation of the rules
  17. // is handled in builder.go
  18. import (
  19. "fmt"
  20. "path/filepath"
  21. "strings"
  22. "android/soong/bazel"
  23. "android/soong/bazel/cquery"
  24. "android/soong/remoteexec"
  25. "github.com/google/blueprint"
  26. "github.com/google/blueprint/proptools"
  27. "android/soong/android"
  28. "android/soong/cc"
  29. "android/soong/dexpreopt"
  30. "android/soong/java/config"
  31. "android/soong/tradefed"
  32. )
  33. func init() {
  34. registerJavaBuildComponents(android.InitRegistrationContext)
  35. RegisterJavaSdkMemberTypes()
  36. }
  37. func registerJavaBuildComponents(ctx android.RegistrationContext) {
  38. ctx.RegisterModuleType("java_defaults", DefaultsFactory)
  39. ctx.RegisterModuleType("java_library", LibraryFactory)
  40. ctx.RegisterModuleType("java_library_static", LibraryStaticFactory)
  41. ctx.RegisterModuleType("java_library_host", LibraryHostFactory)
  42. ctx.RegisterModuleType("java_binary", BinaryFactory)
  43. ctx.RegisterModuleType("java_binary_host", BinaryHostFactory)
  44. ctx.RegisterModuleType("java_test", TestFactory)
  45. ctx.RegisterModuleType("java_test_helper_library", TestHelperLibraryFactory)
  46. ctx.RegisterModuleType("java_test_host", TestHostFactory)
  47. ctx.RegisterModuleType("java_test_import", JavaTestImportFactory)
  48. ctx.RegisterModuleType("java_import", ImportFactory)
  49. ctx.RegisterModuleType("java_import_host", ImportFactoryHost)
  50. ctx.RegisterModuleType("java_device_for_host", DeviceForHostFactory)
  51. ctx.RegisterModuleType("java_host_for_device", HostForDeviceFactory)
  52. ctx.RegisterModuleType("dex_import", DexImportFactory)
  53. ctx.RegisterModuleType("java_api_library", ApiLibraryFactory)
  54. ctx.RegisterModuleType("java_api_contribution", ApiContributionFactory)
  55. // This mutator registers dependencies on dex2oat for modules that should be
  56. // dexpreopted. This is done late when the final variants have been
  57. // established, to not get the dependencies split into the wrong variants and
  58. // to support the checks in dexpreoptDisabled().
  59. ctx.FinalDepsMutators(func(ctx android.RegisterMutatorsContext) {
  60. ctx.BottomUp("dexpreopt_tool_deps", dexpreoptToolDepsMutator).Parallel()
  61. // needs access to ApexInfoProvider which is available after variant creation
  62. ctx.BottomUp("jacoco_deps", jacocoDepsMutator).Parallel()
  63. })
  64. ctx.RegisterSingletonType("logtags", LogtagsSingleton)
  65. ctx.RegisterSingletonType("kythe_java_extract", kytheExtractJavaFactory)
  66. }
  67. func RegisterJavaSdkMemberTypes() {
  68. // Register sdk member types.
  69. android.RegisterSdkMemberType(javaHeaderLibsSdkMemberType)
  70. android.RegisterSdkMemberType(javaLibsSdkMemberType)
  71. android.RegisterSdkMemberType(javaBootLibsSdkMemberType)
  72. android.RegisterSdkMemberType(javaSystemserverLibsSdkMemberType)
  73. android.RegisterSdkMemberType(javaTestSdkMemberType)
  74. }
  75. var (
  76. // Supports adding java header libraries to module_exports and sdk.
  77. javaHeaderLibsSdkMemberType = &librarySdkMemberType{
  78. android.SdkMemberTypeBase{
  79. PropertyName: "java_header_libs",
  80. SupportsSdk: true,
  81. },
  82. func(_ android.SdkMemberContext, j *Library) android.Path {
  83. headerJars := j.HeaderJars()
  84. if len(headerJars) != 1 {
  85. panic(fmt.Errorf("there must be only one header jar from %q", j.Name()))
  86. }
  87. return headerJars[0]
  88. },
  89. sdkSnapshotFilePathForJar,
  90. copyEverythingToSnapshot,
  91. }
  92. // Export implementation classes jar as part of the sdk.
  93. exportImplementationClassesJar = func(_ android.SdkMemberContext, j *Library) android.Path {
  94. implementationJars := j.ImplementationAndResourcesJars()
  95. if len(implementationJars) != 1 {
  96. panic(fmt.Errorf("there must be only one implementation jar from %q", j.Name()))
  97. }
  98. return implementationJars[0]
  99. }
  100. // Supports adding java implementation libraries to module_exports but not sdk.
  101. javaLibsSdkMemberType = &librarySdkMemberType{
  102. android.SdkMemberTypeBase{
  103. PropertyName: "java_libs",
  104. },
  105. exportImplementationClassesJar,
  106. sdkSnapshotFilePathForJar,
  107. copyEverythingToSnapshot,
  108. }
  109. snapshotRequiresImplementationJar = func(ctx android.SdkMemberContext) bool {
  110. // In the S build the build will break if updatable-media does not provide a full implementation
  111. // jar. That issue was fixed in Tiramisu by b/229932396.
  112. if ctx.IsTargetBuildBeforeTiramisu() && ctx.Name() == "updatable-media" {
  113. return true
  114. }
  115. return false
  116. }
  117. // Supports adding java boot libraries to module_exports and sdk.
  118. //
  119. // The build has some implicit dependencies (via the boot jars configuration) on a number of
  120. // modules, e.g. core-oj, apache-xml, that are part of the java boot class path and which are
  121. // provided by mainline modules (e.g. art, conscrypt, runtime-i18n) but which are not otherwise
  122. // used outside those mainline modules.
  123. //
  124. // As they are not needed outside the mainline modules adding them to the sdk/module-exports as
  125. // either java_libs, or java_header_libs would end up exporting more information than was strictly
  126. // necessary. The java_boot_libs property to allow those modules to be exported as part of the
  127. // sdk/module_exports without exposing any unnecessary information.
  128. javaBootLibsSdkMemberType = &librarySdkMemberType{
  129. android.SdkMemberTypeBase{
  130. PropertyName: "java_boot_libs",
  131. SupportsSdk: true,
  132. },
  133. func(ctx android.SdkMemberContext, j *Library) android.Path {
  134. if snapshotRequiresImplementationJar(ctx) {
  135. return exportImplementationClassesJar(ctx, j)
  136. }
  137. // Java boot libs are only provided in the SDK to provide access to their dex implementation
  138. // jar for use by dexpreopting and boot jars package check. They do not need to provide an
  139. // actual implementation jar but the java_import will need a file that exists so just copy an
  140. // empty file. Any attempt to use that file as a jar will cause a build error.
  141. return ctx.SnapshotBuilder().EmptyFile()
  142. },
  143. func(ctx android.SdkMemberContext, osPrefix, name string) string {
  144. if snapshotRequiresImplementationJar(ctx) {
  145. return sdkSnapshotFilePathForJar(ctx, osPrefix, name)
  146. }
  147. // Create a special name for the implementation jar to try and provide some useful information
  148. // to a developer that attempts to compile against this.
  149. // TODO(b/175714559): Provide a proper error message in Soong not ninja.
  150. return filepath.Join(osPrefix, "java_boot_libs", "snapshot", "jars", "are", "invalid", name+jarFileSuffix)
  151. },
  152. onlyCopyJarToSnapshot,
  153. }
  154. // Supports adding java systemserver libraries to module_exports and sdk.
  155. //
  156. // The build has some implicit dependencies (via the systemserver jars configuration) on a number
  157. // of modules that are part of the java systemserver classpath and which are provided by mainline
  158. // modules but which are not otherwise used outside those mainline modules.
  159. //
  160. // As they are not needed outside the mainline modules adding them to the sdk/module-exports as
  161. // either java_libs, or java_header_libs would end up exporting more information than was strictly
  162. // necessary. The java_systemserver_libs property to allow those modules to be exported as part of
  163. // the sdk/module_exports without exposing any unnecessary information.
  164. javaSystemserverLibsSdkMemberType = &librarySdkMemberType{
  165. android.SdkMemberTypeBase{
  166. PropertyName: "java_systemserver_libs",
  167. SupportsSdk: true,
  168. // This was only added in Tiramisu.
  169. SupportedBuildReleaseSpecification: "Tiramisu+",
  170. },
  171. func(ctx android.SdkMemberContext, j *Library) android.Path {
  172. // Java systemserver libs are only provided in the SDK to provide access to their dex
  173. // implementation jar for use by dexpreopting. They do not need to provide an actual
  174. // implementation jar but the java_import will need a file that exists so just copy an empty
  175. // file. Any attempt to use that file as a jar will cause a build error.
  176. return ctx.SnapshotBuilder().EmptyFile()
  177. },
  178. func(_ android.SdkMemberContext, osPrefix, name string) string {
  179. // Create a special name for the implementation jar to try and provide some useful information
  180. // to a developer that attempts to compile against this.
  181. // TODO(b/175714559): Provide a proper error message in Soong not ninja.
  182. return filepath.Join(osPrefix, "java_systemserver_libs", "snapshot", "jars", "are", "invalid", name+jarFileSuffix)
  183. },
  184. onlyCopyJarToSnapshot,
  185. }
  186. // Supports adding java test libraries to module_exports but not sdk.
  187. javaTestSdkMemberType = &testSdkMemberType{
  188. SdkMemberTypeBase: android.SdkMemberTypeBase{
  189. PropertyName: "java_tests",
  190. },
  191. }
  192. // Rule for generating device binary default wrapper
  193. deviceBinaryWrapper = pctx.StaticRule("deviceBinaryWrapper", blueprint.RuleParams{
  194. Command: `echo -e '#!/system/bin/sh\n` +
  195. `export CLASSPATH=/system/framework/$jar_name\n` +
  196. `exec app_process /$partition/bin $main_class "$$@"'> ${out}`,
  197. Description: "Generating device binary wrapper ${jar_name}",
  198. }, "jar_name", "partition", "main_class")
  199. )
  200. // JavaInfo contains information about a java module for use by modules that depend on it.
  201. type JavaInfo struct {
  202. // HeaderJars is a list of jars that can be passed as the javac classpath in order to link
  203. // against this module. If empty, ImplementationJars should be used instead.
  204. HeaderJars android.Paths
  205. // set of header jars for all transitive libs deps
  206. TransitiveLibsHeaderJars *android.DepSet
  207. // set of header jars for all transitive static libs deps
  208. TransitiveStaticLibsHeaderJars *android.DepSet
  209. // ImplementationAndResourceJars is a list of jars that contain the implementations of classes
  210. // in the module as well as any resources included in the module.
  211. ImplementationAndResourcesJars android.Paths
  212. // ImplementationJars is a list of jars that contain the implementations of classes in the
  213. //module.
  214. ImplementationJars android.Paths
  215. // ResourceJars is a list of jars that contain the resources included in the module.
  216. ResourceJars android.Paths
  217. // AidlIncludeDirs is a list of directories that should be passed to the aidl tool when
  218. // depending on this module.
  219. AidlIncludeDirs android.Paths
  220. // SrcJarArgs is a list of arguments to pass to soong_zip to package the sources of this
  221. // module.
  222. SrcJarArgs []string
  223. // SrcJarDeps is a list of paths to depend on when packaging the sources of this module.
  224. SrcJarDeps android.Paths
  225. // ExportedPlugins is a list of paths that should be used as annotation processors for any
  226. // module that depends on this module.
  227. ExportedPlugins android.Paths
  228. // ExportedPluginClasses is a list of classes that should be run as annotation processors for
  229. // any module that depends on this module.
  230. ExportedPluginClasses []string
  231. // ExportedPluginDisableTurbine is true if this module's annotation processors generate APIs,
  232. // requiring disbling turbine for any modules that depend on it.
  233. ExportedPluginDisableTurbine bool
  234. // JacocoReportClassesFile is the path to a jar containing uninstrumented classes that will be
  235. // instrumented by jacoco.
  236. JacocoReportClassesFile android.Path
  237. }
  238. var JavaInfoProvider = blueprint.NewProvider(JavaInfo{})
  239. // SyspropPublicStubInfo contains info about the sysprop public stub library that corresponds to
  240. // the sysprop implementation library.
  241. type SyspropPublicStubInfo struct {
  242. // JavaInfo is the JavaInfoProvider of the sysprop public stub library that corresponds to
  243. // the sysprop implementation library.
  244. JavaInfo JavaInfo
  245. }
  246. var SyspropPublicStubInfoProvider = blueprint.NewProvider(SyspropPublicStubInfo{})
  247. // Methods that need to be implemented for a module that is added to apex java_libs property.
  248. type ApexDependency interface {
  249. HeaderJars() android.Paths
  250. ImplementationAndResourcesJars() android.Paths
  251. }
  252. // Provides build path and install path to DEX jars.
  253. type UsesLibraryDependency interface {
  254. DexJarBuildPath() OptionalDexJarPath
  255. DexJarInstallPath() android.Path
  256. ClassLoaderContexts() dexpreopt.ClassLoaderContextMap
  257. }
  258. // Provides transitive Proguard flag files to downstream DEX jars.
  259. type LibraryDependency interface {
  260. ExportedProguardFlagFiles() android.Paths
  261. }
  262. // TODO(jungjw): Move this to kythe.go once it's created.
  263. type xref interface {
  264. XrefJavaFiles() android.Paths
  265. }
  266. func (j *Module) XrefJavaFiles() android.Paths {
  267. return j.kytheFiles
  268. }
  269. type dependencyTag struct {
  270. blueprint.BaseDependencyTag
  271. name string
  272. // True if the dependency is relinked at runtime.
  273. runtimeLinked bool
  274. // True if the dependency is a toolchain, for example an annotation processor.
  275. toolchain bool
  276. }
  277. // installDependencyTag is a dependency tag that is annotated to cause the installed files of the
  278. // dependency to be installed when the parent module is installed.
  279. type installDependencyTag struct {
  280. blueprint.BaseDependencyTag
  281. android.InstallAlwaysNeededDependencyTag
  282. name string
  283. }
  284. func (d dependencyTag) LicenseAnnotations() []android.LicenseAnnotation {
  285. if d.runtimeLinked {
  286. return []android.LicenseAnnotation{android.LicenseAnnotationSharedDependency}
  287. } else if d.toolchain {
  288. return []android.LicenseAnnotation{android.LicenseAnnotationToolchain}
  289. }
  290. return nil
  291. }
  292. var _ android.LicenseAnnotationsDependencyTag = dependencyTag{}
  293. type usesLibraryDependencyTag struct {
  294. dependencyTag
  295. sdkVersion int // SDK version in which the library appared as a standalone library.
  296. optional bool // If the dependency is optional or required.
  297. }
  298. func makeUsesLibraryDependencyTag(sdkVersion int, optional bool) usesLibraryDependencyTag {
  299. return usesLibraryDependencyTag{
  300. dependencyTag: dependencyTag{
  301. name: fmt.Sprintf("uses-library-%d", sdkVersion),
  302. runtimeLinked: true,
  303. },
  304. sdkVersion: sdkVersion,
  305. optional: optional,
  306. }
  307. }
  308. func IsJniDepTag(depTag blueprint.DependencyTag) bool {
  309. return depTag == jniLibTag
  310. }
  311. var (
  312. dataNativeBinsTag = dependencyTag{name: "dataNativeBins"}
  313. dataDeviceBinsTag = dependencyTag{name: "dataDeviceBins"}
  314. staticLibTag = dependencyTag{name: "staticlib"}
  315. libTag = dependencyTag{name: "javalib", runtimeLinked: true}
  316. sdkLibTag = dependencyTag{name: "sdklib", runtimeLinked: true}
  317. java9LibTag = dependencyTag{name: "java9lib", runtimeLinked: true}
  318. pluginTag = dependencyTag{name: "plugin", toolchain: true}
  319. errorpronePluginTag = dependencyTag{name: "errorprone-plugin", toolchain: true}
  320. exportedPluginTag = dependencyTag{name: "exported-plugin", toolchain: true}
  321. bootClasspathTag = dependencyTag{name: "bootclasspath", runtimeLinked: true}
  322. systemModulesTag = dependencyTag{name: "system modules", runtimeLinked: true}
  323. frameworkResTag = dependencyTag{name: "framework-res"}
  324. kotlinStdlibTag = dependencyTag{name: "kotlin-stdlib", runtimeLinked: true}
  325. kotlinAnnotationsTag = dependencyTag{name: "kotlin-annotations", runtimeLinked: true}
  326. kotlinPluginTag = dependencyTag{name: "kotlin-plugin", toolchain: true}
  327. proguardRaiseTag = dependencyTag{name: "proguard-raise"}
  328. certificateTag = dependencyTag{name: "certificate"}
  329. instrumentationForTag = dependencyTag{name: "instrumentation_for"}
  330. extraLintCheckTag = dependencyTag{name: "extra-lint-check", toolchain: true}
  331. jniLibTag = dependencyTag{name: "jnilib", runtimeLinked: true}
  332. r8LibraryJarTag = dependencyTag{name: "r8-libraryjar", runtimeLinked: true}
  333. syspropPublicStubDepTag = dependencyTag{name: "sysprop public stub"}
  334. javaApiContributionTag = dependencyTag{name: "java-api-contribution"}
  335. depApiSrcsTag = dependencyTag{name: "dep-api-srcs"}
  336. jniInstallTag = installDependencyTag{name: "jni install"}
  337. binaryInstallTag = installDependencyTag{name: "binary install"}
  338. usesLibReqTag = makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, false)
  339. usesLibOptTag = makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, true)
  340. usesLibCompat28OptTag = makeUsesLibraryDependencyTag(28, true)
  341. usesLibCompat29ReqTag = makeUsesLibraryDependencyTag(29, false)
  342. usesLibCompat30OptTag = makeUsesLibraryDependencyTag(30, true)
  343. )
  344. func IsLibDepTag(depTag blueprint.DependencyTag) bool {
  345. return depTag == libTag || depTag == sdkLibTag
  346. }
  347. func IsStaticLibDepTag(depTag blueprint.DependencyTag) bool {
  348. return depTag == staticLibTag
  349. }
  350. type sdkDep struct {
  351. useModule, useFiles, invalidVersion bool
  352. // The modules that will be added to the bootclasspath when targeting 1.8 or lower
  353. bootclasspath []string
  354. // The default system modules to use. Will be an empty string if no system
  355. // modules are to be used.
  356. systemModules string
  357. // The modules that will be added to the classpath regardless of the Java language level targeted
  358. classpath []string
  359. // The modules that will be added ot the classpath when targeting 1.9 or higher
  360. // (normally these will be on the bootclasspath when targeting 1.8 or lower)
  361. java9Classpath []string
  362. frameworkResModule string
  363. jars android.Paths
  364. aidl android.OptionalPath
  365. noStandardLibs, noFrameworksLibs bool
  366. }
  367. func (s sdkDep) hasStandardLibs() bool {
  368. return !s.noStandardLibs
  369. }
  370. func (s sdkDep) hasFrameworkLibs() bool {
  371. return !s.noStandardLibs && !s.noFrameworksLibs
  372. }
  373. type jniLib struct {
  374. name string
  375. path android.Path
  376. target android.Target
  377. coverageFile android.OptionalPath
  378. unstrippedFile android.Path
  379. partition string
  380. }
  381. func sdkDeps(ctx android.BottomUpMutatorContext, sdkContext android.SdkContext, d dexer) {
  382. sdkDep := decodeSdkDep(ctx, sdkContext)
  383. if sdkDep.useModule {
  384. ctx.AddVariationDependencies(nil, bootClasspathTag, sdkDep.bootclasspath...)
  385. ctx.AddVariationDependencies(nil, java9LibTag, sdkDep.java9Classpath...)
  386. ctx.AddVariationDependencies(nil, sdkLibTag, sdkDep.classpath...)
  387. if d.effectiveOptimizeEnabled() && sdkDep.hasStandardLibs() {
  388. ctx.AddVariationDependencies(nil, proguardRaiseTag,
  389. android.JavaApiLibraryNames(ctx.Config(), config.LegacyCorePlatformBootclasspathLibraries)...,
  390. )
  391. }
  392. if d.effectiveOptimizeEnabled() && sdkDep.hasFrameworkLibs() {
  393. ctx.AddVariationDependencies(nil, proguardRaiseTag, config.FrameworkLibraries...)
  394. }
  395. }
  396. if sdkDep.systemModules != "" {
  397. ctx.AddVariationDependencies(nil, systemModulesTag, sdkDep.systemModules)
  398. }
  399. }
  400. type deps struct {
  401. // bootClasspath is the list of jars that form the boot classpath (generally the java.* and
  402. // android.* classes) for tools that still use it. javac targeting 1.9 or higher uses
  403. // systemModules and java9Classpath instead.
  404. bootClasspath classpath
  405. // classpath is the list of jars that form the classpath for javac and kotlinc rules. It
  406. // contains header jars for all static and non-static dependencies.
  407. classpath classpath
  408. // dexClasspath is the list of jars that form the classpath for d8 and r8 rules. It contains
  409. // header jars for all non-static dependencies. Static dependencies have already been
  410. // combined into the program jar.
  411. dexClasspath classpath
  412. // java9Classpath is the list of jars that will be added to the classpath when targeting
  413. // 1.9 or higher. It generally contains the android.* classes, while the java.* classes
  414. // are provided by systemModules.
  415. java9Classpath classpath
  416. processorPath classpath
  417. errorProneProcessorPath classpath
  418. processorClasses []string
  419. staticJars android.Paths
  420. staticHeaderJars android.Paths
  421. staticResourceJars android.Paths
  422. aidlIncludeDirs android.Paths
  423. srcs android.Paths
  424. srcJars android.Paths
  425. systemModules *systemModules
  426. aidlPreprocess android.OptionalPath
  427. kotlinStdlib android.Paths
  428. kotlinAnnotations android.Paths
  429. kotlinPlugins android.Paths
  430. disableTurbine bool
  431. }
  432. func checkProducesJars(ctx android.ModuleContext, dep android.SourceFileProducer) {
  433. for _, f := range dep.Srcs() {
  434. if f.Ext() != ".jar" {
  435. ctx.ModuleErrorf("genrule %q must generate files ending with .jar to be used as a libs or static_libs dependency",
  436. ctx.OtherModuleName(dep.(blueprint.Module)))
  437. }
  438. }
  439. }
  440. func getJavaVersion(ctx android.ModuleContext, javaVersion string, sdkContext android.SdkContext) javaVersion {
  441. if javaVersion != "" {
  442. return normalizeJavaVersion(ctx, javaVersion)
  443. } else if ctx.Device() {
  444. return defaultJavaLanguageVersion(ctx, sdkContext.SdkVersion(ctx))
  445. } else {
  446. return JAVA_VERSION_17
  447. }
  448. }
  449. // Java version for stubs generation
  450. func getStubsJavaVersion() javaVersion {
  451. return JAVA_VERSION_8
  452. }
  453. type javaVersion int
  454. const (
  455. JAVA_VERSION_UNSUPPORTED = 0
  456. JAVA_VERSION_6 = 6
  457. JAVA_VERSION_7 = 7
  458. JAVA_VERSION_8 = 8
  459. JAVA_VERSION_9 = 9
  460. JAVA_VERSION_11 = 11
  461. JAVA_VERSION_17 = 17
  462. )
  463. func (v javaVersion) String() string {
  464. switch v {
  465. case JAVA_VERSION_6:
  466. return "1.6"
  467. case JAVA_VERSION_7:
  468. return "1.7"
  469. case JAVA_VERSION_8:
  470. return "1.8"
  471. case JAVA_VERSION_9:
  472. return "1.9"
  473. case JAVA_VERSION_11:
  474. return "11"
  475. case JAVA_VERSION_17:
  476. return "17"
  477. default:
  478. return "unsupported"
  479. }
  480. }
  481. func (v javaVersion) StringForKotlinc() string {
  482. // $ ./external/kotlinc/bin/kotlinc -jvm-target foo
  483. // error: unknown JVM target version: foo
  484. // Supported versions: 1.6, 1.8, 9, 10, 11, 12, 13, 14, 15, 16, 17
  485. switch v {
  486. case JAVA_VERSION_7:
  487. return "1.6"
  488. case JAVA_VERSION_9:
  489. return "9"
  490. default:
  491. return v.String()
  492. }
  493. }
  494. // Returns true if javac targeting this version uses system modules instead of a bootclasspath.
  495. func (v javaVersion) usesJavaModules() bool {
  496. return v >= 9
  497. }
  498. func normalizeJavaVersion(ctx android.BaseModuleContext, javaVersion string) javaVersion {
  499. switch javaVersion {
  500. case "1.6", "6":
  501. return JAVA_VERSION_6
  502. case "1.7", "7":
  503. return JAVA_VERSION_7
  504. case "1.8", "8":
  505. return JAVA_VERSION_8
  506. case "1.9", "9":
  507. return JAVA_VERSION_9
  508. case "11":
  509. return JAVA_VERSION_11
  510. case "17":
  511. return JAVA_VERSION_17
  512. case "10", "12", "13", "14", "15", "16":
  513. ctx.PropertyErrorf("java_version", "Java language level %s is not supported", javaVersion)
  514. return JAVA_VERSION_UNSUPPORTED
  515. default:
  516. ctx.PropertyErrorf("java_version", "Unrecognized Java language level")
  517. return JAVA_VERSION_UNSUPPORTED
  518. }
  519. }
  520. //
  521. // Java libraries (.jar file)
  522. //
  523. type Library struct {
  524. Module
  525. exportedProguardFlagFiles android.Paths
  526. InstallMixin func(ctx android.ModuleContext, installPath android.Path) (extraInstallDeps android.Paths)
  527. }
  528. var _ LibraryDependency = (*Library)(nil)
  529. func (j *Library) ExportedProguardFlagFiles() android.Paths {
  530. return j.exportedProguardFlagFiles
  531. }
  532. var _ android.ApexModule = (*Library)(nil)
  533. // Provides access to the list of permitted packages from apex boot jars.
  534. type PermittedPackagesForUpdatableBootJars interface {
  535. PermittedPackagesForUpdatableBootJars() []string
  536. }
  537. var _ PermittedPackagesForUpdatableBootJars = (*Library)(nil)
  538. func (j *Library) PermittedPackagesForUpdatableBootJars() []string {
  539. return j.properties.Permitted_packages
  540. }
  541. func shouldUncompressDex(ctx android.ModuleContext, dexpreopter *dexpreopter) bool {
  542. // Store uncompressed (and aligned) any dex files from jars in APEXes.
  543. if apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo); !apexInfo.IsForPlatform() {
  544. return true
  545. }
  546. // Store uncompressed (and do not strip) dex files from boot class path jars.
  547. if inList(ctx.ModuleName(), ctx.Config().BootJars()) {
  548. return true
  549. }
  550. // Store uncompressed dex files that are preopted on /system.
  551. if !dexpreopter.dexpreoptDisabled(ctx) && (ctx.Host() || !dexpreopter.odexOnSystemOther(ctx, dexpreopter.installPath)) {
  552. return true
  553. }
  554. if ctx.Config().UncompressPrivAppDex() &&
  555. inList(ctx.ModuleName(), ctx.Config().ModulesLoadedByPrivilegedModules()) {
  556. return true
  557. }
  558. return false
  559. }
  560. // Sets `dexer.dexProperties.Uncompress_dex` to the proper value.
  561. func setUncompressDex(ctx android.ModuleContext, dexpreopter *dexpreopter, dexer *dexer) {
  562. if dexer.dexProperties.Uncompress_dex == nil {
  563. // If the value was not force-set by the user, use reasonable default based on the module.
  564. dexer.dexProperties.Uncompress_dex = proptools.BoolPtr(shouldUncompressDex(ctx, dexpreopter))
  565. }
  566. }
  567. func (j *Library) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  568. j.provideHiddenAPIPropertyInfo(ctx)
  569. j.sdkVersion = j.SdkVersion(ctx)
  570. j.minSdkVersion = j.MinSdkVersion(ctx)
  571. j.maxSdkVersion = j.MaxSdkVersion(ctx)
  572. apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
  573. if !apexInfo.IsForPlatform() {
  574. j.hideApexVariantFromMake = true
  575. }
  576. j.checkSdkVersions(ctx)
  577. if ctx.Device() {
  578. j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
  579. ctx, android.PathForModuleInstall(ctx, "framework", j.Stem()+".jar"))
  580. j.dexpreopter.isSDKLibrary = j.deviceProperties.IsSDKLibrary
  581. setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
  582. j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
  583. j.classLoaderContexts = j.usesLibrary.classLoaderContextForUsesLibDeps(ctx)
  584. }
  585. j.compile(ctx, nil)
  586. // Collect the module directory for IDE info in java/jdeps.go.
  587. j.modulePaths = append(j.modulePaths, ctx.ModuleDir())
  588. exclusivelyForApex := !apexInfo.IsForPlatform()
  589. if (Bool(j.properties.Installable) || ctx.Host()) && !exclusivelyForApex {
  590. var extraInstallDeps android.Paths
  591. if j.InstallMixin != nil {
  592. extraInstallDeps = j.InstallMixin(ctx, j.outputFile)
  593. }
  594. hostDexNeeded := Bool(j.deviceProperties.Hostdex) && !ctx.Host()
  595. if hostDexNeeded {
  596. j.hostdexInstallFile = ctx.InstallFile(
  597. android.PathForHostDexInstall(ctx, "framework"),
  598. j.Stem()+"-hostdex.jar", j.outputFile)
  599. }
  600. var installDir android.InstallPath
  601. if ctx.InstallInTestcases() {
  602. var archDir string
  603. if !ctx.Host() {
  604. archDir = ctx.DeviceConfig().DeviceArch()
  605. }
  606. installDir = android.PathForModuleInstall(ctx, ctx.ModuleName(), archDir)
  607. } else {
  608. installDir = android.PathForModuleInstall(ctx, "framework")
  609. }
  610. j.installFile = ctx.InstallFile(installDir, j.Stem()+".jar", j.outputFile, extraInstallDeps...)
  611. }
  612. j.exportedProguardFlagFiles = append(j.exportedProguardFlagFiles,
  613. android.PathsForModuleSrc(ctx, j.dexProperties.Optimize.Proguard_flags_files)...)
  614. ctx.VisitDirectDeps(func(m android.Module) {
  615. if lib, ok := m.(LibraryDependency); ok && ctx.OtherModuleDependencyTag(m) == staticLibTag {
  616. j.exportedProguardFlagFiles = append(j.exportedProguardFlagFiles, lib.ExportedProguardFlagFiles()...)
  617. }
  618. })
  619. j.exportedProguardFlagFiles = android.FirstUniquePaths(j.exportedProguardFlagFiles)
  620. }
  621. func (j *Library) DepsMutator(ctx android.BottomUpMutatorContext) {
  622. j.deps(ctx)
  623. j.usesLibrary.deps(ctx, false)
  624. }
  625. const (
  626. aidlIncludeDir = "aidl"
  627. javaDir = "java"
  628. jarFileSuffix = ".jar"
  629. testConfigSuffix = "-AndroidTest.xml"
  630. )
  631. // path to the jar file of a java library. Relative to <sdk_root>/<api_dir>
  632. func sdkSnapshotFilePathForJar(_ android.SdkMemberContext, osPrefix, name string) string {
  633. return sdkSnapshotFilePathForMember(osPrefix, name, jarFileSuffix)
  634. }
  635. func sdkSnapshotFilePathForMember(osPrefix, name string, suffix string) string {
  636. return filepath.Join(javaDir, osPrefix, name+suffix)
  637. }
  638. type librarySdkMemberType struct {
  639. android.SdkMemberTypeBase
  640. // Function to retrieve the appropriate output jar (implementation or header) from
  641. // the library.
  642. jarToExportGetter func(ctx android.SdkMemberContext, j *Library) android.Path
  643. // Function to compute the snapshot relative path to which the named library's
  644. // jar should be copied.
  645. snapshotPathGetter func(ctx android.SdkMemberContext, osPrefix, name string) string
  646. // True if only the jar should be copied to the snapshot, false if the jar plus any additional
  647. // files like aidl files should also be copied.
  648. onlyCopyJarToSnapshot bool
  649. }
  650. const (
  651. onlyCopyJarToSnapshot = true
  652. copyEverythingToSnapshot = false
  653. )
  654. func (mt *librarySdkMemberType) AddDependencies(ctx android.SdkDependencyContext, dependencyTag blueprint.DependencyTag, names []string) {
  655. ctx.AddVariationDependencies(nil, dependencyTag, names...)
  656. }
  657. func (mt *librarySdkMemberType) IsInstance(module android.Module) bool {
  658. _, ok := module.(*Library)
  659. return ok
  660. }
  661. func (mt *librarySdkMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
  662. return ctx.SnapshotBuilder().AddPrebuiltModule(member, "java_import")
  663. }
  664. func (mt *librarySdkMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
  665. return &librarySdkMemberProperties{}
  666. }
  667. type librarySdkMemberProperties struct {
  668. android.SdkMemberPropertiesBase
  669. JarToExport android.Path `android:"arch_variant"`
  670. AidlIncludeDirs android.Paths
  671. // The list of permitted packages that need to be passed to the prebuilts as they are used to
  672. // create the updatable-bcp-packages.txt file.
  673. PermittedPackages []string
  674. // The value of the min_sdk_version property, translated into a number where possible.
  675. MinSdkVersion *string `supported_build_releases:"Tiramisu+"`
  676. DexPreoptProfileGuided *bool `supported_build_releases:"UpsideDownCake+"`
  677. }
  678. func (p *librarySdkMemberProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
  679. j := variant.(*Library)
  680. p.JarToExport = ctx.MemberType().(*librarySdkMemberType).jarToExportGetter(ctx, j)
  681. p.AidlIncludeDirs = j.AidlIncludeDirs()
  682. p.PermittedPackages = j.PermittedPackagesForUpdatableBootJars()
  683. // If the min_sdk_version was set then add the canonical representation of the API level to the
  684. // snapshot.
  685. if j.deviceProperties.Min_sdk_version != nil {
  686. canonical, err := android.ReplaceFinalizedCodenames(ctx.SdkModuleContext().Config(), j.minSdkVersion.String())
  687. if err != nil {
  688. ctx.ModuleErrorf("%s", err)
  689. }
  690. p.MinSdkVersion = proptools.StringPtr(canonical)
  691. }
  692. if j.dexpreopter.dexpreoptProperties.Dex_preopt_result.Profile_guided {
  693. p.DexPreoptProfileGuided = proptools.BoolPtr(true)
  694. }
  695. }
  696. func (p *librarySdkMemberProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
  697. builder := ctx.SnapshotBuilder()
  698. memberType := ctx.MemberType().(*librarySdkMemberType)
  699. exportedJar := p.JarToExport
  700. if exportedJar != nil {
  701. // Delegate the creation of the snapshot relative path to the member type.
  702. snapshotRelativeJavaLibPath := memberType.snapshotPathGetter(ctx, p.OsPrefix(), ctx.Name())
  703. // Copy the exported jar to the snapshot.
  704. builder.CopyToSnapshot(exportedJar, snapshotRelativeJavaLibPath)
  705. propertySet.AddProperty("jars", []string{snapshotRelativeJavaLibPath})
  706. }
  707. if p.MinSdkVersion != nil {
  708. propertySet.AddProperty("min_sdk_version", *p.MinSdkVersion)
  709. }
  710. if len(p.PermittedPackages) > 0 {
  711. propertySet.AddProperty("permitted_packages", p.PermittedPackages)
  712. }
  713. dexPreoptSet := propertySet.AddPropertySet("dex_preopt")
  714. if p.DexPreoptProfileGuided != nil {
  715. dexPreoptSet.AddProperty("profile_guided", proptools.Bool(p.DexPreoptProfileGuided))
  716. }
  717. // Do not copy anything else to the snapshot.
  718. if memberType.onlyCopyJarToSnapshot {
  719. return
  720. }
  721. aidlIncludeDirs := p.AidlIncludeDirs
  722. if len(aidlIncludeDirs) != 0 {
  723. sdkModuleContext := ctx.SdkModuleContext()
  724. for _, dir := range aidlIncludeDirs {
  725. // TODO(jiyong): copy parcelable declarations only
  726. aidlFiles, _ := sdkModuleContext.GlobWithDeps(dir.String()+"/**/*.aidl", nil)
  727. for _, file := range aidlFiles {
  728. builder.CopyToSnapshot(android.PathForSource(sdkModuleContext, file), filepath.Join(aidlIncludeDir, file))
  729. }
  730. }
  731. // TODO(b/151933053) - add aidl include dirs property
  732. }
  733. }
  734. // java_library builds and links sources into a `.jar` file for the device, and possibly for the host as well.
  735. //
  736. // By default, a java_library has a single variant that produces a `.jar` file containing `.class` files that were
  737. // compiled against the device bootclasspath. This jar is not suitable for installing on a device, but can be used
  738. // as a `static_libs` dependency of another module.
  739. //
  740. // Specifying `installable: true` will product a `.jar` file containing `classes.dex` files, suitable for installing on
  741. // a device.
  742. //
  743. // Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
  744. // compiled against the host bootclasspath.
  745. func LibraryFactory() android.Module {
  746. module := &Library{}
  747. module.addHostAndDeviceProperties()
  748. module.initModuleAndImport(module)
  749. android.InitApexModule(module)
  750. android.InitBazelModule(module)
  751. InitJavaModule(module, android.HostAndDeviceSupported)
  752. return module
  753. }
  754. // java_library_static is an obsolete alias for java_library.
  755. func LibraryStaticFactory() android.Module {
  756. return LibraryFactory()
  757. }
  758. // java_library_host builds and links sources into a `.jar` file for the host.
  759. //
  760. // A java_library_host has a single variant that produces a `.jar` file containing `.class` files that were
  761. // compiled against the host bootclasspath.
  762. func LibraryHostFactory() android.Module {
  763. module := &Library{}
  764. module.addHostProperties()
  765. module.Module.properties.Installable = proptools.BoolPtr(true)
  766. android.InitApexModule(module)
  767. android.InitBazelModule(module)
  768. InitJavaModule(module, android.HostSupported)
  769. return module
  770. }
  771. //
  772. // Java Tests
  773. //
  774. // Test option struct.
  775. type TestOptions struct {
  776. android.CommonTestOptions
  777. // a list of extra test configuration files that should be installed with the module.
  778. Extra_test_configs []string `android:"path,arch_variant"`
  779. // Extra <option> tags to add to the auto generated test xml file. The "key"
  780. // is optional in each of these.
  781. Tradefed_options []tradefed.Option
  782. }
  783. type testProperties struct {
  784. // list of compatibility suites (for example "cts", "vts") that the module should be
  785. // installed into.
  786. Test_suites []string `android:"arch_variant"`
  787. // the name of the test configuration (for example "AndroidTest.xml") that should be
  788. // installed with the module.
  789. Test_config *string `android:"path,arch_variant"`
  790. // the name of the test configuration template (for example "AndroidTestTemplate.xml") that
  791. // should be installed with the module.
  792. Test_config_template *string `android:"path,arch_variant"`
  793. // list of files or filegroup modules that provide data that should be installed alongside
  794. // the test
  795. Data []string `android:"path"`
  796. // Flag to indicate whether or not to create test config automatically. If AndroidTest.xml
  797. // doesn't exist next to the Android.bp, this attribute doesn't need to be set to true
  798. // explicitly.
  799. Auto_gen_config *bool
  800. // Add parameterized mainline modules to auto generated test config. The options will be
  801. // handled by TradeFed to do downloading and installing the specified modules on the device.
  802. Test_mainline_modules []string
  803. // Test options.
  804. Test_options TestOptions
  805. // Names of modules containing JNI libraries that should be installed alongside the test.
  806. Jni_libs []string
  807. // Install the test into a folder named for the module in all test suites.
  808. Per_testcase_directory *bool
  809. }
  810. type hostTestProperties struct {
  811. // list of native binary modules that should be installed alongside the test
  812. Data_native_bins []string `android:"arch_variant"`
  813. // list of device binary modules that should be installed alongside the test
  814. // This property only adds the first variant of the dependency
  815. Data_device_bins_first []string `android:"arch_variant"`
  816. // list of device binary modules that should be installed alongside the test
  817. // This property adds 64bit AND 32bit variants of the dependency
  818. Data_device_bins_both []string `android:"arch_variant"`
  819. // list of device binary modules that should be installed alongside the test
  820. // This property only adds 64bit variants of the dependency
  821. Data_device_bins_64 []string `android:"arch_variant"`
  822. // list of device binary modules that should be installed alongside the test
  823. // This property adds 32bit variants of the dependency if available, or else
  824. // defaults to the 64bit variant
  825. Data_device_bins_prefer32 []string `android:"arch_variant"`
  826. // list of device binary modules that should be installed alongside the test
  827. // This property only adds 32bit variants of the dependency
  828. Data_device_bins_32 []string `android:"arch_variant"`
  829. }
  830. type testHelperLibraryProperties struct {
  831. // list of compatibility suites (for example "cts", "vts") that the module should be
  832. // installed into.
  833. Test_suites []string `android:"arch_variant"`
  834. // Install the test into a folder named for the module in all test suites.
  835. Per_testcase_directory *bool
  836. }
  837. type prebuiltTestProperties struct {
  838. // list of compatibility suites (for example "cts", "vts") that the module should be
  839. // installed into.
  840. Test_suites []string `android:"arch_variant"`
  841. // the name of the test configuration (for example "AndroidTest.xml") that should be
  842. // installed with the module.
  843. Test_config *string `android:"path,arch_variant"`
  844. }
  845. type Test struct {
  846. Library
  847. testProperties testProperties
  848. testConfig android.Path
  849. extraTestConfigs android.Paths
  850. data android.Paths
  851. }
  852. type TestHost struct {
  853. Test
  854. testHostProperties hostTestProperties
  855. }
  856. type TestHelperLibrary struct {
  857. Library
  858. testHelperLibraryProperties testHelperLibraryProperties
  859. }
  860. type JavaTestImport struct {
  861. Import
  862. prebuiltTestProperties prebuiltTestProperties
  863. testConfig android.Path
  864. dexJarFile android.Path
  865. }
  866. func (j *Test) InstallInTestcases() bool {
  867. // Host java tests install into $(HOST_OUT_JAVA_LIBRARIES), and then are copied into
  868. // testcases by base_rules.mk.
  869. return !j.Host()
  870. }
  871. func (j *TestHelperLibrary) InstallInTestcases() bool {
  872. return true
  873. }
  874. func (j *JavaTestImport) InstallInTestcases() bool {
  875. return true
  876. }
  877. func (j *TestHost) addDataDeviceBinsDeps(ctx android.BottomUpMutatorContext) {
  878. if len(j.testHostProperties.Data_device_bins_first) > 0 {
  879. deviceVariations := ctx.Config().AndroidFirstDeviceTarget.Variations()
  880. ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_first...)
  881. }
  882. var maybeAndroid32Target *android.Target
  883. var maybeAndroid64Target *android.Target
  884. android32TargetList := android.FirstTarget(ctx.Config().Targets[android.Android], "lib32")
  885. android64TargetList := android.FirstTarget(ctx.Config().Targets[android.Android], "lib64")
  886. if len(android32TargetList) > 0 {
  887. maybeAndroid32Target = &android32TargetList[0]
  888. }
  889. if len(android64TargetList) > 0 {
  890. maybeAndroid64Target = &android64TargetList[0]
  891. }
  892. if len(j.testHostProperties.Data_device_bins_both) > 0 {
  893. if maybeAndroid32Target == nil && maybeAndroid64Target == nil {
  894. ctx.PropertyErrorf("data_device_bins_both", "no device targets available. Targets: %q", ctx.Config().Targets)
  895. return
  896. }
  897. if maybeAndroid32Target != nil {
  898. ctx.AddFarVariationDependencies(
  899. maybeAndroid32Target.Variations(),
  900. dataDeviceBinsTag,
  901. j.testHostProperties.Data_device_bins_both...,
  902. )
  903. }
  904. if maybeAndroid64Target != nil {
  905. ctx.AddFarVariationDependencies(
  906. maybeAndroid64Target.Variations(),
  907. dataDeviceBinsTag,
  908. j.testHostProperties.Data_device_bins_both...,
  909. )
  910. }
  911. }
  912. if len(j.testHostProperties.Data_device_bins_prefer32) > 0 {
  913. if maybeAndroid32Target != nil {
  914. ctx.AddFarVariationDependencies(
  915. maybeAndroid32Target.Variations(),
  916. dataDeviceBinsTag,
  917. j.testHostProperties.Data_device_bins_prefer32...,
  918. )
  919. } else {
  920. if maybeAndroid64Target == nil {
  921. ctx.PropertyErrorf("data_device_bins_prefer32", "no device targets available. Targets: %q", ctx.Config().Targets)
  922. return
  923. }
  924. ctx.AddFarVariationDependencies(
  925. maybeAndroid64Target.Variations(),
  926. dataDeviceBinsTag,
  927. j.testHostProperties.Data_device_bins_prefer32...,
  928. )
  929. }
  930. }
  931. if len(j.testHostProperties.Data_device_bins_32) > 0 {
  932. if maybeAndroid32Target == nil {
  933. ctx.PropertyErrorf("data_device_bins_32", "cannot find 32bit device target. Targets: %q", ctx.Config().Targets)
  934. return
  935. }
  936. deviceVariations := maybeAndroid32Target.Variations()
  937. ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_32...)
  938. }
  939. if len(j.testHostProperties.Data_device_bins_64) > 0 {
  940. if maybeAndroid64Target == nil {
  941. ctx.PropertyErrorf("data_device_bins_64", "cannot find 64bit device target. Targets: %q", ctx.Config().Targets)
  942. return
  943. }
  944. deviceVariations := maybeAndroid64Target.Variations()
  945. ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_64...)
  946. }
  947. }
  948. func (j *TestHost) DepsMutator(ctx android.BottomUpMutatorContext) {
  949. if len(j.testHostProperties.Data_native_bins) > 0 {
  950. for _, target := range ctx.MultiTargets() {
  951. ctx.AddVariationDependencies(target.Variations(), dataNativeBinsTag, j.testHostProperties.Data_native_bins...)
  952. }
  953. }
  954. if len(j.testProperties.Jni_libs) > 0 {
  955. for _, target := range ctx.MultiTargets() {
  956. sharedLibVariations := append(target.Variations(), blueprint.Variation{Mutator: "link", Variation: "shared"})
  957. ctx.AddFarVariationDependencies(sharedLibVariations, jniLibTag, j.testProperties.Jni_libs...)
  958. }
  959. }
  960. j.addDataDeviceBinsDeps(ctx)
  961. j.deps(ctx)
  962. }
  963. func (j *TestHost) AddExtraResource(p android.Path) {
  964. j.extraResources = append(j.extraResources, p)
  965. }
  966. func (j *TestHost) dataDeviceBins() []string {
  967. ret := make([]string, 0,
  968. len(j.testHostProperties.Data_device_bins_first)+
  969. len(j.testHostProperties.Data_device_bins_both)+
  970. len(j.testHostProperties.Data_device_bins_prefer32)+
  971. len(j.testHostProperties.Data_device_bins_32)+
  972. len(j.testHostProperties.Data_device_bins_64),
  973. )
  974. ret = append(ret, j.testHostProperties.Data_device_bins_first...)
  975. ret = append(ret, j.testHostProperties.Data_device_bins_both...)
  976. ret = append(ret, j.testHostProperties.Data_device_bins_prefer32...)
  977. ret = append(ret, j.testHostProperties.Data_device_bins_32...)
  978. ret = append(ret, j.testHostProperties.Data_device_bins_64...)
  979. return ret
  980. }
  981. func (j *TestHost) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  982. var configs []tradefed.Config
  983. dataDeviceBins := j.dataDeviceBins()
  984. if len(dataDeviceBins) > 0 {
  985. // add Tradefed configuration to push device bins to device for testing
  986. remoteDir := filepath.Join("/data/local/tests/unrestricted/", j.Name())
  987. options := []tradefed.Option{{Name: "cleanup", Value: "true"}}
  988. for _, bin := range dataDeviceBins {
  989. fullPath := filepath.Join(remoteDir, bin)
  990. options = append(options, tradefed.Option{Name: "push-file", Key: bin, Value: fullPath})
  991. }
  992. configs = append(configs, tradefed.Object{
  993. Type: "target_preparer",
  994. Class: "com.android.tradefed.targetprep.PushFilePreparer",
  995. Options: options,
  996. })
  997. }
  998. j.Test.generateAndroidBuildActionsWithConfig(ctx, configs)
  999. }
  1000. func (j *Test) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  1001. j.generateAndroidBuildActionsWithConfig(ctx, nil)
  1002. }
  1003. func (j *Test) generateAndroidBuildActionsWithConfig(ctx android.ModuleContext, configs []tradefed.Config) {
  1004. if j.testProperties.Test_options.Unit_test == nil && ctx.Host() {
  1005. // TODO(b/): Clean temporary heuristic to avoid unexpected onboarding.
  1006. defaultUnitTest := !inList("tradefed", j.properties.Libs) && !inList("cts", j.testProperties.Test_suites)
  1007. j.testProperties.Test_options.Unit_test = proptools.BoolPtr(defaultUnitTest)
  1008. }
  1009. j.testConfig = tradefed.AutoGenTestConfig(ctx, tradefed.AutoGenTestConfigOptions{
  1010. TestConfigProp: j.testProperties.Test_config,
  1011. TestConfigTemplateProp: j.testProperties.Test_config_template,
  1012. TestSuites: j.testProperties.Test_suites,
  1013. Config: configs,
  1014. OptionsForAutogenerated: j.testProperties.Test_options.Tradefed_options,
  1015. AutoGenConfig: j.testProperties.Auto_gen_config,
  1016. UnitTest: j.testProperties.Test_options.Unit_test,
  1017. DeviceTemplate: "${JavaTestConfigTemplate}",
  1018. HostTemplate: "${JavaHostTestConfigTemplate}",
  1019. HostUnitTestTemplate: "${JavaHostUnitTestConfigTemplate}",
  1020. })
  1021. j.data = android.PathsForModuleSrc(ctx, j.testProperties.Data)
  1022. j.extraTestConfigs = android.PathsForModuleSrc(ctx, j.testProperties.Test_options.Extra_test_configs)
  1023. ctx.VisitDirectDepsWithTag(dataNativeBinsTag, func(dep android.Module) {
  1024. j.data = append(j.data, android.OutputFileForModule(ctx, dep, ""))
  1025. })
  1026. ctx.VisitDirectDepsWithTag(dataDeviceBinsTag, func(dep android.Module) {
  1027. j.data = append(j.data, android.OutputFileForModule(ctx, dep, ""))
  1028. })
  1029. ctx.VisitDirectDepsWithTag(jniLibTag, func(dep android.Module) {
  1030. sharedLibInfo := ctx.OtherModuleProvider(dep, cc.SharedLibraryInfoProvider).(cc.SharedLibraryInfo)
  1031. if sharedLibInfo.SharedLibrary != nil {
  1032. // Copy to an intermediate output directory to append "lib[64]" to the path,
  1033. // so that it's compatible with the default rpath values.
  1034. var relPath string
  1035. if sharedLibInfo.Target.Arch.ArchType.Multilib == "lib64" {
  1036. relPath = filepath.Join("lib64", sharedLibInfo.SharedLibrary.Base())
  1037. } else {
  1038. relPath = filepath.Join("lib", sharedLibInfo.SharedLibrary.Base())
  1039. }
  1040. relocatedLib := android.PathForModuleOut(ctx, "relocated").Join(ctx, relPath)
  1041. ctx.Build(pctx, android.BuildParams{
  1042. Rule: android.Cp,
  1043. Input: sharedLibInfo.SharedLibrary,
  1044. Output: relocatedLib,
  1045. })
  1046. j.data = append(j.data, relocatedLib)
  1047. } else {
  1048. ctx.PropertyErrorf("jni_libs", "%q of type %q is not supported", dep.Name(), ctx.OtherModuleType(dep))
  1049. }
  1050. })
  1051. j.Library.GenerateAndroidBuildActions(ctx)
  1052. }
  1053. func (j *TestHelperLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  1054. j.Library.GenerateAndroidBuildActions(ctx)
  1055. }
  1056. func (j *JavaTestImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  1057. j.testConfig = tradefed.AutoGenTestConfig(ctx, tradefed.AutoGenTestConfigOptions{
  1058. TestConfigProp: j.prebuiltTestProperties.Test_config,
  1059. TestSuites: j.prebuiltTestProperties.Test_suites,
  1060. DeviceTemplate: "${JavaTestConfigTemplate}",
  1061. HostTemplate: "${JavaHostTestConfigTemplate}",
  1062. HostUnitTestTemplate: "${JavaHostUnitTestConfigTemplate}",
  1063. })
  1064. j.Import.GenerateAndroidBuildActions(ctx)
  1065. }
  1066. type testSdkMemberType struct {
  1067. android.SdkMemberTypeBase
  1068. }
  1069. func (mt *testSdkMemberType) AddDependencies(ctx android.SdkDependencyContext, dependencyTag blueprint.DependencyTag, names []string) {
  1070. ctx.AddVariationDependencies(nil, dependencyTag, names...)
  1071. }
  1072. func (mt *testSdkMemberType) IsInstance(module android.Module) bool {
  1073. _, ok := module.(*Test)
  1074. return ok
  1075. }
  1076. func (mt *testSdkMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
  1077. return ctx.SnapshotBuilder().AddPrebuiltModule(member, "java_test_import")
  1078. }
  1079. func (mt *testSdkMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
  1080. return &testSdkMemberProperties{}
  1081. }
  1082. type testSdkMemberProperties struct {
  1083. android.SdkMemberPropertiesBase
  1084. JarToExport android.Path
  1085. TestConfig android.Path
  1086. }
  1087. func (p *testSdkMemberProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
  1088. test := variant.(*Test)
  1089. implementationJars := test.ImplementationJars()
  1090. if len(implementationJars) != 1 {
  1091. panic(fmt.Errorf("there must be only one implementation jar from %q", test.Name()))
  1092. }
  1093. p.JarToExport = implementationJars[0]
  1094. p.TestConfig = test.testConfig
  1095. }
  1096. func (p *testSdkMemberProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
  1097. builder := ctx.SnapshotBuilder()
  1098. exportedJar := p.JarToExport
  1099. if exportedJar != nil {
  1100. snapshotRelativeJavaLibPath := sdkSnapshotFilePathForJar(ctx, p.OsPrefix(), ctx.Name())
  1101. builder.CopyToSnapshot(exportedJar, snapshotRelativeJavaLibPath)
  1102. propertySet.AddProperty("jars", []string{snapshotRelativeJavaLibPath})
  1103. }
  1104. testConfig := p.TestConfig
  1105. if testConfig != nil {
  1106. snapshotRelativeTestConfigPath := sdkSnapshotFilePathForMember(p.OsPrefix(), ctx.Name(), testConfigSuffix)
  1107. builder.CopyToSnapshot(testConfig, snapshotRelativeTestConfigPath)
  1108. propertySet.AddProperty("test_config", snapshotRelativeTestConfigPath)
  1109. }
  1110. }
  1111. // java_test builds a and links sources into a `.jar` file for the device, and possibly for the host as well, and
  1112. // creates an `AndroidTest.xml` file to allow running the test with `atest` or a `TEST_MAPPING` file.
  1113. //
  1114. // By default, a java_test has a single variant that produces a `.jar` file containing `classes.dex` files that were
  1115. // compiled against the device bootclasspath.
  1116. //
  1117. // Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
  1118. // compiled against the host bootclasspath.
  1119. func TestFactory() android.Module {
  1120. module := &Test{}
  1121. module.addHostAndDeviceProperties()
  1122. module.AddProperties(&module.testProperties)
  1123. module.Module.properties.Installable = proptools.BoolPtr(true)
  1124. module.Module.dexpreopter.isTest = true
  1125. module.Module.linter.properties.Lint.Test = proptools.BoolPtr(true)
  1126. InitJavaModule(module, android.HostAndDeviceSupported)
  1127. return module
  1128. }
  1129. // java_test_helper_library creates a java library and makes sure that it is added to the appropriate test suite.
  1130. func TestHelperLibraryFactory() android.Module {
  1131. module := &TestHelperLibrary{}
  1132. module.addHostAndDeviceProperties()
  1133. module.AddProperties(&module.testHelperLibraryProperties)
  1134. module.Module.properties.Installable = proptools.BoolPtr(true)
  1135. module.Module.dexpreopter.isTest = true
  1136. module.Module.linter.properties.Lint.Test = proptools.BoolPtr(true)
  1137. InitJavaModule(module, android.HostAndDeviceSupported)
  1138. return module
  1139. }
  1140. // java_test_import imports one or more `.jar` files into the build graph as if they were built by a java_test module
  1141. // and makes sure that it is added to the appropriate test suite.
  1142. //
  1143. // By default, a java_test_import has a single variant that expects a `.jar` file containing `.class` files that were
  1144. // compiled against an Android classpath.
  1145. //
  1146. // Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
  1147. // for host modules.
  1148. func JavaTestImportFactory() android.Module {
  1149. module := &JavaTestImport{}
  1150. module.AddProperties(
  1151. &module.Import.properties,
  1152. &module.prebuiltTestProperties)
  1153. module.Import.properties.Installable = proptools.BoolPtr(true)
  1154. android.InitPrebuiltModule(module, &module.properties.Jars)
  1155. android.InitApexModule(module)
  1156. InitJavaModule(module, android.HostAndDeviceSupported)
  1157. return module
  1158. }
  1159. // java_test_host builds a and links sources into a `.jar` file for the host, and creates an `AndroidTest.xml` file to
  1160. // allow running the test with `atest` or a `TEST_MAPPING` file.
  1161. //
  1162. // A java_test_host has a single variant that produces a `.jar` file containing `.class` files that were
  1163. // compiled against the host bootclasspath.
  1164. func TestHostFactory() android.Module {
  1165. module := &TestHost{}
  1166. module.addHostProperties()
  1167. module.AddProperties(&module.testProperties)
  1168. module.AddProperties(&module.testHostProperties)
  1169. InitTestHost(
  1170. module,
  1171. proptools.BoolPtr(true),
  1172. nil,
  1173. nil)
  1174. InitJavaModuleMultiTargets(module, android.HostSupported)
  1175. return module
  1176. }
  1177. func InitTestHost(th *TestHost, installable *bool, testSuites []string, autoGenConfig *bool) {
  1178. th.properties.Installable = installable
  1179. th.testProperties.Auto_gen_config = autoGenConfig
  1180. th.testProperties.Test_suites = testSuites
  1181. }
  1182. //
  1183. // Java Binaries (.jar file plus wrapper script)
  1184. //
  1185. type binaryProperties struct {
  1186. // installable script to execute the resulting jar
  1187. Wrapper *string `android:"path,arch_variant"`
  1188. // Name of the class containing main to be inserted into the manifest as Main-Class.
  1189. Main_class *string
  1190. // Names of modules containing JNI libraries that should be installed alongside the host
  1191. // variant of the binary.
  1192. Jni_libs []string `android:"arch_variant"`
  1193. }
  1194. type Binary struct {
  1195. Library
  1196. binaryProperties binaryProperties
  1197. isWrapperVariant bool
  1198. wrapperFile android.Path
  1199. binaryFile android.InstallPath
  1200. }
  1201. func (j *Binary) HostToolPath() android.OptionalPath {
  1202. return android.OptionalPathForPath(j.binaryFile)
  1203. }
  1204. func (j *Binary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  1205. if ctx.Arch().ArchType == android.Common {
  1206. // Compile the jar
  1207. if j.binaryProperties.Main_class != nil {
  1208. if j.properties.Manifest != nil {
  1209. ctx.PropertyErrorf("main_class", "main_class cannot be used when manifest is set")
  1210. }
  1211. manifestFile := android.PathForModuleOut(ctx, "manifest.txt")
  1212. GenerateMainClassManifest(ctx, manifestFile, String(j.binaryProperties.Main_class))
  1213. j.overrideManifest = android.OptionalPathForPath(manifestFile)
  1214. }
  1215. j.Library.GenerateAndroidBuildActions(ctx)
  1216. } else {
  1217. // Handle the binary wrapper
  1218. j.isWrapperVariant = true
  1219. if j.binaryProperties.Wrapper != nil {
  1220. j.wrapperFile = android.PathForModuleSrc(ctx, *j.binaryProperties.Wrapper)
  1221. } else {
  1222. if ctx.Windows() {
  1223. ctx.PropertyErrorf("wrapper", "wrapper is required for Windows")
  1224. }
  1225. if ctx.Device() {
  1226. // device binary should have a main_class property if it does not
  1227. // have a specific wrapper, so that a default wrapper can
  1228. // be generated for it.
  1229. if j.binaryProperties.Main_class == nil {
  1230. ctx.PropertyErrorf("main_class", "main_class property "+
  1231. "is required for device binary if no default wrapper is assigned")
  1232. } else {
  1233. wrapper := android.PathForModuleOut(ctx, ctx.ModuleName()+".sh")
  1234. jarName := j.Stem() + ".jar"
  1235. partition := j.PartitionTag(ctx.DeviceConfig())
  1236. ctx.Build(pctx, android.BuildParams{
  1237. Rule: deviceBinaryWrapper,
  1238. Output: wrapper,
  1239. Args: map[string]string{
  1240. "jar_name": jarName,
  1241. "partition": partition,
  1242. "main_class": String(j.binaryProperties.Main_class),
  1243. },
  1244. })
  1245. j.wrapperFile = wrapper
  1246. }
  1247. } else {
  1248. j.wrapperFile = android.PathForSource(ctx, "build/soong/scripts/jar-wrapper.sh")
  1249. }
  1250. }
  1251. ext := ""
  1252. if ctx.Windows() {
  1253. ext = ".bat"
  1254. }
  1255. // The host installation rules make the installed wrapper depend on all the dependencies
  1256. // of the wrapper variant, which will include the common variant's jar file and any JNI
  1257. // libraries. This is verified by TestBinary.
  1258. j.binaryFile = ctx.InstallExecutable(android.PathForModuleInstall(ctx, "bin"),
  1259. ctx.ModuleName()+ext, j.wrapperFile)
  1260. }
  1261. }
  1262. func (j *Binary) DepsMutator(ctx android.BottomUpMutatorContext) {
  1263. if ctx.Arch().ArchType == android.Common {
  1264. j.deps(ctx)
  1265. }
  1266. if ctx.Arch().ArchType != android.Common {
  1267. // These dependencies ensure the host installation rules will install the jar file and
  1268. // the jni libraries when the wrapper is installed.
  1269. ctx.AddVariationDependencies(nil, jniInstallTag, j.binaryProperties.Jni_libs...)
  1270. ctx.AddVariationDependencies(
  1271. []blueprint.Variation{{Mutator: "arch", Variation: android.CommonArch.String()}},
  1272. binaryInstallTag, ctx.ModuleName())
  1273. }
  1274. }
  1275. // java_binary builds a `.jar` file and a shell script that executes it for the device, and possibly for the host
  1276. // as well.
  1277. //
  1278. // By default, a java_binary has a single variant that produces a `.jar` file containing `classes.dex` files that were
  1279. // compiled against the device bootclasspath.
  1280. //
  1281. // Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
  1282. // compiled against the host bootclasspath.
  1283. func BinaryFactory() android.Module {
  1284. module := &Binary{}
  1285. module.addHostAndDeviceProperties()
  1286. module.AddProperties(&module.binaryProperties)
  1287. module.Module.properties.Installable = proptools.BoolPtr(true)
  1288. android.InitAndroidArchModule(module, android.HostAndDeviceSupported, android.MultilibCommonFirst)
  1289. android.InitDefaultableModule(module)
  1290. android.InitBazelModule(module)
  1291. return module
  1292. }
  1293. // java_binary_host builds a `.jar` file and a shell script that executes it for the host.
  1294. //
  1295. // A java_binary_host has a single variant that produces a `.jar` file containing `.class` files that were
  1296. // compiled against the host bootclasspath.
  1297. func BinaryHostFactory() android.Module {
  1298. module := &Binary{}
  1299. module.addHostProperties()
  1300. module.AddProperties(&module.binaryProperties)
  1301. module.Module.properties.Installable = proptools.BoolPtr(true)
  1302. android.InitAndroidArchModule(module, android.HostSupported, android.MultilibCommonFirst)
  1303. android.InitDefaultableModule(module)
  1304. android.InitBazelModule(module)
  1305. return module
  1306. }
  1307. type JavaApiContribution struct {
  1308. android.ModuleBase
  1309. android.DefaultableModuleBase
  1310. properties struct {
  1311. // name of the API surface
  1312. Api_surface *string
  1313. // relative path to the API signature text file
  1314. Api_file *string `android:"path"`
  1315. }
  1316. }
  1317. func ApiContributionFactory() android.Module {
  1318. module := &JavaApiContribution{}
  1319. android.InitAndroidModule(module)
  1320. android.InitDefaultableModule(module)
  1321. module.AddProperties(&module.properties)
  1322. return module
  1323. }
  1324. type JavaApiImportInfo struct {
  1325. ApiFile android.Path
  1326. }
  1327. var JavaApiImportProvider = blueprint.NewProvider(JavaApiImportInfo{})
  1328. func (ap *JavaApiContribution) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  1329. var apiFile android.Path = nil
  1330. if apiFileString := ap.properties.Api_file; apiFileString != nil {
  1331. apiFile = android.PathForModuleSrc(ctx, String(apiFileString))
  1332. }
  1333. ctx.SetProvider(JavaApiImportProvider, JavaApiImportInfo{
  1334. ApiFile: apiFile,
  1335. })
  1336. }
  1337. type JavaApiLibraryDepsInfo struct {
  1338. JavaInfo
  1339. StubsSrcJar android.Path
  1340. }
  1341. var JavaApiLibraryDepsProvider = blueprint.NewProvider(JavaApiLibraryDepsInfo{})
  1342. type ApiLibrary struct {
  1343. android.ModuleBase
  1344. android.DefaultableModuleBase
  1345. hiddenAPI
  1346. dexer
  1347. properties JavaApiLibraryProperties
  1348. stubsSrcJar android.WritablePath
  1349. stubsJar android.WritablePath
  1350. stubsJarWithoutStaticLibs android.WritablePath
  1351. extractedSrcJar android.WritablePath
  1352. // .dex of stubs, used for hiddenapi processing
  1353. dexJarFile OptionalDexJarPath
  1354. }
  1355. type JavaApiLibraryProperties struct {
  1356. // name of the API surface
  1357. Api_surface *string
  1358. // list of Java API contribution modules that consists this API surface
  1359. // This is a list of Soong modules
  1360. Api_contributions []string
  1361. // list of api.txt files relative to this directory that contribute to the
  1362. // API surface.
  1363. // This is a list of relative paths
  1364. Api_files []string
  1365. // List of flags to be passed to the javac compiler to generate jar file
  1366. Javacflags []string
  1367. // List of shared java libs that this module has dependencies to and
  1368. // should be passed as classpath in javac invocation
  1369. Libs []string
  1370. // List of java libs that this module has static dependencies to and will be
  1371. // merge zipped after metalava invocation
  1372. Static_libs []string
  1373. // Java Api library to provide the full API surface text files and jar file.
  1374. // If this property is set, the provided full API surface text files and
  1375. // jar file are passed to metalava invocation.
  1376. Dep_api_srcs *string
  1377. }
  1378. func ApiLibraryFactory() android.Module {
  1379. module := &ApiLibrary{}
  1380. android.InitAndroidArchModule(module, android.DeviceSupported, android.MultilibCommon)
  1381. module.AddProperties(&module.properties)
  1382. android.InitDefaultableModule(module)
  1383. return module
  1384. }
  1385. func (al *ApiLibrary) ApiSurface() *string {
  1386. return al.properties.Api_surface
  1387. }
  1388. func (al *ApiLibrary) StubsJar() android.Path {
  1389. return al.stubsJar
  1390. }
  1391. func metalavaStubCmd(ctx android.ModuleContext, rule *android.RuleBuilder,
  1392. srcs android.Paths, homeDir android.WritablePath) *android.RuleBuilderCommand {
  1393. rule.Command().Text("rm -rf").Flag(homeDir.String())
  1394. rule.Command().Text("mkdir -p").Flag(homeDir.String())
  1395. cmd := rule.Command()
  1396. cmd.FlagWithArg("ANDROID_PREFS_ROOT=", homeDir.String())
  1397. if metalavaUseRbe(ctx) {
  1398. rule.Remoteable(android.RemoteRuleSupports{RBE: true})
  1399. execStrategy := ctx.Config().GetenvWithDefault("RBE_METALAVA_EXEC_STRATEGY", remoteexec.LocalExecStrategy)
  1400. labels := map[string]string{"type": "tool", "name": "metalava"}
  1401. pool := ctx.Config().GetenvWithDefault("RBE_METALAVA_POOL", "java16")
  1402. rule.Rewrapper(&remoteexec.REParams{
  1403. Labels: labels,
  1404. ExecStrategy: execStrategy,
  1405. ToolchainInputs: []string{config.JavaCmd(ctx).String()},
  1406. Platform: map[string]string{remoteexec.PoolKey: pool},
  1407. })
  1408. }
  1409. cmd.BuiltTool("metalava").ImplicitTool(ctx.Config().HostJavaToolPath(ctx, "metalava.jar")).
  1410. Flag(config.JavacVmFlags).
  1411. Flag("-J--add-opens=java.base/java.util=ALL-UNNAMED").
  1412. FlagWithArg("-encoding ", "UTF-8").
  1413. FlagWithInputList("--source-files ", srcs, " ")
  1414. cmd.Flag("--no-banner").
  1415. Flag("--color").
  1416. Flag("--quiet").
  1417. Flag("--format=v2").
  1418. Flag("--include-annotations").
  1419. // The flag makes nullability issues as warnings rather than errors by replacing
  1420. // @Nullable/@NonNull in the listed packages APIs with @RecentlyNullable/@RecentlyNonNull,
  1421. // and these packages are meant to have everything annotated
  1422. // @RecentlyNullable/@RecentlyNonNull.
  1423. FlagWithArg("--force-convert-to-warning-nullability-annotations ", "+*:-android.*:+android.icu.*:-dalvik.*").
  1424. FlagWithArg("--repeat-errors-max ", "10").
  1425. FlagWithArg("--hide ", "UnresolvedImport").
  1426. FlagWithArg("--hide ", "InvalidNullabilityOverride").
  1427. FlagWithArg("--hide ", "ChangedDefault")
  1428. return cmd
  1429. }
  1430. func (al *ApiLibrary) HeaderJars() android.Paths {
  1431. return android.Paths{al.stubsJar}
  1432. }
  1433. func (al *ApiLibrary) OutputDirAndDeps() (android.Path, android.Paths) {
  1434. return nil, nil
  1435. }
  1436. func (al *ApiLibrary) stubsFlags(ctx android.ModuleContext, cmd *android.RuleBuilderCommand, stubsDir android.OptionalPath) {
  1437. if stubsDir.Valid() {
  1438. cmd.FlagWithArg("--stubs ", stubsDir.String())
  1439. }
  1440. }
  1441. // This method extracts the stub java files from the srcjar file provided from dep_api_srcs module
  1442. // and replaces the java stubs generated by invoking metalava in this module.
  1443. // This method is used because metalava can generate compilable from-text stubs only when
  1444. // the codebase encompasses all classes listed in the input API text file, but a class can extend
  1445. // a class that is not within the same API domain.
  1446. func (al *ApiLibrary) extractApiSrcs(ctx android.ModuleContext, rule *android.RuleBuilder, stubsDir android.OptionalPath, depApiSrcsSrcJar android.Path) {
  1447. generatedStubsList := android.PathForModuleOut(ctx, "metalava", "sources.txt")
  1448. unzippedSrcJarDir := android.PathForModuleOut(ctx, "metalava", "unzipDir")
  1449. rule.Command().
  1450. BuiltTool("list_files").
  1451. Text(stubsDir.String()).
  1452. FlagWithOutput("--out ", generatedStubsList).
  1453. FlagWithArg("--extensions ", ".java").
  1454. FlagWithArg("--root ", unzippedSrcJarDir.String())
  1455. rule.Command().
  1456. Text("unzip").
  1457. Flag("-q").
  1458. Input(depApiSrcsSrcJar).
  1459. FlagWithArg("-d ", unzippedSrcJarDir.String())
  1460. rule.Command().
  1461. BuiltTool("soong_zip").
  1462. Flag("-srcjar").
  1463. Flag("-write_if_changed").
  1464. FlagWithArg("-C ", unzippedSrcJarDir.String()).
  1465. FlagWithInput("-l ", generatedStubsList).
  1466. FlagWithOutput("-o ", al.stubsSrcJar)
  1467. }
  1468. func (al *ApiLibrary) DepsMutator(ctx android.BottomUpMutatorContext) {
  1469. apiContributions := al.properties.Api_contributions
  1470. for _, apiContributionName := range apiContributions {
  1471. ctx.AddDependency(ctx.Module(), javaApiContributionTag, apiContributionName)
  1472. }
  1473. ctx.AddVariationDependencies(nil, libTag, al.properties.Libs...)
  1474. ctx.AddVariationDependencies(nil, staticLibTag, al.properties.Static_libs...)
  1475. if al.properties.Dep_api_srcs != nil {
  1476. ctx.AddVariationDependencies(nil, depApiSrcsTag, String(al.properties.Dep_api_srcs))
  1477. }
  1478. }
  1479. func (al *ApiLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  1480. rule := android.NewRuleBuilder(pctx, ctx)
  1481. rule.Sbox(android.PathForModuleOut(ctx, "metalava"),
  1482. android.PathForModuleOut(ctx, "metalava.sbox.textproto")).
  1483. SandboxInputs()
  1484. var stubsDir android.OptionalPath
  1485. stubsDir = android.OptionalPathForPath(android.PathForModuleOut(ctx, "metalava", "stubsDir"))
  1486. rule.Command().Text("rm -rf").Text(stubsDir.String())
  1487. rule.Command().Text("mkdir -p").Text(stubsDir.String())
  1488. homeDir := android.PathForModuleOut(ctx, "metalava", "home")
  1489. var srcFiles android.Paths
  1490. var classPaths android.Paths
  1491. var staticLibs android.Paths
  1492. var depApiSrcsStubsSrcJar android.Path
  1493. ctx.VisitDirectDeps(func(dep android.Module) {
  1494. tag := ctx.OtherModuleDependencyTag(dep)
  1495. switch tag {
  1496. case javaApiContributionTag:
  1497. provider := ctx.OtherModuleProvider(dep, JavaApiImportProvider).(JavaApiImportInfo)
  1498. providerApiFile := provider.ApiFile
  1499. if providerApiFile == nil {
  1500. ctx.ModuleErrorf("Error: %s has an empty api file.", dep.Name())
  1501. }
  1502. srcFiles = append(srcFiles, android.PathForSource(ctx, providerApiFile.String()))
  1503. case libTag:
  1504. provider := ctx.OtherModuleProvider(dep, JavaInfoProvider).(JavaInfo)
  1505. classPaths = append(classPaths, provider.HeaderJars...)
  1506. case staticLibTag:
  1507. provider := ctx.OtherModuleProvider(dep, JavaInfoProvider).(JavaInfo)
  1508. staticLibs = append(staticLibs, provider.HeaderJars...)
  1509. case depApiSrcsTag:
  1510. provider := ctx.OtherModuleProvider(dep, JavaApiLibraryDepsProvider).(JavaApiLibraryDepsInfo)
  1511. classPaths = append(classPaths, provider.HeaderJars...)
  1512. depApiSrcsStubsSrcJar = provider.StubsSrcJar
  1513. }
  1514. })
  1515. // Add the api_files inputs
  1516. for _, api := range al.properties.Api_files {
  1517. // Use MaybeExistentPathForSource since the api file might not exist during analysis.
  1518. // This will be provided by the orchestrator in the combined execution.
  1519. srcFiles = append(srcFiles, android.MaybeExistentPathForSource(ctx, ctx.ModuleDir(), api))
  1520. }
  1521. if srcFiles == nil {
  1522. ctx.ModuleErrorf("Error: %s has an empty api file.", ctx.ModuleName())
  1523. }
  1524. cmd := metalavaStubCmd(ctx, rule, srcFiles, homeDir)
  1525. al.stubsFlags(ctx, cmd, stubsDir)
  1526. al.stubsSrcJar = android.PathForModuleOut(ctx, "metalava", ctx.ModuleName()+"-"+"stubs.srcjar")
  1527. if depApiSrcsStubsSrcJar != nil {
  1528. al.extractApiSrcs(ctx, rule, stubsDir, depApiSrcsStubsSrcJar)
  1529. } else {
  1530. rule.Command().
  1531. BuiltTool("soong_zip").
  1532. Flag("-write_if_changed").
  1533. Flag("-jar").
  1534. FlagWithOutput("-o ", al.stubsSrcJar).
  1535. FlagWithArg("-C ", stubsDir.String()).
  1536. FlagWithArg("-D ", stubsDir.String())
  1537. }
  1538. rule.Build("metalava", "metalava merged")
  1539. al.stubsJarWithoutStaticLibs = android.PathForModuleOut(ctx, ctx.ModuleName(), "stubs.jar")
  1540. al.stubsJar = android.PathForModuleOut(ctx, ctx.ModuleName(), fmt.Sprintf("%s.jar", ctx.ModuleName()))
  1541. var flags javaBuilderFlags
  1542. flags.javaVersion = getStubsJavaVersion()
  1543. flags.javacFlags = strings.Join(al.properties.Javacflags, " ")
  1544. flags.classpath = classpath(classPaths)
  1545. TransformJavaToClasses(ctx, al.stubsJarWithoutStaticLibs, 0, android.Paths{},
  1546. android.Paths{al.stubsSrcJar}, flags, android.Paths{})
  1547. builder := android.NewRuleBuilder(pctx, ctx)
  1548. builder.Command().
  1549. BuiltTool("merge_zips").
  1550. Output(al.stubsJar).
  1551. Inputs(android.Paths{al.stubsJarWithoutStaticLibs}).
  1552. Inputs(staticLibs)
  1553. builder.Build("merge_zips", "merge jar files")
  1554. // compile stubs to .dex for hiddenapi processing
  1555. dexParams := &compileDexParams{
  1556. flags: javaBuilderFlags{},
  1557. sdkVersion: al.SdkVersion(ctx),
  1558. minSdkVersion: al.MinSdkVersion(ctx),
  1559. classesJar: al.stubsJar,
  1560. jarName: ctx.ModuleName() + ".jar",
  1561. }
  1562. dexOutputFile := al.dexer.compileDex(ctx, dexParams)
  1563. uncompressed := true
  1564. al.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), al.stubsJar, &uncompressed)
  1565. dexOutputFile = al.hiddenAPIEncodeDex(ctx, dexOutputFile)
  1566. al.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
  1567. ctx.Phony(ctx.ModuleName(), al.stubsJar)
  1568. ctx.SetProvider(JavaInfoProvider, JavaInfo{
  1569. HeaderJars: android.PathsIfNonNil(al.stubsJar),
  1570. ImplementationAndResourcesJars: android.PathsIfNonNil(al.stubsJar),
  1571. ImplementationJars: android.PathsIfNonNil(al.stubsJar),
  1572. AidlIncludeDirs: android.Paths{},
  1573. })
  1574. ctx.SetProvider(JavaApiLibraryDepsProvider, JavaApiLibraryDepsInfo{
  1575. JavaInfo: JavaInfo{
  1576. HeaderJars: android.PathsIfNonNil(al.stubsJar),
  1577. },
  1578. StubsSrcJar: al.stubsSrcJar,
  1579. })
  1580. }
  1581. func (al *ApiLibrary) DexJarBuildPath() OptionalDexJarPath {
  1582. return al.dexJarFile
  1583. }
  1584. func (al *ApiLibrary) DexJarInstallPath() android.Path {
  1585. return al.dexJarFile.Path()
  1586. }
  1587. func (al *ApiLibrary) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
  1588. return nil
  1589. }
  1590. // java_api_library constitutes the sdk, and does not build against one
  1591. func (al *ApiLibrary) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
  1592. return android.SdkSpecNone
  1593. }
  1594. // java_api_library is always at "current". Return FutureApiLevel
  1595. func (al *ApiLibrary) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
  1596. return android.FutureApiLevel
  1597. }
  1598. // implement the following interfaces for hiddenapi processing
  1599. var _ hiddenAPIModule = (*ApiLibrary)(nil)
  1600. var _ UsesLibraryDependency = (*ApiLibrary)(nil)
  1601. //
  1602. // Java prebuilts
  1603. //
  1604. type ImportProperties struct {
  1605. Jars []string `android:"path,arch_variant"`
  1606. // The version of the SDK that the source prebuilt file was built against. Defaults to the
  1607. // current version if not specified.
  1608. Sdk_version *string
  1609. // The minimum version of the SDK that this module supports. Defaults to sdk_version if not
  1610. // specified.
  1611. Min_sdk_version *string
  1612. // The max sdk version placeholder used to replace maxSdkVersion attributes on permission
  1613. // and uses-permission tags in manifest_fixer.
  1614. Replace_max_sdk_version_placeholder *string
  1615. Installable *bool
  1616. // If not empty, classes are restricted to the specified packages and their sub-packages.
  1617. Permitted_packages []string
  1618. // List of shared java libs that this module has dependencies to
  1619. Libs []string
  1620. // List of files to remove from the jar file(s)
  1621. Exclude_files []string
  1622. // List of directories to remove from the jar file(s)
  1623. Exclude_dirs []string
  1624. // if set to true, run Jetifier against .jar file. Defaults to false.
  1625. Jetifier *bool
  1626. // set the name of the output
  1627. Stem *string
  1628. Aidl struct {
  1629. // directories that should be added as include directories for any aidl sources of modules
  1630. // that depend on this module, as well as to aidl for this module.
  1631. Export_include_dirs []string
  1632. }
  1633. }
  1634. type Import struct {
  1635. android.ModuleBase
  1636. android.DefaultableModuleBase
  1637. android.ApexModuleBase
  1638. android.BazelModuleBase
  1639. prebuilt android.Prebuilt
  1640. // Functionality common to Module and Import.
  1641. embeddableInModuleAndImport
  1642. hiddenAPI
  1643. dexer
  1644. dexpreopter
  1645. properties ImportProperties
  1646. // output file containing classes.dex and resources
  1647. dexJarFile OptionalDexJarPath
  1648. dexJarInstallFile android.Path
  1649. combinedClasspathFile android.Path
  1650. classLoaderContexts dexpreopt.ClassLoaderContextMap
  1651. exportAidlIncludeDirs android.Paths
  1652. hideApexVariantFromMake bool
  1653. sdkVersion android.SdkSpec
  1654. minSdkVersion android.ApiLevel
  1655. }
  1656. var _ PermittedPackagesForUpdatableBootJars = (*Import)(nil)
  1657. func (j *Import) PermittedPackagesForUpdatableBootJars() []string {
  1658. return j.properties.Permitted_packages
  1659. }
  1660. func (j *Import) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
  1661. return android.SdkSpecFrom(ctx, String(j.properties.Sdk_version))
  1662. }
  1663. func (j *Import) SystemModules() string {
  1664. return "none"
  1665. }
  1666. func (j *Import) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
  1667. if j.properties.Min_sdk_version != nil {
  1668. return android.ApiLevelFrom(ctx, *j.properties.Min_sdk_version)
  1669. }
  1670. return j.SdkVersion(ctx).ApiLevel
  1671. }
  1672. func (j *Import) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.ApiLevel {
  1673. if j.properties.Replace_max_sdk_version_placeholder != nil {
  1674. return android.ApiLevelFrom(ctx, *j.properties.Replace_max_sdk_version_placeholder)
  1675. }
  1676. // Default is PrivateApiLevel
  1677. return android.SdkSpecPrivate.ApiLevel
  1678. }
  1679. func (j *Import) TargetSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
  1680. return j.SdkVersion(ctx).ApiLevel
  1681. }
  1682. func (j *Import) Prebuilt() *android.Prebuilt {
  1683. return &j.prebuilt
  1684. }
  1685. func (j *Import) PrebuiltSrcs() []string {
  1686. return j.properties.Jars
  1687. }
  1688. func (j *Import) Name() string {
  1689. return j.prebuilt.Name(j.ModuleBase.Name())
  1690. }
  1691. func (j *Import) Stem() string {
  1692. return proptools.StringDefault(j.properties.Stem, j.ModuleBase.Name())
  1693. }
  1694. func (a *Import) JacocoReportClassesFile() android.Path {
  1695. return nil
  1696. }
  1697. func (j *Import) LintDepSets() LintDepSets {
  1698. return LintDepSets{}
  1699. }
  1700. func (j *Import) getStrictUpdatabilityLinting() bool {
  1701. return false
  1702. }
  1703. func (j *Import) setStrictUpdatabilityLinting(bool) {
  1704. }
  1705. func (j *Import) DepsMutator(ctx android.BottomUpMutatorContext) {
  1706. ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
  1707. if ctx.Device() && Bool(j.dexProperties.Compile_dex) {
  1708. sdkDeps(ctx, android.SdkContext(j), j.dexer)
  1709. }
  1710. }
  1711. func (j *Import) commonBuildActions(ctx android.ModuleContext) {
  1712. //TODO(b/231322772) these should come from Bazel once available
  1713. j.sdkVersion = j.SdkVersion(ctx)
  1714. j.minSdkVersion = j.MinSdkVersion(ctx)
  1715. if !ctx.Provider(android.ApexInfoProvider).(android.ApexInfo).IsForPlatform() {
  1716. j.hideApexVariantFromMake = true
  1717. }
  1718. if ctx.Windows() {
  1719. j.HideFromMake()
  1720. }
  1721. }
  1722. func (j *Import) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  1723. j.commonBuildActions(ctx)
  1724. jars := android.PathsForModuleSrc(ctx, j.properties.Jars)
  1725. jarName := j.Stem() + ".jar"
  1726. outputFile := android.PathForModuleOut(ctx, "combined", jarName)
  1727. TransformJarsToJar(ctx, outputFile, "for prebuilts", jars, android.OptionalPath{},
  1728. false, j.properties.Exclude_files, j.properties.Exclude_dirs)
  1729. if Bool(j.properties.Jetifier) {
  1730. inputFile := outputFile
  1731. outputFile = android.PathForModuleOut(ctx, "jetifier", jarName)
  1732. TransformJetifier(ctx, outputFile, inputFile)
  1733. }
  1734. j.combinedClasspathFile = outputFile
  1735. j.classLoaderContexts = make(dexpreopt.ClassLoaderContextMap)
  1736. var flags javaBuilderFlags
  1737. j.collectTransitiveHeaderJars(ctx)
  1738. ctx.VisitDirectDeps(func(module android.Module) {
  1739. tag := ctx.OtherModuleDependencyTag(module)
  1740. if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
  1741. dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
  1742. switch tag {
  1743. case libTag, sdkLibTag:
  1744. flags.classpath = append(flags.classpath, dep.HeaderJars...)
  1745. flags.dexClasspath = append(flags.dexClasspath, dep.HeaderJars...)
  1746. case staticLibTag:
  1747. flags.classpath = append(flags.classpath, dep.HeaderJars...)
  1748. case bootClasspathTag:
  1749. flags.bootClasspath = append(flags.bootClasspath, dep.HeaderJars...)
  1750. }
  1751. } else if dep, ok := module.(SdkLibraryDependency); ok {
  1752. switch tag {
  1753. case libTag, sdkLibTag:
  1754. flags.classpath = append(flags.classpath, dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))...)
  1755. }
  1756. }
  1757. addCLCFromDep(ctx, module, j.classLoaderContexts)
  1758. })
  1759. j.maybeInstall(ctx, jarName, outputFile)
  1760. j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.properties.Aidl.Export_include_dirs)
  1761. if ctx.Device() {
  1762. // If this is a variant created for a prebuilt_apex then use the dex implementation jar
  1763. // obtained from the associated deapexer module.
  1764. ai := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
  1765. if ai.ForPrebuiltApex {
  1766. // Get the path of the dex implementation jar from the `deapexer` module.
  1767. di := android.FindDeapexerProviderForModule(ctx)
  1768. if di == nil {
  1769. return // An error has been reported by FindDeapexerProviderForModule.
  1770. }
  1771. dexJarFileApexRootRelative := apexRootRelativePathToJavaLib(j.BaseModuleName())
  1772. if dexOutputPath := di.PrebuiltExportPath(dexJarFileApexRootRelative); dexOutputPath != nil {
  1773. dexJarFile := makeDexJarPathFromPath(dexOutputPath)
  1774. j.dexJarFile = dexJarFile
  1775. installPath := android.PathForModuleInPartitionInstall(ctx, "apex", ai.ApexVariationName, apexRootRelativePathToJavaLib(j.BaseModuleName()))
  1776. j.dexJarInstallFile = installPath
  1777. j.dexpreopter.installPath = j.dexpreopter.getInstallPath(ctx, installPath)
  1778. setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
  1779. j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
  1780. if profilePath := di.PrebuiltExportPath(dexJarFileApexRootRelative + ".prof"); profilePath != nil {
  1781. j.dexpreopter.inputProfilePathOnHost = profilePath
  1782. }
  1783. j.dexpreopt(ctx, dexOutputPath)
  1784. // Initialize the hiddenapi structure.
  1785. j.initHiddenAPI(ctx, dexJarFile, outputFile, j.dexProperties.Uncompress_dex)
  1786. } else {
  1787. // This should never happen as a variant for a prebuilt_apex is only created if the
  1788. // prebuilt_apex has been configured to export the java library dex file.
  1789. ctx.ModuleErrorf("internal error: no dex implementation jar available from prebuilt APEX %s", di.ApexModuleName())
  1790. }
  1791. } else if Bool(j.dexProperties.Compile_dex) {
  1792. sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
  1793. if sdkDep.invalidVersion {
  1794. ctx.AddMissingDependencies(sdkDep.bootclasspath)
  1795. ctx.AddMissingDependencies(sdkDep.java9Classpath)
  1796. } else if sdkDep.useFiles {
  1797. // sdkDep.jar is actually equivalent to turbine header.jar.
  1798. flags.classpath = append(flags.classpath, sdkDep.jars...)
  1799. }
  1800. // Dex compilation
  1801. j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
  1802. ctx, android.PathForModuleInstall(ctx, "framework", jarName))
  1803. setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
  1804. j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
  1805. var dexOutputFile android.OutputPath
  1806. dexParams := &compileDexParams{
  1807. flags: flags,
  1808. sdkVersion: j.SdkVersion(ctx),
  1809. minSdkVersion: j.MinSdkVersion(ctx),
  1810. classesJar: outputFile,
  1811. jarName: jarName,
  1812. }
  1813. dexOutputFile = j.dexer.compileDex(ctx, dexParams)
  1814. if ctx.Failed() {
  1815. return
  1816. }
  1817. // Initialize the hiddenapi structure.
  1818. j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), outputFile, j.dexProperties.Uncompress_dex)
  1819. // Encode hidden API flags in dex file.
  1820. dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
  1821. j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
  1822. j.dexJarInstallFile = android.PathForModuleInstall(ctx, "framework", jarName)
  1823. }
  1824. }
  1825. ctx.SetProvider(JavaInfoProvider, JavaInfo{
  1826. HeaderJars: android.PathsIfNonNil(j.combinedClasspathFile),
  1827. TransitiveLibsHeaderJars: j.transitiveLibsHeaderJars,
  1828. TransitiveStaticLibsHeaderJars: j.transitiveStaticLibsHeaderJars,
  1829. ImplementationAndResourcesJars: android.PathsIfNonNil(j.combinedClasspathFile),
  1830. ImplementationJars: android.PathsIfNonNil(j.combinedClasspathFile),
  1831. AidlIncludeDirs: j.exportAidlIncludeDirs,
  1832. })
  1833. }
  1834. func (j *Import) maybeInstall(ctx android.ModuleContext, jarName string, outputFile android.Path) {
  1835. if !Bool(j.properties.Installable) {
  1836. return
  1837. }
  1838. var installDir android.InstallPath
  1839. if ctx.InstallInTestcases() {
  1840. var archDir string
  1841. if !ctx.Host() {
  1842. archDir = ctx.DeviceConfig().DeviceArch()
  1843. }
  1844. installDir = android.PathForModuleInstall(ctx, ctx.ModuleName(), archDir)
  1845. } else {
  1846. installDir = android.PathForModuleInstall(ctx, "framework")
  1847. }
  1848. ctx.InstallFile(installDir, jarName, outputFile)
  1849. }
  1850. func (j *Import) OutputFiles(tag string) (android.Paths, error) {
  1851. switch tag {
  1852. case "", ".jar":
  1853. return android.Paths{j.combinedClasspathFile}, nil
  1854. default:
  1855. return nil, fmt.Errorf("unsupported module reference tag %q", tag)
  1856. }
  1857. }
  1858. var _ android.OutputFileProducer = (*Import)(nil)
  1859. func (j *Import) HeaderJars() android.Paths {
  1860. if j.combinedClasspathFile == nil {
  1861. return nil
  1862. }
  1863. return android.Paths{j.combinedClasspathFile}
  1864. }
  1865. func (j *Import) ImplementationAndResourcesJars() android.Paths {
  1866. if j.combinedClasspathFile == nil {
  1867. return nil
  1868. }
  1869. return android.Paths{j.combinedClasspathFile}
  1870. }
  1871. func (j *Import) DexJarBuildPath() OptionalDexJarPath {
  1872. return j.dexJarFile
  1873. }
  1874. func (j *Import) DexJarInstallPath() android.Path {
  1875. return j.dexJarInstallFile
  1876. }
  1877. func (j *Import) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
  1878. return j.classLoaderContexts
  1879. }
  1880. var _ android.ApexModule = (*Import)(nil)
  1881. // Implements android.ApexModule
  1882. func (j *Import) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
  1883. return j.depIsInSameApex(ctx, dep)
  1884. }
  1885. // Implements android.ApexModule
  1886. func (j *Import) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
  1887. sdkVersion android.ApiLevel) error {
  1888. sdkVersionSpec := j.SdkVersion(ctx)
  1889. minSdkVersion := j.MinSdkVersion(ctx)
  1890. if !minSdkVersion.Specified() {
  1891. return fmt.Errorf("min_sdk_version is not specified")
  1892. }
  1893. // If the module is compiling against core (via sdk_version), skip comparison check.
  1894. if sdkVersionSpec.Kind == android.SdkCore {
  1895. return nil
  1896. }
  1897. if minSdkVersion.GreaterThan(sdkVersion) {
  1898. return fmt.Errorf("newer SDK(%v)", minSdkVersion)
  1899. }
  1900. return nil
  1901. }
  1902. // requiredFilesFromPrebuiltApexForImport returns information about the files that a java_import or
  1903. // java_sdk_library_import with the specified base module name requires to be exported from a
  1904. // prebuilt_apex/apex_set.
  1905. func requiredFilesFromPrebuiltApexForImport(name string, d *dexpreopter) []string {
  1906. dexJarFileApexRootRelative := apexRootRelativePathToJavaLib(name)
  1907. // Add the dex implementation jar to the set of exported files.
  1908. files := []string{
  1909. dexJarFileApexRootRelative,
  1910. }
  1911. if BoolDefault(d.importDexpreoptProperties.Dex_preopt.Profile_guided, false) {
  1912. files = append(files, dexJarFileApexRootRelative+".prof")
  1913. }
  1914. return files
  1915. }
  1916. // apexRootRelativePathToJavaLib returns the path, relative to the root of the apex's contents, for
  1917. // the java library with the specified name.
  1918. func apexRootRelativePathToJavaLib(name string) string {
  1919. return filepath.Join("javalib", name+".jar")
  1920. }
  1921. var _ android.RequiredFilesFromPrebuiltApex = (*Import)(nil)
  1922. func (j *Import) RequiredFilesFromPrebuiltApex(_ android.BaseModuleContext) []string {
  1923. name := j.BaseModuleName()
  1924. return requiredFilesFromPrebuiltApexForImport(name, &j.dexpreopter)
  1925. }
  1926. // Add compile time check for interface implementation
  1927. var _ android.IDEInfo = (*Import)(nil)
  1928. var _ android.IDECustomizedModuleName = (*Import)(nil)
  1929. // Collect information for opening IDE project files in java/jdeps.go.
  1930. func (j *Import) IDEInfo(dpInfo *android.IdeInfo) {
  1931. dpInfo.Jars = append(dpInfo.Jars, j.PrebuiltSrcs()...)
  1932. }
  1933. func (j *Import) IDECustomizedModuleName() string {
  1934. // TODO(b/113562217): Extract the base module name from the Import name, often the Import name
  1935. // has a prefix "prebuilt_". Remove the prefix explicitly if needed until we find a better
  1936. // solution to get the Import name.
  1937. return android.RemoveOptionalPrebuiltPrefix(j.Name())
  1938. }
  1939. var _ android.PrebuiltInterface = (*Import)(nil)
  1940. func (j *Import) IsInstallable() bool {
  1941. return Bool(j.properties.Installable)
  1942. }
  1943. var _ DexpreopterInterface = (*Import)(nil)
  1944. // java_import imports one or more `.jar` files into the build graph as if they were built by a java_library module.
  1945. //
  1946. // By default, a java_import has a single variant that expects a `.jar` file containing `.class` files that were
  1947. // compiled against an Android classpath.
  1948. //
  1949. // Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
  1950. // for host modules.
  1951. func ImportFactory() android.Module {
  1952. module := &Import{}
  1953. module.AddProperties(
  1954. &module.properties,
  1955. &module.dexer.dexProperties,
  1956. &module.importDexpreoptProperties,
  1957. )
  1958. module.initModuleAndImport(module)
  1959. module.dexProperties.Optimize.EnabledByDefault = false
  1960. android.InitPrebuiltModule(module, &module.properties.Jars)
  1961. android.InitApexModule(module)
  1962. android.InitBazelModule(module)
  1963. InitJavaModule(module, android.HostAndDeviceSupported)
  1964. return module
  1965. }
  1966. // java_import imports one or more `.jar` files into the build graph as if they were built by a java_library_host
  1967. // module.
  1968. //
  1969. // A java_import_host has a single variant that expects a `.jar` file containing `.class` files that were
  1970. // compiled against a host bootclasspath.
  1971. func ImportFactoryHost() android.Module {
  1972. module := &Import{}
  1973. module.AddProperties(&module.properties)
  1974. android.InitPrebuiltModule(module, &module.properties.Jars)
  1975. android.InitApexModule(module)
  1976. android.InitBazelModule(module)
  1977. InitJavaModule(module, android.HostSupported)
  1978. return module
  1979. }
  1980. // dex_import module
  1981. type DexImportProperties struct {
  1982. Jars []string `android:"path"`
  1983. // set the name of the output
  1984. Stem *string
  1985. }
  1986. type DexImport struct {
  1987. android.ModuleBase
  1988. android.DefaultableModuleBase
  1989. android.ApexModuleBase
  1990. prebuilt android.Prebuilt
  1991. properties DexImportProperties
  1992. dexJarFile OptionalDexJarPath
  1993. dexpreopter
  1994. hideApexVariantFromMake bool
  1995. }
  1996. func (j *DexImport) Prebuilt() *android.Prebuilt {
  1997. return &j.prebuilt
  1998. }
  1999. func (j *DexImport) PrebuiltSrcs() []string {
  2000. return j.properties.Jars
  2001. }
  2002. func (j *DexImport) Name() string {
  2003. return j.prebuilt.Name(j.ModuleBase.Name())
  2004. }
  2005. func (j *DexImport) Stem() string {
  2006. return proptools.StringDefault(j.properties.Stem, j.ModuleBase.Name())
  2007. }
  2008. func (a *DexImport) JacocoReportClassesFile() android.Path {
  2009. return nil
  2010. }
  2011. func (a *DexImport) LintDepSets() LintDepSets {
  2012. return LintDepSets{}
  2013. }
  2014. func (j *DexImport) IsInstallable() bool {
  2015. return true
  2016. }
  2017. func (j *DexImport) getStrictUpdatabilityLinting() bool {
  2018. return false
  2019. }
  2020. func (j *DexImport) setStrictUpdatabilityLinting(bool) {
  2021. }
  2022. func (j *DexImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  2023. if len(j.properties.Jars) != 1 {
  2024. ctx.PropertyErrorf("jars", "exactly one jar must be provided")
  2025. }
  2026. apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
  2027. if !apexInfo.IsForPlatform() {
  2028. j.hideApexVariantFromMake = true
  2029. }
  2030. j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
  2031. ctx, android.PathForModuleInstall(ctx, "framework", j.Stem()+".jar"))
  2032. j.dexpreopter.uncompressedDex = shouldUncompressDex(ctx, &j.dexpreopter)
  2033. inputJar := ctx.ExpandSource(j.properties.Jars[0], "jars")
  2034. dexOutputFile := android.PathForModuleOut(ctx, ctx.ModuleName()+".jar")
  2035. if j.dexpreopter.uncompressedDex {
  2036. rule := android.NewRuleBuilder(pctx, ctx)
  2037. temporary := android.PathForModuleOut(ctx, ctx.ModuleName()+".jar.unaligned")
  2038. rule.Temporary(temporary)
  2039. // use zip2zip to uncompress classes*.dex files
  2040. rule.Command().
  2041. BuiltTool("zip2zip").
  2042. FlagWithInput("-i ", inputJar).
  2043. FlagWithOutput("-o ", temporary).
  2044. FlagWithArg("-0 ", "'classes*.dex'")
  2045. // use zipalign to align uncompressed classes*.dex files
  2046. rule.Command().
  2047. BuiltTool("zipalign").
  2048. Flag("-f").
  2049. Text("4").
  2050. Input(temporary).
  2051. Output(dexOutputFile)
  2052. rule.DeleteTemporaryFiles()
  2053. rule.Build("uncompress_dex", "uncompress dex")
  2054. } else {
  2055. ctx.Build(pctx, android.BuildParams{
  2056. Rule: android.Cp,
  2057. Input: inputJar,
  2058. Output: dexOutputFile,
  2059. })
  2060. }
  2061. j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
  2062. j.dexpreopt(ctx, dexOutputFile)
  2063. if apexInfo.IsForPlatform() {
  2064. ctx.InstallFile(android.PathForModuleInstall(ctx, "framework"),
  2065. j.Stem()+".jar", dexOutputFile)
  2066. }
  2067. }
  2068. func (j *DexImport) DexJarBuildPath() OptionalDexJarPath {
  2069. return j.dexJarFile
  2070. }
  2071. var _ android.ApexModule = (*DexImport)(nil)
  2072. // Implements android.ApexModule
  2073. func (j *DexImport) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
  2074. sdkVersion android.ApiLevel) error {
  2075. // we don't check prebuilt modules for sdk_version
  2076. return nil
  2077. }
  2078. // dex_import imports a `.jar` file containing classes.dex files.
  2079. //
  2080. // A dex_import module cannot be used as a dependency of a java_* or android_* module, it can only be installed
  2081. // to the device.
  2082. func DexImportFactory() android.Module {
  2083. module := &DexImport{}
  2084. module.AddProperties(&module.properties)
  2085. android.InitPrebuiltModule(module, &module.properties.Jars)
  2086. android.InitApexModule(module)
  2087. InitJavaModule(module, android.DeviceSupported)
  2088. return module
  2089. }
  2090. // Defaults
  2091. type Defaults struct {
  2092. android.ModuleBase
  2093. android.DefaultsModuleBase
  2094. android.ApexModuleBase
  2095. }
  2096. // java_defaults provides a set of properties that can be inherited by other java or android modules.
  2097. //
  2098. // A module can use the properties from a java_defaults module using `defaults: ["defaults_module_name"]`. Each
  2099. // property in the defaults module that exists in the depending module will be prepended to the depending module's
  2100. // value for that property.
  2101. //
  2102. // Example:
  2103. //
  2104. // java_defaults {
  2105. // name: "example_defaults",
  2106. // srcs: ["common/**/*.java"],
  2107. // javacflags: ["-Xlint:all"],
  2108. // aaptflags: ["--auto-add-overlay"],
  2109. // }
  2110. //
  2111. // java_library {
  2112. // name: "example",
  2113. // defaults: ["example_defaults"],
  2114. // srcs: ["example/**/*.java"],
  2115. // }
  2116. //
  2117. // is functionally identical to:
  2118. //
  2119. // java_library {
  2120. // name: "example",
  2121. // srcs: [
  2122. // "common/**/*.java",
  2123. // "example/**/*.java",
  2124. // ],
  2125. // javacflags: ["-Xlint:all"],
  2126. // }
  2127. func DefaultsFactory() android.Module {
  2128. module := &Defaults{}
  2129. module.AddProperties(
  2130. &CommonProperties{},
  2131. &DeviceProperties{},
  2132. &OverridableDeviceProperties{},
  2133. &DexProperties{},
  2134. &DexpreoptProperties{},
  2135. &android.ProtoProperties{},
  2136. &aaptProperties{},
  2137. &androidLibraryProperties{},
  2138. &appProperties{},
  2139. &appTestProperties{},
  2140. &overridableAppProperties{},
  2141. &testProperties{},
  2142. &ImportProperties{},
  2143. &AARImportProperties{},
  2144. &sdkLibraryProperties{},
  2145. &commonToSdkLibraryAndImportProperties{},
  2146. &DexImportProperties{},
  2147. &android.ApexProperties{},
  2148. &RuntimeResourceOverlayProperties{},
  2149. &LintProperties{},
  2150. &appTestHelperAppProperties{},
  2151. &JavaApiLibraryProperties{},
  2152. )
  2153. android.InitDefaultsModule(module)
  2154. return module
  2155. }
  2156. func kytheExtractJavaFactory() android.Singleton {
  2157. return &kytheExtractJavaSingleton{}
  2158. }
  2159. type kytheExtractJavaSingleton struct {
  2160. }
  2161. func (ks *kytheExtractJavaSingleton) GenerateBuildActions(ctx android.SingletonContext) {
  2162. var xrefTargets android.Paths
  2163. ctx.VisitAllModules(func(module android.Module) {
  2164. if javaModule, ok := module.(xref); ok {
  2165. xrefTargets = append(xrefTargets, javaModule.XrefJavaFiles()...)
  2166. }
  2167. })
  2168. // TODO(asmundak): perhaps emit a rule to output a warning if there were no xrefTargets
  2169. if len(xrefTargets) > 0 {
  2170. ctx.Phony("xref_java", xrefTargets...)
  2171. }
  2172. }
  2173. var Bool = proptools.Bool
  2174. var BoolDefault = proptools.BoolDefault
  2175. var String = proptools.String
  2176. var inList = android.InList
  2177. // Add class loader context (CLC) of a given dependency to the current CLC.
  2178. func addCLCFromDep(ctx android.ModuleContext, depModule android.Module,
  2179. clcMap dexpreopt.ClassLoaderContextMap) {
  2180. dep, ok := depModule.(UsesLibraryDependency)
  2181. if !ok {
  2182. return
  2183. }
  2184. depName := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(depModule))
  2185. var sdkLib *string
  2186. if lib, ok := depModule.(SdkLibraryDependency); ok && lib.sharedLibrary() {
  2187. // A shared SDK library. This should be added as a top-level CLC element.
  2188. sdkLib = &depName
  2189. } else if ulib, ok := depModule.(ProvidesUsesLib); ok {
  2190. // A non-SDK library disguised as an SDK library by the means of `provides_uses_lib`
  2191. // property. This should be handled in the same way as a shared SDK library.
  2192. sdkLib = ulib.ProvidesUsesLib()
  2193. }
  2194. depTag := ctx.OtherModuleDependencyTag(depModule)
  2195. if IsLibDepTag(depTag) {
  2196. // Ok, propagate <uses-library> through non-static library dependencies.
  2197. } else if tag, ok := depTag.(usesLibraryDependencyTag); ok && tag.sdkVersion == dexpreopt.AnySdkVersion {
  2198. // Ok, propagate <uses-library> through non-compatibility <uses-library> dependencies.
  2199. } else if depTag == staticLibTag {
  2200. // Propagate <uses-library> through static library dependencies, unless it is a component
  2201. // library (such as stubs). Component libraries have a dependency on their SDK library,
  2202. // which should not be pulled just because of a static component library.
  2203. if sdkLib != nil {
  2204. return
  2205. }
  2206. } else {
  2207. // Don't propagate <uses-library> for other dependency tags.
  2208. return
  2209. }
  2210. // If this is an SDK (or SDK-like) library, then it should be added as a node in the CLC tree,
  2211. // and its CLC should be added as subtree of that node. Otherwise the library is not a
  2212. // <uses_library> and should not be added to CLC, but the transitive <uses-library> dependencies
  2213. // from its CLC should be added to the current CLC.
  2214. if sdkLib != nil {
  2215. clcMap.AddContext(ctx, dexpreopt.AnySdkVersion, *sdkLib, false,
  2216. dep.DexJarBuildPath().PathOrNil(), dep.DexJarInstallPath(), dep.ClassLoaderContexts())
  2217. } else {
  2218. clcMap.AddContextMap(dep.ClassLoaderContexts(), depName)
  2219. }
  2220. }
  2221. type javaResourcesAttributes struct {
  2222. Resources bazel.LabelListAttribute
  2223. Resource_strip_prefix *string
  2224. }
  2225. func (m *Library) convertJavaResourcesAttributes(ctx android.TopDownMutatorContext) *javaResourcesAttributes {
  2226. var resources bazel.LabelList
  2227. var resourceStripPrefix *string
  2228. if m.properties.Java_resources != nil && len(m.properties.Java_resource_dirs) > 0 {
  2229. ctx.ModuleErrorf("bp2build doesn't support both java_resources and java_resource_dirs being set on the same module.")
  2230. }
  2231. if m.properties.Java_resources != nil {
  2232. resources.Append(android.BazelLabelForModuleSrc(ctx, m.properties.Java_resources))
  2233. resourceStripPrefix = proptools.StringPtr(ctx.ModuleDir())
  2234. }
  2235. //TODO(b/179889880) handle case where glob includes files outside package
  2236. resDeps := ResourceDirsToFiles(
  2237. ctx,
  2238. m.properties.Java_resource_dirs,
  2239. m.properties.Exclude_java_resource_dirs,
  2240. m.properties.Exclude_java_resources,
  2241. )
  2242. for i, resDep := range resDeps {
  2243. dir, files := resDep.dir, resDep.files
  2244. resources.Append(bazel.MakeLabelList(android.RootToModuleRelativePaths(ctx, files)))
  2245. // Bazel includes the relative path from the WORKSPACE root when placing the resource
  2246. // inside the JAR file, so we need to remove that prefix
  2247. resourceStripPrefix = proptools.StringPtr(dir.String())
  2248. if i > 0 {
  2249. // TODO(b/226423379) allow multiple resource prefixes
  2250. ctx.ModuleErrorf("bp2build does not support more than one directory in java_resource_dirs (b/226423379)")
  2251. }
  2252. }
  2253. return &javaResourcesAttributes{
  2254. Resources: bazel.MakeLabelListAttribute(resources),
  2255. Resource_strip_prefix: resourceStripPrefix,
  2256. }
  2257. }
  2258. type javaCommonAttributes struct {
  2259. *javaResourcesAttributes
  2260. *kotlinAttributes
  2261. Srcs bazel.LabelListAttribute
  2262. Plugins bazel.LabelListAttribute
  2263. Javacopts bazel.StringListAttribute
  2264. Sdk_version bazel.StringAttribute
  2265. Java_version bazel.StringAttribute
  2266. }
  2267. type javaDependencyLabels struct {
  2268. // Dependencies which DO NOT contribute to the API visible to upstream dependencies.
  2269. Deps bazel.LabelListAttribute
  2270. // Dependencies which DO contribute to the API visible to upstream dependencies.
  2271. StaticDeps bazel.LabelListAttribute
  2272. }
  2273. type eventLogTagsAttributes struct {
  2274. Srcs bazel.LabelListAttribute
  2275. }
  2276. type aidlLibraryAttributes struct {
  2277. Srcs bazel.LabelListAttribute
  2278. Tags bazel.StringListAttribute
  2279. }
  2280. type javaAidlLibraryAttributes struct {
  2281. Deps bazel.LabelListAttribute
  2282. Tags bazel.StringListAttribute
  2283. }
  2284. // bp2BuildJavaInfo has information needed for the conversion of java*_modules
  2285. // that is needed bor Bp2Build conversion but that requires different handling
  2286. // depending on the module type.
  2287. type bp2BuildJavaInfo struct {
  2288. // separates dependencies into dynamic dependencies and static dependencies.
  2289. DepLabels *javaDependencyLabels
  2290. hasKotlin bool
  2291. }
  2292. // convertLibraryAttrsBp2Build returns a javaCommonAttributes struct with
  2293. // converted attributes shared across java_* modules and a bp2BuildJavaInfo struct
  2294. // which has other non-attribute information needed for bp2build conversion
  2295. // that needs different handling depending on the module types, and thus needs
  2296. // to be returned to the calling function.
  2297. func (m *Library) convertLibraryAttrsBp2Build(ctx android.TopDownMutatorContext) (*javaCommonAttributes, *bp2BuildJavaInfo) {
  2298. var srcs bazel.LabelListAttribute
  2299. var deps bazel.LabelListAttribute
  2300. var staticDeps bazel.LabelList
  2301. archVariantProps := m.GetArchVariantProperties(ctx, &CommonProperties{})
  2302. for axis, configToProps := range archVariantProps {
  2303. for config, _props := range configToProps {
  2304. if archProps, ok := _props.(*CommonProperties); ok {
  2305. archSrcs := android.BazelLabelForModuleSrcExcludes(ctx, archProps.Srcs, archProps.Exclude_srcs)
  2306. srcs.SetSelectValue(axis, config, archSrcs)
  2307. }
  2308. }
  2309. }
  2310. srcs.ResolveExcludes()
  2311. javaSrcPartition := "java"
  2312. protoSrcPartition := "proto"
  2313. logtagSrcPartition := "logtag"
  2314. aidlSrcPartition := "aidl"
  2315. kotlinPartition := "kotlin"
  2316. srcPartitions := bazel.PartitionLabelListAttribute(ctx, &srcs, bazel.LabelPartitions{
  2317. javaSrcPartition: bazel.LabelPartition{Extensions: []string{".java"}, Keep_remainder: true},
  2318. logtagSrcPartition: bazel.LabelPartition{Extensions: []string{".logtags", ".logtag"}},
  2319. protoSrcPartition: android.ProtoSrcLabelPartition,
  2320. aidlSrcPartition: android.AidlSrcLabelPartition,
  2321. kotlinPartition: bazel.LabelPartition{Extensions: []string{".kt"}},
  2322. })
  2323. javaSrcs := srcPartitions[javaSrcPartition]
  2324. kotlinSrcs := srcPartitions[kotlinPartition]
  2325. javaSrcs.Append(kotlinSrcs)
  2326. if !srcPartitions[logtagSrcPartition].IsEmpty() {
  2327. logtagsLibName := m.Name() + "_logtags"
  2328. ctx.CreateBazelTargetModule(
  2329. bazel.BazelTargetModuleProperties{
  2330. Rule_class: "event_log_tags",
  2331. Bzl_load_location: "//build/bazel/rules/java:event_log_tags.bzl",
  2332. },
  2333. android.CommonAttributes{Name: logtagsLibName},
  2334. &eventLogTagsAttributes{
  2335. Srcs: srcPartitions[logtagSrcPartition],
  2336. },
  2337. )
  2338. logtagsSrcs := bazel.MakeLabelList([]bazel.Label{{Label: ":" + logtagsLibName}})
  2339. javaSrcs.Append(bazel.MakeLabelListAttribute(logtagsSrcs))
  2340. }
  2341. if !srcPartitions[aidlSrcPartition].IsEmpty() {
  2342. aidlLibs, aidlSrcs := srcPartitions[aidlSrcPartition].Partition(func(src bazel.Label) bool {
  2343. return android.IsConvertedToAidlLibrary(ctx, src.OriginalModuleName)
  2344. })
  2345. apexAvailableTags := android.ApexAvailableTagsWithoutTestApexes(ctx, ctx.Module())
  2346. if !aidlSrcs.IsEmpty() {
  2347. aidlLibName := m.Name() + "_aidl_library"
  2348. ctx.CreateBazelTargetModule(
  2349. bazel.BazelTargetModuleProperties{
  2350. Rule_class: "aidl_library",
  2351. Bzl_load_location: "//build/bazel/rules/aidl:aidl_library.bzl",
  2352. },
  2353. android.CommonAttributes{Name: aidlLibName},
  2354. &aidlLibraryAttributes{
  2355. Srcs: aidlSrcs,
  2356. Tags: apexAvailableTags,
  2357. },
  2358. )
  2359. aidlLibs.Add(&bazel.LabelAttribute{Value: &bazel.Label{Label: ":" + aidlLibName}})
  2360. }
  2361. javaAidlLibName := m.Name() + "_java_aidl_library"
  2362. ctx.CreateBazelTargetModule(
  2363. bazel.BazelTargetModuleProperties{
  2364. Rule_class: "java_aidl_library",
  2365. Bzl_load_location: "//build/bazel/rules/java:java_aidl_library.bzl",
  2366. },
  2367. android.CommonAttributes{Name: javaAidlLibName},
  2368. &javaAidlLibraryAttributes{
  2369. Deps: aidlLibs,
  2370. Tags: apexAvailableTags,
  2371. },
  2372. )
  2373. staticDeps.Add(&bazel.Label{Label: ":" + javaAidlLibName})
  2374. }
  2375. var javacopts []string
  2376. if m.properties.Javacflags != nil {
  2377. javacopts = append(javacopts, m.properties.Javacflags...)
  2378. }
  2379. epEnabled := m.properties.Errorprone.Enabled
  2380. //TODO(b/227504307) add configuration that depends on RUN_ERROR_PRONE environment variable
  2381. if Bool(epEnabled) {
  2382. javacopts = append(javacopts, m.properties.Errorprone.Javacflags...)
  2383. }
  2384. commonAttrs := &javaCommonAttributes{
  2385. Srcs: javaSrcs,
  2386. javaResourcesAttributes: m.convertJavaResourcesAttributes(ctx),
  2387. Plugins: bazel.MakeLabelListAttribute(
  2388. android.BazelLabelForModuleDeps(ctx, m.properties.Plugins),
  2389. ),
  2390. Javacopts: bazel.MakeStringListAttribute(javacopts),
  2391. Java_version: bazel.StringAttribute{Value: m.properties.Java_version},
  2392. Sdk_version: bazel.StringAttribute{Value: m.deviceProperties.Sdk_version},
  2393. }
  2394. for axis, configToProps := range archVariantProps {
  2395. for config, _props := range configToProps {
  2396. if archProps, ok := _props.(*CommonProperties); ok {
  2397. var libLabels []bazel.Label
  2398. for _, d := range archProps.Libs {
  2399. neverlinkLabel := android.BazelLabelForModuleDepSingle(ctx, d)
  2400. neverlinkLabel.Label = neverlinkLabel.Label + "-neverlink"
  2401. libLabels = append(libLabels, neverlinkLabel)
  2402. }
  2403. deps.SetSelectValue(axis, config, bazel.MakeLabelList(libLabels))
  2404. }
  2405. }
  2406. }
  2407. protoDepLabel := bp2buildProto(ctx, &m.Module, srcPartitions[protoSrcPartition])
  2408. // Soong does not differentiate between a java_library and the Bazel equivalent of
  2409. // a java_proto_library + proto_library pair. Instead, in Soong proto sources are
  2410. // listed directly in the srcs of a java_library, and the classes produced
  2411. // by protoc are included directly in the resulting JAR. Thus upstream dependencies
  2412. // that depend on a java_library with proto sources can link directly to the protobuf API,
  2413. // and so this should be a static dependency.
  2414. staticDeps.Add(protoDepLabel)
  2415. depLabels := &javaDependencyLabels{}
  2416. depLabels.Deps = deps
  2417. for axis, configToProps := range archVariantProps {
  2418. for config, _props := range configToProps {
  2419. if archProps, ok := _props.(*CommonProperties); ok {
  2420. archStaticLibs := android.BazelLabelForModuleDeps(
  2421. ctx,
  2422. android.LastUniqueStrings(android.CopyOf(archProps.Static_libs)))
  2423. depLabels.StaticDeps.SetSelectValue(axis, config, archStaticLibs)
  2424. }
  2425. }
  2426. }
  2427. depLabels.StaticDeps.Value.Append(staticDeps)
  2428. hasKotlin := !kotlinSrcs.IsEmpty()
  2429. commonAttrs.kotlinAttributes = &kotlinAttributes{
  2430. Kotlincflags: &m.properties.Kotlincflags,
  2431. }
  2432. if len(m.properties.Common_srcs) != 0 {
  2433. hasKotlin = true
  2434. commonAttrs.kotlinAttributes.Common_srcs = bazel.MakeLabelListAttribute(android.BazelLabelForModuleSrc(ctx, m.properties.Common_srcs))
  2435. }
  2436. bp2BuildInfo := &bp2BuildJavaInfo{
  2437. DepLabels: depLabels,
  2438. hasKotlin: hasKotlin,
  2439. }
  2440. return commonAttrs, bp2BuildInfo
  2441. }
  2442. type javaLibraryAttributes struct {
  2443. *javaCommonAttributes
  2444. Deps bazel.LabelListAttribute
  2445. Exports bazel.LabelListAttribute
  2446. Neverlink bazel.BoolAttribute
  2447. }
  2448. type kotlinAttributes struct {
  2449. Common_srcs bazel.LabelListAttribute
  2450. Kotlincflags *[]string
  2451. }
  2452. func ktJvmLibraryBazelTargetModuleProperties() bazel.BazelTargetModuleProperties {
  2453. return bazel.BazelTargetModuleProperties{
  2454. Rule_class: "kt_jvm_library",
  2455. Bzl_load_location: "//build/bazel/rules/kotlin:kt_jvm_library.bzl",
  2456. }
  2457. }
  2458. func javaLibraryBazelTargetModuleProperties() bazel.BazelTargetModuleProperties {
  2459. return bazel.BazelTargetModuleProperties{
  2460. Rule_class: "java_library",
  2461. Bzl_load_location: "//build/bazel/rules/java:library.bzl",
  2462. }
  2463. }
  2464. func javaLibraryBp2Build(ctx android.TopDownMutatorContext, m *Library) {
  2465. commonAttrs, bp2BuildInfo := m.convertLibraryAttrsBp2Build(ctx)
  2466. depLabels := bp2BuildInfo.DepLabels
  2467. deps := depLabels.Deps
  2468. if !commonAttrs.Srcs.IsEmpty() {
  2469. deps.Append(depLabels.StaticDeps) // we should only append these if there are sources to use them
  2470. } else if !deps.IsEmpty() {
  2471. ctx.ModuleErrorf("Module has direct dependencies but no sources. Bazel will not allow this.")
  2472. }
  2473. var props bazel.BazelTargetModuleProperties
  2474. attrs := &javaLibraryAttributes{
  2475. javaCommonAttributes: commonAttrs,
  2476. Deps: deps,
  2477. Exports: depLabels.StaticDeps,
  2478. }
  2479. name := m.Name()
  2480. if !bp2BuildInfo.hasKotlin {
  2481. props = javaLibraryBazelTargetModuleProperties()
  2482. } else {
  2483. props = ktJvmLibraryBazelTargetModuleProperties()
  2484. }
  2485. ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: name}, attrs)
  2486. neverlinkProp := true
  2487. neverLinkAttrs := &javaLibraryAttributes{
  2488. Exports: bazel.MakeSingleLabelListAttribute(bazel.Label{Label: ":" + name}),
  2489. Neverlink: bazel.BoolAttribute{Value: &neverlinkProp},
  2490. javaCommonAttributes: &javaCommonAttributes{
  2491. Sdk_version: bazel.StringAttribute{Value: m.deviceProperties.Sdk_version},
  2492. Java_version: bazel.StringAttribute{Value: m.properties.Java_version},
  2493. },
  2494. }
  2495. ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: name + "-neverlink"}, neverLinkAttrs)
  2496. }
  2497. type javaBinaryHostAttributes struct {
  2498. *javaCommonAttributes
  2499. Deps bazel.LabelListAttribute
  2500. Runtime_deps bazel.LabelListAttribute
  2501. Main_class string
  2502. Jvm_flags bazel.StringListAttribute
  2503. }
  2504. // JavaBinaryHostBp2Build is for java_binary_host bp2build.
  2505. func javaBinaryHostBp2Build(ctx android.TopDownMutatorContext, m *Binary) {
  2506. commonAttrs, bp2BuildInfo := m.convertLibraryAttrsBp2Build(ctx)
  2507. depLabels := bp2BuildInfo.DepLabels
  2508. deps := depLabels.Deps
  2509. deps.Append(depLabels.StaticDeps)
  2510. if m.binaryProperties.Jni_libs != nil {
  2511. deps.Append(bazel.MakeLabelListAttribute(android.BazelLabelForModuleDeps(ctx, m.binaryProperties.Jni_libs)))
  2512. }
  2513. var runtimeDeps bazel.LabelListAttribute
  2514. if commonAttrs.Srcs.IsEmpty() {
  2515. // if there are no sources, then the dependencies can only be used at runtime
  2516. runtimeDeps = deps
  2517. deps = bazel.LabelListAttribute{}
  2518. }
  2519. mainClass := ""
  2520. if m.binaryProperties.Main_class != nil {
  2521. mainClass = *m.binaryProperties.Main_class
  2522. }
  2523. if m.properties.Manifest != nil {
  2524. mainClassInManifest, err := android.GetMainClassInManifest(ctx.Config(), android.PathForModuleSrc(ctx, *m.properties.Manifest).String())
  2525. if err != nil {
  2526. return
  2527. }
  2528. mainClass = mainClassInManifest
  2529. }
  2530. // Attribute jvm_flags
  2531. var jvmFlags bazel.StringListAttribute
  2532. if m.binaryProperties.Jni_libs != nil {
  2533. jniLibPackages := map[string]bool{}
  2534. for _, jniLibLabel := range android.BazelLabelForModuleDeps(ctx, m.binaryProperties.Jni_libs).Includes {
  2535. jniLibPackage := jniLibLabel.Label
  2536. indexOfColon := strings.Index(jniLibLabel.Label, ":")
  2537. if indexOfColon > 0 {
  2538. // JNI lib from other package
  2539. jniLibPackage = jniLibLabel.Label[2:indexOfColon]
  2540. } else if indexOfColon == 0 {
  2541. // JNI lib in the same package of java_binary
  2542. packageOfCurrentModule := m.GetBazelLabel(ctx, m)
  2543. jniLibPackage = packageOfCurrentModule[2:strings.Index(packageOfCurrentModule, ":")]
  2544. }
  2545. if _, inMap := jniLibPackages[jniLibPackage]; !inMap {
  2546. jniLibPackages[jniLibPackage] = true
  2547. }
  2548. }
  2549. jniLibPaths := []string{}
  2550. for jniLibPackage, _ := range jniLibPackages {
  2551. // See cs/f:.*/third_party/bazel/.*java_stub_template.txt for the use of RUNPATH
  2552. jniLibPaths = append(jniLibPaths, "$${RUNPATH}"+jniLibPackage)
  2553. }
  2554. jvmFlags = bazel.MakeStringListAttribute([]string{"-Djava.library.path=" + strings.Join(jniLibPaths, ":")})
  2555. }
  2556. props := bazel.BazelTargetModuleProperties{
  2557. Rule_class: "java_binary",
  2558. Bzl_load_location: "@rules_java//java:defs.bzl",
  2559. }
  2560. binAttrs := &javaBinaryHostAttributes{
  2561. Runtime_deps: runtimeDeps,
  2562. Main_class: mainClass,
  2563. Jvm_flags: jvmFlags,
  2564. }
  2565. if commonAttrs.Srcs.IsEmpty() {
  2566. binAttrs.javaCommonAttributes = commonAttrs
  2567. ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, binAttrs)
  2568. return
  2569. }
  2570. libName := m.Name() + "_lib"
  2571. var libProps bazel.BazelTargetModuleProperties
  2572. if bp2BuildInfo.hasKotlin {
  2573. libProps = ktJvmLibraryBazelTargetModuleProperties()
  2574. } else {
  2575. libProps = javaLibraryBazelTargetModuleProperties()
  2576. }
  2577. libAttrs := &javaLibraryAttributes{
  2578. Deps: deps,
  2579. javaCommonAttributes: commonAttrs,
  2580. }
  2581. ctx.CreateBazelTargetModule(libProps, android.CommonAttributes{Name: libName}, libAttrs)
  2582. binAttrs.Runtime_deps.Add(&bazel.LabelAttribute{Value: &bazel.Label{Label: ":" + libName}})
  2583. // Create the BazelTargetModule.
  2584. ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, binAttrs)
  2585. }
  2586. type bazelJavaImportAttributes struct {
  2587. Jars bazel.LabelListAttribute
  2588. Exports bazel.LabelListAttribute
  2589. }
  2590. // java_import bp2Build converter.
  2591. func (i *Import) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
  2592. var jars bazel.LabelListAttribute
  2593. archVariantProps := i.GetArchVariantProperties(ctx, &ImportProperties{})
  2594. for axis, configToProps := range archVariantProps {
  2595. for config, _props := range configToProps {
  2596. if archProps, ok := _props.(*ImportProperties); ok {
  2597. archJars := android.BazelLabelForModuleSrcExcludes(ctx, archProps.Jars, []string(nil))
  2598. jars.SetSelectValue(axis, config, archJars)
  2599. }
  2600. }
  2601. }
  2602. attrs := &bazelJavaImportAttributes{
  2603. Jars: jars,
  2604. }
  2605. props := bazel.BazelTargetModuleProperties{
  2606. Rule_class: "java_import",
  2607. Bzl_load_location: "//build/bazel/rules/java:import.bzl",
  2608. }
  2609. name := android.RemoveOptionalPrebuiltPrefix(i.Name())
  2610. ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: name}, attrs)
  2611. neverlink := true
  2612. neverlinkAttrs := &javaLibraryAttributes{
  2613. Neverlink: bazel.BoolAttribute{Value: &neverlink},
  2614. Exports: bazel.MakeSingleLabelListAttribute(bazel.Label{Label: ":" + name}),
  2615. javaCommonAttributes: &javaCommonAttributes{
  2616. Sdk_version: bazel.StringAttribute{Value: proptools.StringPtr("none")},
  2617. },
  2618. }
  2619. ctx.CreateBazelTargetModule(
  2620. javaLibraryBazelTargetModuleProperties(),
  2621. android.CommonAttributes{Name: name + "-neverlink"},
  2622. neverlinkAttrs)
  2623. }
  2624. var _ android.MixedBuildBuildable = (*Import)(nil)
  2625. func (i *Import) getBazelModuleLabel(ctx android.BaseModuleContext) string {
  2626. return android.RemoveOptionalPrebuiltPrefixFromBazelLabel(i.GetBazelLabel(ctx, i))
  2627. }
  2628. func (i *Import) ProcessBazelQueryResponse(ctx android.ModuleContext) {
  2629. i.commonBuildActions(ctx)
  2630. bazelCtx := ctx.Config().BazelContext
  2631. filePaths, err := bazelCtx.GetOutputFiles(i.getBazelModuleLabel(ctx), android.GetConfigKey(ctx))
  2632. if err != nil {
  2633. ctx.ModuleErrorf(err.Error())
  2634. return
  2635. }
  2636. bazelJars := android.Paths{}
  2637. for _, bazelOutputFile := range filePaths {
  2638. bazelJars = append(bazelJars, android.PathForBazelOut(ctx, bazelOutputFile))
  2639. }
  2640. jarName := android.RemoveOptionalPrebuiltPrefix(i.Name()) + ".jar"
  2641. outputFile := android.PathForModuleOut(ctx, "bazelCombined", jarName)
  2642. TransformJarsToJar(ctx, outputFile, "combine prebuilt jars", bazelJars,
  2643. android.OptionalPath{}, // manifest
  2644. false, // stripDirEntries
  2645. []string{}, // filesToStrip
  2646. []string{}, // dirsToStrip
  2647. )
  2648. i.combinedClasspathFile = outputFile
  2649. ctx.SetProvider(JavaInfoProvider, JavaInfo{
  2650. HeaderJars: android.PathsIfNonNil(i.combinedClasspathFile),
  2651. ImplementationAndResourcesJars: android.PathsIfNonNil(i.combinedClasspathFile),
  2652. ImplementationJars: android.PathsIfNonNil(i.combinedClasspathFile),
  2653. //TODO(b/240308299) include AIDL information from Bazel
  2654. })
  2655. i.maybeInstall(ctx, jarName, outputFile)
  2656. }
  2657. func (i *Import) QueueBazelCall(ctx android.BaseModuleContext) {
  2658. bazelCtx := ctx.Config().BazelContext
  2659. bazelCtx.QueueBazelRequest(i.getBazelModuleLabel(ctx), cquery.GetOutputFiles, android.GetConfigKey(ctx))
  2660. }
  2661. func (i *Import) IsMixedBuildSupported(ctx android.BaseModuleContext) bool {
  2662. return true
  2663. }