java.go 67 KB

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