base.go 80 KB

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