base.go 81 KB

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