base.go 81 KB

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