java.go 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545
  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. "github.com/google/blueprint"
  25. "github.com/google/blueprint/proptools"
  26. "android/soong/android"
  27. "android/soong/cc"
  28. "android/soong/dexpreopt"
  29. "android/soong/java/config"
  30. "android/soong/tradefed"
  31. )
  32. func init() {
  33. registerJavaBuildComponents(android.InitRegistrationContext)
  34. RegisterJavaSdkMemberTypes()
  35. }
  36. func registerJavaBuildComponents(ctx android.RegistrationContext) {
  37. ctx.RegisterModuleType("java_defaults", DefaultsFactory)
  38. ctx.RegisterModuleType("java_library", LibraryFactory)
  39. ctx.RegisterModuleType("java_library_static", LibraryStaticFactory)
  40. ctx.RegisterModuleType("java_library_host", LibraryHostFactory)
  41. ctx.RegisterModuleType("java_binary", BinaryFactory)
  42. ctx.RegisterModuleType("java_binary_host", BinaryHostFactory)
  43. ctx.RegisterModuleType("java_test", TestFactory)
  44. ctx.RegisterModuleType("java_test_helper_library", TestHelperLibraryFactory)
  45. ctx.RegisterModuleType("java_test_host", TestHostFactory)
  46. ctx.RegisterModuleType("java_test_import", JavaTestImportFactory)
  47. ctx.RegisterModuleType("java_import", ImportFactory)
  48. ctx.RegisterModuleType("java_import_host", ImportFactoryHost)
  49. ctx.RegisterModuleType("java_device_for_host", DeviceForHostFactory)
  50. ctx.RegisterModuleType("java_host_for_device", HostForDeviceFactory)
  51. ctx.RegisterModuleType("dex_import", DexImportFactory)
  52. // This mutator registers dependencies on dex2oat for modules that should be
  53. // dexpreopted. This is done late when the final variants have been
  54. // established, to not get the dependencies split into the wrong variants and
  55. // to support the checks in dexpreoptDisabled().
  56. ctx.FinalDepsMutators(func(ctx android.RegisterMutatorsContext) {
  57. ctx.BottomUp("dexpreopt_tool_deps", dexpreoptToolDepsMutator).Parallel()
  58. })
  59. ctx.RegisterSingletonType("logtags", LogtagsSingleton)
  60. ctx.RegisterSingletonType("kythe_java_extract", kytheExtractJavaFactory)
  61. }
  62. func RegisterJavaSdkMemberTypes() {
  63. // Register sdk member types.
  64. android.RegisterSdkMemberType(javaHeaderLibsSdkMemberType)
  65. android.RegisterSdkMemberType(javaLibsSdkMemberType)
  66. android.RegisterSdkMemberType(javaBootLibsSdkMemberType)
  67. android.RegisterSdkMemberType(javaSystemserverLibsSdkMemberType)
  68. android.RegisterSdkMemberType(javaTestSdkMemberType)
  69. }
  70. var (
  71. // Supports adding java header libraries to module_exports and sdk.
  72. javaHeaderLibsSdkMemberType = &librarySdkMemberType{
  73. android.SdkMemberTypeBase{
  74. PropertyName: "java_header_libs",
  75. SupportsSdk: true,
  76. },
  77. func(_ android.SdkMemberContext, j *Library) android.Path {
  78. headerJars := j.HeaderJars()
  79. if len(headerJars) != 1 {
  80. panic(fmt.Errorf("there must be only one header jar from %q", j.Name()))
  81. }
  82. return headerJars[0]
  83. },
  84. sdkSnapshotFilePathForJar,
  85. copyEverythingToSnapshot,
  86. }
  87. // Export implementation classes jar as part of the sdk.
  88. exportImplementationClassesJar = func(_ android.SdkMemberContext, j *Library) android.Path {
  89. implementationJars := j.ImplementationAndResourcesJars()
  90. if len(implementationJars) != 1 {
  91. panic(fmt.Errorf("there must be only one implementation jar from %q", j.Name()))
  92. }
  93. return implementationJars[0]
  94. }
  95. // Supports adding java implementation libraries to module_exports but not sdk.
  96. javaLibsSdkMemberType = &librarySdkMemberType{
  97. android.SdkMemberTypeBase{
  98. PropertyName: "java_libs",
  99. },
  100. exportImplementationClassesJar,
  101. sdkSnapshotFilePathForJar,
  102. copyEverythingToSnapshot,
  103. }
  104. snapshotRequiresImplementationJar = func(ctx android.SdkMemberContext) bool {
  105. // In the S build the build will break if updatable-media does not provide a full implementation
  106. // jar. That issue was fixed in Tiramisu by b/229932396.
  107. if ctx.IsTargetBuildBeforeTiramisu() && ctx.Name() == "updatable-media" {
  108. return true
  109. }
  110. return false
  111. }
  112. // Supports adding java boot libraries to module_exports and sdk.
  113. //
  114. // The build has some implicit dependencies (via the boot jars configuration) on a number of
  115. // modules, e.g. core-oj, apache-xml, that are part of the java boot class path and which are
  116. // provided by mainline modules (e.g. art, conscrypt, runtime-i18n) but which are not otherwise
  117. // used outside those mainline modules.
  118. //
  119. // As they are not needed outside the mainline modules adding them to the sdk/module-exports as
  120. // either java_libs, or java_header_libs would end up exporting more information than was strictly
  121. // necessary. The java_boot_libs property to allow those modules to be exported as part of the
  122. // sdk/module_exports without exposing any unnecessary information.
  123. javaBootLibsSdkMemberType = &librarySdkMemberType{
  124. android.SdkMemberTypeBase{
  125. PropertyName: "java_boot_libs",
  126. SupportsSdk: true,
  127. },
  128. func(ctx android.SdkMemberContext, j *Library) android.Path {
  129. if snapshotRequiresImplementationJar(ctx) {
  130. return exportImplementationClassesJar(ctx, j)
  131. }
  132. // Java boot libs are only provided in the SDK to provide access to their dex implementation
  133. // jar for use by dexpreopting and boot jars package check. They do not need to provide an
  134. // actual implementation jar but the java_import will need a file that exists so just copy an
  135. // empty file. Any attempt to use that file as a jar will cause a build error.
  136. return ctx.SnapshotBuilder().EmptyFile()
  137. },
  138. func(ctx android.SdkMemberContext, osPrefix, name string) string {
  139. if snapshotRequiresImplementationJar(ctx) {
  140. return sdkSnapshotFilePathForJar(ctx, osPrefix, name)
  141. }
  142. // Create a special name for the implementation jar to try and provide some useful information
  143. // to a developer that attempts to compile against this.
  144. // TODO(b/175714559): Provide a proper error message in Soong not ninja.
  145. return filepath.Join(osPrefix, "java_boot_libs", "snapshot", "jars", "are", "invalid", name+jarFileSuffix)
  146. },
  147. onlyCopyJarToSnapshot,
  148. }
  149. // Supports adding java systemserver libraries to module_exports and sdk.
  150. //
  151. // The build has some implicit dependencies (via the systemserver jars configuration) on a number
  152. // of modules that are part of the java systemserver classpath and which are provided by mainline
  153. // modules but which are not otherwise used outside those mainline modules.
  154. //
  155. // As they are not needed outside the mainline modules adding them to the sdk/module-exports as
  156. // either java_libs, or java_header_libs would end up exporting more information than was strictly
  157. // necessary. The java_systemserver_libs property to allow those modules to be exported as part of
  158. // the sdk/module_exports without exposing any unnecessary information.
  159. javaSystemserverLibsSdkMemberType = &librarySdkMemberType{
  160. android.SdkMemberTypeBase{
  161. PropertyName: "java_systemserver_libs",
  162. SupportsSdk: true,
  163. // This was only added in Tiramisu.
  164. SupportedBuildReleaseSpecification: "Tiramisu+",
  165. },
  166. func(ctx android.SdkMemberContext, j *Library) android.Path {
  167. // Java systemserver libs are only provided in the SDK to provide access to their dex
  168. // implementation jar for use by dexpreopting. They do not need to provide an actual
  169. // implementation jar but the java_import will need a file that exists so just copy an empty
  170. // file. Any attempt to use that file as a jar will cause a build error.
  171. return ctx.SnapshotBuilder().EmptyFile()
  172. },
  173. func(_ android.SdkMemberContext, osPrefix, name string) string {
  174. // Create a special name for the implementation jar to try and provide some useful information
  175. // to a developer that attempts to compile against this.
  176. // TODO(b/175714559): Provide a proper error message in Soong not ninja.
  177. return filepath.Join(osPrefix, "java_systemserver_libs", "snapshot", "jars", "are", "invalid", name+jarFileSuffix)
  178. },
  179. onlyCopyJarToSnapshot,
  180. }
  181. // Supports adding java test libraries to module_exports but not sdk.
  182. javaTestSdkMemberType = &testSdkMemberType{
  183. SdkMemberTypeBase: android.SdkMemberTypeBase{
  184. PropertyName: "java_tests",
  185. },
  186. }
  187. )
  188. // JavaInfo contains information about a java module for use by modules that depend on it.
  189. type JavaInfo struct {
  190. // HeaderJars is a list of jars that can be passed as the javac classpath in order to link
  191. // against this module. If empty, ImplementationJars should be used instead.
  192. HeaderJars android.Paths
  193. // ImplementationAndResourceJars is a list of jars that contain the implementations of classes
  194. // in the module as well as any resources included in the module.
  195. ImplementationAndResourcesJars android.Paths
  196. // ImplementationJars is a list of jars that contain the implementations of classes in the
  197. //module.
  198. ImplementationJars android.Paths
  199. // ResourceJars is a list of jars that contain the resources included in the module.
  200. ResourceJars android.Paths
  201. // AidlIncludeDirs is a list of directories that should be passed to the aidl tool when
  202. // depending on this module.
  203. AidlIncludeDirs android.Paths
  204. // SrcJarArgs is a list of arguments to pass to soong_zip to package the sources of this
  205. // module.
  206. SrcJarArgs []string
  207. // SrcJarDeps is a list of paths to depend on when packaging the sources of this module.
  208. SrcJarDeps android.Paths
  209. // ExportedPlugins is a list of paths that should be used as annotation processors for any
  210. // module that depends on this module.
  211. ExportedPlugins android.Paths
  212. // ExportedPluginClasses is a list of classes that should be run as annotation processors for
  213. // any module that depends on this module.
  214. ExportedPluginClasses []string
  215. // ExportedPluginDisableTurbine is true if this module's annotation processors generate APIs,
  216. // requiring disbling turbine for any modules that depend on it.
  217. ExportedPluginDisableTurbine bool
  218. // JacocoReportClassesFile is the path to a jar containing uninstrumented classes that will be
  219. // instrumented by jacoco.
  220. JacocoReportClassesFile android.Path
  221. }
  222. var JavaInfoProvider = blueprint.NewProvider(JavaInfo{})
  223. // SyspropPublicStubInfo contains info about the sysprop public stub library that corresponds to
  224. // the sysprop implementation library.
  225. type SyspropPublicStubInfo struct {
  226. // JavaInfo is the JavaInfoProvider of the sysprop public stub library that corresponds to
  227. // the sysprop implementation library.
  228. JavaInfo JavaInfo
  229. }
  230. var SyspropPublicStubInfoProvider = blueprint.NewProvider(SyspropPublicStubInfo{})
  231. // Methods that need to be implemented for a module that is added to apex java_libs property.
  232. type ApexDependency interface {
  233. HeaderJars() android.Paths
  234. ImplementationAndResourcesJars() android.Paths
  235. }
  236. // Provides build path and install path to DEX jars.
  237. type UsesLibraryDependency interface {
  238. DexJarBuildPath() OptionalDexJarPath
  239. DexJarInstallPath() android.Path
  240. ClassLoaderContexts() dexpreopt.ClassLoaderContextMap
  241. }
  242. // TODO(jungjw): Move this to kythe.go once it's created.
  243. type xref interface {
  244. XrefJavaFiles() android.Paths
  245. }
  246. func (j *Module) XrefJavaFiles() android.Paths {
  247. return j.kytheFiles
  248. }
  249. type dependencyTag struct {
  250. blueprint.BaseDependencyTag
  251. name string
  252. // True if the dependency is relinked at runtime.
  253. runtimeLinked bool
  254. // True if the dependency is a toolchain, for example an annotation processor.
  255. toolchain bool
  256. }
  257. // installDependencyTag is a dependency tag that is annotated to cause the installed files of the
  258. // dependency to be installed when the parent module is installed.
  259. type installDependencyTag struct {
  260. blueprint.BaseDependencyTag
  261. android.InstallAlwaysNeededDependencyTag
  262. name string
  263. }
  264. func (d dependencyTag) LicenseAnnotations() []android.LicenseAnnotation {
  265. if d.runtimeLinked {
  266. return []android.LicenseAnnotation{android.LicenseAnnotationSharedDependency}
  267. } else if d.toolchain {
  268. return []android.LicenseAnnotation{android.LicenseAnnotationToolchain}
  269. }
  270. return nil
  271. }
  272. var _ android.LicenseAnnotationsDependencyTag = dependencyTag{}
  273. type usesLibraryDependencyTag struct {
  274. dependencyTag
  275. sdkVersion int // SDK version in which the library appared as a standalone library.
  276. optional bool // If the dependency is optional or required.
  277. }
  278. func makeUsesLibraryDependencyTag(sdkVersion int, optional bool) usesLibraryDependencyTag {
  279. return usesLibraryDependencyTag{
  280. dependencyTag: dependencyTag{
  281. name: fmt.Sprintf("uses-library-%d", sdkVersion),
  282. runtimeLinked: true,
  283. },
  284. sdkVersion: sdkVersion,
  285. optional: optional,
  286. }
  287. }
  288. func IsJniDepTag(depTag blueprint.DependencyTag) bool {
  289. return depTag == jniLibTag
  290. }
  291. var (
  292. dataNativeBinsTag = dependencyTag{name: "dataNativeBins"}
  293. dataDeviceBinsTag = dependencyTag{name: "dataDeviceBins"}
  294. staticLibTag = dependencyTag{name: "staticlib"}
  295. libTag = dependencyTag{name: "javalib", runtimeLinked: true}
  296. java9LibTag = dependencyTag{name: "java9lib", runtimeLinked: true}
  297. pluginTag = dependencyTag{name: "plugin", toolchain: true}
  298. errorpronePluginTag = dependencyTag{name: "errorprone-plugin", toolchain: true}
  299. exportedPluginTag = dependencyTag{name: "exported-plugin", toolchain: true}
  300. bootClasspathTag = dependencyTag{name: "bootclasspath", runtimeLinked: true}
  301. systemModulesTag = dependencyTag{name: "system modules", runtimeLinked: true}
  302. frameworkResTag = dependencyTag{name: "framework-res"}
  303. kotlinStdlibTag = dependencyTag{name: "kotlin-stdlib", runtimeLinked: true}
  304. kotlinAnnotationsTag = dependencyTag{name: "kotlin-annotations", runtimeLinked: true}
  305. kotlinPluginTag = dependencyTag{name: "kotlin-plugin", toolchain: true}
  306. proguardRaiseTag = dependencyTag{name: "proguard-raise"}
  307. certificateTag = dependencyTag{name: "certificate"}
  308. instrumentationForTag = dependencyTag{name: "instrumentation_for"}
  309. extraLintCheckTag = dependencyTag{name: "extra-lint-check", toolchain: true}
  310. jniLibTag = dependencyTag{name: "jnilib", runtimeLinked: true}
  311. syspropPublicStubDepTag = dependencyTag{name: "sysprop public stub"}
  312. jniInstallTag = installDependencyTag{name: "jni install"}
  313. binaryInstallTag = installDependencyTag{name: "binary install"}
  314. usesLibReqTag = makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, false)
  315. usesLibOptTag = makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, true)
  316. usesLibCompat28OptTag = makeUsesLibraryDependencyTag(28, true)
  317. usesLibCompat29ReqTag = makeUsesLibraryDependencyTag(29, false)
  318. usesLibCompat30OptTag = makeUsesLibraryDependencyTag(30, true)
  319. )
  320. func IsLibDepTag(depTag blueprint.DependencyTag) bool {
  321. return depTag == libTag
  322. }
  323. func IsStaticLibDepTag(depTag blueprint.DependencyTag) bool {
  324. return depTag == staticLibTag
  325. }
  326. type sdkDep struct {
  327. useModule, useFiles, invalidVersion bool
  328. // The modules that will be added to the bootclasspath when targeting 1.8 or lower
  329. bootclasspath []string
  330. // The default system modules to use. Will be an empty string if no system
  331. // modules are to be used.
  332. systemModules string
  333. // The modules that will be added to the classpath regardless of the Java language level targeted
  334. classpath []string
  335. // The modules that will be added ot the classpath when targeting 1.9 or higher
  336. // (normally these will be on the bootclasspath when targeting 1.8 or lower)
  337. java9Classpath []string
  338. frameworkResModule string
  339. jars android.Paths
  340. aidl android.OptionalPath
  341. noStandardLibs, noFrameworksLibs bool
  342. }
  343. func (s sdkDep) hasStandardLibs() bool {
  344. return !s.noStandardLibs
  345. }
  346. func (s sdkDep) hasFrameworkLibs() bool {
  347. return !s.noStandardLibs && !s.noFrameworksLibs
  348. }
  349. type jniLib struct {
  350. name string
  351. path android.Path
  352. target android.Target
  353. coverageFile android.OptionalPath
  354. unstrippedFile android.Path
  355. }
  356. func sdkDeps(ctx android.BottomUpMutatorContext, sdkContext android.SdkContext, d dexer) {
  357. sdkDep := decodeSdkDep(ctx, sdkContext)
  358. if sdkDep.useModule {
  359. ctx.AddVariationDependencies(nil, bootClasspathTag, sdkDep.bootclasspath...)
  360. ctx.AddVariationDependencies(nil, java9LibTag, sdkDep.java9Classpath...)
  361. ctx.AddVariationDependencies(nil, libTag, sdkDep.classpath...)
  362. if d.effectiveOptimizeEnabled() && sdkDep.hasStandardLibs() {
  363. ctx.AddVariationDependencies(nil, proguardRaiseTag, config.LegacyCorePlatformBootclasspathLibraries...)
  364. }
  365. if d.effectiveOptimizeEnabled() && sdkDep.hasFrameworkLibs() {
  366. ctx.AddVariationDependencies(nil, proguardRaiseTag, config.FrameworkLibraries...)
  367. }
  368. }
  369. if sdkDep.systemModules != "" {
  370. ctx.AddVariationDependencies(nil, systemModulesTag, sdkDep.systemModules)
  371. }
  372. }
  373. type deps struct {
  374. // bootClasspath is the list of jars that form the boot classpath (generally the java.* and
  375. // android.* classes) for tools that still use it. javac targeting 1.9 or higher uses
  376. // systemModules and java9Classpath instead.
  377. bootClasspath classpath
  378. // classpath is the list of jars that form the classpath for javac and kotlinc rules. It
  379. // contains header jars for all static and non-static dependencies.
  380. classpath classpath
  381. // dexClasspath is the list of jars that form the classpath for d8 and r8 rules. It contains
  382. // header jars for all non-static dependencies. Static dependencies have already been
  383. // combined into the program jar.
  384. dexClasspath classpath
  385. // java9Classpath is the list of jars that will be added to the classpath when targeting
  386. // 1.9 or higher. It generally contains the android.* classes, while the java.* classes
  387. // are provided by systemModules.
  388. java9Classpath classpath
  389. processorPath classpath
  390. errorProneProcessorPath classpath
  391. processorClasses []string
  392. staticJars android.Paths
  393. staticHeaderJars android.Paths
  394. staticResourceJars android.Paths
  395. aidlIncludeDirs android.Paths
  396. srcs android.Paths
  397. srcJars android.Paths
  398. systemModules *systemModules
  399. aidlPreprocess android.OptionalPath
  400. kotlinStdlib android.Paths
  401. kotlinAnnotations android.Paths
  402. kotlinPlugins android.Paths
  403. disableTurbine bool
  404. }
  405. func checkProducesJars(ctx android.ModuleContext, dep android.SourceFileProducer) {
  406. for _, f := range dep.Srcs() {
  407. if f.Ext() != ".jar" {
  408. ctx.ModuleErrorf("genrule %q must generate files ending with .jar to be used as a libs or static_libs dependency",
  409. ctx.OtherModuleName(dep.(blueprint.Module)))
  410. }
  411. }
  412. }
  413. func getJavaVersion(ctx android.ModuleContext, javaVersion string, sdkContext android.SdkContext) javaVersion {
  414. if javaVersion != "" {
  415. return normalizeJavaVersion(ctx, javaVersion)
  416. } else if ctx.Device() {
  417. return defaultJavaLanguageVersion(ctx, sdkContext.SdkVersion(ctx))
  418. } else if ctx.Config().TargetsJava17() {
  419. // Temporary experimental flag to be able to try and build with
  420. // java version 17 options. The flag, if used, just sets Java
  421. // 17 as the default version, leaving any components that
  422. // target an older version intact.
  423. return JAVA_VERSION_17
  424. } else {
  425. return JAVA_VERSION_11
  426. }
  427. }
  428. type javaVersion int
  429. const (
  430. JAVA_VERSION_UNSUPPORTED = 0
  431. JAVA_VERSION_6 = 6
  432. JAVA_VERSION_7 = 7
  433. JAVA_VERSION_8 = 8
  434. JAVA_VERSION_9 = 9
  435. JAVA_VERSION_11 = 11
  436. JAVA_VERSION_17 = 17
  437. )
  438. func (v javaVersion) String() string {
  439. switch v {
  440. case JAVA_VERSION_6:
  441. return "1.6"
  442. case JAVA_VERSION_7:
  443. return "1.7"
  444. case JAVA_VERSION_8:
  445. return "1.8"
  446. case JAVA_VERSION_9:
  447. return "1.9"
  448. case JAVA_VERSION_11:
  449. return "11"
  450. case JAVA_VERSION_17:
  451. return "17"
  452. default:
  453. return "unsupported"
  454. }
  455. }
  456. func (v javaVersion) StringForKotlinc() string {
  457. // $ ./external/kotlinc/bin/kotlinc -jvm-target foo
  458. // error: unknown JVM target version: foo
  459. // Supported versions: 1.6, 1.8, 9, 10, 11, 12, 13, 14, 15, 16, 17
  460. switch v {
  461. case JAVA_VERSION_7:
  462. return "1.6"
  463. case JAVA_VERSION_9:
  464. return "9"
  465. default:
  466. return v.String()
  467. }
  468. }
  469. // Returns true if javac targeting this version uses system modules instead of a bootclasspath.
  470. func (v javaVersion) usesJavaModules() bool {
  471. return v >= 9
  472. }
  473. func normalizeJavaVersion(ctx android.BaseModuleContext, javaVersion string) javaVersion {
  474. switch javaVersion {
  475. case "1.6", "6":
  476. return JAVA_VERSION_6
  477. case "1.7", "7":
  478. return JAVA_VERSION_7
  479. case "1.8", "8":
  480. return JAVA_VERSION_8
  481. case "1.9", "9":
  482. return JAVA_VERSION_9
  483. case "11":
  484. return JAVA_VERSION_11
  485. case "17":
  486. return JAVA_VERSION_17
  487. case "10", "12", "13", "14", "15", "16":
  488. ctx.PropertyErrorf("java_version", "Java language level %s is not supported", javaVersion)
  489. return JAVA_VERSION_UNSUPPORTED
  490. default:
  491. ctx.PropertyErrorf("java_version", "Unrecognized Java language level")
  492. return JAVA_VERSION_UNSUPPORTED
  493. }
  494. }
  495. //
  496. // Java libraries (.jar file)
  497. //
  498. type Library struct {
  499. Module
  500. InstallMixin func(ctx android.ModuleContext, installPath android.Path) (extraInstallDeps android.Paths)
  501. }
  502. var _ android.ApexModule = (*Library)(nil)
  503. // Provides access to the list of permitted packages from apex boot jars.
  504. type PermittedPackagesForUpdatableBootJars interface {
  505. PermittedPackagesForUpdatableBootJars() []string
  506. }
  507. var _ PermittedPackagesForUpdatableBootJars = (*Library)(nil)
  508. func (j *Library) PermittedPackagesForUpdatableBootJars() []string {
  509. return j.properties.Permitted_packages
  510. }
  511. func shouldUncompressDex(ctx android.ModuleContext, dexpreopter *dexpreopter) bool {
  512. // Store uncompressed (and aligned) any dex files from jars in APEXes.
  513. if apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo); !apexInfo.IsForPlatform() {
  514. return true
  515. }
  516. // Store uncompressed (and do not strip) dex files from boot class path jars.
  517. if inList(ctx.ModuleName(), ctx.Config().BootJars()) {
  518. return true
  519. }
  520. // Store uncompressed dex files that are preopted on /system.
  521. if !dexpreopter.dexpreoptDisabled(ctx) && (ctx.Host() || !dexpreopter.odexOnSystemOther(ctx, dexpreopter.installPath)) {
  522. return true
  523. }
  524. if ctx.Config().UncompressPrivAppDex() &&
  525. inList(ctx.ModuleName(), ctx.Config().ModulesLoadedByPrivilegedModules()) {
  526. return true
  527. }
  528. return false
  529. }
  530. // Sets `dexer.dexProperties.Uncompress_dex` to the proper value.
  531. func setUncompressDex(ctx android.ModuleContext, dexpreopter *dexpreopter, dexer *dexer) {
  532. if dexer.dexProperties.Uncompress_dex == nil {
  533. // If the value was not force-set by the user, use reasonable default based on the module.
  534. dexer.dexProperties.Uncompress_dex = proptools.BoolPtr(shouldUncompressDex(ctx, dexpreopter))
  535. }
  536. }
  537. func (j *Library) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  538. j.sdkVersion = j.SdkVersion(ctx)
  539. j.minSdkVersion = j.MinSdkVersion(ctx)
  540. j.maxSdkVersion = j.MaxSdkVersion(ctx)
  541. apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
  542. if !apexInfo.IsForPlatform() {
  543. j.hideApexVariantFromMake = true
  544. }
  545. j.checkSdkVersions(ctx)
  546. if ctx.Device() {
  547. j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
  548. ctx, android.PathForModuleInstall(ctx, "framework", j.Stem()+".jar"))
  549. j.dexpreopter.isSDKLibrary = j.deviceProperties.IsSDKLibrary
  550. setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
  551. j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
  552. j.classLoaderContexts = j.usesLibrary.classLoaderContextForUsesLibDeps(ctx)
  553. }
  554. j.compile(ctx, nil)
  555. // Collect the module directory for IDE info in java/jdeps.go.
  556. j.modulePaths = append(j.modulePaths, ctx.ModuleDir())
  557. exclusivelyForApex := !apexInfo.IsForPlatform()
  558. if (Bool(j.properties.Installable) || ctx.Host()) && !exclusivelyForApex {
  559. var extraInstallDeps android.Paths
  560. if j.InstallMixin != nil {
  561. extraInstallDeps = j.InstallMixin(ctx, j.outputFile)
  562. }
  563. hostDexNeeded := Bool(j.deviceProperties.Hostdex) && !ctx.Host()
  564. if hostDexNeeded {
  565. j.hostdexInstallFile = ctx.InstallFile(
  566. android.PathForHostDexInstall(ctx, "framework"),
  567. j.Stem()+"-hostdex.jar", j.outputFile)
  568. }
  569. var installDir android.InstallPath
  570. if ctx.InstallInTestcases() {
  571. var archDir string
  572. if !ctx.Host() {
  573. archDir = ctx.DeviceConfig().DeviceArch()
  574. }
  575. installDir = android.PathForModuleInstall(ctx, ctx.ModuleName(), archDir)
  576. } else {
  577. installDir = android.PathForModuleInstall(ctx, "framework")
  578. }
  579. j.installFile = ctx.InstallFile(installDir, j.Stem()+".jar", j.outputFile, extraInstallDeps...)
  580. }
  581. }
  582. func (j *Library) DepsMutator(ctx android.BottomUpMutatorContext) {
  583. j.deps(ctx)
  584. j.usesLibrary.deps(ctx, false)
  585. }
  586. const (
  587. aidlIncludeDir = "aidl"
  588. javaDir = "java"
  589. jarFileSuffix = ".jar"
  590. testConfigSuffix = "-AndroidTest.xml"
  591. )
  592. // path to the jar file of a java library. Relative to <sdk_root>/<api_dir>
  593. func sdkSnapshotFilePathForJar(_ android.SdkMemberContext, osPrefix, name string) string {
  594. return sdkSnapshotFilePathForMember(osPrefix, name, jarFileSuffix)
  595. }
  596. func sdkSnapshotFilePathForMember(osPrefix, name string, suffix string) string {
  597. return filepath.Join(javaDir, osPrefix, name+suffix)
  598. }
  599. type librarySdkMemberType struct {
  600. android.SdkMemberTypeBase
  601. // Function to retrieve the appropriate output jar (implementation or header) from
  602. // the library.
  603. jarToExportGetter func(ctx android.SdkMemberContext, j *Library) android.Path
  604. // Function to compute the snapshot relative path to which the named library's
  605. // jar should be copied.
  606. snapshotPathGetter func(ctx android.SdkMemberContext, osPrefix, name string) string
  607. // True if only the jar should be copied to the snapshot, false if the jar plus any additional
  608. // files like aidl files should also be copied.
  609. onlyCopyJarToSnapshot bool
  610. }
  611. const (
  612. onlyCopyJarToSnapshot = true
  613. copyEverythingToSnapshot = false
  614. )
  615. func (mt *librarySdkMemberType) AddDependencies(ctx android.SdkDependencyContext, dependencyTag blueprint.DependencyTag, names []string) {
  616. ctx.AddVariationDependencies(nil, dependencyTag, names...)
  617. }
  618. func (mt *librarySdkMemberType) IsInstance(module android.Module) bool {
  619. _, ok := module.(*Library)
  620. return ok
  621. }
  622. func (mt *librarySdkMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
  623. return ctx.SnapshotBuilder().AddPrebuiltModule(member, "java_import")
  624. }
  625. func (mt *librarySdkMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
  626. return &librarySdkMemberProperties{}
  627. }
  628. type librarySdkMemberProperties struct {
  629. android.SdkMemberPropertiesBase
  630. JarToExport android.Path `android:"arch_variant"`
  631. AidlIncludeDirs android.Paths
  632. // The list of permitted packages that need to be passed to the prebuilts as they are used to
  633. // create the updatable-bcp-packages.txt file.
  634. PermittedPackages []string
  635. }
  636. func (p *librarySdkMemberProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
  637. j := variant.(*Library)
  638. p.JarToExport = ctx.MemberType().(*librarySdkMemberType).jarToExportGetter(ctx, j)
  639. p.AidlIncludeDirs = j.AidlIncludeDirs()
  640. p.PermittedPackages = j.PermittedPackagesForUpdatableBootJars()
  641. }
  642. func (p *librarySdkMemberProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
  643. builder := ctx.SnapshotBuilder()
  644. memberType := ctx.MemberType().(*librarySdkMemberType)
  645. exportedJar := p.JarToExport
  646. if exportedJar != nil {
  647. // Delegate the creation of the snapshot relative path to the member type.
  648. snapshotRelativeJavaLibPath := memberType.snapshotPathGetter(ctx, p.OsPrefix(), ctx.Name())
  649. // Copy the exported jar to the snapshot.
  650. builder.CopyToSnapshot(exportedJar, snapshotRelativeJavaLibPath)
  651. propertySet.AddProperty("jars", []string{snapshotRelativeJavaLibPath})
  652. }
  653. if len(p.PermittedPackages) > 0 {
  654. propertySet.AddProperty("permitted_packages", p.PermittedPackages)
  655. }
  656. // Do not copy anything else to the snapshot.
  657. if memberType.onlyCopyJarToSnapshot {
  658. return
  659. }
  660. aidlIncludeDirs := p.AidlIncludeDirs
  661. if len(aidlIncludeDirs) != 0 {
  662. sdkModuleContext := ctx.SdkModuleContext()
  663. for _, dir := range aidlIncludeDirs {
  664. // TODO(jiyong): copy parcelable declarations only
  665. aidlFiles, _ := sdkModuleContext.GlobWithDeps(dir.String()+"/**/*.aidl", nil)
  666. for _, file := range aidlFiles {
  667. builder.CopyToSnapshot(android.PathForSource(sdkModuleContext, file), filepath.Join(aidlIncludeDir, file))
  668. }
  669. }
  670. // TODO(b/151933053) - add aidl include dirs property
  671. }
  672. }
  673. // java_library builds and links sources into a `.jar` file for the device, and possibly for the host as well.
  674. //
  675. // By default, a java_library has a single variant that produces a `.jar` file containing `.class` files that were
  676. // compiled against the device bootclasspath. This jar is not suitable for installing on a device, but can be used
  677. // as a `static_libs` dependency of another module.
  678. //
  679. // Specifying `installable: true` will product a `.jar` file containing `classes.dex` files, suitable for installing on
  680. // a device.
  681. //
  682. // Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
  683. // compiled against the host bootclasspath.
  684. func LibraryFactory() android.Module {
  685. module := &Library{}
  686. module.addHostAndDeviceProperties()
  687. module.initModuleAndImport(module)
  688. android.InitApexModule(module)
  689. android.InitSdkAwareModule(module)
  690. android.InitBazelModule(module)
  691. InitJavaModule(module, android.HostAndDeviceSupported)
  692. return module
  693. }
  694. // java_library_static is an obsolete alias for java_library.
  695. func LibraryStaticFactory() android.Module {
  696. return LibraryFactory()
  697. }
  698. // java_library_host builds and links sources into a `.jar` file for the host.
  699. //
  700. // A java_library_host has a single variant that produces a `.jar` file containing `.class` files that were
  701. // compiled against the host bootclasspath.
  702. func LibraryHostFactory() android.Module {
  703. module := &Library{}
  704. module.addHostProperties()
  705. module.Module.properties.Installable = proptools.BoolPtr(true)
  706. android.InitApexModule(module)
  707. android.InitSdkAwareModule(module)
  708. android.InitBazelModule(module)
  709. InitJavaModule(module, android.HostSupported)
  710. return module
  711. }
  712. //
  713. // Java Tests
  714. //
  715. // Test option struct.
  716. type TestOptions struct {
  717. android.CommonTestOptions
  718. // a list of extra test configuration files that should be installed with the module.
  719. Extra_test_configs []string `android:"path,arch_variant"`
  720. }
  721. type testProperties struct {
  722. // list of compatibility suites (for example "cts", "vts") that the module should be
  723. // installed into.
  724. Test_suites []string `android:"arch_variant"`
  725. // the name of the test configuration (for example "AndroidTest.xml") that should be
  726. // installed with the module.
  727. Test_config *string `android:"path,arch_variant"`
  728. // the name of the test configuration template (for example "AndroidTestTemplate.xml") that
  729. // should be installed with the module.
  730. Test_config_template *string `android:"path,arch_variant"`
  731. // list of files or filegroup modules that provide data that should be installed alongside
  732. // the test
  733. Data []string `android:"path"`
  734. // Flag to indicate whether or not to create test config automatically. If AndroidTest.xml
  735. // doesn't exist next to the Android.bp, this attribute doesn't need to be set to true
  736. // explicitly.
  737. Auto_gen_config *bool
  738. // Add parameterized mainline modules to auto generated test config. The options will be
  739. // handled by TradeFed to do downloading and installing the specified modules on the device.
  740. Test_mainline_modules []string
  741. // Test options.
  742. Test_options TestOptions
  743. // Names of modules containing JNI libraries that should be installed alongside the test.
  744. Jni_libs []string
  745. // Install the test into a folder named for the module in all test suites.
  746. Per_testcase_directory *bool
  747. }
  748. type hostTestProperties struct {
  749. // list of native binary modules that should be installed alongside the test
  750. Data_native_bins []string `android:"arch_variant"`
  751. // list of device binary modules that should be installed alongside the test
  752. // This property only adds the first variant of the dependency
  753. Data_device_bins_first []string `android:"arch_variant"`
  754. // list of device binary modules that should be installed alongside the test
  755. // This property adds 64bit AND 32bit variants of the dependency
  756. Data_device_bins_both []string `android:"arch_variant"`
  757. // list of device binary modules that should be installed alongside the test
  758. // This property only adds 64bit variants of the dependency
  759. Data_device_bins_64 []string `android:"arch_variant"`
  760. // list of device binary modules that should be installed alongside the test
  761. // This property adds 32bit variants of the dependency if available, or else
  762. // defaults to the 64bit variant
  763. Data_device_bins_prefer32 []string `android:"arch_variant"`
  764. // list of device binary modules that should be installed alongside the test
  765. // This property only adds 32bit variants of the dependency
  766. Data_device_bins_32 []string `android:"arch_variant"`
  767. }
  768. type testHelperLibraryProperties struct {
  769. // list of compatibility suites (for example "cts", "vts") that the module should be
  770. // installed into.
  771. Test_suites []string `android:"arch_variant"`
  772. // Install the test into a folder named for the module in all test suites.
  773. Per_testcase_directory *bool
  774. }
  775. type prebuiltTestProperties struct {
  776. // list of compatibility suites (for example "cts", "vts") that the module should be
  777. // installed into.
  778. Test_suites []string `android:"arch_variant"`
  779. // the name of the test configuration (for example "AndroidTest.xml") that should be
  780. // installed with the module.
  781. Test_config *string `android:"path,arch_variant"`
  782. }
  783. type Test struct {
  784. Library
  785. testProperties testProperties
  786. testConfig android.Path
  787. extraTestConfigs android.Paths
  788. data android.Paths
  789. }
  790. type TestHost struct {
  791. Test
  792. testHostProperties hostTestProperties
  793. }
  794. type TestHelperLibrary struct {
  795. Library
  796. testHelperLibraryProperties testHelperLibraryProperties
  797. }
  798. type JavaTestImport struct {
  799. Import
  800. prebuiltTestProperties prebuiltTestProperties
  801. testConfig android.Path
  802. dexJarFile android.Path
  803. }
  804. func (j *Test) InstallInTestcases() bool {
  805. // Host java tests install into $(HOST_OUT_JAVA_LIBRARIES), and then are copied into
  806. // testcases by base_rules.mk.
  807. return !j.Host()
  808. }
  809. func (j *TestHelperLibrary) InstallInTestcases() bool {
  810. return true
  811. }
  812. func (j *JavaTestImport) InstallInTestcases() bool {
  813. return true
  814. }
  815. func (j *TestHost) addDataDeviceBinsDeps(ctx android.BottomUpMutatorContext) {
  816. if len(j.testHostProperties.Data_device_bins_first) > 0 {
  817. deviceVariations := ctx.Config().AndroidFirstDeviceTarget.Variations()
  818. ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_first...)
  819. }
  820. var maybeAndroid32Target *android.Target
  821. var maybeAndroid64Target *android.Target
  822. android32TargetList := android.FirstTarget(ctx.Config().Targets[android.Android], "lib32")
  823. android64TargetList := android.FirstTarget(ctx.Config().Targets[android.Android], "lib64")
  824. if len(android32TargetList) > 0 {
  825. maybeAndroid32Target = &android32TargetList[0]
  826. }
  827. if len(android64TargetList) > 0 {
  828. maybeAndroid64Target = &android64TargetList[0]
  829. }
  830. if len(j.testHostProperties.Data_device_bins_both) > 0 {
  831. if maybeAndroid32Target == nil && maybeAndroid64Target == nil {
  832. ctx.PropertyErrorf("data_device_bins_both", "no device targets available. Targets: %q", ctx.Config().Targets)
  833. return
  834. }
  835. if maybeAndroid32Target != nil {
  836. ctx.AddFarVariationDependencies(
  837. maybeAndroid32Target.Variations(),
  838. dataDeviceBinsTag,
  839. j.testHostProperties.Data_device_bins_both...,
  840. )
  841. }
  842. if maybeAndroid64Target != nil {
  843. ctx.AddFarVariationDependencies(
  844. maybeAndroid64Target.Variations(),
  845. dataDeviceBinsTag,
  846. j.testHostProperties.Data_device_bins_both...,
  847. )
  848. }
  849. }
  850. if len(j.testHostProperties.Data_device_bins_prefer32) > 0 {
  851. if maybeAndroid32Target != nil {
  852. ctx.AddFarVariationDependencies(
  853. maybeAndroid32Target.Variations(),
  854. dataDeviceBinsTag,
  855. j.testHostProperties.Data_device_bins_prefer32...,
  856. )
  857. } else {
  858. if maybeAndroid64Target == nil {
  859. ctx.PropertyErrorf("data_device_bins_prefer32", "no device targets available. Targets: %q", ctx.Config().Targets)
  860. return
  861. }
  862. ctx.AddFarVariationDependencies(
  863. maybeAndroid64Target.Variations(),
  864. dataDeviceBinsTag,
  865. j.testHostProperties.Data_device_bins_prefer32...,
  866. )
  867. }
  868. }
  869. if len(j.testHostProperties.Data_device_bins_32) > 0 {
  870. if maybeAndroid32Target == nil {
  871. ctx.PropertyErrorf("data_device_bins_32", "cannot find 32bit device target. Targets: %q", ctx.Config().Targets)
  872. return
  873. }
  874. deviceVariations := maybeAndroid32Target.Variations()
  875. ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_32...)
  876. }
  877. if len(j.testHostProperties.Data_device_bins_64) > 0 {
  878. if maybeAndroid64Target == nil {
  879. ctx.PropertyErrorf("data_device_bins_64", "cannot find 64bit device target. Targets: %q", ctx.Config().Targets)
  880. return
  881. }
  882. deviceVariations := maybeAndroid64Target.Variations()
  883. ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_64...)
  884. }
  885. }
  886. func (j *TestHost) DepsMutator(ctx android.BottomUpMutatorContext) {
  887. if len(j.testHostProperties.Data_native_bins) > 0 {
  888. for _, target := range ctx.MultiTargets() {
  889. ctx.AddVariationDependencies(target.Variations(), dataNativeBinsTag, j.testHostProperties.Data_native_bins...)
  890. }
  891. }
  892. if len(j.testProperties.Jni_libs) > 0 {
  893. for _, target := range ctx.MultiTargets() {
  894. sharedLibVariations := append(target.Variations(), blueprint.Variation{Mutator: "link", Variation: "shared"})
  895. ctx.AddFarVariationDependencies(sharedLibVariations, jniLibTag, j.testProperties.Jni_libs...)
  896. }
  897. }
  898. j.addDataDeviceBinsDeps(ctx)
  899. j.deps(ctx)
  900. }
  901. func (j *TestHost) AddExtraResource(p android.Path) {
  902. j.extraResources = append(j.extraResources, p)
  903. }
  904. func (j *TestHost) dataDeviceBins() []string {
  905. ret := make([]string, 0,
  906. len(j.testHostProperties.Data_device_bins_first)+
  907. len(j.testHostProperties.Data_device_bins_both)+
  908. len(j.testHostProperties.Data_device_bins_prefer32)+
  909. len(j.testHostProperties.Data_device_bins_32)+
  910. len(j.testHostProperties.Data_device_bins_64),
  911. )
  912. ret = append(ret, j.testHostProperties.Data_device_bins_first...)
  913. ret = append(ret, j.testHostProperties.Data_device_bins_both...)
  914. ret = append(ret, j.testHostProperties.Data_device_bins_prefer32...)
  915. ret = append(ret, j.testHostProperties.Data_device_bins_32...)
  916. ret = append(ret, j.testHostProperties.Data_device_bins_64...)
  917. return ret
  918. }
  919. func (j *TestHost) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  920. var configs []tradefed.Config
  921. dataDeviceBins := j.dataDeviceBins()
  922. if len(dataDeviceBins) > 0 {
  923. // add Tradefed configuration to push device bins to device for testing
  924. remoteDir := filepath.Join("/data/local/tests/unrestricted/", j.Name())
  925. options := []tradefed.Option{{Name: "cleanup", Value: "true"}}
  926. for _, bin := range dataDeviceBins {
  927. fullPath := filepath.Join(remoteDir, bin)
  928. options = append(options, tradefed.Option{Name: "push-file", Key: bin, Value: fullPath})
  929. }
  930. configs = append(configs, tradefed.Object{
  931. Type: "target_preparer",
  932. Class: "com.android.tradefed.targetprep.PushFilePreparer",
  933. Options: options,
  934. })
  935. }
  936. j.Test.generateAndroidBuildActionsWithConfig(ctx, configs)
  937. }
  938. func (j *Test) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  939. j.generateAndroidBuildActionsWithConfig(ctx, nil)
  940. }
  941. func (j *Test) generateAndroidBuildActionsWithConfig(ctx android.ModuleContext, configs []tradefed.Config) {
  942. if j.testProperties.Test_options.Unit_test == nil && ctx.Host() {
  943. // TODO(b/): Clean temporary heuristic to avoid unexpected onboarding.
  944. defaultUnitTest := !inList("tradefed", j.properties.Libs) && !inList("cts", j.testProperties.Test_suites)
  945. j.testProperties.Test_options.Unit_test = proptools.BoolPtr(defaultUnitTest)
  946. }
  947. j.testConfig = tradefed.AutoGenJavaTestConfig(ctx, j.testProperties.Test_config, j.testProperties.Test_config_template,
  948. j.testProperties.Test_suites, configs, j.testProperties.Auto_gen_config, j.testProperties.Test_options.Unit_test)
  949. j.data = android.PathsForModuleSrc(ctx, j.testProperties.Data)
  950. j.extraTestConfigs = android.PathsForModuleSrc(ctx, j.testProperties.Test_options.Extra_test_configs)
  951. ctx.VisitDirectDepsWithTag(dataNativeBinsTag, func(dep android.Module) {
  952. j.data = append(j.data, android.OutputFileForModule(ctx, dep, ""))
  953. })
  954. ctx.VisitDirectDepsWithTag(dataDeviceBinsTag, func(dep android.Module) {
  955. j.data = append(j.data, android.OutputFileForModule(ctx, dep, ""))
  956. })
  957. ctx.VisitDirectDepsWithTag(jniLibTag, func(dep android.Module) {
  958. sharedLibInfo := ctx.OtherModuleProvider(dep, cc.SharedLibraryInfoProvider).(cc.SharedLibraryInfo)
  959. if sharedLibInfo.SharedLibrary != nil {
  960. // Copy to an intermediate output directory to append "lib[64]" to the path,
  961. // so that it's compatible with the default rpath values.
  962. var relPath string
  963. if sharedLibInfo.Target.Arch.ArchType.Multilib == "lib64" {
  964. relPath = filepath.Join("lib64", sharedLibInfo.SharedLibrary.Base())
  965. } else {
  966. relPath = filepath.Join("lib", sharedLibInfo.SharedLibrary.Base())
  967. }
  968. relocatedLib := android.PathForModuleOut(ctx, "relocated").Join(ctx, relPath)
  969. ctx.Build(pctx, android.BuildParams{
  970. Rule: android.Cp,
  971. Input: sharedLibInfo.SharedLibrary,
  972. Output: relocatedLib,
  973. })
  974. j.data = append(j.data, relocatedLib)
  975. } else {
  976. ctx.PropertyErrorf("jni_libs", "%q of type %q is not supported", dep.Name(), ctx.OtherModuleType(dep))
  977. }
  978. })
  979. j.Library.GenerateAndroidBuildActions(ctx)
  980. }
  981. func (j *TestHelperLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  982. j.Library.GenerateAndroidBuildActions(ctx)
  983. }
  984. func (j *JavaTestImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  985. j.testConfig = tradefed.AutoGenJavaTestConfig(ctx, j.prebuiltTestProperties.Test_config, nil,
  986. j.prebuiltTestProperties.Test_suites, nil, nil, nil)
  987. j.Import.GenerateAndroidBuildActions(ctx)
  988. }
  989. type testSdkMemberType struct {
  990. android.SdkMemberTypeBase
  991. }
  992. func (mt *testSdkMemberType) AddDependencies(ctx android.SdkDependencyContext, dependencyTag blueprint.DependencyTag, names []string) {
  993. ctx.AddVariationDependencies(nil, dependencyTag, names...)
  994. }
  995. func (mt *testSdkMemberType) IsInstance(module android.Module) bool {
  996. _, ok := module.(*Test)
  997. return ok
  998. }
  999. func (mt *testSdkMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
  1000. return ctx.SnapshotBuilder().AddPrebuiltModule(member, "java_test_import")
  1001. }
  1002. func (mt *testSdkMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
  1003. return &testSdkMemberProperties{}
  1004. }
  1005. type testSdkMemberProperties struct {
  1006. android.SdkMemberPropertiesBase
  1007. JarToExport android.Path
  1008. TestConfig android.Path
  1009. }
  1010. func (p *testSdkMemberProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
  1011. test := variant.(*Test)
  1012. implementationJars := test.ImplementationJars()
  1013. if len(implementationJars) != 1 {
  1014. panic(fmt.Errorf("there must be only one implementation jar from %q", test.Name()))
  1015. }
  1016. p.JarToExport = implementationJars[0]
  1017. p.TestConfig = test.testConfig
  1018. }
  1019. func (p *testSdkMemberProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
  1020. builder := ctx.SnapshotBuilder()
  1021. exportedJar := p.JarToExport
  1022. if exportedJar != nil {
  1023. snapshotRelativeJavaLibPath := sdkSnapshotFilePathForJar(ctx, p.OsPrefix(), ctx.Name())
  1024. builder.CopyToSnapshot(exportedJar, snapshotRelativeJavaLibPath)
  1025. propertySet.AddProperty("jars", []string{snapshotRelativeJavaLibPath})
  1026. }
  1027. testConfig := p.TestConfig
  1028. if testConfig != nil {
  1029. snapshotRelativeTestConfigPath := sdkSnapshotFilePathForMember(p.OsPrefix(), ctx.Name(), testConfigSuffix)
  1030. builder.CopyToSnapshot(testConfig, snapshotRelativeTestConfigPath)
  1031. propertySet.AddProperty("test_config", snapshotRelativeTestConfigPath)
  1032. }
  1033. }
  1034. // java_test builds a and links sources into a `.jar` file for the device, and possibly for the host as well, and
  1035. // creates an `AndroidTest.xml` file to allow running the test with `atest` or a `TEST_MAPPING` file.
  1036. //
  1037. // By default, a java_test has a single variant that produces a `.jar` file containing `classes.dex` files that were
  1038. // compiled against the device bootclasspath.
  1039. //
  1040. // Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
  1041. // compiled against the host bootclasspath.
  1042. func TestFactory() android.Module {
  1043. module := &Test{}
  1044. module.addHostAndDeviceProperties()
  1045. module.AddProperties(&module.testProperties)
  1046. module.Module.properties.Installable = proptools.BoolPtr(true)
  1047. module.Module.dexpreopter.isTest = true
  1048. module.Module.linter.properties.Lint.Test = proptools.BoolPtr(true)
  1049. android.InitSdkAwareModule(module)
  1050. InitJavaModule(module, android.HostAndDeviceSupported)
  1051. return module
  1052. }
  1053. // java_test_helper_library creates a java library and makes sure that it is added to the appropriate test suite.
  1054. func TestHelperLibraryFactory() android.Module {
  1055. module := &TestHelperLibrary{}
  1056. module.addHostAndDeviceProperties()
  1057. module.AddProperties(&module.testHelperLibraryProperties)
  1058. module.Module.properties.Installable = proptools.BoolPtr(true)
  1059. module.Module.dexpreopter.isTest = true
  1060. module.Module.linter.properties.Lint.Test = proptools.BoolPtr(true)
  1061. InitJavaModule(module, android.HostAndDeviceSupported)
  1062. return module
  1063. }
  1064. // java_test_import imports one or more `.jar` files into the build graph as if they were built by a java_test module
  1065. // and makes sure that it is added to the appropriate test suite.
  1066. //
  1067. // By default, a java_test_import has a single variant that expects a `.jar` file containing `.class` files that were
  1068. // compiled against an Android classpath.
  1069. //
  1070. // Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
  1071. // for host modules.
  1072. func JavaTestImportFactory() android.Module {
  1073. module := &JavaTestImport{}
  1074. module.AddProperties(
  1075. &module.Import.properties,
  1076. &module.prebuiltTestProperties)
  1077. module.Import.properties.Installable = proptools.BoolPtr(true)
  1078. android.InitPrebuiltModule(module, &module.properties.Jars)
  1079. android.InitApexModule(module)
  1080. android.InitSdkAwareModule(module)
  1081. InitJavaModule(module, android.HostAndDeviceSupported)
  1082. return module
  1083. }
  1084. // java_test_host builds a and links sources into a `.jar` file for the host, and creates an `AndroidTest.xml` file to
  1085. // allow running the test with `atest` or a `TEST_MAPPING` file.
  1086. //
  1087. // A java_test_host has a single variant that produces a `.jar` file containing `.class` files that were
  1088. // compiled against the host bootclasspath.
  1089. func TestHostFactory() android.Module {
  1090. module := &TestHost{}
  1091. module.addHostProperties()
  1092. module.AddProperties(&module.testProperties)
  1093. module.AddProperties(&module.testHostProperties)
  1094. InitTestHost(
  1095. module,
  1096. proptools.BoolPtr(true),
  1097. nil,
  1098. nil)
  1099. InitJavaModuleMultiTargets(module, android.HostSupported)
  1100. return module
  1101. }
  1102. func InitTestHost(th *TestHost, installable *bool, testSuites []string, autoGenConfig *bool) {
  1103. th.properties.Installable = installable
  1104. th.testProperties.Auto_gen_config = autoGenConfig
  1105. th.testProperties.Test_suites = testSuites
  1106. }
  1107. //
  1108. // Java Binaries (.jar file plus wrapper script)
  1109. //
  1110. type binaryProperties struct {
  1111. // installable script to execute the resulting jar
  1112. Wrapper *string `android:"path,arch_variant"`
  1113. // Name of the class containing main to be inserted into the manifest as Main-Class.
  1114. Main_class *string
  1115. // Names of modules containing JNI libraries that should be installed alongside the host
  1116. // variant of the binary.
  1117. Jni_libs []string `android:"arch_variant"`
  1118. }
  1119. type Binary struct {
  1120. Library
  1121. binaryProperties binaryProperties
  1122. isWrapperVariant bool
  1123. wrapperFile android.Path
  1124. binaryFile android.InstallPath
  1125. }
  1126. func (j *Binary) HostToolPath() android.OptionalPath {
  1127. return android.OptionalPathForPath(j.binaryFile)
  1128. }
  1129. func (j *Binary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  1130. if ctx.Arch().ArchType == android.Common {
  1131. // Compile the jar
  1132. if j.binaryProperties.Main_class != nil {
  1133. if j.properties.Manifest != nil {
  1134. ctx.PropertyErrorf("main_class", "main_class cannot be used when manifest is set")
  1135. }
  1136. manifestFile := android.PathForModuleOut(ctx, "manifest.txt")
  1137. GenerateMainClassManifest(ctx, manifestFile, String(j.binaryProperties.Main_class))
  1138. j.overrideManifest = android.OptionalPathForPath(manifestFile)
  1139. }
  1140. j.Library.GenerateAndroidBuildActions(ctx)
  1141. } else {
  1142. // Handle the binary wrapper
  1143. j.isWrapperVariant = true
  1144. if j.binaryProperties.Wrapper != nil {
  1145. j.wrapperFile = android.PathForModuleSrc(ctx, *j.binaryProperties.Wrapper)
  1146. } else {
  1147. if ctx.Windows() {
  1148. ctx.PropertyErrorf("wrapper", "wrapper is required for Windows")
  1149. }
  1150. j.wrapperFile = android.PathForSource(ctx, "build/soong/scripts/jar-wrapper.sh")
  1151. }
  1152. ext := ""
  1153. if ctx.Windows() {
  1154. ext = ".bat"
  1155. }
  1156. // The host installation rules make the installed wrapper depend on all the dependencies
  1157. // of the wrapper variant, which will include the common variant's jar file and any JNI
  1158. // libraries. This is verified by TestBinary.
  1159. j.binaryFile = ctx.InstallExecutable(android.PathForModuleInstall(ctx, "bin"),
  1160. ctx.ModuleName()+ext, j.wrapperFile)
  1161. }
  1162. }
  1163. func (j *Binary) DepsMutator(ctx android.BottomUpMutatorContext) {
  1164. if ctx.Arch().ArchType == android.Common {
  1165. j.deps(ctx)
  1166. }
  1167. if ctx.Arch().ArchType != android.Common {
  1168. // These dependencies ensure the host installation rules will install the jar file and
  1169. // the jni libraries when the wrapper is installed.
  1170. ctx.AddVariationDependencies(nil, jniInstallTag, j.binaryProperties.Jni_libs...)
  1171. ctx.AddVariationDependencies(
  1172. []blueprint.Variation{{Mutator: "arch", Variation: android.CommonArch.String()}},
  1173. binaryInstallTag, ctx.ModuleName())
  1174. }
  1175. }
  1176. // java_binary builds a `.jar` file and a shell script that executes it for the device, and possibly for the host
  1177. // as well.
  1178. //
  1179. // By default, a java_binary has a single variant that produces a `.jar` file containing `classes.dex` files that were
  1180. // compiled against the device bootclasspath.
  1181. //
  1182. // Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
  1183. // compiled against the host bootclasspath.
  1184. func BinaryFactory() android.Module {
  1185. module := &Binary{}
  1186. module.addHostAndDeviceProperties()
  1187. module.AddProperties(&module.binaryProperties)
  1188. module.Module.properties.Installable = proptools.BoolPtr(true)
  1189. android.InitAndroidArchModule(module, android.HostAndDeviceSupported, android.MultilibCommonFirst)
  1190. android.InitDefaultableModule(module)
  1191. android.InitBazelModule(module)
  1192. return module
  1193. }
  1194. // java_binary_host builds a `.jar` file and a shell script that executes it for the host.
  1195. //
  1196. // A java_binary_host has a single variant that produces a `.jar` file containing `.class` files that were
  1197. // compiled against the host bootclasspath.
  1198. func BinaryHostFactory() android.Module {
  1199. module := &Binary{}
  1200. module.addHostProperties()
  1201. module.AddProperties(&module.binaryProperties)
  1202. module.Module.properties.Installable = proptools.BoolPtr(true)
  1203. android.InitAndroidArchModule(module, android.HostSupported, android.MultilibCommonFirst)
  1204. android.InitDefaultableModule(module)
  1205. android.InitBazelModule(module)
  1206. return module
  1207. }
  1208. //
  1209. // Java prebuilts
  1210. //
  1211. type ImportProperties struct {
  1212. Jars []string `android:"path,arch_variant"`
  1213. // The version of the SDK that the source prebuilt file was built against. Defaults to the
  1214. // current version if not specified.
  1215. Sdk_version *string
  1216. // The minimum version of the SDK that this module supports. Defaults to sdk_version if not
  1217. // specified.
  1218. Min_sdk_version *string
  1219. // The max sdk version placeholder used to replace maxSdkVersion attributes on permission
  1220. // and uses-permission tags in manifest_fixer.
  1221. Replace_max_sdk_version_placeholder *string
  1222. Installable *bool
  1223. // If not empty, classes are restricted to the specified packages and their sub-packages.
  1224. Permitted_packages []string
  1225. // List of shared java libs that this module has dependencies to
  1226. Libs []string
  1227. // List of files to remove from the jar file(s)
  1228. Exclude_files []string
  1229. // List of directories to remove from the jar file(s)
  1230. Exclude_dirs []string
  1231. // if set to true, run Jetifier against .jar file. Defaults to false.
  1232. Jetifier *bool
  1233. // set the name of the output
  1234. Stem *string
  1235. Aidl struct {
  1236. // directories that should be added as include directories for any aidl sources of modules
  1237. // that depend on this module, as well as to aidl for this module.
  1238. Export_include_dirs []string
  1239. }
  1240. }
  1241. type Import struct {
  1242. android.ModuleBase
  1243. android.DefaultableModuleBase
  1244. android.ApexModuleBase
  1245. android.BazelModuleBase
  1246. prebuilt android.Prebuilt
  1247. android.SdkBase
  1248. // Functionality common to Module and Import.
  1249. embeddableInModuleAndImport
  1250. hiddenAPI
  1251. dexer
  1252. dexpreopter
  1253. properties ImportProperties
  1254. // output file containing classes.dex and resources
  1255. dexJarFile OptionalDexJarPath
  1256. dexJarInstallFile android.Path
  1257. combinedClasspathFile android.Path
  1258. classLoaderContexts dexpreopt.ClassLoaderContextMap
  1259. exportAidlIncludeDirs android.Paths
  1260. hideApexVariantFromMake bool
  1261. sdkVersion android.SdkSpec
  1262. minSdkVersion android.SdkSpec
  1263. }
  1264. var _ PermittedPackagesForUpdatableBootJars = (*Import)(nil)
  1265. func (j *Import) PermittedPackagesForUpdatableBootJars() []string {
  1266. return j.properties.Permitted_packages
  1267. }
  1268. func (j *Import) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
  1269. return android.SdkSpecFrom(ctx, String(j.properties.Sdk_version))
  1270. }
  1271. func (j *Import) SystemModules() string {
  1272. return "none"
  1273. }
  1274. func (j *Import) MinSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
  1275. if j.properties.Min_sdk_version != nil {
  1276. return android.SdkSpecFrom(ctx, *j.properties.Min_sdk_version)
  1277. }
  1278. return j.SdkVersion(ctx)
  1279. }
  1280. func (j *Import) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.SdkSpec {
  1281. if j.properties.Replace_max_sdk_version_placeholder != nil {
  1282. return android.SdkSpecFrom(ctx, *j.properties.Replace_max_sdk_version_placeholder)
  1283. }
  1284. return android.SdkSpecFrom(ctx, "")
  1285. }
  1286. func (j *Import) TargetSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
  1287. return j.SdkVersion(ctx)
  1288. }
  1289. func (j *Import) Prebuilt() *android.Prebuilt {
  1290. return &j.prebuilt
  1291. }
  1292. func (j *Import) PrebuiltSrcs() []string {
  1293. return j.properties.Jars
  1294. }
  1295. func (j *Import) Name() string {
  1296. return j.prebuilt.Name(j.ModuleBase.Name())
  1297. }
  1298. func (j *Import) Stem() string {
  1299. return proptools.StringDefault(j.properties.Stem, j.ModuleBase.Name())
  1300. }
  1301. func (a *Import) JacocoReportClassesFile() android.Path {
  1302. return nil
  1303. }
  1304. func (j *Import) LintDepSets() LintDepSets {
  1305. return LintDepSets{}
  1306. }
  1307. func (j *Import) getStrictUpdatabilityLinting() bool {
  1308. return false
  1309. }
  1310. func (j *Import) setStrictUpdatabilityLinting(bool) {
  1311. }
  1312. func (j *Import) DepsMutator(ctx android.BottomUpMutatorContext) {
  1313. ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
  1314. if ctx.Device() && Bool(j.dexProperties.Compile_dex) {
  1315. sdkDeps(ctx, android.SdkContext(j), j.dexer)
  1316. }
  1317. }
  1318. func (j *Import) commonBuildActions(ctx android.ModuleContext) {
  1319. //TODO(b/231322772) these should come from Bazel once available
  1320. j.sdkVersion = j.SdkVersion(ctx)
  1321. j.minSdkVersion = j.MinSdkVersion(ctx)
  1322. if !ctx.Provider(android.ApexInfoProvider).(android.ApexInfo).IsForPlatform() {
  1323. j.hideApexVariantFromMake = true
  1324. }
  1325. if ctx.Windows() {
  1326. j.HideFromMake()
  1327. }
  1328. }
  1329. func (j *Import) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  1330. j.commonBuildActions(ctx)
  1331. jars := android.PathsForModuleSrc(ctx, j.properties.Jars)
  1332. jarName := j.Stem() + ".jar"
  1333. outputFile := android.PathForModuleOut(ctx, "combined", jarName)
  1334. TransformJarsToJar(ctx, outputFile, "for prebuilts", jars, android.OptionalPath{},
  1335. false, j.properties.Exclude_files, j.properties.Exclude_dirs)
  1336. if Bool(j.properties.Jetifier) {
  1337. inputFile := outputFile
  1338. outputFile = android.PathForModuleOut(ctx, "jetifier", jarName)
  1339. TransformJetifier(ctx, outputFile, inputFile)
  1340. }
  1341. j.combinedClasspathFile = outputFile
  1342. j.classLoaderContexts = make(dexpreopt.ClassLoaderContextMap)
  1343. var flags javaBuilderFlags
  1344. ctx.VisitDirectDeps(func(module android.Module) {
  1345. tag := ctx.OtherModuleDependencyTag(module)
  1346. if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
  1347. dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
  1348. switch tag {
  1349. case libTag:
  1350. flags.classpath = append(flags.classpath, dep.HeaderJars...)
  1351. flags.dexClasspath = append(flags.dexClasspath, dep.HeaderJars...)
  1352. case staticLibTag:
  1353. flags.classpath = append(flags.classpath, dep.HeaderJars...)
  1354. case bootClasspathTag:
  1355. flags.bootClasspath = append(flags.bootClasspath, dep.HeaderJars...)
  1356. }
  1357. } else if dep, ok := module.(SdkLibraryDependency); ok {
  1358. switch tag {
  1359. case libTag:
  1360. flags.classpath = append(flags.classpath, dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))...)
  1361. }
  1362. }
  1363. addCLCFromDep(ctx, module, j.classLoaderContexts)
  1364. })
  1365. j.maybeInstall(ctx, jarName, outputFile)
  1366. j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.properties.Aidl.Export_include_dirs)
  1367. if ctx.Device() {
  1368. // If this is a variant created for a prebuilt_apex then use the dex implementation jar
  1369. // obtained from the associated deapexer module.
  1370. ai := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
  1371. if ai.ForPrebuiltApex {
  1372. // Get the path of the dex implementation jar from the `deapexer` module.
  1373. di := android.FindDeapexerProviderForModule(ctx)
  1374. if di == nil {
  1375. return // An error has been reported by FindDeapexerProviderForModule.
  1376. }
  1377. if dexOutputPath := di.PrebuiltExportPath(apexRootRelativePathToJavaLib(j.BaseModuleName())); dexOutputPath != nil {
  1378. dexJarFile := makeDexJarPathFromPath(dexOutputPath)
  1379. j.dexJarFile = dexJarFile
  1380. installPath := android.PathForModuleInPartitionInstall(ctx, "apex", ai.ApexVariationName, apexRootRelativePathToJavaLib(j.BaseModuleName()))
  1381. j.dexJarInstallFile = installPath
  1382. j.dexpreopter.installPath = j.dexpreopter.getInstallPath(ctx, installPath)
  1383. setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
  1384. j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
  1385. j.dexpreopt(ctx, dexOutputPath)
  1386. // Initialize the hiddenapi structure.
  1387. j.initHiddenAPI(ctx, dexJarFile, outputFile, j.dexProperties.Uncompress_dex)
  1388. } else {
  1389. // This should never happen as a variant for a prebuilt_apex is only created if the
  1390. // prebuilt_apex has been configured to export the java library dex file.
  1391. ctx.ModuleErrorf("internal error: no dex implementation jar available from prebuilt APEX %s", di.ApexModuleName())
  1392. }
  1393. } else if Bool(j.dexProperties.Compile_dex) {
  1394. sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
  1395. if sdkDep.invalidVersion {
  1396. ctx.AddMissingDependencies(sdkDep.bootclasspath)
  1397. ctx.AddMissingDependencies(sdkDep.java9Classpath)
  1398. } else if sdkDep.useFiles {
  1399. // sdkDep.jar is actually equivalent to turbine header.jar.
  1400. flags.classpath = append(flags.classpath, sdkDep.jars...)
  1401. }
  1402. // Dex compilation
  1403. j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
  1404. ctx, android.PathForModuleInstall(ctx, "framework", jarName))
  1405. setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
  1406. j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
  1407. var dexOutputFile android.OutputPath
  1408. dexOutputFile = j.dexer.compileDex(ctx, flags, j.MinSdkVersion(ctx), outputFile, jarName)
  1409. if ctx.Failed() {
  1410. return
  1411. }
  1412. // Initialize the hiddenapi structure.
  1413. j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), outputFile, j.dexProperties.Uncompress_dex)
  1414. // Encode hidden API flags in dex file.
  1415. dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
  1416. j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
  1417. j.dexJarInstallFile = android.PathForModuleInstall(ctx, "framework", jarName)
  1418. }
  1419. }
  1420. ctx.SetProvider(JavaInfoProvider, JavaInfo{
  1421. HeaderJars: android.PathsIfNonNil(j.combinedClasspathFile),
  1422. ImplementationAndResourcesJars: android.PathsIfNonNil(j.combinedClasspathFile),
  1423. ImplementationJars: android.PathsIfNonNil(j.combinedClasspathFile),
  1424. AidlIncludeDirs: j.exportAidlIncludeDirs,
  1425. })
  1426. }
  1427. func (j *Import) maybeInstall(ctx android.ModuleContext, jarName string, outputFile android.Path) {
  1428. if !Bool(j.properties.Installable) {
  1429. return
  1430. }
  1431. var installDir android.InstallPath
  1432. if ctx.InstallInTestcases() {
  1433. var archDir string
  1434. if !ctx.Host() {
  1435. archDir = ctx.DeviceConfig().DeviceArch()
  1436. }
  1437. installDir = android.PathForModuleInstall(ctx, ctx.ModuleName(), archDir)
  1438. } else {
  1439. installDir = android.PathForModuleInstall(ctx, "framework")
  1440. }
  1441. ctx.InstallFile(installDir, jarName, outputFile)
  1442. }
  1443. func (j *Import) OutputFiles(tag string) (android.Paths, error) {
  1444. switch tag {
  1445. case "", ".jar":
  1446. return android.Paths{j.combinedClasspathFile}, nil
  1447. default:
  1448. return nil, fmt.Errorf("unsupported module reference tag %q", tag)
  1449. }
  1450. }
  1451. var _ android.OutputFileProducer = (*Import)(nil)
  1452. func (j *Import) HeaderJars() android.Paths {
  1453. if j.combinedClasspathFile == nil {
  1454. return nil
  1455. }
  1456. return android.Paths{j.combinedClasspathFile}
  1457. }
  1458. func (j *Import) ImplementationAndResourcesJars() android.Paths {
  1459. if j.combinedClasspathFile == nil {
  1460. return nil
  1461. }
  1462. return android.Paths{j.combinedClasspathFile}
  1463. }
  1464. func (j *Import) DexJarBuildPath() OptionalDexJarPath {
  1465. return j.dexJarFile
  1466. }
  1467. func (j *Import) DexJarInstallPath() android.Path {
  1468. return j.dexJarInstallFile
  1469. }
  1470. func (j *Import) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
  1471. return j.classLoaderContexts
  1472. }
  1473. var _ android.ApexModule = (*Import)(nil)
  1474. // Implements android.ApexModule
  1475. func (j *Import) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
  1476. return j.depIsInSameApex(ctx, dep)
  1477. }
  1478. // Implements android.ApexModule
  1479. func (j *Import) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
  1480. sdkVersion android.ApiLevel) error {
  1481. sdkSpec := j.MinSdkVersion(ctx)
  1482. if !sdkSpec.Specified() {
  1483. return fmt.Errorf("min_sdk_version is not specified")
  1484. }
  1485. if sdkSpec.Kind == android.SdkCore {
  1486. return nil
  1487. }
  1488. if sdkSpec.ApiLevel.GreaterThan(sdkVersion) {
  1489. return fmt.Errorf("newer SDK(%v)", sdkSpec.ApiLevel)
  1490. }
  1491. return nil
  1492. }
  1493. // requiredFilesFromPrebuiltApexForImport returns information about the files that a java_import or
  1494. // java_sdk_library_import with the specified base module name requires to be exported from a
  1495. // prebuilt_apex/apex_set.
  1496. func requiredFilesFromPrebuiltApexForImport(name string) []string {
  1497. // Add the dex implementation jar to the set of exported files.
  1498. return []string{
  1499. apexRootRelativePathToJavaLib(name),
  1500. }
  1501. }
  1502. // apexRootRelativePathToJavaLib returns the path, relative to the root of the apex's contents, for
  1503. // the java library with the specified name.
  1504. func apexRootRelativePathToJavaLib(name string) string {
  1505. return filepath.Join("javalib", name+".jar")
  1506. }
  1507. var _ android.RequiredFilesFromPrebuiltApex = (*Import)(nil)
  1508. func (j *Import) RequiredFilesFromPrebuiltApex(_ android.BaseModuleContext) []string {
  1509. name := j.BaseModuleName()
  1510. return requiredFilesFromPrebuiltApexForImport(name)
  1511. }
  1512. // Add compile time check for interface implementation
  1513. var _ android.IDEInfo = (*Import)(nil)
  1514. var _ android.IDECustomizedModuleName = (*Import)(nil)
  1515. // Collect information for opening IDE project files in java/jdeps.go.
  1516. func (j *Import) IDEInfo(dpInfo *android.IdeInfo) {
  1517. dpInfo.Jars = append(dpInfo.Jars, j.PrebuiltSrcs()...)
  1518. }
  1519. func (j *Import) IDECustomizedModuleName() string {
  1520. // TODO(b/113562217): Extract the base module name from the Import name, often the Import name
  1521. // has a prefix "prebuilt_". Remove the prefix explicitly if needed until we find a better
  1522. // solution to get the Import name.
  1523. return android.RemoveOptionalPrebuiltPrefix(j.Name())
  1524. }
  1525. var _ android.PrebuiltInterface = (*Import)(nil)
  1526. func (j *Import) IsInstallable() bool {
  1527. return Bool(j.properties.Installable)
  1528. }
  1529. var _ DexpreopterInterface = (*Import)(nil)
  1530. // java_import imports one or more `.jar` files into the build graph as if they were built by a java_library module.
  1531. //
  1532. // By default, a java_import has a single variant that expects a `.jar` file containing `.class` files that were
  1533. // compiled against an Android classpath.
  1534. //
  1535. // Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
  1536. // for host modules.
  1537. func ImportFactory() android.Module {
  1538. module := &Import{}
  1539. module.AddProperties(
  1540. &module.properties,
  1541. &module.dexer.dexProperties,
  1542. )
  1543. module.initModuleAndImport(module)
  1544. module.dexProperties.Optimize.EnabledByDefault = false
  1545. android.InitPrebuiltModule(module, &module.properties.Jars)
  1546. android.InitApexModule(module)
  1547. android.InitSdkAwareModule(module)
  1548. android.InitBazelModule(module)
  1549. InitJavaModule(module, android.HostAndDeviceSupported)
  1550. return module
  1551. }
  1552. // java_import imports one or more `.jar` files into the build graph as if they were built by a java_library_host
  1553. // module.
  1554. //
  1555. // A java_import_host has a single variant that expects a `.jar` file containing `.class` files that were
  1556. // compiled against a host bootclasspath.
  1557. func ImportFactoryHost() android.Module {
  1558. module := &Import{}
  1559. module.AddProperties(&module.properties)
  1560. android.InitPrebuiltModule(module, &module.properties.Jars)
  1561. android.InitApexModule(module)
  1562. android.InitBazelModule(module)
  1563. InitJavaModule(module, android.HostSupported)
  1564. return module
  1565. }
  1566. // dex_import module
  1567. type DexImportProperties struct {
  1568. Jars []string `android:"path"`
  1569. // set the name of the output
  1570. Stem *string
  1571. }
  1572. type DexImport struct {
  1573. android.ModuleBase
  1574. android.DefaultableModuleBase
  1575. android.ApexModuleBase
  1576. prebuilt android.Prebuilt
  1577. properties DexImportProperties
  1578. dexJarFile OptionalDexJarPath
  1579. dexpreopter
  1580. hideApexVariantFromMake bool
  1581. }
  1582. func (j *DexImport) Prebuilt() *android.Prebuilt {
  1583. return &j.prebuilt
  1584. }
  1585. func (j *DexImport) PrebuiltSrcs() []string {
  1586. return j.properties.Jars
  1587. }
  1588. func (j *DexImport) Name() string {
  1589. return j.prebuilt.Name(j.ModuleBase.Name())
  1590. }
  1591. func (j *DexImport) Stem() string {
  1592. return proptools.StringDefault(j.properties.Stem, j.ModuleBase.Name())
  1593. }
  1594. func (a *DexImport) JacocoReportClassesFile() android.Path {
  1595. return nil
  1596. }
  1597. func (a *DexImport) LintDepSets() LintDepSets {
  1598. return LintDepSets{}
  1599. }
  1600. func (j *DexImport) IsInstallable() bool {
  1601. return true
  1602. }
  1603. func (j *DexImport) getStrictUpdatabilityLinting() bool {
  1604. return false
  1605. }
  1606. func (j *DexImport) setStrictUpdatabilityLinting(bool) {
  1607. }
  1608. func (j *DexImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  1609. if len(j.properties.Jars) != 1 {
  1610. ctx.PropertyErrorf("jars", "exactly one jar must be provided")
  1611. }
  1612. apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
  1613. if !apexInfo.IsForPlatform() {
  1614. j.hideApexVariantFromMake = true
  1615. }
  1616. j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
  1617. ctx, android.PathForModuleInstall(ctx, "framework", j.Stem()+".jar"))
  1618. j.dexpreopter.uncompressedDex = shouldUncompressDex(ctx, &j.dexpreopter)
  1619. inputJar := ctx.ExpandSource(j.properties.Jars[0], "jars")
  1620. dexOutputFile := android.PathForModuleOut(ctx, ctx.ModuleName()+".jar")
  1621. if j.dexpreopter.uncompressedDex {
  1622. rule := android.NewRuleBuilder(pctx, ctx)
  1623. temporary := android.PathForModuleOut(ctx, ctx.ModuleName()+".jar.unaligned")
  1624. rule.Temporary(temporary)
  1625. // use zip2zip to uncompress classes*.dex files
  1626. rule.Command().
  1627. BuiltTool("zip2zip").
  1628. FlagWithInput("-i ", inputJar).
  1629. FlagWithOutput("-o ", temporary).
  1630. FlagWithArg("-0 ", "'classes*.dex'")
  1631. // use zipalign to align uncompressed classes*.dex files
  1632. rule.Command().
  1633. BuiltTool("zipalign").
  1634. Flag("-f").
  1635. Text("4").
  1636. Input(temporary).
  1637. Output(dexOutputFile)
  1638. rule.DeleteTemporaryFiles()
  1639. rule.Build("uncompress_dex", "uncompress dex")
  1640. } else {
  1641. ctx.Build(pctx, android.BuildParams{
  1642. Rule: android.Cp,
  1643. Input: inputJar,
  1644. Output: dexOutputFile,
  1645. })
  1646. }
  1647. j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
  1648. j.dexpreopt(ctx, dexOutputFile)
  1649. if apexInfo.IsForPlatform() {
  1650. ctx.InstallFile(android.PathForModuleInstall(ctx, "framework"),
  1651. j.Stem()+".jar", dexOutputFile)
  1652. }
  1653. }
  1654. func (j *DexImport) DexJarBuildPath() OptionalDexJarPath {
  1655. return j.dexJarFile
  1656. }
  1657. var _ android.ApexModule = (*DexImport)(nil)
  1658. // Implements android.ApexModule
  1659. func (j *DexImport) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
  1660. sdkVersion android.ApiLevel) error {
  1661. // we don't check prebuilt modules for sdk_version
  1662. return nil
  1663. }
  1664. // dex_import imports a `.jar` file containing classes.dex files.
  1665. //
  1666. // A dex_import module cannot be used as a dependency of a java_* or android_* module, it can only be installed
  1667. // to the device.
  1668. func DexImportFactory() android.Module {
  1669. module := &DexImport{}
  1670. module.AddProperties(&module.properties)
  1671. android.InitPrebuiltModule(module, &module.properties.Jars)
  1672. android.InitApexModule(module)
  1673. InitJavaModule(module, android.DeviceSupported)
  1674. return module
  1675. }
  1676. // Defaults
  1677. type Defaults struct {
  1678. android.ModuleBase
  1679. android.DefaultsModuleBase
  1680. android.ApexModuleBase
  1681. }
  1682. // java_defaults provides a set of properties that can be inherited by other java or android modules.
  1683. //
  1684. // A module can use the properties from a java_defaults module using `defaults: ["defaults_module_name"]`. Each
  1685. // property in the defaults module that exists in the depending module will be prepended to the depending module's
  1686. // value for that property.
  1687. //
  1688. // Example:
  1689. //
  1690. // java_defaults {
  1691. // name: "example_defaults",
  1692. // srcs: ["common/**/*.java"],
  1693. // javacflags: ["-Xlint:all"],
  1694. // aaptflags: ["--auto-add-overlay"],
  1695. // }
  1696. //
  1697. // java_library {
  1698. // name: "example",
  1699. // defaults: ["example_defaults"],
  1700. // srcs: ["example/**/*.java"],
  1701. // }
  1702. //
  1703. // is functionally identical to:
  1704. //
  1705. // java_library {
  1706. // name: "example",
  1707. // srcs: [
  1708. // "common/**/*.java",
  1709. // "example/**/*.java",
  1710. // ],
  1711. // javacflags: ["-Xlint:all"],
  1712. // }
  1713. func DefaultsFactory() android.Module {
  1714. module := &Defaults{}
  1715. module.AddProperties(
  1716. &CommonProperties{},
  1717. &DeviceProperties{},
  1718. &OverridableDeviceProperties{},
  1719. &DexProperties{},
  1720. &DexpreoptProperties{},
  1721. &android.ProtoProperties{},
  1722. &aaptProperties{},
  1723. &androidLibraryProperties{},
  1724. &appProperties{},
  1725. &appTestProperties{},
  1726. &overridableAppProperties{},
  1727. &testProperties{},
  1728. &ImportProperties{},
  1729. &AARImportProperties{},
  1730. &sdkLibraryProperties{},
  1731. &commonToSdkLibraryAndImportProperties{},
  1732. &DexImportProperties{},
  1733. &android.ApexProperties{},
  1734. &RuntimeResourceOverlayProperties{},
  1735. &LintProperties{},
  1736. &appTestHelperAppProperties{},
  1737. )
  1738. android.InitDefaultsModule(module)
  1739. return module
  1740. }
  1741. func kytheExtractJavaFactory() android.Singleton {
  1742. return &kytheExtractJavaSingleton{}
  1743. }
  1744. type kytheExtractJavaSingleton struct {
  1745. }
  1746. func (ks *kytheExtractJavaSingleton) GenerateBuildActions(ctx android.SingletonContext) {
  1747. var xrefTargets android.Paths
  1748. ctx.VisitAllModules(func(module android.Module) {
  1749. if javaModule, ok := module.(xref); ok {
  1750. xrefTargets = append(xrefTargets, javaModule.XrefJavaFiles()...)
  1751. }
  1752. })
  1753. // TODO(asmundak): perhaps emit a rule to output a warning if there were no xrefTargets
  1754. if len(xrefTargets) > 0 {
  1755. ctx.Phony("xref_java", xrefTargets...)
  1756. }
  1757. }
  1758. var Bool = proptools.Bool
  1759. var BoolDefault = proptools.BoolDefault
  1760. var String = proptools.String
  1761. var inList = android.InList
  1762. // Add class loader context (CLC) of a given dependency to the current CLC.
  1763. func addCLCFromDep(ctx android.ModuleContext, depModule android.Module,
  1764. clcMap dexpreopt.ClassLoaderContextMap) {
  1765. dep, ok := depModule.(UsesLibraryDependency)
  1766. if !ok {
  1767. return
  1768. }
  1769. depName := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(depModule))
  1770. var sdkLib *string
  1771. if lib, ok := depModule.(SdkLibraryDependency); ok && lib.sharedLibrary() {
  1772. // A shared SDK library. This should be added as a top-level CLC element.
  1773. sdkLib = &depName
  1774. } else if ulib, ok := depModule.(ProvidesUsesLib); ok {
  1775. // A non-SDK library disguised as an SDK library by the means of `provides_uses_lib`
  1776. // property. This should be handled in the same way as a shared SDK library.
  1777. sdkLib = ulib.ProvidesUsesLib()
  1778. }
  1779. depTag := ctx.OtherModuleDependencyTag(depModule)
  1780. if depTag == libTag {
  1781. // Ok, propagate <uses-library> through non-static library dependencies.
  1782. } else if tag, ok := depTag.(usesLibraryDependencyTag); ok && tag.sdkVersion == dexpreopt.AnySdkVersion {
  1783. // Ok, propagate <uses-library> through non-compatibility <uses-library> dependencies.
  1784. } else if depTag == staticLibTag {
  1785. // Propagate <uses-library> through static library dependencies, unless it is a component
  1786. // library (such as stubs). Component libraries have a dependency on their SDK library,
  1787. // which should not be pulled just because of a static component library.
  1788. if sdkLib != nil {
  1789. return
  1790. }
  1791. } else {
  1792. // Don't propagate <uses-library> for other dependency tags.
  1793. return
  1794. }
  1795. // If this is an SDK (or SDK-like) library, then it should be added as a node in the CLC tree,
  1796. // and its CLC should be added as subtree of that node. Otherwise the library is not a
  1797. // <uses_library> and should not be added to CLC, but the transitive <uses-library> dependencies
  1798. // from its CLC should be added to the current CLC.
  1799. if sdkLib != nil {
  1800. clcMap.AddContext(ctx, dexpreopt.AnySdkVersion, *sdkLib, false,
  1801. dep.DexJarBuildPath().PathOrNil(), dep.DexJarInstallPath(), dep.ClassLoaderContexts())
  1802. } else {
  1803. clcMap.AddContextMap(dep.ClassLoaderContexts(), depName)
  1804. }
  1805. }
  1806. type javaResourcesAttributes struct {
  1807. Resources bazel.LabelListAttribute
  1808. Resource_strip_prefix *string
  1809. }
  1810. func (m *Library) convertJavaResourcesAttributes(ctx android.TopDownMutatorContext) *javaResourcesAttributes {
  1811. var resources bazel.LabelList
  1812. var resourceStripPrefix *string
  1813. if m.properties.Java_resources != nil {
  1814. resources.Append(android.BazelLabelForModuleSrc(ctx, m.properties.Java_resources))
  1815. }
  1816. //TODO(b/179889880) handle case where glob includes files outside package
  1817. resDeps := ResourceDirsToFiles(
  1818. ctx,
  1819. m.properties.Java_resource_dirs,
  1820. m.properties.Exclude_java_resource_dirs,
  1821. m.properties.Exclude_java_resources,
  1822. )
  1823. for i, resDep := range resDeps {
  1824. dir, files := resDep.dir, resDep.files
  1825. resources.Append(bazel.MakeLabelList(android.RootToModuleRelativePaths(ctx, files)))
  1826. // Bazel includes the relative path from the WORKSPACE root when placing the resource
  1827. // inside the JAR file, so we need to remove that prefix
  1828. resourceStripPrefix = proptools.StringPtr(dir.String())
  1829. if i > 0 {
  1830. // TODO(b/226423379) allow multiple resource prefixes
  1831. ctx.ModuleErrorf("bp2build does not support more than one directory in java_resource_dirs (b/226423379)")
  1832. }
  1833. }
  1834. return &javaResourcesAttributes{
  1835. Resources: bazel.MakeLabelListAttribute(resources),
  1836. Resource_strip_prefix: resourceStripPrefix,
  1837. }
  1838. }
  1839. type javaCommonAttributes struct {
  1840. *javaResourcesAttributes
  1841. Srcs bazel.LabelListAttribute
  1842. Plugins bazel.LabelListAttribute
  1843. Javacopts bazel.StringListAttribute
  1844. }
  1845. type javaDependencyLabels struct {
  1846. // Dependencies which DO NOT contribute to the API visible to upstream dependencies.
  1847. Deps bazel.LabelListAttribute
  1848. // Dependencies which DO contribute to the API visible to upstream dependencies.
  1849. StaticDeps bazel.LabelListAttribute
  1850. }
  1851. // convertLibraryAttrsBp2Build converts a few shared attributes from java_* modules
  1852. // and also separates dependencies into dynamic dependencies and static dependencies.
  1853. // Each corresponding Bazel target type, can have a different method for handling
  1854. // dynamic vs. static dependencies, and so these are returned to the calling function.
  1855. type eventLogTagsAttributes struct {
  1856. Srcs bazel.LabelListAttribute
  1857. }
  1858. func (m *Library) convertLibraryAttrsBp2Build(ctx android.TopDownMutatorContext) (*javaCommonAttributes, *javaDependencyLabels) {
  1859. var srcs bazel.LabelListAttribute
  1860. archVariantProps := m.GetArchVariantProperties(ctx, &CommonProperties{})
  1861. for axis, configToProps := range archVariantProps {
  1862. for config, _props := range configToProps {
  1863. if archProps, ok := _props.(*CommonProperties); ok {
  1864. archSrcs := android.BazelLabelForModuleSrcExcludes(ctx, archProps.Srcs, archProps.Exclude_srcs)
  1865. srcs.SetSelectValue(axis, config, archSrcs)
  1866. }
  1867. }
  1868. }
  1869. javaSrcPartition := "java"
  1870. protoSrcPartition := "proto"
  1871. logtagSrcPartition := "logtag"
  1872. srcPartitions := bazel.PartitionLabelListAttribute(ctx, &srcs, bazel.LabelPartitions{
  1873. javaSrcPartition: bazel.LabelPartition{Extensions: []string{".java"}, Keep_remainder: true},
  1874. logtagSrcPartition: bazel.LabelPartition{Extensions: []string{".logtags", ".logtag"}},
  1875. protoSrcPartition: android.ProtoSrcLabelPartition,
  1876. })
  1877. javaSrcs := srcPartitions[javaSrcPartition]
  1878. var logtagsSrcs bazel.LabelList
  1879. if !srcPartitions[logtagSrcPartition].IsEmpty() {
  1880. logtagsLibName := m.Name() + "_logtags"
  1881. logtagsSrcs = bazel.MakeLabelList([]bazel.Label{{Label: ":" + logtagsLibName}})
  1882. ctx.CreateBazelTargetModule(
  1883. bazel.BazelTargetModuleProperties{
  1884. Rule_class: "event_log_tags",
  1885. Bzl_load_location: "//build/make/tools:event_log_tags.bzl",
  1886. },
  1887. android.CommonAttributes{Name: logtagsLibName},
  1888. &eventLogTagsAttributes{
  1889. Srcs: srcPartitions[logtagSrcPartition],
  1890. },
  1891. )
  1892. }
  1893. javaSrcs.Append(bazel.MakeLabelListAttribute(logtagsSrcs))
  1894. var javacopts []string
  1895. if m.properties.Javacflags != nil {
  1896. javacopts = append(javacopts, m.properties.Javacflags...)
  1897. }
  1898. if m.properties.Java_version != nil {
  1899. javaVersion := normalizeJavaVersion(ctx, *m.properties.Java_version).String()
  1900. javacopts = append(javacopts, fmt.Sprintf("-source %s -target %s", javaVersion, javaVersion))
  1901. }
  1902. epEnabled := m.properties.Errorprone.Enabled
  1903. //TODO(b/227504307) add configuration that depends on RUN_ERROR_PRONE environment variable
  1904. if Bool(epEnabled) {
  1905. javacopts = append(javacopts, m.properties.Errorprone.Javacflags...)
  1906. }
  1907. commonAttrs := &javaCommonAttributes{
  1908. Srcs: javaSrcs,
  1909. javaResourcesAttributes: m.convertJavaResourcesAttributes(ctx),
  1910. Plugins: bazel.MakeLabelListAttribute(
  1911. android.BazelLabelForModuleDeps(ctx, m.properties.Plugins),
  1912. ),
  1913. Javacopts: bazel.MakeStringListAttribute(javacopts),
  1914. }
  1915. depLabels := &javaDependencyLabels{}
  1916. var deps bazel.LabelList
  1917. if m.properties.Libs != nil {
  1918. deps.Append(android.BazelLabelForModuleDeps(ctx, android.LastUniqueStrings(android.CopyOf(m.properties.Libs))))
  1919. }
  1920. var staticDeps bazel.LabelList
  1921. if m.properties.Static_libs != nil {
  1922. staticDeps.Append(android.BazelLabelForModuleDeps(ctx, android.LastUniqueStrings(android.CopyOf(m.properties.Static_libs))))
  1923. }
  1924. protoDepLabel := bp2buildProto(ctx, &m.Module, srcPartitions[protoSrcPartition])
  1925. // Soong does not differentiate between a java_library and the Bazel equivalent of
  1926. // a java_proto_library + proto_library pair. Instead, in Soong proto sources are
  1927. // listed directly in the srcs of a java_library, and the classes produced
  1928. // by protoc are included directly in the resulting JAR. Thus upstream dependencies
  1929. // that depend on a java_library with proto sources can link directly to the protobuf API,
  1930. // and so this should be a static dependency.
  1931. staticDeps.Add(protoDepLabel)
  1932. depLabels.Deps = bazel.MakeLabelListAttribute(deps)
  1933. depLabels.StaticDeps = bazel.MakeLabelListAttribute(staticDeps)
  1934. return commonAttrs, depLabels
  1935. }
  1936. type javaLibraryAttributes struct {
  1937. *javaCommonAttributes
  1938. Deps bazel.LabelListAttribute
  1939. Exports bazel.LabelListAttribute
  1940. }
  1941. func javaLibraryBp2Build(ctx android.TopDownMutatorContext, m *Library) {
  1942. commonAttrs, depLabels := m.convertLibraryAttrsBp2Build(ctx)
  1943. deps := depLabels.Deps
  1944. if !commonAttrs.Srcs.IsEmpty() {
  1945. deps.Append(depLabels.StaticDeps) // we should only append these if there are sources to use them
  1946. sdkVersion := m.SdkVersion(ctx)
  1947. if sdkVersion.Kind == android.SdkPublic && sdkVersion.ApiLevel == android.FutureApiLevel {
  1948. // TODO(b/220869005) remove forced dependency on current public android.jar
  1949. deps.Add(bazel.MakeLabelAttribute("//prebuilts/sdk:public_current_android_sdk_java_import"))
  1950. }
  1951. } else if !depLabels.Deps.IsEmpty() {
  1952. ctx.ModuleErrorf("Module has direct dependencies but no sources. Bazel will not allow this.")
  1953. }
  1954. attrs := &javaLibraryAttributes{
  1955. javaCommonAttributes: commonAttrs,
  1956. Deps: deps,
  1957. Exports: depLabels.StaticDeps,
  1958. }
  1959. props := bazel.BazelTargetModuleProperties{
  1960. Rule_class: "java_library",
  1961. Bzl_load_location: "//build/bazel/rules/java:library.bzl",
  1962. }
  1963. ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, attrs)
  1964. }
  1965. type javaBinaryHostAttributes struct {
  1966. *javaCommonAttributes
  1967. Deps bazel.LabelListAttribute
  1968. Runtime_deps bazel.LabelListAttribute
  1969. Main_class string
  1970. Jvm_flags bazel.StringListAttribute
  1971. }
  1972. // JavaBinaryHostBp2Build is for java_binary_host bp2build.
  1973. func javaBinaryHostBp2Build(ctx android.TopDownMutatorContext, m *Binary) {
  1974. commonAttrs, depLabels := m.convertLibraryAttrsBp2Build(ctx)
  1975. deps := depLabels.Deps
  1976. deps.Append(depLabels.StaticDeps)
  1977. if m.binaryProperties.Jni_libs != nil {
  1978. deps.Append(bazel.MakeLabelListAttribute(android.BazelLabelForModuleDeps(ctx, m.binaryProperties.Jni_libs)))
  1979. }
  1980. var runtimeDeps bazel.LabelListAttribute
  1981. if commonAttrs.Srcs.IsEmpty() {
  1982. // if there are no sources, then the dependencies can only be used at runtime
  1983. runtimeDeps = deps
  1984. deps = bazel.LabelListAttribute{}
  1985. }
  1986. mainClass := ""
  1987. if m.binaryProperties.Main_class != nil {
  1988. mainClass = *m.binaryProperties.Main_class
  1989. }
  1990. if m.properties.Manifest != nil {
  1991. mainClassInManifest, err := android.GetMainClassInManifest(ctx.Config(), android.PathForModuleSrc(ctx, *m.properties.Manifest).String())
  1992. if err != nil {
  1993. return
  1994. }
  1995. mainClass = mainClassInManifest
  1996. }
  1997. attrs := &javaBinaryHostAttributes{
  1998. javaCommonAttributes: commonAttrs,
  1999. Deps: deps,
  2000. Runtime_deps: runtimeDeps,
  2001. Main_class: mainClass,
  2002. }
  2003. // Attribute jvm_flags
  2004. if m.binaryProperties.Jni_libs != nil {
  2005. jniLibPackages := map[string]bool{}
  2006. for _, jniLibLabel := range android.BazelLabelForModuleDeps(ctx, m.binaryProperties.Jni_libs).Includes {
  2007. jniLibPackage := jniLibLabel.Label
  2008. indexOfColon := strings.Index(jniLibLabel.Label, ":")
  2009. if indexOfColon > 0 {
  2010. // JNI lib from other package
  2011. jniLibPackage = jniLibLabel.Label[2:indexOfColon]
  2012. } else if indexOfColon == 0 {
  2013. // JNI lib in the same package of java_binary
  2014. packageOfCurrentModule := m.GetBazelLabel(ctx, m)
  2015. jniLibPackage = packageOfCurrentModule[2:strings.Index(packageOfCurrentModule, ":")]
  2016. }
  2017. if _, inMap := jniLibPackages[jniLibPackage]; !inMap {
  2018. jniLibPackages[jniLibPackage] = true
  2019. }
  2020. }
  2021. jniLibPaths := []string{}
  2022. for jniLibPackage, _ := range jniLibPackages {
  2023. // See cs/f:.*/third_party/bazel/.*java_stub_template.txt for the use of RUNPATH
  2024. jniLibPaths = append(jniLibPaths, "$${RUNPATH}"+jniLibPackage)
  2025. }
  2026. attrs.Jvm_flags = bazel.MakeStringListAttribute([]string{"-Djava.library.path=" + strings.Join(jniLibPaths, ":")})
  2027. }
  2028. props := bazel.BazelTargetModuleProperties{
  2029. Rule_class: "java_binary",
  2030. }
  2031. // Create the BazelTargetModule.
  2032. ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, attrs)
  2033. }
  2034. type bazelJavaImportAttributes struct {
  2035. Jars bazel.LabelListAttribute
  2036. }
  2037. // java_import bp2Build converter.
  2038. func (i *Import) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
  2039. var jars bazel.LabelListAttribute
  2040. archVariantProps := i.GetArchVariantProperties(ctx, &ImportProperties{})
  2041. for axis, configToProps := range archVariantProps {
  2042. for config, _props := range configToProps {
  2043. if archProps, ok := _props.(*ImportProperties); ok {
  2044. archJars := android.BazelLabelForModuleSrcExcludes(ctx, archProps.Jars, []string(nil))
  2045. jars.SetSelectValue(axis, config, archJars)
  2046. }
  2047. }
  2048. }
  2049. attrs := &bazelJavaImportAttributes{
  2050. Jars: jars,
  2051. }
  2052. props := bazel.BazelTargetModuleProperties{Rule_class: "java_import"}
  2053. ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: android.RemoveOptionalPrebuiltPrefix(i.Name())}, attrs)
  2054. }
  2055. var _ android.MixedBuildBuildable = (*Import)(nil)
  2056. func (i *Import) getBazelModuleLabel(ctx android.BaseModuleContext) string {
  2057. return android.RemoveOptionalPrebuiltPrefixFromBazelLabel(i.GetBazelLabel(ctx, i))
  2058. }
  2059. func (i *Import) ProcessBazelQueryResponse(ctx android.ModuleContext) {
  2060. i.commonBuildActions(ctx)
  2061. bazelCtx := ctx.Config().BazelContext
  2062. filePaths, err := bazelCtx.GetOutputFiles(i.getBazelModuleLabel(ctx), android.GetConfigKey(ctx))
  2063. if err != nil {
  2064. ctx.ModuleErrorf(err.Error())
  2065. return
  2066. }
  2067. bazelJars := android.Paths{}
  2068. for _, bazelOutputFile := range filePaths {
  2069. bazelJars = append(bazelJars, android.PathForBazelOut(ctx, bazelOutputFile))
  2070. }
  2071. jarName := android.RemoveOptionalPrebuiltPrefix(i.Name()) + ".jar"
  2072. outputFile := android.PathForModuleOut(ctx, "bazelCombined", jarName)
  2073. TransformJarsToJar(ctx, outputFile, "combine prebuilt jars", bazelJars,
  2074. android.OptionalPath{}, // manifest
  2075. false, // stripDirEntries
  2076. []string{}, // filesToStrip
  2077. []string{}, // dirsToStrip
  2078. )
  2079. i.combinedClasspathFile = outputFile
  2080. ctx.SetProvider(JavaInfoProvider, JavaInfo{
  2081. HeaderJars: android.PathsIfNonNil(i.combinedClasspathFile),
  2082. ImplementationAndResourcesJars: android.PathsIfNonNil(i.combinedClasspathFile),
  2083. ImplementationJars: android.PathsIfNonNil(i.combinedClasspathFile),
  2084. //TODO(b/240308299) include AIDL information from Bazel
  2085. })
  2086. i.maybeInstall(ctx, jarName, outputFile)
  2087. }
  2088. func (i *Import) QueueBazelCall(ctx android.BaseModuleContext) {
  2089. bazelCtx := ctx.Config().BazelContext
  2090. bazelCtx.QueueBazelRequest(i.getBazelModuleLabel(ctx), cquery.GetOutputFiles, android.GetConfigKey(ctx))
  2091. }
  2092. func (i *Import) IsMixedBuildSupported(ctx android.BaseModuleContext) bool {
  2093. return true
  2094. }