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