base.go 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176
  1. // Copyright 2021 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. import (
  16. "fmt"
  17. "path/filepath"
  18. "strconv"
  19. "strings"
  20. "github.com/google/blueprint/pathtools"
  21. "github.com/google/blueprint/proptools"
  22. "android/soong/android"
  23. "android/soong/dexpreopt"
  24. "android/soong/java/config"
  25. )
  26. // This file contains the definition and the implementation of the base module that most
  27. // source-based Java module structs embed.
  28. // TODO:
  29. // Autogenerated files:
  30. // Renderscript
  31. // Post-jar passes:
  32. // Proguard
  33. // Rmtypedefs
  34. // DroidDoc
  35. // Findbugs
  36. // Properties that are common to most Java modules, i.e. whether it's a host or device module.
  37. type CommonProperties struct {
  38. // list of source files used to compile the Java module. May be .java, .kt, .logtags, .proto,
  39. // or .aidl files.
  40. Srcs []string `android:"path,arch_variant"`
  41. // list Kotlin of source files containing Kotlin code that should be treated as common code in
  42. // a codebase that supports Kotlin multiplatform. See
  43. // https://kotlinlang.org/docs/reference/multiplatform.html. May be only be .kt files.
  44. Common_srcs []string `android:"path,arch_variant"`
  45. // list of source files that should not be used to build the Java module.
  46. // This is most useful in the arch/multilib variants to remove non-common files
  47. Exclude_srcs []string `android:"path,arch_variant"`
  48. // list of directories containing Java resources
  49. Java_resource_dirs []string `android:"arch_variant"`
  50. // list of directories that should be excluded from java_resource_dirs
  51. Exclude_java_resource_dirs []string `android:"arch_variant"`
  52. // list of files to use as Java resources
  53. Java_resources []string `android:"path,arch_variant"`
  54. // list of files that should be excluded from java_resources and java_resource_dirs
  55. Exclude_java_resources []string `android:"path,arch_variant"`
  56. // list of module-specific flags that will be used for javac compiles
  57. Javacflags []string `android:"arch_variant"`
  58. // list of module-specific flags that will be used for kotlinc compiles
  59. Kotlincflags []string `android:"arch_variant"`
  60. // list of java libraries that will be in the classpath
  61. Libs []string `android:"arch_variant"`
  62. // list of java libraries that will be compiled into the resulting jar
  63. Static_libs []string `android:"arch_variant"`
  64. // manifest file to be included in resulting jar
  65. Manifest *string `android:"path"`
  66. // if not blank, run jarjar using the specified rules file
  67. Jarjar_rules *string `android:"path,arch_variant"`
  68. // If not blank, set the java version passed to javac as -source and -target
  69. Java_version *string
  70. // If set to true, allow this module to be dexed and installed on devices. Has no
  71. // effect on host modules, which are always considered installable.
  72. Installable *bool
  73. // If set to true, include sources used to compile the module in to the final jar
  74. Include_srcs *bool
  75. // If not empty, classes are restricted to the specified packages and their sub-packages.
  76. // This restriction is checked after applying jarjar rules and including static libs.
  77. Permitted_packages []string
  78. // List of modules to use as annotation processors
  79. Plugins []string
  80. // List of modules to export to libraries that directly depend on this library as annotation
  81. // processors. Note that if the plugins set generates_api: true this will disable the turbine
  82. // optimization on modules that depend on this module, which will reduce parallelism and cause
  83. // more recompilation.
  84. Exported_plugins []string
  85. // The number of Java source entries each Javac instance can process
  86. Javac_shard_size *int64
  87. // Add host jdk tools.jar to bootclasspath
  88. Use_tools_jar *bool
  89. Openjdk9 struct {
  90. // List of source files that should only be used when passing -source 1.9 or higher
  91. Srcs []string `android:"path"`
  92. // List of javac flags that should only be used when passing -source 1.9 or higher
  93. Javacflags []string
  94. }
  95. // When compiling language level 9+ .java code in packages that are part of
  96. // a system module, patch_module names the module that your sources and
  97. // dependencies should be patched into. The Android runtime currently
  98. // doesn't implement the JEP 261 module system so this option is only
  99. // supported at compile time. It should only be needed to compile tests in
  100. // packages that exist in libcore and which are inconvenient to move
  101. // elsewhere.
  102. Patch_module *string `android:"arch_variant"`
  103. Jacoco struct {
  104. // List of classes to include for instrumentation with jacoco to collect coverage
  105. // information at runtime when building with coverage enabled. If unset defaults to all
  106. // classes.
  107. // Supports '*' as the last character of an entry in the list as a wildcard match.
  108. // If preceded by '.' it matches all classes in the package and subpackages, otherwise
  109. // it matches classes in the package that have the class name as a prefix.
  110. Include_filter []string
  111. // List of classes to exclude from instrumentation with jacoco to collect coverage
  112. // information at runtime when building with coverage enabled. Overrides classes selected
  113. // by the include_filter property.
  114. // Supports '*' as the last character of an entry in the list as a wildcard match.
  115. // If preceded by '.' it matches all classes in the package and subpackages, otherwise
  116. // it matches classes in the package that have the class name as a prefix.
  117. Exclude_filter []string
  118. }
  119. Errorprone struct {
  120. // List of javac flags that should only be used when running errorprone.
  121. Javacflags []string
  122. // List of java_plugin modules that provide extra errorprone checks.
  123. Extra_check_modules []string
  124. // This property can be in 3 states. When set to true, errorprone will
  125. // be run during the regular build. When set to false, errorprone will
  126. // never be run. When unset, errorprone will be run when the RUN_ERROR_PRONE
  127. // environment variable is true. Setting this to false will improve build
  128. // performance more than adding -XepDisableAllChecks in javacflags.
  129. Enabled *bool
  130. }
  131. Proto struct {
  132. // List of extra options that will be passed to the proto generator.
  133. Output_params []string
  134. }
  135. // If true, then jacocoagent is automatically added as a libs dependency so that
  136. // r8 will not strip instrumentation classes out of dexed libraries.
  137. Instrument bool `blueprint:"mutated"`
  138. // If true, then the module supports statically including the jacocoagent
  139. // into the library.
  140. Supports_static_instrumentation bool `blueprint:"mutated"`
  141. // List of files to include in the META-INF/services folder of the resulting jar.
  142. Services []string `android:"path,arch_variant"`
  143. // If true, package the kotlin stdlib into the jar. Defaults to true.
  144. Static_kotlin_stdlib *bool `android:"arch_variant"`
  145. // A list of java_library instances that provide additional hiddenapi annotations for the library.
  146. Hiddenapi_additional_annotations []string
  147. }
  148. // Properties that are specific to device modules. Host module factories should not add these when
  149. // constructing a new module.
  150. type DeviceProperties struct {
  151. // If not blank, set to the version of the sdk to compile against.
  152. // Defaults to an empty string, which compiles the module against the private platform APIs.
  153. // Values are of one of the following forms:
  154. // 1) numerical API level, "current", "none", or "core_platform"
  155. // 2) An SDK kind with an API level: "<sdk kind>_<API level>"
  156. // See build/soong/android/sdk_version.go for the complete and up to date list of SDK kinds.
  157. // If the SDK kind is empty, it will be set to public.
  158. Sdk_version *string
  159. // if not blank, set the minimum version of the sdk that the compiled artifacts will run against.
  160. // Defaults to sdk_version if not set. See sdk_version for possible values.
  161. Min_sdk_version *string
  162. // if not blank, set the maximum version of the sdk that the compiled artifacts will run against.
  163. // Defaults to empty string "". See sdk_version for possible values.
  164. Max_sdk_version *string
  165. // if not blank, set the maxSdkVersion properties of permission and uses-permission tags.
  166. // Defaults to empty string "". See sdk_version for possible values.
  167. Replace_max_sdk_version_placeholder *string
  168. // if not blank, set the targetSdkVersion in the AndroidManifest.xml.
  169. // Defaults to sdk_version if not set. See sdk_version for possible values.
  170. Target_sdk_version *string
  171. // Whether to compile against the platform APIs instead of an SDK.
  172. // If true, then sdk_version must be empty. The value of this field
  173. // is ignored when module's type isn't android_app, android_test, or android_test_helper_app.
  174. Platform_apis *bool
  175. Aidl struct {
  176. // Top level directories to pass to aidl tool
  177. Include_dirs []string
  178. // Directories rooted at the Android.bp file to pass to aidl tool
  179. Local_include_dirs []string
  180. // directories that should be added as include directories for any aidl sources of modules
  181. // that depend on this module, as well as to aidl for this module.
  182. Export_include_dirs []string
  183. // whether to generate traces (for systrace) for this interface
  184. Generate_traces *bool
  185. // whether to generate Binder#GetTransaction name method.
  186. Generate_get_transaction_name *bool
  187. // whether all interfaces should be annotated with required permissions.
  188. Enforce_permissions *bool
  189. // allowlist for interfaces that (temporarily) do not require annotation for permissions.
  190. Enforce_permissions_exceptions []string `android:"path"`
  191. // list of flags that will be passed to the AIDL compiler
  192. Flags []string
  193. }
  194. // If true, export a copy of the module as a -hostdex module for host testing.
  195. Hostdex *bool
  196. Target struct {
  197. Hostdex struct {
  198. // Additional required dependencies to add to -hostdex modules.
  199. Required []string
  200. }
  201. }
  202. // When targeting 1.9 and above, override the modules to use with --system,
  203. // otherwise provides defaults libraries to add to the bootclasspath.
  204. System_modules *string
  205. IsSDKLibrary bool `blueprint:"mutated"`
  206. // If true, generate the signature file of APK Signing Scheme V4, along side the signed APK file.
  207. // Defaults to false.
  208. V4_signature *bool
  209. // Only for libraries created by a sysprop_library module, SyspropPublicStub is the name of the
  210. // public stubs library.
  211. SyspropPublicStub string `blueprint:"mutated"`
  212. HiddenAPIPackageProperties
  213. HiddenAPIFlagFileProperties
  214. }
  215. // Device properties that can be overridden by overriding module (e.g. override_android_app)
  216. type OverridableDeviceProperties struct {
  217. // set the name of the output. If not set, `name` is used.
  218. // To override a module with this property set, overriding module might need to set this as well.
  219. // Otherwise, both the overridden and the overriding modules will have the same output name, which
  220. // can cause the duplicate output error.
  221. Stem *string
  222. }
  223. // Functionality common to Module and Import
  224. //
  225. // It is embedded in Module so its functionality can be used by methods in Module
  226. // but it is currently only initialized by Import and Library.
  227. type embeddableInModuleAndImport struct {
  228. // Functionality related to this being used as a component of a java_sdk_library.
  229. EmbeddableSdkLibraryComponent
  230. }
  231. func (e *embeddableInModuleAndImport) initModuleAndImport(module android.Module) {
  232. e.initSdkLibraryComponent(module)
  233. }
  234. // Module/Import's DepIsInSameApex(...) delegates to this method.
  235. //
  236. // This cannot implement DepIsInSameApex(...) directly as that leads to ambiguity with
  237. // the one provided by ApexModuleBase.
  238. func (e *embeddableInModuleAndImport) depIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
  239. // dependencies other than the static linkage are all considered crossing APEX boundary
  240. if staticLibTag == ctx.OtherModuleDependencyTag(dep) {
  241. return true
  242. }
  243. return false
  244. }
  245. // OptionalDexJarPath can be either unset, hold a valid path to a dex jar file,
  246. // or an invalid path describing the reason it is invalid.
  247. //
  248. // It is unset if a dex jar isn't applicable, i.e. no build rule has been
  249. // requested to create one.
  250. //
  251. // If a dex jar has been requested to be built then it is set, and it may be
  252. // either a valid android.Path, or invalid with a reason message. The latter
  253. // happens if the source that should produce the dex file isn't able to.
  254. //
  255. // E.g. it is invalid with a reason message if there is a prebuilt APEX that
  256. // could produce the dex jar through a deapexer module, but the APEX isn't
  257. // installable so doing so wouldn't be safe.
  258. type OptionalDexJarPath struct {
  259. isSet bool
  260. path android.OptionalPath
  261. }
  262. // IsSet returns true if a path has been set, either invalid or valid.
  263. func (o OptionalDexJarPath) IsSet() bool {
  264. return o.isSet
  265. }
  266. // Valid returns true if there is a path that is valid.
  267. func (o OptionalDexJarPath) Valid() bool {
  268. return o.isSet && o.path.Valid()
  269. }
  270. // Path returns the valid path, or panics if it's either not set or is invalid.
  271. func (o OptionalDexJarPath) Path() android.Path {
  272. if !o.isSet {
  273. panic("path isn't set")
  274. }
  275. return o.path.Path()
  276. }
  277. // PathOrNil returns the path if it's set and valid, or else nil.
  278. func (o OptionalDexJarPath) PathOrNil() android.Path {
  279. if o.Valid() {
  280. return o.Path()
  281. }
  282. return nil
  283. }
  284. // InvalidReason returns the reason for an invalid path, which is never "". It
  285. // returns "" for an unset or valid path.
  286. func (o OptionalDexJarPath) InvalidReason() string {
  287. if !o.isSet {
  288. return ""
  289. }
  290. return o.path.InvalidReason()
  291. }
  292. func (o OptionalDexJarPath) String() string {
  293. if !o.isSet {
  294. return "<unset>"
  295. }
  296. return o.path.String()
  297. }
  298. // makeUnsetDexJarPath returns an unset OptionalDexJarPath.
  299. func makeUnsetDexJarPath() OptionalDexJarPath {
  300. return OptionalDexJarPath{isSet: false}
  301. }
  302. // makeDexJarPathFromOptionalPath returns an OptionalDexJarPath that is set with
  303. // the given OptionalPath, which may be valid or invalid.
  304. func makeDexJarPathFromOptionalPath(path android.OptionalPath) OptionalDexJarPath {
  305. return OptionalDexJarPath{isSet: true, path: path}
  306. }
  307. // makeDexJarPathFromPath returns an OptionalDexJarPath that is set with the
  308. // valid given path. It returns an unset OptionalDexJarPath if the given path is
  309. // nil.
  310. func makeDexJarPathFromPath(path android.Path) OptionalDexJarPath {
  311. if path == nil {
  312. return makeUnsetDexJarPath()
  313. }
  314. return makeDexJarPathFromOptionalPath(android.OptionalPathForPath(path))
  315. }
  316. // Module contains the properties and members used by all java module types
  317. type Module struct {
  318. android.ModuleBase
  319. android.DefaultableModuleBase
  320. android.ApexModuleBase
  321. android.BazelModuleBase
  322. // Functionality common to Module and Import.
  323. embeddableInModuleAndImport
  324. properties CommonProperties
  325. protoProperties android.ProtoProperties
  326. deviceProperties DeviceProperties
  327. overridableDeviceProperties OverridableDeviceProperties
  328. // jar file containing header classes including static library dependencies, suitable for
  329. // inserting into the bootclasspath/classpath of another compile
  330. headerJarFile android.Path
  331. // jar file containing implementation classes including static library dependencies but no
  332. // resources
  333. implementationJarFile android.Path
  334. // jar file containing only resources including from static library dependencies
  335. resourceJar android.Path
  336. // args and dependencies to package source files into a srcjar
  337. srcJarArgs []string
  338. srcJarDeps android.Paths
  339. // jar file containing implementation classes and resources including static library
  340. // dependencies
  341. implementationAndResourcesJar android.Path
  342. // output file containing classes.dex and resources
  343. dexJarFile OptionalDexJarPath
  344. // output file containing uninstrumented classes that will be instrumented by jacoco
  345. jacocoReportClassesFile android.Path
  346. // output file of the module, which may be a classes jar or a dex jar
  347. outputFile android.Path
  348. extraOutputFiles android.Paths
  349. exportAidlIncludeDirs android.Paths
  350. ignoredAidlPermissionList android.Paths
  351. logtagsSrcs android.Paths
  352. // installed file for binary dependency
  353. installFile android.Path
  354. // installed file for hostdex copy
  355. hostdexInstallFile android.InstallPath
  356. // list of unique .java and .kt source files
  357. uniqueSrcFiles android.Paths
  358. // list of srcjars that was passed to javac
  359. compiledSrcJars android.Paths
  360. // manifest file to use instead of properties.Manifest
  361. overrideManifest android.OptionalPath
  362. // list of plugins that this java module is exporting
  363. exportedPluginJars android.Paths
  364. // list of plugins that this java module is exporting
  365. exportedPluginClasses []string
  366. // if true, the exported plugins generate API and require disabling turbine.
  367. exportedDisableTurbine bool
  368. // list of source files, collected from srcFiles with unique java and all kt files,
  369. // will be used by android.IDEInfo struct
  370. expandIDEInfoCompiledSrcs []string
  371. // expanded Jarjar_rules
  372. expandJarjarRules android.Path
  373. // Extra files generated by the module type to be added as java resources.
  374. extraResources android.Paths
  375. hiddenAPI
  376. dexer
  377. dexpreopter
  378. usesLibrary
  379. linter
  380. // list of the xref extraction files
  381. kytheFiles android.Paths
  382. // Collect the module directory for IDE info in java/jdeps.go.
  383. modulePaths []string
  384. hideApexVariantFromMake bool
  385. sdkVersion android.SdkSpec
  386. minSdkVersion android.SdkSpec
  387. maxSdkVersion android.SdkSpec
  388. sourceExtensions []string
  389. }
  390. func (j *Module) CheckStableSdkVersion(ctx android.BaseModuleContext) error {
  391. sdkVersion := j.SdkVersion(ctx)
  392. if sdkVersion.Stable() {
  393. return nil
  394. }
  395. if sdkVersion.Kind == android.SdkCorePlatform {
  396. if useLegacyCorePlatformApi(ctx, j.BaseModuleName()) {
  397. return fmt.Errorf("non stable SDK %v - uses legacy core platform", sdkVersion)
  398. } else {
  399. // Treat stable core platform as stable.
  400. return nil
  401. }
  402. } else {
  403. return fmt.Errorf("non stable SDK %v", sdkVersion)
  404. }
  405. }
  406. // checkSdkVersions enforces restrictions around SDK dependencies.
  407. func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
  408. if j.RequiresStableAPIs(ctx) {
  409. if sc, ok := ctx.Module().(android.SdkContext); ok {
  410. if !sc.SdkVersion(ctx).Specified() {
  411. ctx.PropertyErrorf("sdk_version",
  412. "sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
  413. }
  414. }
  415. }
  416. // Make sure this module doesn't statically link to modules with lower-ranked SDK link type.
  417. // See rank() for details.
  418. ctx.VisitDirectDeps(func(module android.Module) {
  419. tag := ctx.OtherModuleDependencyTag(module)
  420. switch module.(type) {
  421. // TODO(satayev): cover other types as well, e.g. imports
  422. case *Library, *AndroidLibrary:
  423. switch tag {
  424. case bootClasspathTag, sdkLibTag, libTag, staticLibTag, java9LibTag:
  425. j.checkSdkLinkType(ctx, module.(moduleWithSdkDep), tag.(dependencyTag))
  426. }
  427. }
  428. })
  429. }
  430. func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
  431. if sc, ok := ctx.Module().(android.SdkContext); ok {
  432. usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
  433. sdkVersionSpecified := sc.SdkVersion(ctx).Specified()
  434. if usePlatformAPI && sdkVersionSpecified {
  435. ctx.PropertyErrorf("platform_apis", "This module has conflicting settings. sdk_version is not empty, which means this module cannot use platform APIs. However platform_apis is set to true.")
  436. } else if !usePlatformAPI && !sdkVersionSpecified {
  437. ctx.PropertyErrorf("platform_apis", "This module has conflicting settings. sdk_version is empty, which means that this module is build against platform APIs. However platform_apis is not set to true")
  438. }
  439. }
  440. }
  441. func (j *Module) addHostProperties() {
  442. j.AddProperties(
  443. &j.properties,
  444. &j.protoProperties,
  445. &j.usesLibraryProperties,
  446. )
  447. }
  448. func (j *Module) addHostAndDeviceProperties() {
  449. j.addHostProperties()
  450. j.AddProperties(
  451. &j.deviceProperties,
  452. &j.overridableDeviceProperties,
  453. &j.dexer.dexProperties,
  454. &j.dexpreoptProperties,
  455. &j.linter.properties,
  456. )
  457. }
  458. // provideHiddenAPIPropertyInfo populates a HiddenAPIPropertyInfo from hidden API properties and
  459. // makes it available through the hiddenAPIPropertyInfoProvider.
  460. func (j *Module) provideHiddenAPIPropertyInfo(ctx android.ModuleContext) {
  461. hiddenAPIInfo := newHiddenAPIPropertyInfo()
  462. // Populate with flag file paths from the properties.
  463. hiddenAPIInfo.extractFlagFilesFromProperties(ctx, &j.deviceProperties.HiddenAPIFlagFileProperties)
  464. // Populate with package rules from the properties.
  465. hiddenAPIInfo.extractPackageRulesFromProperties(&j.deviceProperties.HiddenAPIPackageProperties)
  466. ctx.SetProvider(hiddenAPIPropertyInfoProvider, hiddenAPIInfo)
  467. }
  468. func (j *Module) OutputFiles(tag string) (android.Paths, error) {
  469. switch tag {
  470. case "":
  471. return append(android.Paths{j.outputFile}, j.extraOutputFiles...), nil
  472. case android.DefaultDistTag:
  473. return android.Paths{j.outputFile}, nil
  474. case ".jar":
  475. return android.Paths{j.implementationAndResourcesJar}, nil
  476. case ".hjar":
  477. return android.Paths{j.headerJarFile}, nil
  478. case ".proguard_map":
  479. if j.dexer.proguardDictionary.Valid() {
  480. return android.Paths{j.dexer.proguardDictionary.Path()}, nil
  481. }
  482. return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
  483. default:
  484. return nil, fmt.Errorf("unsupported module reference tag %q", tag)
  485. }
  486. }
  487. var _ android.OutputFileProducer = (*Module)(nil)
  488. func InitJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
  489. initJavaModule(module, hod, false)
  490. }
  491. func InitJavaModuleMultiTargets(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
  492. initJavaModule(module, hod, true)
  493. }
  494. func initJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported, multiTargets bool) {
  495. multilib := android.MultilibCommon
  496. if multiTargets {
  497. android.InitAndroidMultiTargetsArchModule(module, hod, multilib)
  498. } else {
  499. android.InitAndroidArchModule(module, hod, multilib)
  500. }
  501. android.InitDefaultableModule(module)
  502. }
  503. func (j *Module) shouldInstrument(ctx android.BaseModuleContext) bool {
  504. return j.properties.Instrument &&
  505. ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") &&
  506. ctx.DeviceConfig().JavaCoverageEnabledForPath(ctx.ModuleDir())
  507. }
  508. func (j *Module) shouldInstrumentStatic(ctx android.BaseModuleContext) bool {
  509. return j.properties.Supports_static_instrumentation &&
  510. j.shouldInstrument(ctx) &&
  511. (ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_STATIC") ||
  512. ctx.Config().UnbundledBuild())
  513. }
  514. func (j *Module) shouldInstrumentInApex(ctx android.BaseModuleContext) bool {
  515. // Force enable the instrumentation for java code that is built for APEXes ...
  516. // except for the jacocoagent itself (because instrumenting jacocoagent using jacocoagent
  517. // doesn't make sense) or framework libraries (e.g. libraries found in the InstrumentFrameworkModules list) unless EMMA_INSTRUMENT_FRAMEWORK is true.
  518. apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
  519. isJacocoAgent := ctx.ModuleName() == "jacocoagent"
  520. if j.DirectlyInAnyApex() && !isJacocoAgent && !apexInfo.IsForPlatform() {
  521. if !inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
  522. return true
  523. } else if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
  524. return true
  525. }
  526. }
  527. return false
  528. }
  529. func (j *Module) setInstrument(value bool) {
  530. j.properties.Instrument = value
  531. }
  532. func (j *Module) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
  533. return android.SdkSpecFrom(ctx, String(j.deviceProperties.Sdk_version))
  534. }
  535. func (j *Module) SystemModules() string {
  536. return proptools.String(j.deviceProperties.System_modules)
  537. }
  538. func (j *Module) MinSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
  539. if j.deviceProperties.Min_sdk_version != nil {
  540. return android.SdkSpecFrom(ctx, *j.deviceProperties.Min_sdk_version)
  541. }
  542. return j.SdkVersion(ctx)
  543. }
  544. func (j *Module) MaxSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
  545. maxSdkVersion := proptools.StringDefault(j.deviceProperties.Max_sdk_version, "")
  546. // SdkSpecFrom returns SdkSpecPrivate for this, which may be confusing.
  547. // TODO(b/208456999): ideally MaxSdkVersion should be an ApiLevel and not SdkSpec.
  548. return android.SdkSpecFrom(ctx, maxSdkVersion)
  549. }
  550. func (j *Module) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.SdkSpec {
  551. replaceMaxSdkVersionPlaceholder := proptools.StringDefault(j.deviceProperties.Replace_max_sdk_version_placeholder, "")
  552. return android.SdkSpecFrom(ctx, replaceMaxSdkVersionPlaceholder)
  553. }
  554. func (j *Module) MinSdkVersionString() string {
  555. return j.minSdkVersion.Raw
  556. }
  557. func (j *Module) TargetSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
  558. if j.deviceProperties.Target_sdk_version != nil {
  559. return android.SdkSpecFrom(ctx, *j.deviceProperties.Target_sdk_version)
  560. }
  561. return j.SdkVersion(ctx)
  562. }
  563. func (j *Module) AvailableFor(what string) bool {
  564. if what == android.AvailableToPlatform && Bool(j.deviceProperties.Hostdex) {
  565. // Exception: for hostdex: true libraries, the platform variant is created
  566. // even if it's not marked as available to platform. In that case, the platform
  567. // variant is used only for the hostdex and not installed to the device.
  568. return true
  569. }
  570. return j.ApexModuleBase.AvailableFor(what)
  571. }
  572. func (j *Module) deps(ctx android.BottomUpMutatorContext) {
  573. if ctx.Device() {
  574. j.linter.deps(ctx)
  575. sdkDeps(ctx, android.SdkContext(j), j.dexer)
  576. if j.deviceProperties.SyspropPublicStub != "" {
  577. // This is a sysprop implementation library that has a corresponding sysprop public
  578. // stubs library, and a dependency on it so that dependencies on the implementation can
  579. // be forwarded to the public stubs library when necessary.
  580. ctx.AddVariationDependencies(nil, syspropPublicStubDepTag, j.deviceProperties.SyspropPublicStub)
  581. }
  582. }
  583. libDeps := ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
  584. ctx.AddVariationDependencies(nil, staticLibTag, j.properties.Static_libs...)
  585. // Add dependency on libraries that provide additional hidden api annotations.
  586. ctx.AddVariationDependencies(nil, hiddenApiAnnotationsTag, j.properties.Hiddenapi_additional_annotations...)
  587. if ctx.DeviceConfig().VndkVersion() != "" && ctx.Config().EnforceInterPartitionJavaSdkLibrary() {
  588. // Require java_sdk_library at inter-partition java dependency to ensure stable
  589. // interface between partitions. If inter-partition java_library dependency is detected,
  590. // raise build error because java_library doesn't have a stable interface.
  591. //
  592. // Inputs:
  593. // PRODUCT_ENFORCE_INTER_PARTITION_JAVA_SDK_LIBRARY
  594. // if true, enable enforcement
  595. // PRODUCT_INTER_PARTITION_JAVA_LIBRARY_ALLOWLIST
  596. // exception list of java_library names to allow inter-partition dependency
  597. for idx := range j.properties.Libs {
  598. if libDeps[idx] == nil {
  599. continue
  600. }
  601. if javaDep, ok := libDeps[idx].(javaSdkLibraryEnforceContext); ok {
  602. // java_sdk_library is always allowed at inter-partition dependency.
  603. // So, skip check.
  604. if _, ok := javaDep.(*SdkLibrary); ok {
  605. continue
  606. }
  607. j.checkPartitionsForJavaDependency(ctx, "libs", javaDep)
  608. }
  609. }
  610. }
  611. // For library dependencies that are component libraries (like stubs), add the implementation
  612. // as a dependency (dexpreopt needs to be against the implementation library, not stubs).
  613. for _, dep := range libDeps {
  614. if dep != nil {
  615. if component, ok := dep.(SdkLibraryComponentDependency); ok {
  616. if lib := component.OptionalSdkLibraryImplementation(); lib != nil {
  617. // Add library as optional if it's one of the optional compatibility libs.
  618. tag := usesLibReqTag
  619. if android.InList(*lib, dexpreopt.OptionalCompatUsesLibs) {
  620. tag = usesLibOptTag
  621. }
  622. ctx.AddVariationDependencies(nil, tag, *lib)
  623. }
  624. }
  625. }
  626. }
  627. ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
  628. ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
  629. ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
  630. android.ProtoDeps(ctx, &j.protoProperties)
  631. if j.hasSrcExt(".proto") {
  632. protoDeps(ctx, &j.protoProperties)
  633. }
  634. if j.hasSrcExt(".kt") {
  635. // TODO(ccross): move this to a mutator pass that can tell if generated sources contain
  636. // Kotlin files
  637. ctx.AddVariationDependencies(nil, kotlinStdlibTag,
  638. "kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8")
  639. ctx.AddVariationDependencies(nil, kotlinAnnotationsTag, "kotlin-annotations")
  640. }
  641. // Framework libraries need special handling in static coverage builds: they should not have
  642. // static dependency on jacoco, otherwise there would be multiple conflicting definitions of
  643. // the same jacoco classes coming from different bootclasspath jars.
  644. if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
  645. if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
  646. j.properties.Instrument = true
  647. }
  648. } else if j.shouldInstrumentStatic(ctx) {
  649. ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
  650. }
  651. if j.useCompose() {
  652. ctx.AddVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), kotlinPluginTag,
  653. "androidx.compose.compiler_compiler-hosted")
  654. }
  655. }
  656. func hasSrcExt(srcs []string, ext string) bool {
  657. for _, src := range srcs {
  658. if filepath.Ext(src) == ext {
  659. return true
  660. }
  661. }
  662. return false
  663. }
  664. func (j *Module) hasSrcExt(ext string) bool {
  665. return hasSrcExt(j.properties.Srcs, ext)
  666. }
  667. func (j *Module) individualAidlFlags(ctx android.ModuleContext, aidlFile android.Path) string {
  668. var flags string
  669. if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
  670. if !android.InList(aidlFile.String(), j.ignoredAidlPermissionList.Strings()) {
  671. flags = "-Wmissing-permission-annotation -Werror"
  672. }
  673. }
  674. return flags
  675. }
  676. func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
  677. aidlIncludeDirs android.Paths, aidlSrcs android.Paths) (string, android.Paths) {
  678. aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
  679. aidlIncludes = append(aidlIncludes,
  680. android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
  681. aidlIncludes = append(aidlIncludes,
  682. android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
  683. var flags []string
  684. var deps android.Paths
  685. var includeDirs android.Paths
  686. flags = append(flags, j.deviceProperties.Aidl.Flags...)
  687. if aidlPreprocess.Valid() {
  688. flags = append(flags, "-p"+aidlPreprocess.String())
  689. deps = append(deps, aidlPreprocess.Path())
  690. } else if len(aidlIncludeDirs) > 0 {
  691. includeDirs = append(includeDirs, aidlIncludeDirs...)
  692. }
  693. if len(j.exportAidlIncludeDirs) > 0 {
  694. includeDirs = append(includeDirs, j.exportAidlIncludeDirs...)
  695. }
  696. if len(aidlIncludes) > 0 {
  697. includeDirs = append(includeDirs, aidlIncludes...)
  698. }
  699. includeDirs = append(includeDirs, android.PathForModuleSrc(ctx))
  700. if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
  701. includeDirs = append(includeDirs, src.Path())
  702. }
  703. flags = append(flags, android.JoinWithPrefix(includeDirs.Strings(), "-I"))
  704. // add flags for dirs containing AIDL srcs that haven't been specified yet
  705. flags = append(flags, genAidlIncludeFlags(ctx, aidlSrcs, includeDirs))
  706. sdkVersion := (j.SdkVersion(ctx)).Kind
  707. defaultTrace := ((sdkVersion == android.SdkSystemServer) || (sdkVersion == android.SdkCore) || (sdkVersion == android.SdkCorePlatform) || (sdkVersion == android.SdkModule) || (sdkVersion == android.SdkSystem))
  708. if proptools.BoolDefault(j.deviceProperties.Aidl.Generate_traces, defaultTrace) {
  709. flags = append(flags, "-t")
  710. }
  711. if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
  712. flags = append(flags, "--transaction_names")
  713. }
  714. if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
  715. exceptions := j.deviceProperties.Aidl.Enforce_permissions_exceptions
  716. j.ignoredAidlPermissionList = android.PathsForModuleSrcExcludes(ctx, exceptions, nil)
  717. }
  718. aidlMinSdkVersion := j.MinSdkVersion(ctx).ApiLevel.String()
  719. flags = append(flags, "--min_sdk_version="+aidlMinSdkVersion)
  720. return strings.Join(flags, " "), deps
  721. }
  722. func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
  723. var flags javaBuilderFlags
  724. // javaVersion flag.
  725. flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
  726. epEnabled := j.properties.Errorprone.Enabled
  727. if (ctx.Config().RunErrorProne() && epEnabled == nil) || Bool(epEnabled) {
  728. if config.ErrorProneClasspath == nil && !ctx.Config().RunningInsideUnitTest() {
  729. ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
  730. }
  731. errorProneFlags := []string{
  732. "-Xplugin:ErrorProne",
  733. "${config.ErrorProneChecks}",
  734. }
  735. errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
  736. flags.errorProneExtraJavacFlags = "${config.ErrorProneHeapFlags} ${config.ErrorProneFlags} " +
  737. "'" + strings.Join(errorProneFlags, " ") + "'"
  738. flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
  739. }
  740. // classpath
  741. flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
  742. flags.classpath = append(flags.classpath, deps.classpath...)
  743. flags.dexClasspath = append(flags.dexClasspath, deps.dexClasspath...)
  744. flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
  745. flags.processorPath = append(flags.processorPath, deps.processorPath...)
  746. flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
  747. flags.processors = append(flags.processors, deps.processorClasses...)
  748. flags.processors = android.FirstUniqueStrings(flags.processors)
  749. if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
  750. decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
  751. // Give host-side tools a version of OpenJDK's standard libraries
  752. // close to what they're targeting. As of Dec 2017, AOSP is only
  753. // bundling OpenJDK 8 and 9, so nothing < 8 is available.
  754. //
  755. // When building with OpenJDK 8, the following should have no
  756. // effect since those jars would be available by default.
  757. //
  758. // When building with OpenJDK 9 but targeting a version < 1.8,
  759. // putting them on the bootclasspath means that:
  760. // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
  761. // b) references to existing APIs are not reinterpreted in an
  762. // OpenJDK 9-specific way, eg. calls to subclasses of
  763. // java.nio.Buffer as in http://b/70862583
  764. java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
  765. flags.bootClasspath = append(flags.bootClasspath,
  766. android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
  767. android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
  768. if Bool(j.properties.Use_tools_jar) {
  769. flags.bootClasspath = append(flags.bootClasspath,
  770. android.PathForSource(ctx, java8Home, "lib/tools.jar"))
  771. }
  772. }
  773. // systemModules
  774. flags.systemModules = deps.systemModules
  775. return flags
  776. }
  777. func (j *Module) collectJavacFlags(
  778. ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
  779. // javac flags.
  780. javacFlags := j.properties.Javacflags
  781. if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() {
  782. // For non-host binaries, override the -g flag passed globally to remove
  783. // local variable debug info to reduce disk and memory usage.
  784. javacFlags = append(javacFlags, "-g:source,lines")
  785. }
  786. javacFlags = append(javacFlags, "-Xlint:-dep-ann")
  787. if flags.javaVersion.usesJavaModules() {
  788. javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
  789. if j.properties.Patch_module != nil {
  790. // Manually specify build directory in case it is not under the repo root.
  791. // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
  792. // just adding a symlink under the root doesn't help.)
  793. patchPaths := []string{".", ctx.Config().SoongOutDir()}
  794. // b/150878007
  795. //
  796. // Workaround to support *Bazel-executed* JDK9 javac in Bazel's
  797. // execution root for --patch-module. If this javac command line is
  798. // invoked within Bazel's execution root working directory, the top
  799. // level directories (e.g. libcore/, tools/, frameworks/) are all
  800. // symlinks. JDK9 javac does not traverse into symlinks, which causes
  801. // --patch-module to fail source file lookups when invoked in the
  802. // execution root.
  803. //
  804. // Short of patching javac or enumerating *all* directories as possible
  805. // input dirs, manually add the top level dir of the source files to be
  806. // compiled.
  807. topLevelDirs := map[string]bool{}
  808. for _, srcFilePath := range srcFiles {
  809. srcFileParts := strings.Split(srcFilePath.String(), "/")
  810. // Ignore source files that are already in the top level directory
  811. // as well as generated files in the out directory. The out
  812. // directory may be an absolute path, which means srcFileParts[0] is the
  813. // empty string, so check that as well. Note that "out" in Bazel's execution
  814. // root is *not* a symlink, which doesn't cause problems for --patch-modules
  815. // anyway, so it's fine to not apply this workaround for generated
  816. // source files.
  817. if len(srcFileParts) > 1 &&
  818. srcFileParts[0] != "" &&
  819. srcFileParts[0] != "out" {
  820. topLevelDirs[srcFileParts[0]] = true
  821. }
  822. }
  823. patchPaths = append(patchPaths, android.SortedStringKeys(topLevelDirs)...)
  824. classPath := flags.classpath.FormJavaClassPath("")
  825. if classPath != "" {
  826. patchPaths = append(patchPaths, classPath)
  827. }
  828. javacFlags = append(
  829. javacFlags,
  830. "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
  831. }
  832. }
  833. if len(javacFlags) > 0 {
  834. // optimization.
  835. ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
  836. flags.javacFlags = "$javacFlags"
  837. }
  838. return flags
  839. }
  840. func (j *Module) AddJSONData(d *map[string]interface{}) {
  841. (&j.ModuleBase).AddJSONData(d)
  842. (*d)["Java"] = map[string]interface{}{
  843. "SourceExtensions": j.sourceExtensions,
  844. }
  845. }
  846. func (j *Module) compile(ctx android.ModuleContext, aaptSrcJar android.Path) {
  847. j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
  848. deps := j.collectDeps(ctx)
  849. flags := j.collectBuilderFlags(ctx, deps)
  850. if flags.javaVersion.usesJavaModules() {
  851. j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
  852. }
  853. srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
  854. j.sourceExtensions = []string{}
  855. for _, ext := range []string{".kt", ".proto", ".aidl", ".java", ".logtags"} {
  856. if hasSrcExt(srcFiles.Strings(), ext) {
  857. j.sourceExtensions = append(j.sourceExtensions, ext)
  858. }
  859. }
  860. if hasSrcExt(srcFiles.Strings(), ".proto") {
  861. flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
  862. }
  863. kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
  864. if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
  865. ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
  866. }
  867. aidlSrcs := srcFiles.FilterByExt(".aidl")
  868. flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs, aidlSrcs)
  869. nonGeneratedSrcJars := srcFiles.FilterByExt(".srcjar")
  870. srcFiles = j.genSources(ctx, srcFiles, flags)
  871. // Collect javac flags only after computing the full set of srcFiles to
  872. // ensure that the --patch-module lookup paths are complete.
  873. flags = j.collectJavacFlags(ctx, flags, srcFiles)
  874. srcJars := srcFiles.FilterByExt(".srcjar")
  875. srcJars = append(srcJars, deps.srcJars...)
  876. if aaptSrcJar != nil {
  877. srcJars = append(srcJars, aaptSrcJar)
  878. }
  879. srcFiles = srcFiles.FilterOutByExt(".srcjar")
  880. if j.properties.Jarjar_rules != nil {
  881. j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
  882. }
  883. jarName := ctx.ModuleName() + ".jar"
  884. var uniqueJavaFiles android.Paths
  885. set := make(map[string]bool)
  886. for _, v := range srcFiles.FilterByExt(".java") {
  887. if _, found := set[v.String()]; !found {
  888. set[v.String()] = true
  889. uniqueJavaFiles = append(uniqueJavaFiles, v)
  890. }
  891. }
  892. var uniqueKtFiles android.Paths
  893. for _, v := range srcFiles.FilterByExt(".kt") {
  894. if _, found := set[v.String()]; !found {
  895. set[v.String()] = true
  896. uniqueKtFiles = append(uniqueKtFiles, v)
  897. }
  898. }
  899. var uniqueSrcFiles android.Paths
  900. uniqueSrcFiles = append(uniqueSrcFiles, uniqueJavaFiles...)
  901. uniqueSrcFiles = append(uniqueSrcFiles, uniqueKtFiles...)
  902. j.uniqueSrcFiles = uniqueSrcFiles
  903. // We don't currently run annotation processors in turbine, which means we can't use turbine
  904. // generated header jars when an annotation processor that generates API is enabled. One
  905. // exception (handled further below) is when kotlin sources are enabled, in which case turbine
  906. // is used to run all of the annotation processors.
  907. disableTurbine := deps.disableTurbine
  908. // Collect .java and .kt files for AIDEGen
  909. j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
  910. var kotlinJars android.Paths
  911. var kotlinHeaderJars android.Paths
  912. if srcFiles.HasExt(".kt") {
  913. // When using kotlin sources turbine is used to generate annotation processor sources,
  914. // including for annotation processors that generate API, so we can use turbine for
  915. // java sources too.
  916. disableTurbine = false
  917. // user defined kotlin flags.
  918. kotlincFlags := j.properties.Kotlincflags
  919. CheckKotlincFlags(ctx, kotlincFlags)
  920. // Workaround for KT-46512
  921. kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
  922. // If there are kotlin files, compile them first but pass all the kotlin and java files
  923. // kotlinc will use the java files to resolve types referenced by the kotlin files, but
  924. // won't emit any classes for them.
  925. kotlincFlags = append(kotlincFlags, "-no-stdlib")
  926. if ctx.Device() {
  927. kotlincFlags = append(kotlincFlags, "-no-jdk")
  928. }
  929. for _, plugin := range deps.kotlinPlugins {
  930. kotlincFlags = append(kotlincFlags, "-Xplugin="+plugin.String())
  931. }
  932. flags.kotlincDeps = append(flags.kotlincDeps, deps.kotlinPlugins...)
  933. if len(kotlincFlags) > 0 {
  934. // optimization.
  935. ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
  936. flags.kotlincFlags += "$kotlincFlags"
  937. }
  938. // Collect common .kt files for AIDEGen
  939. j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
  940. flags.classpath = append(flags.classpath, deps.kotlinStdlib...)
  941. flags.classpath = append(flags.classpath, deps.kotlinAnnotations...)
  942. flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
  943. flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
  944. if len(flags.processorPath) > 0 {
  945. // Use kapt for annotation processing
  946. kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
  947. kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
  948. kotlinKapt(ctx, kaptSrcJar, kaptResJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
  949. srcJars = append(srcJars, kaptSrcJar)
  950. kotlinJars = append(kotlinJars, kaptResJar)
  951. // Disable annotation processing in javac, it's already been handled by kapt
  952. flags.processorPath = nil
  953. flags.processors = nil
  954. }
  955. kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
  956. kotlinHeaderJar := android.PathForModuleOut(ctx, "kotlin_headers", jarName)
  957. kotlinCompile(ctx, kotlinJar, kotlinHeaderJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
  958. if ctx.Failed() {
  959. return
  960. }
  961. // Make javac rule depend on the kotlinc rule
  962. flags.classpath = append(classpath{kotlinHeaderJar}, flags.classpath...)
  963. kotlinJars = append(kotlinJars, kotlinJar)
  964. kotlinHeaderJars = append(kotlinHeaderJars, kotlinHeaderJar)
  965. // Jar kotlin classes into the final jar after javac
  966. if BoolDefault(j.properties.Static_kotlin_stdlib, true) {
  967. kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
  968. kotlinJars = append(kotlinJars, deps.kotlinAnnotations...)
  969. kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinStdlib...)
  970. kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinAnnotations...)
  971. } else {
  972. flags.dexClasspath = append(flags.dexClasspath, deps.kotlinStdlib...)
  973. flags.dexClasspath = append(flags.dexClasspath, deps.kotlinAnnotations...)
  974. }
  975. }
  976. jars := append(android.Paths(nil), kotlinJars...)
  977. j.compiledSrcJars = srcJars
  978. enableSharding := false
  979. var headerJarFileWithoutDepsOrJarjar android.Path
  980. if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !disableTurbine {
  981. if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
  982. enableSharding = true
  983. // Formerly, there was a check here that prevented annotation processors
  984. // from being used when sharding was enabled, as some annotation processors
  985. // do not function correctly in sharded environments. It was removed to
  986. // allow for the use of annotation processors that do function correctly
  987. // with sharding enabled. See: b/77284273.
  988. }
  989. headerJarFileWithoutDepsOrJarjar, j.headerJarFile =
  990. j.compileJavaHeader(ctx, uniqueJavaFiles, srcJars, deps, flags, jarName, kotlinHeaderJars)
  991. if ctx.Failed() {
  992. return
  993. }
  994. }
  995. if len(uniqueJavaFiles) > 0 || len(srcJars) > 0 {
  996. hasErrorproneableFiles := false
  997. for _, ext := range j.sourceExtensions {
  998. if ext != ".proto" && ext != ".aidl" {
  999. // Skip running errorprone on pure proto or pure aidl modules. Some modules take a long time to
  1000. // compile, and it's not useful to have warnings on these generated sources.
  1001. hasErrorproneableFiles = true
  1002. break
  1003. }
  1004. }
  1005. var extraJarDeps android.Paths
  1006. if Bool(j.properties.Errorprone.Enabled) {
  1007. // If error-prone is enabled, enable errorprone flags on the regular
  1008. // build.
  1009. flags = enableErrorproneFlags(flags)
  1010. } else if hasErrorproneableFiles && ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
  1011. // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
  1012. // a new jar file just for compiling with the errorprone compiler to.
  1013. // This is because we don't want to cause the java files to get completely
  1014. // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
  1015. // We also don't want to run this if errorprone is enabled by default for
  1016. // this module, or else we could have duplicated errorprone messages.
  1017. errorproneFlags := enableErrorproneFlags(flags)
  1018. errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
  1019. transformJavaToClasses(ctx, errorprone, -1, uniqueJavaFiles, srcJars, errorproneFlags, nil,
  1020. "errorprone", "errorprone")
  1021. extraJarDeps = append(extraJarDeps, errorprone)
  1022. }
  1023. if enableSharding {
  1024. if headerJarFileWithoutDepsOrJarjar != nil {
  1025. flags.classpath = append(classpath{headerJarFileWithoutDepsOrJarjar}, flags.classpath...)
  1026. }
  1027. shardSize := int(*(j.properties.Javac_shard_size))
  1028. var shardSrcs []android.Paths
  1029. if len(uniqueJavaFiles) > 0 {
  1030. shardSrcs = android.ShardPaths(uniqueJavaFiles, shardSize)
  1031. for idx, shardSrc := range shardSrcs {
  1032. classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
  1033. nil, flags, extraJarDeps)
  1034. jars = append(jars, classes)
  1035. }
  1036. }
  1037. if len(srcJars) > 0 {
  1038. classes := j.compileJavaClasses(ctx, jarName, len(shardSrcs),
  1039. nil, srcJars, flags, extraJarDeps)
  1040. jars = append(jars, classes)
  1041. }
  1042. } else {
  1043. classes := j.compileJavaClasses(ctx, jarName, -1, uniqueJavaFiles, srcJars, flags, extraJarDeps)
  1044. jars = append(jars, classes)
  1045. }
  1046. if ctx.Failed() {
  1047. return
  1048. }
  1049. }
  1050. j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
  1051. var includeSrcJar android.WritablePath
  1052. if Bool(j.properties.Include_srcs) {
  1053. includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
  1054. TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
  1055. }
  1056. dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
  1057. j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
  1058. fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
  1059. extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
  1060. var resArgs []string
  1061. var resDeps android.Paths
  1062. resArgs = append(resArgs, dirArgs...)
  1063. resDeps = append(resDeps, dirDeps...)
  1064. resArgs = append(resArgs, fileArgs...)
  1065. resDeps = append(resDeps, fileDeps...)
  1066. resArgs = append(resArgs, extraArgs...)
  1067. resDeps = append(resDeps, extraDeps...)
  1068. if len(resArgs) > 0 {
  1069. resourceJar := android.PathForModuleOut(ctx, "res", jarName)
  1070. TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
  1071. j.resourceJar = resourceJar
  1072. if ctx.Failed() {
  1073. return
  1074. }
  1075. }
  1076. var resourceJars android.Paths
  1077. if j.resourceJar != nil {
  1078. resourceJars = append(resourceJars, j.resourceJar)
  1079. }
  1080. if Bool(j.properties.Include_srcs) {
  1081. resourceJars = append(resourceJars, includeSrcJar)
  1082. }
  1083. resourceJars = append(resourceJars, deps.staticResourceJars...)
  1084. if len(resourceJars) > 1 {
  1085. combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
  1086. TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
  1087. false, nil, nil)
  1088. j.resourceJar = combinedJar
  1089. } else if len(resourceJars) == 1 {
  1090. j.resourceJar = resourceJars[0]
  1091. }
  1092. if len(deps.staticJars) > 0 {
  1093. jars = append(jars, deps.staticJars...)
  1094. }
  1095. manifest := j.overrideManifest
  1096. if !manifest.Valid() && j.properties.Manifest != nil {
  1097. manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
  1098. }
  1099. services := android.PathsForModuleSrc(ctx, j.properties.Services)
  1100. if len(services) > 0 {
  1101. servicesJar := android.PathForModuleOut(ctx, "services", jarName)
  1102. var zipargs []string
  1103. for _, file := range services {
  1104. serviceFile := file.String()
  1105. zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
  1106. }
  1107. rule := zip
  1108. args := map[string]string{
  1109. "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
  1110. }
  1111. if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
  1112. rule = zipRE
  1113. args["implicits"] = strings.Join(services.Strings(), ",")
  1114. }
  1115. ctx.Build(pctx, android.BuildParams{
  1116. Rule: rule,
  1117. Output: servicesJar,
  1118. Implicits: services,
  1119. Args: args,
  1120. })
  1121. jars = append(jars, servicesJar)
  1122. }
  1123. // Combine the classes built from sources, any manifests, and any static libraries into
  1124. // classes.jar. If there is only one input jar this step will be skipped.
  1125. var outputFile android.OutputPath
  1126. if len(jars) == 1 && !manifest.Valid() {
  1127. // Optimization: skip the combine step as there is nothing to do
  1128. // TODO(ccross): this leaves any module-info.class files, but those should only come from
  1129. // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
  1130. // any if len(jars) == 1.
  1131. // Transform the single path to the jar into an OutputPath as that is required by the following
  1132. // code.
  1133. if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok {
  1134. // The path contains an embedded OutputPath so reuse that.
  1135. outputFile = moduleOutPath.OutputPath
  1136. } else if outputPath, ok := jars[0].(android.OutputPath); ok {
  1137. // The path is an OutputPath so reuse it directly.
  1138. outputFile = outputPath
  1139. } else {
  1140. // The file is not in the out directory so create an OutputPath into which it can be copied
  1141. // and which the following code can use to refer to it.
  1142. combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
  1143. ctx.Build(pctx, android.BuildParams{
  1144. Rule: android.Cp,
  1145. Input: jars[0],
  1146. Output: combinedJar,
  1147. })
  1148. outputFile = combinedJar.OutputPath
  1149. }
  1150. } else {
  1151. combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
  1152. TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
  1153. false, nil, nil)
  1154. outputFile = combinedJar.OutputPath
  1155. }
  1156. // jarjar implementation jar if necessary
  1157. if j.expandJarjarRules != nil {
  1158. // Transform classes.jar into classes-jarjar.jar
  1159. jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
  1160. TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
  1161. outputFile = jarjarFile
  1162. // jarjar resource jar if necessary
  1163. if j.resourceJar != nil {
  1164. resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
  1165. TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
  1166. j.resourceJar = resourceJarJarFile
  1167. }
  1168. if ctx.Failed() {
  1169. return
  1170. }
  1171. }
  1172. // Check package restrictions if necessary.
  1173. if len(j.properties.Permitted_packages) > 0 {
  1174. // Time stamp file created by the package check rule.
  1175. pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
  1176. // Create a rule to copy the output jar to another path and add a validate dependency that
  1177. // will check that the jar only contains the permitted packages. The new location will become
  1178. // the output file of this module.
  1179. inputFile := outputFile
  1180. outputFile = android.PathForModuleOut(ctx, "package-check", jarName).OutputPath
  1181. ctx.Build(pctx, android.BuildParams{
  1182. Rule: android.Cp,
  1183. Input: inputFile,
  1184. Output: outputFile,
  1185. // Make sure that any dependency on the output file will cause ninja to run the package check
  1186. // rule.
  1187. Validation: pkgckFile,
  1188. })
  1189. // Check packages and create a timestamp file when complete.
  1190. CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
  1191. if ctx.Failed() {
  1192. return
  1193. }
  1194. }
  1195. j.implementationJarFile = outputFile
  1196. if j.headerJarFile == nil {
  1197. j.headerJarFile = j.implementationJarFile
  1198. }
  1199. // enforce syntax check to jacoco filters for any build (http://b/183622051)
  1200. specs := j.jacocoModuleToZipCommand(ctx)
  1201. if ctx.Failed() {
  1202. return
  1203. }
  1204. if j.shouldInstrument(ctx) {
  1205. outputFile = j.instrument(ctx, flags, outputFile, jarName, specs)
  1206. }
  1207. // merge implementation jar with resources if necessary
  1208. implementationAndResourcesJar := outputFile
  1209. if j.resourceJar != nil {
  1210. jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
  1211. combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
  1212. TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
  1213. false, nil, nil)
  1214. implementationAndResourcesJar = combinedJar
  1215. }
  1216. j.implementationAndResourcesJar = implementationAndResourcesJar
  1217. // Enable dex compilation for the APEX variants, unless it is disabled explicitly
  1218. compileDex := j.dexProperties.Compile_dex
  1219. apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
  1220. if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
  1221. if compileDex == nil {
  1222. compileDex = proptools.BoolPtr(true)
  1223. }
  1224. if j.deviceProperties.Hostdex == nil {
  1225. j.deviceProperties.Hostdex = proptools.BoolPtr(true)
  1226. }
  1227. }
  1228. if ctx.Device() && (Bool(j.properties.Installable) || Bool(compileDex)) {
  1229. if j.hasCode(ctx) {
  1230. if j.shouldInstrumentStatic(ctx) {
  1231. j.dexer.extraProguardFlagFiles = append(j.dexer.extraProguardFlagFiles,
  1232. android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
  1233. }
  1234. // Dex compilation
  1235. var dexOutputFile android.OutputPath
  1236. dexOutputFile = j.dexer.compileDex(ctx, flags, j.MinSdkVersion(ctx), implementationAndResourcesJar, jarName)
  1237. if ctx.Failed() {
  1238. return
  1239. }
  1240. // merge dex jar with resources if necessary
  1241. if j.resourceJar != nil {
  1242. jars := android.Paths{dexOutputFile, j.resourceJar}
  1243. combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
  1244. TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
  1245. false, nil, nil)
  1246. if *j.dexProperties.Uncompress_dex {
  1247. combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
  1248. TransformZipAlign(ctx, combinedAlignedJar, combinedJar)
  1249. dexOutputFile = combinedAlignedJar
  1250. } else {
  1251. dexOutputFile = combinedJar
  1252. }
  1253. }
  1254. // Initialize the hiddenapi structure.
  1255. j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), j.implementationJarFile, j.dexProperties.Uncompress_dex)
  1256. // Encode hidden API flags in dex file, if needed.
  1257. dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
  1258. j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
  1259. // Dexpreopting
  1260. j.dexpreopt(ctx, dexOutputFile)
  1261. outputFile = dexOutputFile
  1262. } else {
  1263. // There is no code to compile into a dex jar, make sure the resources are propagated
  1264. // to the APK if this is an app.
  1265. outputFile = implementationAndResourcesJar
  1266. j.dexJarFile = makeDexJarPathFromPath(j.resourceJar)
  1267. }
  1268. if ctx.Failed() {
  1269. return
  1270. }
  1271. } else {
  1272. outputFile = implementationAndResourcesJar
  1273. }
  1274. if ctx.Device() {
  1275. lintSDKVersion := func(sdkSpec android.SdkSpec) int {
  1276. if v := sdkSpec.ApiLevel; !v.IsPreview() {
  1277. return v.FinalInt()
  1278. } else {
  1279. // When running metalava, we pass --version-codename. When that value
  1280. // is not REL, metalava will add 1 to the --current-version argument.
  1281. // On old branches, PLATFORM_SDK_VERSION is the latest version (for that
  1282. // branch) and the codename is REL, except potentially on the most
  1283. // recent non-master branch. On that branch, it goes through two other
  1284. // phases before it gets to the phase previously described:
  1285. // - PLATFORM_SDK_VERSION has not been updated yet, and the codename
  1286. // is not rel. This happens for most of the internal branch's life
  1287. // while the branch has been cut but is still under active development.
  1288. // - PLATFORM_SDK_VERSION has been set, but the codename is still not
  1289. // REL. This happens briefly during the release process. During this
  1290. // state the code to add --current-version is commented out, and then
  1291. // that commenting out is reverted after the codename is set to REL.
  1292. // On the master branch, the PLATFORM_SDK_VERSION always represents a
  1293. // prior version and the codename is always non-REL.
  1294. //
  1295. // We need to add one here to match metalava adding 1. Technically
  1296. // this means that in the state described in the second bullet point
  1297. // above, this number is 1 higher than it should be.
  1298. return ctx.Config().PlatformSdkVersion().FinalInt() + 1
  1299. }
  1300. }
  1301. j.linter.name = ctx.ModuleName()
  1302. j.linter.srcs = append(srcFiles, nonGeneratedSrcJars...)
  1303. j.linter.srcJars, _ = android.FilterPathList(srcJars, nonGeneratedSrcJars)
  1304. j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
  1305. j.linter.classes = j.implementationJarFile
  1306. j.linter.minSdkVersion = lintSDKVersion(j.MinSdkVersion(ctx))
  1307. j.linter.targetSdkVersion = lintSDKVersion(j.TargetSdkVersion(ctx))
  1308. j.linter.compileSdkVersion = lintSDKVersion(j.SdkVersion(ctx))
  1309. j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
  1310. j.linter.javaLanguageLevel = flags.javaVersion.String()
  1311. j.linter.kotlinLanguageLevel = "1.3"
  1312. if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
  1313. j.linter.buildModuleReportZip = true
  1314. }
  1315. j.linter.lint(ctx)
  1316. }
  1317. ctx.CheckbuildFile(outputFile)
  1318. ctx.SetProvider(JavaInfoProvider, JavaInfo{
  1319. HeaderJars: android.PathsIfNonNil(j.headerJarFile),
  1320. TransitiveLibsHeaderJars: j.transitiveLibsHeaderJars,
  1321. TransitiveStaticLibsHeaderJars: j.transitiveStaticLibsHeaderJars,
  1322. ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
  1323. ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
  1324. ResourceJars: android.PathsIfNonNil(j.resourceJar),
  1325. AidlIncludeDirs: j.exportAidlIncludeDirs,
  1326. SrcJarArgs: j.srcJarArgs,
  1327. SrcJarDeps: j.srcJarDeps,
  1328. ExportedPlugins: j.exportedPluginJars,
  1329. ExportedPluginClasses: j.exportedPluginClasses,
  1330. ExportedPluginDisableTurbine: j.exportedDisableTurbine,
  1331. JacocoReportClassesFile: j.jacocoReportClassesFile,
  1332. })
  1333. // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
  1334. j.outputFile = outputFile.WithoutRel()
  1335. }
  1336. func (j *Module) useCompose() bool {
  1337. return android.InList("androidx.compose.runtime_runtime", j.properties.Static_libs)
  1338. }
  1339. // Returns a copy of the supplied flags, but with all the errorprone-related
  1340. // fields copied to the regular build's fields.
  1341. func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
  1342. flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
  1343. if len(flags.errorProneExtraJavacFlags) > 0 {
  1344. if len(flags.javacFlags) > 0 {
  1345. flags.javacFlags += " " + flags.errorProneExtraJavacFlags
  1346. } else {
  1347. flags.javacFlags = flags.errorProneExtraJavacFlags
  1348. }
  1349. }
  1350. return flags
  1351. }
  1352. func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
  1353. srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
  1354. kzipName := pathtools.ReplaceExtension(jarName, "kzip")
  1355. if idx >= 0 {
  1356. kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
  1357. jarName += strconv.Itoa(idx)
  1358. }
  1359. classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
  1360. TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, flags, extraJarDeps)
  1361. if ctx.Config().EmitXrefRules() {
  1362. extractionFile := android.PathForModuleOut(ctx, kzipName)
  1363. emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
  1364. j.kytheFiles = append(j.kytheFiles, extractionFile)
  1365. }
  1366. return classes
  1367. }
  1368. // Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
  1369. // since some of these flags may be used internally.
  1370. func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
  1371. for _, flag := range flags {
  1372. flag = strings.TrimSpace(flag)
  1373. if !strings.HasPrefix(flag, "-") {
  1374. ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
  1375. } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
  1376. ctx.PropertyErrorf("kotlincflags",
  1377. "Bad flag: `%s`, only use internal compiler for consistency.", flag)
  1378. } else if inList(flag, config.KotlincIllegalFlags) {
  1379. ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
  1380. } else if flag == "-include-runtime" {
  1381. ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
  1382. } else {
  1383. args := strings.Split(flag, " ")
  1384. if args[0] == "-kotlin-home" {
  1385. ctx.PropertyErrorf("kotlincflags",
  1386. "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
  1387. }
  1388. }
  1389. }
  1390. }
  1391. func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
  1392. deps deps, flags javaBuilderFlags, jarName string,
  1393. extraJars android.Paths) (headerJar, jarjarAndDepsHeaderJar android.Path) {
  1394. var jars android.Paths
  1395. if len(srcFiles) > 0 || len(srcJars) > 0 {
  1396. // Compile java sources into turbine.jar.
  1397. turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
  1398. TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
  1399. if ctx.Failed() {
  1400. return nil, nil
  1401. }
  1402. jars = append(jars, turbineJar)
  1403. headerJar = turbineJar
  1404. }
  1405. jars = append(jars, extraJars...)
  1406. // Combine any static header libraries into classes-header.jar. If there is only
  1407. // one input jar this step will be skipped.
  1408. jars = append(jars, deps.staticHeaderJars...)
  1409. // we cannot skip the combine step for now if there is only one jar
  1410. // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
  1411. combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
  1412. TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
  1413. false, nil, []string{"META-INF/TRANSITIVE"})
  1414. jarjarAndDepsHeaderJar = combinedJar
  1415. if j.expandJarjarRules != nil {
  1416. // Transform classes.jar into classes-jarjar.jar
  1417. jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
  1418. TransformJarJar(ctx, jarjarFile, jarjarAndDepsHeaderJar, j.expandJarjarRules)
  1419. jarjarAndDepsHeaderJar = jarjarFile
  1420. if ctx.Failed() {
  1421. return nil, nil
  1422. }
  1423. }
  1424. return headerJar, jarjarAndDepsHeaderJar
  1425. }
  1426. func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
  1427. classesJar android.Path, jarName string, specs string) android.OutputPath {
  1428. jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
  1429. instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
  1430. jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
  1431. j.jacocoReportClassesFile = jacocoReportClassesFile
  1432. return instrumentedJar
  1433. }
  1434. type providesTransitiveHeaderJars struct {
  1435. // set of header jars for all transitive libs deps
  1436. transitiveLibsHeaderJars *android.DepSet
  1437. // set of header jars for all transitive static libs deps
  1438. transitiveStaticLibsHeaderJars *android.DepSet
  1439. }
  1440. func (j *providesTransitiveHeaderJars) TransitiveLibsHeaderJars() *android.DepSet {
  1441. return j.transitiveLibsHeaderJars
  1442. }
  1443. func (j *providesTransitiveHeaderJars) TransitiveStaticLibsHeaderJars() *android.DepSet {
  1444. return j.transitiveStaticLibsHeaderJars
  1445. }
  1446. func (j *providesTransitiveHeaderJars) collectTransitiveHeaderJars(ctx android.ModuleContext) {
  1447. directLibs := android.Paths{}
  1448. directStaticLibs := android.Paths{}
  1449. transitiveLibs := []*android.DepSet{}
  1450. transitiveStaticLibs := []*android.DepSet{}
  1451. ctx.VisitDirectDeps(func(module android.Module) {
  1452. // don't add deps of the prebuilt version of the same library
  1453. if ctx.ModuleName() == android.RemoveOptionalPrebuiltPrefix(module.Name()) {
  1454. return
  1455. }
  1456. dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
  1457. if dep.TransitiveLibsHeaderJars != nil {
  1458. transitiveLibs = append(transitiveLibs, dep.TransitiveLibsHeaderJars)
  1459. }
  1460. if dep.TransitiveStaticLibsHeaderJars != nil {
  1461. transitiveStaticLibs = append(transitiveStaticLibs, dep.TransitiveStaticLibsHeaderJars)
  1462. }
  1463. tag := ctx.OtherModuleDependencyTag(module)
  1464. _, isUsesLibDep := tag.(usesLibraryDependencyTag)
  1465. if tag == libTag || tag == r8LibraryJarTag || isUsesLibDep {
  1466. directLibs = append(directLibs, dep.HeaderJars...)
  1467. } else if tag == staticLibTag {
  1468. directStaticLibs = append(directStaticLibs, dep.HeaderJars...)
  1469. }
  1470. })
  1471. j.transitiveLibsHeaderJars = android.NewDepSet(android.POSTORDER, directLibs, transitiveLibs)
  1472. j.transitiveStaticLibsHeaderJars = android.NewDepSet(android.POSTORDER, directStaticLibs, transitiveStaticLibs)
  1473. }
  1474. func (j *Module) HeaderJars() android.Paths {
  1475. if j.headerJarFile == nil {
  1476. return nil
  1477. }
  1478. return android.Paths{j.headerJarFile}
  1479. }
  1480. func (j *Module) ImplementationJars() android.Paths {
  1481. if j.implementationJarFile == nil {
  1482. return nil
  1483. }
  1484. return android.Paths{j.implementationJarFile}
  1485. }
  1486. func (j *Module) DexJarBuildPath() OptionalDexJarPath {
  1487. return j.dexJarFile
  1488. }
  1489. func (j *Module) DexJarInstallPath() android.Path {
  1490. return j.installFile
  1491. }
  1492. func (j *Module) ImplementationAndResourcesJars() android.Paths {
  1493. if j.implementationAndResourcesJar == nil {
  1494. return nil
  1495. }
  1496. return android.Paths{j.implementationAndResourcesJar}
  1497. }
  1498. func (j *Module) AidlIncludeDirs() android.Paths {
  1499. // exportAidlIncludeDirs is type android.Paths already
  1500. return j.exportAidlIncludeDirs
  1501. }
  1502. func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
  1503. return j.classLoaderContexts
  1504. }
  1505. // Collect information for opening IDE project files in java/jdeps.go.
  1506. func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
  1507. dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
  1508. dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
  1509. dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
  1510. dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
  1511. if j.expandJarjarRules != nil {
  1512. dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
  1513. }
  1514. dpInfo.Paths = append(dpInfo.Paths, j.modulePaths...)
  1515. dpInfo.Static_libs = append(dpInfo.Static_libs, j.properties.Static_libs...)
  1516. dpInfo.Libs = append(dpInfo.Libs, j.properties.Libs...)
  1517. }
  1518. func (j *Module) CompilerDeps() []string {
  1519. jdeps := []string{}
  1520. jdeps = append(jdeps, j.properties.Libs...)
  1521. jdeps = append(jdeps, j.properties.Static_libs...)
  1522. return jdeps
  1523. }
  1524. func (j *Module) hasCode(ctx android.ModuleContext) bool {
  1525. srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
  1526. return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
  1527. }
  1528. // Implements android.ApexModule
  1529. func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
  1530. return j.depIsInSameApex(ctx, dep)
  1531. }
  1532. // Implements android.ApexModule
  1533. func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
  1534. sdkSpec := j.MinSdkVersion(ctx)
  1535. if !sdkSpec.Specified() {
  1536. return fmt.Errorf("min_sdk_version is not specified")
  1537. }
  1538. if sdkSpec.Kind == android.SdkCore {
  1539. return nil
  1540. }
  1541. if sdkSpec.ApiLevel.GreaterThan(sdkVersion) {
  1542. return fmt.Errorf("newer SDK(%v)", sdkSpec.ApiLevel)
  1543. }
  1544. return nil
  1545. }
  1546. func (j *Module) Stem() string {
  1547. return proptools.StringDefault(j.overridableDeviceProperties.Stem, j.Name())
  1548. }
  1549. func (j *Module) JacocoReportClassesFile() android.Path {
  1550. return j.jacocoReportClassesFile
  1551. }
  1552. func (j *Module) IsInstallable() bool {
  1553. return Bool(j.properties.Installable)
  1554. }
  1555. type sdkLinkType int
  1556. const (
  1557. // TODO(jiyong) rename these for better readability. Make the allowed
  1558. // and disallowed link types explicit
  1559. // order is important here. See rank()
  1560. javaCore sdkLinkType = iota
  1561. javaSdk
  1562. javaSystem
  1563. javaModule
  1564. javaSystemServer
  1565. javaPlatform
  1566. )
  1567. func (lt sdkLinkType) String() string {
  1568. switch lt {
  1569. case javaCore:
  1570. return "core Java API"
  1571. case javaSdk:
  1572. return "Android API"
  1573. case javaSystem:
  1574. return "system API"
  1575. case javaModule:
  1576. return "module API"
  1577. case javaSystemServer:
  1578. return "system server API"
  1579. case javaPlatform:
  1580. return "private API"
  1581. default:
  1582. panic(fmt.Errorf("unrecognized linktype: %d", lt))
  1583. }
  1584. }
  1585. // rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
  1586. // another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
  1587. // can't statically depend on modules that use Platform API.
  1588. func (lt sdkLinkType) rank() int {
  1589. return int(lt)
  1590. }
  1591. type moduleWithSdkDep interface {
  1592. android.Module
  1593. getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
  1594. }
  1595. func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
  1596. switch name {
  1597. case "core.current.stubs", "legacy.core.platform.api.stubs", "stable.core.platform.api.stubs",
  1598. "stub-annotations", "private-stub-annotations-jar",
  1599. "core-lambda-stubs", "core-generated-annotation-stubs":
  1600. return javaCore, true
  1601. case "android_stubs_current":
  1602. return javaSdk, true
  1603. case "android_system_stubs_current":
  1604. return javaSystem, true
  1605. case "android_module_lib_stubs_current":
  1606. return javaModule, true
  1607. case "android_system_server_stubs_current":
  1608. return javaSystemServer, true
  1609. case "android_test_stubs_current":
  1610. return javaSystem, true
  1611. }
  1612. if stub, linkType := moduleStubLinkType(name); stub {
  1613. return linkType, true
  1614. }
  1615. ver := m.SdkVersion(ctx)
  1616. switch ver.Kind {
  1617. case android.SdkCore:
  1618. return javaCore, false
  1619. case android.SdkSystem:
  1620. return javaSystem, false
  1621. case android.SdkPublic:
  1622. return javaSdk, false
  1623. case android.SdkModule:
  1624. return javaModule, false
  1625. case android.SdkSystemServer:
  1626. return javaSystemServer, false
  1627. case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
  1628. return javaPlatform, false
  1629. }
  1630. if !ver.Valid() {
  1631. panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
  1632. }
  1633. return javaSdk, false
  1634. }
  1635. // checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
  1636. // this module's. See the comment on rank() for details and an example.
  1637. func (j *Module) checkSdkLinkType(
  1638. ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
  1639. if ctx.Host() {
  1640. return
  1641. }
  1642. myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
  1643. if stubs {
  1644. return
  1645. }
  1646. depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
  1647. if myLinkType.rank() < depLinkType.rank() {
  1648. ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
  1649. "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
  1650. "property of the source or target module so that target module is built "+
  1651. "with the same or smaller API set when compared to the source.",
  1652. myLinkType, ctx.OtherModuleName(dep), depLinkType)
  1653. }
  1654. }
  1655. func (j *Module) collectDeps(ctx android.ModuleContext) deps {
  1656. var deps deps
  1657. if ctx.Device() {
  1658. sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
  1659. if sdkDep.invalidVersion {
  1660. ctx.AddMissingDependencies(sdkDep.bootclasspath)
  1661. ctx.AddMissingDependencies(sdkDep.java9Classpath)
  1662. } else if sdkDep.useFiles {
  1663. // sdkDep.jar is actually equivalent to turbine header.jar.
  1664. deps.classpath = append(deps.classpath, sdkDep.jars...)
  1665. deps.dexClasspath = append(deps.dexClasspath, sdkDep.jars...)
  1666. deps.aidlPreprocess = sdkDep.aidl
  1667. } else {
  1668. deps.aidlPreprocess = sdkDep.aidl
  1669. }
  1670. }
  1671. sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
  1672. j.collectTransitiveHeaderJars(ctx)
  1673. ctx.VisitDirectDeps(func(module android.Module) {
  1674. otherName := ctx.OtherModuleName(module)
  1675. tag := ctx.OtherModuleDependencyTag(module)
  1676. if IsJniDepTag(tag) {
  1677. // Handled by AndroidApp.collectAppDeps
  1678. return
  1679. }
  1680. if tag == certificateTag {
  1681. // Handled by AndroidApp.collectAppDeps
  1682. return
  1683. }
  1684. if dep, ok := module.(SdkLibraryDependency); ok {
  1685. switch tag {
  1686. case sdkLibTag, libTag:
  1687. depHeaderJars := dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))
  1688. deps.classpath = append(deps.classpath, depHeaderJars...)
  1689. deps.dexClasspath = append(deps.dexClasspath, depHeaderJars...)
  1690. case staticLibTag:
  1691. ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
  1692. }
  1693. } else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
  1694. dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
  1695. if sdkLinkType != javaPlatform &&
  1696. ctx.OtherModuleHasProvider(module, SyspropPublicStubInfoProvider) {
  1697. // dep is a sysprop implementation library, but this module is not linking against
  1698. // the platform, so it gets the sysprop public stubs library instead. Replace
  1699. // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
  1700. syspropDep := ctx.OtherModuleProvider(module, SyspropPublicStubInfoProvider).(SyspropPublicStubInfo)
  1701. dep = syspropDep.JavaInfo
  1702. }
  1703. switch tag {
  1704. case bootClasspathTag:
  1705. deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
  1706. case sdkLibTag, libTag, instrumentationForTag:
  1707. if _, ok := module.(*Plugin); ok {
  1708. ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a libs dependency", otherName)
  1709. }
  1710. deps.classpath = append(deps.classpath, dep.HeaderJars...)
  1711. deps.dexClasspath = append(deps.dexClasspath, dep.HeaderJars...)
  1712. deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
  1713. addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
  1714. deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
  1715. case java9LibTag:
  1716. deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
  1717. case staticLibTag:
  1718. if _, ok := module.(*Plugin); ok {
  1719. ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a static_libs dependency", otherName)
  1720. }
  1721. deps.classpath = append(deps.classpath, dep.HeaderJars...)
  1722. deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
  1723. deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
  1724. deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
  1725. deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
  1726. addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
  1727. // Turbine doesn't run annotation processors, so any module that uses an
  1728. // annotation processor that generates API is incompatible with the turbine
  1729. // optimization.
  1730. deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
  1731. case pluginTag:
  1732. if plugin, ok := module.(*Plugin); ok {
  1733. if plugin.pluginProperties.Processor_class != nil {
  1734. addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
  1735. } else {
  1736. addPlugins(&deps, dep.ImplementationAndResourcesJars)
  1737. }
  1738. // Turbine doesn't run annotation processors, so any module that uses an
  1739. // annotation processor that generates API is incompatible with the turbine
  1740. // optimization.
  1741. deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
  1742. } else {
  1743. ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
  1744. }
  1745. case errorpronePluginTag:
  1746. if _, ok := module.(*Plugin); ok {
  1747. deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
  1748. } else {
  1749. ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
  1750. }
  1751. case exportedPluginTag:
  1752. if plugin, ok := module.(*Plugin); ok {
  1753. j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
  1754. if plugin.pluginProperties.Processor_class != nil {
  1755. j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
  1756. }
  1757. // Turbine doesn't run annotation processors, so any module that uses an
  1758. // annotation processor that generates API is incompatible with the turbine
  1759. // optimization.
  1760. j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
  1761. } else {
  1762. ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
  1763. }
  1764. case kotlinStdlibTag:
  1765. deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
  1766. case kotlinAnnotationsTag:
  1767. deps.kotlinAnnotations = dep.HeaderJars
  1768. case kotlinPluginTag:
  1769. deps.kotlinPlugins = append(deps.kotlinPlugins, dep.ImplementationAndResourcesJars...)
  1770. case syspropPublicStubDepTag:
  1771. // This is a sysprop implementation library, forward the JavaInfoProvider from
  1772. // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
  1773. ctx.SetProvider(SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
  1774. JavaInfo: dep,
  1775. })
  1776. }
  1777. } else if dep, ok := module.(android.SourceFileProducer); ok {
  1778. switch tag {
  1779. case sdkLibTag, libTag:
  1780. checkProducesJars(ctx, dep)
  1781. deps.classpath = append(deps.classpath, dep.Srcs()...)
  1782. deps.dexClasspath = append(deps.classpath, dep.Srcs()...)
  1783. case staticLibTag:
  1784. checkProducesJars(ctx, dep)
  1785. deps.classpath = append(deps.classpath, dep.Srcs()...)
  1786. deps.staticJars = append(deps.staticJars, dep.Srcs()...)
  1787. deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
  1788. }
  1789. } else {
  1790. switch tag {
  1791. case bootClasspathTag:
  1792. // If a system modules dependency has been added to the bootclasspath
  1793. // then add its libs to the bootclasspath.
  1794. sm := module.(SystemModulesProvider)
  1795. deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
  1796. case systemModulesTag:
  1797. if deps.systemModules != nil {
  1798. panic("Found two system module dependencies")
  1799. }
  1800. sm := module.(SystemModulesProvider)
  1801. outputDir, outputDeps := sm.OutputDirAndDeps()
  1802. deps.systemModules = &systemModules{outputDir, outputDeps}
  1803. case instrumentationForTag:
  1804. ctx.PropertyErrorf("instrumentation_for", "dependency %q of type %q does not provide JavaInfo so is unsuitable for use with this property", ctx.OtherModuleName(module), ctx.OtherModuleType(module))
  1805. }
  1806. }
  1807. addCLCFromDep(ctx, module, j.classLoaderContexts)
  1808. })
  1809. return deps
  1810. }
  1811. func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
  1812. deps.processorPath = append(deps.processorPath, pluginJars...)
  1813. deps.processorClasses = append(deps.processorClasses, pluginClasses...)
  1814. }
  1815. // TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
  1816. // this interface.
  1817. type ProvidesUsesLib interface {
  1818. ProvidesUsesLib() *string
  1819. }
  1820. func (j *Module) ProvidesUsesLib() *string {
  1821. return j.usesLibraryProperties.Provides_uses_lib
  1822. }
  1823. type ModuleWithStem interface {
  1824. Stem() string
  1825. }
  1826. var _ ModuleWithStem = (*Module)(nil)
  1827. func (j *Module) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
  1828. switch ctx.ModuleType() {
  1829. case "java_library", "java_library_host", "java_library_static":
  1830. if lib, ok := ctx.Module().(*Library); ok {
  1831. javaLibraryBp2Build(ctx, lib)
  1832. }
  1833. case "java_binary_host":
  1834. if binary, ok := ctx.Module().(*Binary); ok {
  1835. javaBinaryHostBp2Build(ctx, binary)
  1836. }
  1837. }
  1838. }