base.go 81 KB

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