java.go 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595
  1. // Copyright 2015 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. // This file contains the module types for compiling Java for Android, and converts the properties
  16. // into the flags and filenames necessary to pass to the Module. The final creation of the rules
  17. // is handled in builder.go
  18. import (
  19. "fmt"
  20. "path/filepath"
  21. "strings"
  22. "android/soong/bazel"
  23. "android/soong/bazel/cquery"
  24. "github.com/google/blueprint"
  25. "github.com/google/blueprint/proptools"
  26. "android/soong/android"
  27. "android/soong/cc"
  28. "android/soong/dexpreopt"
  29. "android/soong/java/config"
  30. "android/soong/tradefed"
  31. )
  32. func init() {
  33. registerJavaBuildComponents(android.InitRegistrationContext)
  34. RegisterJavaSdkMemberTypes()
  35. }
  36. func registerJavaBuildComponents(ctx android.RegistrationContext) {
  37. ctx.RegisterModuleType("java_defaults", DefaultsFactory)
  38. ctx.RegisterModuleType("java_library", LibraryFactory)
  39. ctx.RegisterModuleType("java_library_static", LibraryStaticFactory)
  40. ctx.RegisterModuleType("java_library_host", LibraryHostFactory)
  41. ctx.RegisterModuleType("java_binary", BinaryFactory)
  42. ctx.RegisterModuleType("java_binary_host", BinaryHostFactory)
  43. ctx.RegisterModuleType("java_test", TestFactory)
  44. ctx.RegisterModuleType("java_test_helper_library", TestHelperLibraryFactory)
  45. ctx.RegisterModuleType("java_test_host", TestHostFactory)
  46. ctx.RegisterModuleType("java_test_import", JavaTestImportFactory)
  47. ctx.RegisterModuleType("java_import", ImportFactory)
  48. ctx.RegisterModuleType("java_import_host", ImportFactoryHost)
  49. ctx.RegisterModuleType("java_device_for_host", DeviceForHostFactory)
  50. ctx.RegisterModuleType("java_host_for_device", HostForDeviceFactory)
  51. ctx.RegisterModuleType("dex_import", DexImportFactory)
  52. // This mutator registers dependencies on dex2oat for modules that should be
  53. // dexpreopted. This is done late when the final variants have been
  54. // established, to not get the dependencies split into the wrong variants and
  55. // to support the checks in dexpreoptDisabled().
  56. ctx.FinalDepsMutators(func(ctx android.RegisterMutatorsContext) {
  57. ctx.BottomUp("dexpreopt_tool_deps", dexpreoptToolDepsMutator).Parallel()
  58. // needs access to ApexInfoProvider which is available after variant creation
  59. ctx.BottomUp("jacoco_deps", jacocoDepsMutator).Parallel()
  60. })
  61. ctx.RegisterSingletonType("logtags", LogtagsSingleton)
  62. ctx.RegisterSingletonType("kythe_java_extract", kytheExtractJavaFactory)
  63. }
  64. func RegisterJavaSdkMemberTypes() {
  65. // Register sdk member types.
  66. android.RegisterSdkMemberType(javaHeaderLibsSdkMemberType)
  67. android.RegisterSdkMemberType(javaLibsSdkMemberType)
  68. android.RegisterSdkMemberType(javaBootLibsSdkMemberType)
  69. android.RegisterSdkMemberType(javaSystemserverLibsSdkMemberType)
  70. android.RegisterSdkMemberType(javaTestSdkMemberType)
  71. }
  72. var (
  73. // Supports adding java header libraries to module_exports and sdk.
  74. javaHeaderLibsSdkMemberType = &librarySdkMemberType{
  75. android.SdkMemberTypeBase{
  76. PropertyName: "java_header_libs",
  77. SupportsSdk: true,
  78. },
  79. func(_ android.SdkMemberContext, j *Library) android.Path {
  80. headerJars := j.HeaderJars()
  81. if len(headerJars) != 1 {
  82. panic(fmt.Errorf("there must be only one header jar from %q", j.Name()))
  83. }
  84. return headerJars[0]
  85. },
  86. sdkSnapshotFilePathForJar,
  87. copyEverythingToSnapshot,
  88. }
  89. // Export implementation classes jar as part of the sdk.
  90. exportImplementationClassesJar = func(_ android.SdkMemberContext, j *Library) android.Path {
  91. implementationJars := j.ImplementationAndResourcesJars()
  92. if len(implementationJars) != 1 {
  93. panic(fmt.Errorf("there must be only one implementation jar from %q", j.Name()))
  94. }
  95. return implementationJars[0]
  96. }
  97. // Supports adding java implementation libraries to module_exports but not sdk.
  98. javaLibsSdkMemberType = &librarySdkMemberType{
  99. android.SdkMemberTypeBase{
  100. PropertyName: "java_libs",
  101. },
  102. exportImplementationClassesJar,
  103. sdkSnapshotFilePathForJar,
  104. copyEverythingToSnapshot,
  105. }
  106. snapshotRequiresImplementationJar = func(ctx android.SdkMemberContext) bool {
  107. // In the S build the build will break if updatable-media does not provide a full implementation
  108. // jar. That issue was fixed in Tiramisu by b/229932396.
  109. if ctx.IsTargetBuildBeforeTiramisu() && ctx.Name() == "updatable-media" {
  110. return true
  111. }
  112. return false
  113. }
  114. // Supports adding java boot libraries to module_exports and sdk.
  115. //
  116. // The build has some implicit dependencies (via the boot jars configuration) on a number of
  117. // modules, e.g. core-oj, apache-xml, that are part of the java boot class path and which are
  118. // provided by mainline modules (e.g. art, conscrypt, runtime-i18n) but which are not otherwise
  119. // used outside those mainline modules.
  120. //
  121. // As they are not needed outside the mainline modules adding them to the sdk/module-exports as
  122. // either java_libs, or java_header_libs would end up exporting more information than was strictly
  123. // necessary. The java_boot_libs property to allow those modules to be exported as part of the
  124. // sdk/module_exports without exposing any unnecessary information.
  125. javaBootLibsSdkMemberType = &librarySdkMemberType{
  126. android.SdkMemberTypeBase{
  127. PropertyName: "java_boot_libs",
  128. SupportsSdk: true,
  129. },
  130. func(ctx android.SdkMemberContext, j *Library) android.Path {
  131. if snapshotRequiresImplementationJar(ctx) {
  132. return exportImplementationClassesJar(ctx, j)
  133. }
  134. // Java boot libs are only provided in the SDK to provide access to their dex implementation
  135. // jar for use by dexpreopting and boot jars package check. They do not need to provide an
  136. // actual implementation jar but the java_import will need a file that exists so just copy an
  137. // empty file. Any attempt to use that file as a jar will cause a build error.
  138. return ctx.SnapshotBuilder().EmptyFile()
  139. },
  140. func(ctx android.SdkMemberContext, osPrefix, name string) string {
  141. if snapshotRequiresImplementationJar(ctx) {
  142. return sdkSnapshotFilePathForJar(ctx, osPrefix, name)
  143. }
  144. // Create a special name for the implementation jar to try and provide some useful information
  145. // to a developer that attempts to compile against this.
  146. // TODO(b/175714559): Provide a proper error message in Soong not ninja.
  147. return filepath.Join(osPrefix, "java_boot_libs", "snapshot", "jars", "are", "invalid", name+jarFileSuffix)
  148. },
  149. onlyCopyJarToSnapshot,
  150. }
  151. // Supports adding java systemserver libraries to module_exports and sdk.
  152. //
  153. // The build has some implicit dependencies (via the systemserver jars configuration) on a number
  154. // of modules that are part of the java systemserver classpath and which are provided by mainline
  155. // modules but which are not otherwise used outside those mainline modules.
  156. //
  157. // As they are not needed outside the mainline modules adding them to the sdk/module-exports as
  158. // either java_libs, or java_header_libs would end up exporting more information than was strictly
  159. // necessary. The java_systemserver_libs property to allow those modules to be exported as part of
  160. // the sdk/module_exports without exposing any unnecessary information.
  161. javaSystemserverLibsSdkMemberType = &librarySdkMemberType{
  162. android.SdkMemberTypeBase{
  163. PropertyName: "java_systemserver_libs",
  164. SupportsSdk: true,
  165. // This was only added in Tiramisu.
  166. SupportedBuildReleaseSpecification: "Tiramisu+",
  167. },
  168. func(ctx android.SdkMemberContext, j *Library) android.Path {
  169. // Java systemserver libs are only provided in the SDK to provide access to their dex
  170. // implementation jar for use by dexpreopting. They do not need to provide an actual
  171. // implementation jar but the java_import will need a file that exists so just copy an empty
  172. // file. Any attempt to use that file as a jar will cause a build error.
  173. return ctx.SnapshotBuilder().EmptyFile()
  174. },
  175. func(_ android.SdkMemberContext, osPrefix, name string) string {
  176. // Create a special name for the implementation jar to try and provide some useful information
  177. // to a developer that attempts to compile against this.
  178. // TODO(b/175714559): Provide a proper error message in Soong not ninja.
  179. return filepath.Join(osPrefix, "java_systemserver_libs", "snapshot", "jars", "are", "invalid", name+jarFileSuffix)
  180. },
  181. onlyCopyJarToSnapshot,
  182. }
  183. // Supports adding java test libraries to module_exports but not sdk.
  184. javaTestSdkMemberType = &testSdkMemberType{
  185. SdkMemberTypeBase: android.SdkMemberTypeBase{
  186. PropertyName: "java_tests",
  187. },
  188. }
  189. )
  190. // JavaInfo contains information about a java module for use by modules that depend on it.
  191. type JavaInfo struct {
  192. // HeaderJars is a list of jars that can be passed as the javac classpath in order to link
  193. // against this module. If empty, ImplementationJars should be used instead.
  194. HeaderJars android.Paths
  195. // ImplementationAndResourceJars is a list of jars that contain the implementations of classes
  196. // in the module as well as any resources included in the module.
  197. ImplementationAndResourcesJars android.Paths
  198. // ImplementationJars is a list of jars that contain the implementations of classes in the
  199. //module.
  200. ImplementationJars android.Paths
  201. // ResourceJars is a list of jars that contain the resources included in the module.
  202. ResourceJars android.Paths
  203. // AidlIncludeDirs is a list of directories that should be passed to the aidl tool when
  204. // depending on this module.
  205. AidlIncludeDirs android.Paths
  206. // SrcJarArgs is a list of arguments to pass to soong_zip to package the sources of this
  207. // module.
  208. SrcJarArgs []string
  209. // SrcJarDeps is a list of paths to depend on when packaging the sources of this module.
  210. SrcJarDeps android.Paths
  211. // ExportedPlugins is a list of paths that should be used as annotation processors for any
  212. // module that depends on this module.
  213. ExportedPlugins android.Paths
  214. // ExportedPluginClasses is a list of classes that should be run as annotation processors for
  215. // any module that depends on this module.
  216. ExportedPluginClasses []string
  217. // ExportedPluginDisableTurbine is true if this module's annotation processors generate APIs,
  218. // requiring disbling turbine for any modules that depend on it.
  219. ExportedPluginDisableTurbine bool
  220. // JacocoReportClassesFile is the path to a jar containing uninstrumented classes that will be
  221. // instrumented by jacoco.
  222. JacocoReportClassesFile android.Path
  223. }
  224. var JavaInfoProvider = blueprint.NewProvider(JavaInfo{})
  225. // SyspropPublicStubInfo contains info about the sysprop public stub library that corresponds to
  226. // the sysprop implementation library.
  227. type SyspropPublicStubInfo struct {
  228. // JavaInfo is the JavaInfoProvider of the sysprop public stub library that corresponds to
  229. // the sysprop implementation library.
  230. JavaInfo JavaInfo
  231. }
  232. var SyspropPublicStubInfoProvider = blueprint.NewProvider(SyspropPublicStubInfo{})
  233. // Methods that need to be implemented for a module that is added to apex java_libs property.
  234. type ApexDependency interface {
  235. HeaderJars() android.Paths
  236. ImplementationAndResourcesJars() android.Paths
  237. }
  238. // Provides build path and install path to DEX jars.
  239. type UsesLibraryDependency interface {
  240. DexJarBuildPath() OptionalDexJarPath
  241. DexJarInstallPath() android.Path
  242. ClassLoaderContexts() dexpreopt.ClassLoaderContextMap
  243. }
  244. // TODO(jungjw): Move this to kythe.go once it's created.
  245. type xref interface {
  246. XrefJavaFiles() android.Paths
  247. }
  248. func (j *Module) XrefJavaFiles() android.Paths {
  249. return j.kytheFiles
  250. }
  251. type dependencyTag struct {
  252. blueprint.BaseDependencyTag
  253. name string
  254. // True if the dependency is relinked at runtime.
  255. runtimeLinked bool
  256. // True if the dependency is a toolchain, for example an annotation processor.
  257. toolchain bool
  258. }
  259. // installDependencyTag is a dependency tag that is annotated to cause the installed files of the
  260. // dependency to be installed when the parent module is installed.
  261. type installDependencyTag struct {
  262. blueprint.BaseDependencyTag
  263. android.InstallAlwaysNeededDependencyTag
  264. name string
  265. }
  266. func (d dependencyTag) LicenseAnnotations() []android.LicenseAnnotation {
  267. if d.runtimeLinked {
  268. return []android.LicenseAnnotation{android.LicenseAnnotationSharedDependency}
  269. } else if d.toolchain {
  270. return []android.LicenseAnnotation{android.LicenseAnnotationToolchain}
  271. }
  272. return nil
  273. }
  274. var _ android.LicenseAnnotationsDependencyTag = dependencyTag{}
  275. type usesLibraryDependencyTag struct {
  276. dependencyTag
  277. sdkVersion int // SDK version in which the library appared as a standalone library.
  278. optional bool // If the dependency is optional or required.
  279. }
  280. func makeUsesLibraryDependencyTag(sdkVersion int, optional bool) usesLibraryDependencyTag {
  281. return usesLibraryDependencyTag{
  282. dependencyTag: dependencyTag{
  283. name: fmt.Sprintf("uses-library-%d", sdkVersion),
  284. runtimeLinked: true,
  285. },
  286. sdkVersion: sdkVersion,
  287. optional: optional,
  288. }
  289. }
  290. func IsJniDepTag(depTag blueprint.DependencyTag) bool {
  291. return depTag == jniLibTag
  292. }
  293. var (
  294. dataNativeBinsTag = dependencyTag{name: "dataNativeBins"}
  295. dataDeviceBinsTag = dependencyTag{name: "dataDeviceBins"}
  296. staticLibTag = dependencyTag{name: "staticlib"}
  297. libTag = dependencyTag{name: "javalib", runtimeLinked: true}
  298. java9LibTag = dependencyTag{name: "java9lib", runtimeLinked: true}
  299. pluginTag = dependencyTag{name: "plugin", toolchain: true}
  300. errorpronePluginTag = dependencyTag{name: "errorprone-plugin", toolchain: true}
  301. exportedPluginTag = dependencyTag{name: "exported-plugin", toolchain: true}
  302. bootClasspathTag = dependencyTag{name: "bootclasspath", runtimeLinked: true}
  303. systemModulesTag = dependencyTag{name: "system modules", runtimeLinked: true}
  304. frameworkResTag = dependencyTag{name: "framework-res"}
  305. kotlinStdlibTag = dependencyTag{name: "kotlin-stdlib", runtimeLinked: true}
  306. kotlinAnnotationsTag = dependencyTag{name: "kotlin-annotations", runtimeLinked: true}
  307. kotlinPluginTag = dependencyTag{name: "kotlin-plugin", toolchain: true}
  308. proguardRaiseTag = dependencyTag{name: "proguard-raise"}
  309. certificateTag = dependencyTag{name: "certificate"}
  310. instrumentationForTag = dependencyTag{name: "instrumentation_for"}
  311. extraLintCheckTag = dependencyTag{name: "extra-lint-check", toolchain: true}
  312. jniLibTag = dependencyTag{name: "jnilib", runtimeLinked: true}
  313. syspropPublicStubDepTag = dependencyTag{name: "sysprop public stub"}
  314. jniInstallTag = installDependencyTag{name: "jni install"}
  315. binaryInstallTag = installDependencyTag{name: "binary install"}
  316. usesLibReqTag = makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, false)
  317. usesLibOptTag = makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, true)
  318. usesLibCompat28OptTag = makeUsesLibraryDependencyTag(28, true)
  319. usesLibCompat29ReqTag = makeUsesLibraryDependencyTag(29, false)
  320. usesLibCompat30OptTag = makeUsesLibraryDependencyTag(30, true)
  321. )
  322. func IsLibDepTag(depTag blueprint.DependencyTag) bool {
  323. return depTag == libTag
  324. }
  325. func IsStaticLibDepTag(depTag blueprint.DependencyTag) bool {
  326. return depTag == staticLibTag
  327. }
  328. type sdkDep struct {
  329. useModule, useFiles, invalidVersion bool
  330. // The modules that will be added to the bootclasspath when targeting 1.8 or lower
  331. bootclasspath []string
  332. // The default system modules to use. Will be an empty string if no system
  333. // modules are to be used.
  334. systemModules string
  335. // The modules that will be added to the classpath regardless of the Java language level targeted
  336. classpath []string
  337. // The modules that will be added ot the classpath when targeting 1.9 or higher
  338. // (normally these will be on the bootclasspath when targeting 1.8 or lower)
  339. java9Classpath []string
  340. frameworkResModule string
  341. jars android.Paths
  342. aidl android.OptionalPath
  343. noStandardLibs, noFrameworksLibs bool
  344. }
  345. func (s sdkDep) hasStandardLibs() bool {
  346. return !s.noStandardLibs
  347. }
  348. func (s sdkDep) hasFrameworkLibs() bool {
  349. return !s.noStandardLibs && !s.noFrameworksLibs
  350. }
  351. type jniLib struct {
  352. name string
  353. path android.Path
  354. target android.Target
  355. coverageFile android.OptionalPath
  356. unstrippedFile android.Path
  357. }
  358. func sdkDeps(ctx android.BottomUpMutatorContext, sdkContext android.SdkContext, d dexer) {
  359. sdkDep := decodeSdkDep(ctx, sdkContext)
  360. if sdkDep.useModule {
  361. ctx.AddVariationDependencies(nil, bootClasspathTag, sdkDep.bootclasspath...)
  362. ctx.AddVariationDependencies(nil, java9LibTag, sdkDep.java9Classpath...)
  363. ctx.AddVariationDependencies(nil, libTag, sdkDep.classpath...)
  364. if d.effectiveOptimizeEnabled() && sdkDep.hasStandardLibs() {
  365. ctx.AddVariationDependencies(nil, proguardRaiseTag, config.LegacyCorePlatformBootclasspathLibraries...)
  366. }
  367. if d.effectiveOptimizeEnabled() && sdkDep.hasFrameworkLibs() {
  368. ctx.AddVariationDependencies(nil, proguardRaiseTag, config.FrameworkLibraries...)
  369. }
  370. }
  371. if sdkDep.systemModules != "" {
  372. ctx.AddVariationDependencies(nil, systemModulesTag, sdkDep.systemModules)
  373. }
  374. }
  375. type deps struct {
  376. // bootClasspath is the list of jars that form the boot classpath (generally the java.* and
  377. // android.* classes) for tools that still use it. javac targeting 1.9 or higher uses
  378. // systemModules and java9Classpath instead.
  379. bootClasspath classpath
  380. // classpath is the list of jars that form the classpath for javac and kotlinc rules. It
  381. // contains header jars for all static and non-static dependencies.
  382. classpath classpath
  383. // dexClasspath is the list of jars that form the classpath for d8 and r8 rules. It contains
  384. // header jars for all non-static dependencies. Static dependencies have already been
  385. // combined into the program jar.
  386. dexClasspath classpath
  387. // java9Classpath is the list of jars that will be added to the classpath when targeting
  388. // 1.9 or higher. It generally contains the android.* classes, while the java.* classes
  389. // are provided by systemModules.
  390. java9Classpath classpath
  391. processorPath classpath
  392. errorProneProcessorPath classpath
  393. processorClasses []string
  394. staticJars android.Paths
  395. staticHeaderJars android.Paths
  396. staticResourceJars android.Paths
  397. aidlIncludeDirs android.Paths
  398. srcs android.Paths
  399. srcJars android.Paths
  400. systemModules *systemModules
  401. aidlPreprocess android.OptionalPath
  402. kotlinStdlib android.Paths
  403. kotlinAnnotations android.Paths
  404. kotlinPlugins android.Paths
  405. disableTurbine bool
  406. }
  407. func checkProducesJars(ctx android.ModuleContext, dep android.SourceFileProducer) {
  408. for _, f := range dep.Srcs() {
  409. if f.Ext() != ".jar" {
  410. ctx.ModuleErrorf("genrule %q must generate files ending with .jar to be used as a libs or static_libs dependency",
  411. ctx.OtherModuleName(dep.(blueprint.Module)))
  412. }
  413. }
  414. }
  415. func getJavaVersion(ctx android.ModuleContext, javaVersion string, sdkContext android.SdkContext) javaVersion {
  416. if javaVersion != "" {
  417. return normalizeJavaVersion(ctx, javaVersion)
  418. } else if ctx.Device() {
  419. return defaultJavaLanguageVersion(ctx, sdkContext.SdkVersion(ctx))
  420. } else if ctx.Config().TargetsJava17() {
  421. // Temporary experimental flag to be able to try and build with
  422. // java version 17 options. The flag, if used, just sets Java
  423. // 17 as the default version, leaving any components that
  424. // target an older version intact.
  425. return JAVA_VERSION_17
  426. } else {
  427. return JAVA_VERSION_11
  428. }
  429. }
  430. type javaVersion int
  431. const (
  432. JAVA_VERSION_UNSUPPORTED = 0
  433. JAVA_VERSION_6 = 6
  434. JAVA_VERSION_7 = 7
  435. JAVA_VERSION_8 = 8
  436. JAVA_VERSION_9 = 9
  437. JAVA_VERSION_11 = 11
  438. JAVA_VERSION_17 = 17
  439. )
  440. func (v javaVersion) String() string {
  441. switch v {
  442. case JAVA_VERSION_6:
  443. return "1.6"
  444. case JAVA_VERSION_7:
  445. return "1.7"
  446. case JAVA_VERSION_8:
  447. return "1.8"
  448. case JAVA_VERSION_9:
  449. return "1.9"
  450. case JAVA_VERSION_11:
  451. return "11"
  452. case JAVA_VERSION_17:
  453. return "17"
  454. default:
  455. return "unsupported"
  456. }
  457. }
  458. func (v javaVersion) StringForKotlinc() string {
  459. // $ ./external/kotlinc/bin/kotlinc -jvm-target foo
  460. // error: unknown JVM target version: foo
  461. // Supported versions: 1.6, 1.8, 9, 10, 11, 12, 13, 14, 15, 16, 17
  462. switch v {
  463. case JAVA_VERSION_7:
  464. return "1.6"
  465. case JAVA_VERSION_9:
  466. return "9"
  467. default:
  468. return v.String()
  469. }
  470. }
  471. // Returns true if javac targeting this version uses system modules instead of a bootclasspath.
  472. func (v javaVersion) usesJavaModules() bool {
  473. return v >= 9
  474. }
  475. func normalizeJavaVersion(ctx android.BaseModuleContext, javaVersion string) javaVersion {
  476. switch javaVersion {
  477. case "1.6", "6":
  478. return JAVA_VERSION_6
  479. case "1.7", "7":
  480. return JAVA_VERSION_7
  481. case "1.8", "8":
  482. return JAVA_VERSION_8
  483. case "1.9", "9":
  484. return JAVA_VERSION_9
  485. case "11":
  486. return JAVA_VERSION_11
  487. case "17":
  488. return JAVA_VERSION_17
  489. case "10", "12", "13", "14", "15", "16":
  490. ctx.PropertyErrorf("java_version", "Java language level %s is not supported", javaVersion)
  491. return JAVA_VERSION_UNSUPPORTED
  492. default:
  493. ctx.PropertyErrorf("java_version", "Unrecognized Java language level")
  494. return JAVA_VERSION_UNSUPPORTED
  495. }
  496. }
  497. //
  498. // Java libraries (.jar file)
  499. //
  500. type Library struct {
  501. Module
  502. InstallMixin func(ctx android.ModuleContext, installPath android.Path) (extraInstallDeps android.Paths)
  503. }
  504. var _ android.ApexModule = (*Library)(nil)
  505. // Provides access to the list of permitted packages from apex boot jars.
  506. type PermittedPackagesForUpdatableBootJars interface {
  507. PermittedPackagesForUpdatableBootJars() []string
  508. }
  509. var _ PermittedPackagesForUpdatableBootJars = (*Library)(nil)
  510. func (j *Library) PermittedPackagesForUpdatableBootJars() []string {
  511. return j.properties.Permitted_packages
  512. }
  513. func shouldUncompressDex(ctx android.ModuleContext, dexpreopter *dexpreopter) bool {
  514. // Store uncompressed (and aligned) any dex files from jars in APEXes.
  515. if apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo); !apexInfo.IsForPlatform() {
  516. return true
  517. }
  518. // Store uncompressed (and do not strip) dex files from boot class path jars.
  519. if inList(ctx.ModuleName(), ctx.Config().BootJars()) {
  520. return true
  521. }
  522. // Store uncompressed dex files that are preopted on /system.
  523. if !dexpreopter.dexpreoptDisabled(ctx) && (ctx.Host() || !dexpreopter.odexOnSystemOther(ctx, dexpreopter.installPath)) {
  524. return true
  525. }
  526. if ctx.Config().UncompressPrivAppDex() &&
  527. inList(ctx.ModuleName(), ctx.Config().ModulesLoadedByPrivilegedModules()) {
  528. return true
  529. }
  530. return false
  531. }
  532. // Sets `dexer.dexProperties.Uncompress_dex` to the proper value.
  533. func setUncompressDex(ctx android.ModuleContext, dexpreopter *dexpreopter, dexer *dexer) {
  534. if dexer.dexProperties.Uncompress_dex == nil {
  535. // If the value was not force-set by the user, use reasonable default based on the module.
  536. dexer.dexProperties.Uncompress_dex = proptools.BoolPtr(shouldUncompressDex(ctx, dexpreopter))
  537. }
  538. }
  539. func (j *Library) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  540. j.provideHiddenAPIPropertyInfo(ctx)
  541. j.sdkVersion = j.SdkVersion(ctx)
  542. j.minSdkVersion = j.MinSdkVersion(ctx)
  543. j.maxSdkVersion = j.MaxSdkVersion(ctx)
  544. apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
  545. if !apexInfo.IsForPlatform() {
  546. j.hideApexVariantFromMake = true
  547. }
  548. j.checkSdkVersions(ctx)
  549. if ctx.Device() {
  550. j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
  551. ctx, android.PathForModuleInstall(ctx, "framework", j.Stem()+".jar"))
  552. j.dexpreopter.isSDKLibrary = j.deviceProperties.IsSDKLibrary
  553. setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
  554. j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
  555. j.classLoaderContexts = j.usesLibrary.classLoaderContextForUsesLibDeps(ctx)
  556. }
  557. j.compile(ctx, nil)
  558. // Collect the module directory for IDE info in java/jdeps.go.
  559. j.modulePaths = append(j.modulePaths, ctx.ModuleDir())
  560. exclusivelyForApex := !apexInfo.IsForPlatform()
  561. if (Bool(j.properties.Installable) || ctx.Host()) && !exclusivelyForApex {
  562. var extraInstallDeps android.Paths
  563. if j.InstallMixin != nil {
  564. extraInstallDeps = j.InstallMixin(ctx, j.outputFile)
  565. }
  566. hostDexNeeded := Bool(j.deviceProperties.Hostdex) && !ctx.Host()
  567. if hostDexNeeded {
  568. j.hostdexInstallFile = ctx.InstallFile(
  569. android.PathForHostDexInstall(ctx, "framework"),
  570. j.Stem()+"-hostdex.jar", j.outputFile)
  571. }
  572. var installDir android.InstallPath
  573. if ctx.InstallInTestcases() {
  574. var archDir string
  575. if !ctx.Host() {
  576. archDir = ctx.DeviceConfig().DeviceArch()
  577. }
  578. installDir = android.PathForModuleInstall(ctx, ctx.ModuleName(), archDir)
  579. } else {
  580. installDir = android.PathForModuleInstall(ctx, "framework")
  581. }
  582. j.installFile = ctx.InstallFile(installDir, j.Stem()+".jar", j.outputFile, extraInstallDeps...)
  583. }
  584. }
  585. func (j *Library) DepsMutator(ctx android.BottomUpMutatorContext) {
  586. j.deps(ctx)
  587. j.usesLibrary.deps(ctx, false)
  588. }
  589. const (
  590. aidlIncludeDir = "aidl"
  591. javaDir = "java"
  592. jarFileSuffix = ".jar"
  593. testConfigSuffix = "-AndroidTest.xml"
  594. )
  595. // path to the jar file of a java library. Relative to <sdk_root>/<api_dir>
  596. func sdkSnapshotFilePathForJar(_ android.SdkMemberContext, osPrefix, name string) string {
  597. return sdkSnapshotFilePathForMember(osPrefix, name, jarFileSuffix)
  598. }
  599. func sdkSnapshotFilePathForMember(osPrefix, name string, suffix string) string {
  600. return filepath.Join(javaDir, osPrefix, name+suffix)
  601. }
  602. type librarySdkMemberType struct {
  603. android.SdkMemberTypeBase
  604. // Function to retrieve the appropriate output jar (implementation or header) from
  605. // the library.
  606. jarToExportGetter func(ctx android.SdkMemberContext, j *Library) android.Path
  607. // Function to compute the snapshot relative path to which the named library's
  608. // jar should be copied.
  609. snapshotPathGetter func(ctx android.SdkMemberContext, osPrefix, name string) string
  610. // True if only the jar should be copied to the snapshot, false if the jar plus any additional
  611. // files like aidl files should also be copied.
  612. onlyCopyJarToSnapshot bool
  613. }
  614. const (
  615. onlyCopyJarToSnapshot = true
  616. copyEverythingToSnapshot = false
  617. )
  618. func (mt *librarySdkMemberType) AddDependencies(ctx android.SdkDependencyContext, dependencyTag blueprint.DependencyTag, names []string) {
  619. ctx.AddVariationDependencies(nil, dependencyTag, names...)
  620. }
  621. func (mt *librarySdkMemberType) IsInstance(module android.Module) bool {
  622. _, ok := module.(*Library)
  623. return ok
  624. }
  625. func (mt *librarySdkMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
  626. return ctx.SnapshotBuilder().AddPrebuiltModule(member, "java_import")
  627. }
  628. func (mt *librarySdkMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
  629. return &librarySdkMemberProperties{}
  630. }
  631. type librarySdkMemberProperties struct {
  632. android.SdkMemberPropertiesBase
  633. JarToExport android.Path `android:"arch_variant"`
  634. AidlIncludeDirs android.Paths
  635. // The list of permitted packages that need to be passed to the prebuilts as they are used to
  636. // create the updatable-bcp-packages.txt file.
  637. PermittedPackages []string
  638. }
  639. func (p *librarySdkMemberProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
  640. j := variant.(*Library)
  641. p.JarToExport = ctx.MemberType().(*librarySdkMemberType).jarToExportGetter(ctx, j)
  642. p.AidlIncludeDirs = j.AidlIncludeDirs()
  643. p.PermittedPackages = j.PermittedPackagesForUpdatableBootJars()
  644. }
  645. func (p *librarySdkMemberProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
  646. builder := ctx.SnapshotBuilder()
  647. memberType := ctx.MemberType().(*librarySdkMemberType)
  648. exportedJar := p.JarToExport
  649. if exportedJar != nil {
  650. // Delegate the creation of the snapshot relative path to the member type.
  651. snapshotRelativeJavaLibPath := memberType.snapshotPathGetter(ctx, p.OsPrefix(), ctx.Name())
  652. // Copy the exported jar to the snapshot.
  653. builder.CopyToSnapshot(exportedJar, snapshotRelativeJavaLibPath)
  654. propertySet.AddProperty("jars", []string{snapshotRelativeJavaLibPath})
  655. }
  656. if len(p.PermittedPackages) > 0 {
  657. propertySet.AddProperty("permitted_packages", p.PermittedPackages)
  658. }
  659. // Do not copy anything else to the snapshot.
  660. if memberType.onlyCopyJarToSnapshot {
  661. return
  662. }
  663. aidlIncludeDirs := p.AidlIncludeDirs
  664. if len(aidlIncludeDirs) != 0 {
  665. sdkModuleContext := ctx.SdkModuleContext()
  666. for _, dir := range aidlIncludeDirs {
  667. // TODO(jiyong): copy parcelable declarations only
  668. aidlFiles, _ := sdkModuleContext.GlobWithDeps(dir.String()+"/**/*.aidl", nil)
  669. for _, file := range aidlFiles {
  670. builder.CopyToSnapshot(android.PathForSource(sdkModuleContext, file), filepath.Join(aidlIncludeDir, file))
  671. }
  672. }
  673. // TODO(b/151933053) - add aidl include dirs property
  674. }
  675. }
  676. // java_library builds and links sources into a `.jar` file for the device, and possibly for the host as well.
  677. //
  678. // By default, a java_library has a single variant that produces a `.jar` file containing `.class` files that were
  679. // compiled against the device bootclasspath. This jar is not suitable for installing on a device, but can be used
  680. // as a `static_libs` dependency of another module.
  681. //
  682. // Specifying `installable: true` will product a `.jar` file containing `classes.dex` files, suitable for installing on
  683. // a device.
  684. //
  685. // Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
  686. // compiled against the host bootclasspath.
  687. func LibraryFactory() android.Module {
  688. module := &Library{}
  689. module.addHostAndDeviceProperties()
  690. module.initModuleAndImport(module)
  691. android.InitApexModule(module)
  692. android.InitSdkAwareModule(module)
  693. android.InitBazelModule(module)
  694. InitJavaModule(module, android.HostAndDeviceSupported)
  695. return module
  696. }
  697. // java_library_static is an obsolete alias for java_library.
  698. func LibraryStaticFactory() android.Module {
  699. return LibraryFactory()
  700. }
  701. // java_library_host builds and links sources into a `.jar` file for the host.
  702. //
  703. // A java_library_host has a single variant that produces a `.jar` file containing `.class` files that were
  704. // compiled against the host bootclasspath.
  705. func LibraryHostFactory() android.Module {
  706. module := &Library{}
  707. module.addHostProperties()
  708. module.Module.properties.Installable = proptools.BoolPtr(true)
  709. android.InitApexModule(module)
  710. android.InitSdkAwareModule(module)
  711. android.InitBazelModule(module)
  712. InitJavaModule(module, android.HostSupported)
  713. return module
  714. }
  715. //
  716. // Java Tests
  717. //
  718. // Test option struct.
  719. type TestOptions struct {
  720. android.CommonTestOptions
  721. // a list of extra test configuration files that should be installed with the module.
  722. Extra_test_configs []string `android:"path,arch_variant"`
  723. }
  724. type testProperties struct {
  725. // list of compatibility suites (for example "cts", "vts") that the module should be
  726. // installed into.
  727. Test_suites []string `android:"arch_variant"`
  728. // the name of the test configuration (for example "AndroidTest.xml") that should be
  729. // installed with the module.
  730. Test_config *string `android:"path,arch_variant"`
  731. // the name of the test configuration template (for example "AndroidTestTemplate.xml") that
  732. // should be installed with the module.
  733. Test_config_template *string `android:"path,arch_variant"`
  734. // list of files or filegroup modules that provide data that should be installed alongside
  735. // the test
  736. Data []string `android:"path"`
  737. // Flag to indicate whether or not to create test config automatically. If AndroidTest.xml
  738. // doesn't exist next to the Android.bp, this attribute doesn't need to be set to true
  739. // explicitly.
  740. Auto_gen_config *bool
  741. // Add parameterized mainline modules to auto generated test config. The options will be
  742. // handled by TradeFed to do downloading and installing the specified modules on the device.
  743. Test_mainline_modules []string
  744. // Test options.
  745. Test_options TestOptions
  746. // Names of modules containing JNI libraries that should be installed alongside the test.
  747. Jni_libs []string
  748. // Install the test into a folder named for the module in all test suites.
  749. Per_testcase_directory *bool
  750. }
  751. type hostTestProperties struct {
  752. // list of native binary modules that should be installed alongside the test
  753. Data_native_bins []string `android:"arch_variant"`
  754. // list of device binary modules that should be installed alongside the test
  755. // This property only adds the first variant of the dependency
  756. Data_device_bins_first []string `android:"arch_variant"`
  757. // list of device binary modules that should be installed alongside the test
  758. // This property adds 64bit AND 32bit variants of the dependency
  759. Data_device_bins_both []string `android:"arch_variant"`
  760. // list of device binary modules that should be installed alongside the test
  761. // This property only adds 64bit variants of the dependency
  762. Data_device_bins_64 []string `android:"arch_variant"`
  763. // list of device binary modules that should be installed alongside the test
  764. // This property adds 32bit variants of the dependency if available, or else
  765. // defaults to the 64bit variant
  766. Data_device_bins_prefer32 []string `android:"arch_variant"`
  767. // list of device binary modules that should be installed alongside the test
  768. // This property only adds 32bit variants of the dependency
  769. Data_device_bins_32 []string `android:"arch_variant"`
  770. }
  771. type testHelperLibraryProperties struct {
  772. // list of compatibility suites (for example "cts", "vts") that the module should be
  773. // installed into.
  774. Test_suites []string `android:"arch_variant"`
  775. // Install the test into a folder named for the module in all test suites.
  776. Per_testcase_directory *bool
  777. }
  778. type prebuiltTestProperties struct {
  779. // list of compatibility suites (for example "cts", "vts") that the module should be
  780. // installed into.
  781. Test_suites []string `android:"arch_variant"`
  782. // the name of the test configuration (for example "AndroidTest.xml") that should be
  783. // installed with the module.
  784. Test_config *string `android:"path,arch_variant"`
  785. }
  786. type Test struct {
  787. Library
  788. testProperties testProperties
  789. testConfig android.Path
  790. extraTestConfigs android.Paths
  791. data android.Paths
  792. }
  793. type TestHost struct {
  794. Test
  795. testHostProperties hostTestProperties
  796. }
  797. type TestHelperLibrary struct {
  798. Library
  799. testHelperLibraryProperties testHelperLibraryProperties
  800. }
  801. type JavaTestImport struct {
  802. Import
  803. prebuiltTestProperties prebuiltTestProperties
  804. testConfig android.Path
  805. dexJarFile android.Path
  806. }
  807. func (j *Test) InstallInTestcases() bool {
  808. // Host java tests install into $(HOST_OUT_JAVA_LIBRARIES), and then are copied into
  809. // testcases by base_rules.mk.
  810. return !j.Host()
  811. }
  812. func (j *TestHelperLibrary) InstallInTestcases() bool {
  813. return true
  814. }
  815. func (j *JavaTestImport) InstallInTestcases() bool {
  816. return true
  817. }
  818. func (j *TestHost) addDataDeviceBinsDeps(ctx android.BottomUpMutatorContext) {
  819. if len(j.testHostProperties.Data_device_bins_first) > 0 {
  820. deviceVariations := ctx.Config().AndroidFirstDeviceTarget.Variations()
  821. ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_first...)
  822. }
  823. var maybeAndroid32Target *android.Target
  824. var maybeAndroid64Target *android.Target
  825. android32TargetList := android.FirstTarget(ctx.Config().Targets[android.Android], "lib32")
  826. android64TargetList := android.FirstTarget(ctx.Config().Targets[android.Android], "lib64")
  827. if len(android32TargetList) > 0 {
  828. maybeAndroid32Target = &android32TargetList[0]
  829. }
  830. if len(android64TargetList) > 0 {
  831. maybeAndroid64Target = &android64TargetList[0]
  832. }
  833. if len(j.testHostProperties.Data_device_bins_both) > 0 {
  834. if maybeAndroid32Target == nil && maybeAndroid64Target == nil {
  835. ctx.PropertyErrorf("data_device_bins_both", "no device targets available. Targets: %q", ctx.Config().Targets)
  836. return
  837. }
  838. if maybeAndroid32Target != nil {
  839. ctx.AddFarVariationDependencies(
  840. maybeAndroid32Target.Variations(),
  841. dataDeviceBinsTag,
  842. j.testHostProperties.Data_device_bins_both...,
  843. )
  844. }
  845. if maybeAndroid64Target != nil {
  846. ctx.AddFarVariationDependencies(
  847. maybeAndroid64Target.Variations(),
  848. dataDeviceBinsTag,
  849. j.testHostProperties.Data_device_bins_both...,
  850. )
  851. }
  852. }
  853. if len(j.testHostProperties.Data_device_bins_prefer32) > 0 {
  854. if maybeAndroid32Target != nil {
  855. ctx.AddFarVariationDependencies(
  856. maybeAndroid32Target.Variations(),
  857. dataDeviceBinsTag,
  858. j.testHostProperties.Data_device_bins_prefer32...,
  859. )
  860. } else {
  861. if maybeAndroid64Target == nil {
  862. ctx.PropertyErrorf("data_device_bins_prefer32", "no device targets available. Targets: %q", ctx.Config().Targets)
  863. return
  864. }
  865. ctx.AddFarVariationDependencies(
  866. maybeAndroid64Target.Variations(),
  867. dataDeviceBinsTag,
  868. j.testHostProperties.Data_device_bins_prefer32...,
  869. )
  870. }
  871. }
  872. if len(j.testHostProperties.Data_device_bins_32) > 0 {
  873. if maybeAndroid32Target == nil {
  874. ctx.PropertyErrorf("data_device_bins_32", "cannot find 32bit device target. Targets: %q", ctx.Config().Targets)
  875. return
  876. }
  877. deviceVariations := maybeAndroid32Target.Variations()
  878. ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_32...)
  879. }
  880. if len(j.testHostProperties.Data_device_bins_64) > 0 {
  881. if maybeAndroid64Target == nil {
  882. ctx.PropertyErrorf("data_device_bins_64", "cannot find 64bit device target. Targets: %q", ctx.Config().Targets)
  883. return
  884. }
  885. deviceVariations := maybeAndroid64Target.Variations()
  886. ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_64...)
  887. }
  888. }
  889. func (j *TestHost) DepsMutator(ctx android.BottomUpMutatorContext) {
  890. if len(j.testHostProperties.Data_native_bins) > 0 {
  891. for _, target := range ctx.MultiTargets() {
  892. ctx.AddVariationDependencies(target.Variations(), dataNativeBinsTag, j.testHostProperties.Data_native_bins...)
  893. }
  894. }
  895. if len(j.testProperties.Jni_libs) > 0 {
  896. for _, target := range ctx.MultiTargets() {
  897. sharedLibVariations := append(target.Variations(), blueprint.Variation{Mutator: "link", Variation: "shared"})
  898. ctx.AddFarVariationDependencies(sharedLibVariations, jniLibTag, j.testProperties.Jni_libs...)
  899. }
  900. }
  901. j.addDataDeviceBinsDeps(ctx)
  902. j.deps(ctx)
  903. }
  904. func (j *TestHost) AddExtraResource(p android.Path) {
  905. j.extraResources = append(j.extraResources, p)
  906. }
  907. func (j *TestHost) dataDeviceBins() []string {
  908. ret := make([]string, 0,
  909. len(j.testHostProperties.Data_device_bins_first)+
  910. len(j.testHostProperties.Data_device_bins_both)+
  911. len(j.testHostProperties.Data_device_bins_prefer32)+
  912. len(j.testHostProperties.Data_device_bins_32)+
  913. len(j.testHostProperties.Data_device_bins_64),
  914. )
  915. ret = append(ret, j.testHostProperties.Data_device_bins_first...)
  916. ret = append(ret, j.testHostProperties.Data_device_bins_both...)
  917. ret = append(ret, j.testHostProperties.Data_device_bins_prefer32...)
  918. ret = append(ret, j.testHostProperties.Data_device_bins_32...)
  919. ret = append(ret, j.testHostProperties.Data_device_bins_64...)
  920. return ret
  921. }
  922. func (j *TestHost) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  923. var configs []tradefed.Config
  924. dataDeviceBins := j.dataDeviceBins()
  925. if len(dataDeviceBins) > 0 {
  926. // add Tradefed configuration to push device bins to device for testing
  927. remoteDir := filepath.Join("/data/local/tests/unrestricted/", j.Name())
  928. options := []tradefed.Option{{Name: "cleanup", Value: "true"}}
  929. for _, bin := range dataDeviceBins {
  930. fullPath := filepath.Join(remoteDir, bin)
  931. options = append(options, tradefed.Option{Name: "push-file", Key: bin, Value: fullPath})
  932. }
  933. configs = append(configs, tradefed.Object{
  934. Type: "target_preparer",
  935. Class: "com.android.tradefed.targetprep.PushFilePreparer",
  936. Options: options,
  937. })
  938. }
  939. j.Test.generateAndroidBuildActionsWithConfig(ctx, configs)
  940. }
  941. func (j *Test) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  942. j.generateAndroidBuildActionsWithConfig(ctx, nil)
  943. }
  944. func (j *Test) generateAndroidBuildActionsWithConfig(ctx android.ModuleContext, configs []tradefed.Config) {
  945. if j.testProperties.Test_options.Unit_test == nil && ctx.Host() {
  946. // TODO(b/): Clean temporary heuristic to avoid unexpected onboarding.
  947. defaultUnitTest := !inList("tradefed", j.properties.Libs) && !inList("cts", j.testProperties.Test_suites)
  948. j.testProperties.Test_options.Unit_test = proptools.BoolPtr(defaultUnitTest)
  949. }
  950. j.testConfig = tradefed.AutoGenJavaTestConfig(ctx, j.testProperties.Test_config, j.testProperties.Test_config_template,
  951. j.testProperties.Test_suites, configs, j.testProperties.Auto_gen_config, j.testProperties.Test_options.Unit_test)
  952. j.data = android.PathsForModuleSrc(ctx, j.testProperties.Data)
  953. j.extraTestConfigs = android.PathsForModuleSrc(ctx, j.testProperties.Test_options.Extra_test_configs)
  954. ctx.VisitDirectDepsWithTag(dataNativeBinsTag, func(dep android.Module) {
  955. j.data = append(j.data, android.OutputFileForModule(ctx, dep, ""))
  956. })
  957. ctx.VisitDirectDepsWithTag(dataDeviceBinsTag, func(dep android.Module) {
  958. j.data = append(j.data, android.OutputFileForModule(ctx, dep, ""))
  959. })
  960. ctx.VisitDirectDepsWithTag(jniLibTag, func(dep android.Module) {
  961. sharedLibInfo := ctx.OtherModuleProvider(dep, cc.SharedLibraryInfoProvider).(cc.SharedLibraryInfo)
  962. if sharedLibInfo.SharedLibrary != nil {
  963. // Copy to an intermediate output directory to append "lib[64]" to the path,
  964. // so that it's compatible with the default rpath values.
  965. var relPath string
  966. if sharedLibInfo.Target.Arch.ArchType.Multilib == "lib64" {
  967. relPath = filepath.Join("lib64", sharedLibInfo.SharedLibrary.Base())
  968. } else {
  969. relPath = filepath.Join("lib", sharedLibInfo.SharedLibrary.Base())
  970. }
  971. relocatedLib := android.PathForModuleOut(ctx, "relocated").Join(ctx, relPath)
  972. ctx.Build(pctx, android.BuildParams{
  973. Rule: android.Cp,
  974. Input: sharedLibInfo.SharedLibrary,
  975. Output: relocatedLib,
  976. })
  977. j.data = append(j.data, relocatedLib)
  978. } else {
  979. ctx.PropertyErrorf("jni_libs", "%q of type %q is not supported", dep.Name(), ctx.OtherModuleType(dep))
  980. }
  981. })
  982. j.Library.GenerateAndroidBuildActions(ctx)
  983. }
  984. func (j *TestHelperLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  985. j.Library.GenerateAndroidBuildActions(ctx)
  986. }
  987. func (j *JavaTestImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  988. j.testConfig = tradefed.AutoGenJavaTestConfig(ctx, j.prebuiltTestProperties.Test_config, nil,
  989. j.prebuiltTestProperties.Test_suites, nil, nil, nil)
  990. j.Import.GenerateAndroidBuildActions(ctx)
  991. }
  992. type testSdkMemberType struct {
  993. android.SdkMemberTypeBase
  994. }
  995. func (mt *testSdkMemberType) AddDependencies(ctx android.SdkDependencyContext, dependencyTag blueprint.DependencyTag, names []string) {
  996. ctx.AddVariationDependencies(nil, dependencyTag, names...)
  997. }
  998. func (mt *testSdkMemberType) IsInstance(module android.Module) bool {
  999. _, ok := module.(*Test)
  1000. return ok
  1001. }
  1002. func (mt *testSdkMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
  1003. return ctx.SnapshotBuilder().AddPrebuiltModule(member, "java_test_import")
  1004. }
  1005. func (mt *testSdkMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
  1006. return &testSdkMemberProperties{}
  1007. }
  1008. type testSdkMemberProperties struct {
  1009. android.SdkMemberPropertiesBase
  1010. JarToExport android.Path
  1011. TestConfig android.Path
  1012. }
  1013. func (p *testSdkMemberProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
  1014. test := variant.(*Test)
  1015. implementationJars := test.ImplementationJars()
  1016. if len(implementationJars) != 1 {
  1017. panic(fmt.Errorf("there must be only one implementation jar from %q", test.Name()))
  1018. }
  1019. p.JarToExport = implementationJars[0]
  1020. p.TestConfig = test.testConfig
  1021. }
  1022. func (p *testSdkMemberProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
  1023. builder := ctx.SnapshotBuilder()
  1024. exportedJar := p.JarToExport
  1025. if exportedJar != nil {
  1026. snapshotRelativeJavaLibPath := sdkSnapshotFilePathForJar(ctx, p.OsPrefix(), ctx.Name())
  1027. builder.CopyToSnapshot(exportedJar, snapshotRelativeJavaLibPath)
  1028. propertySet.AddProperty("jars", []string{snapshotRelativeJavaLibPath})
  1029. }
  1030. testConfig := p.TestConfig
  1031. if testConfig != nil {
  1032. snapshotRelativeTestConfigPath := sdkSnapshotFilePathForMember(p.OsPrefix(), ctx.Name(), testConfigSuffix)
  1033. builder.CopyToSnapshot(testConfig, snapshotRelativeTestConfigPath)
  1034. propertySet.AddProperty("test_config", snapshotRelativeTestConfigPath)
  1035. }
  1036. }
  1037. // java_test builds a and links sources into a `.jar` file for the device, and possibly for the host as well, and
  1038. // creates an `AndroidTest.xml` file to allow running the test with `atest` or a `TEST_MAPPING` file.
  1039. //
  1040. // By default, a java_test has a single variant that produces a `.jar` file containing `classes.dex` files that were
  1041. // compiled against the device bootclasspath.
  1042. //
  1043. // Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
  1044. // compiled against the host bootclasspath.
  1045. func TestFactory() android.Module {
  1046. module := &Test{}
  1047. module.addHostAndDeviceProperties()
  1048. module.AddProperties(&module.testProperties)
  1049. module.Module.properties.Installable = proptools.BoolPtr(true)
  1050. module.Module.dexpreopter.isTest = true
  1051. module.Module.linter.properties.Lint.Test = proptools.BoolPtr(true)
  1052. android.InitSdkAwareModule(module)
  1053. InitJavaModule(module, android.HostAndDeviceSupported)
  1054. return module
  1055. }
  1056. // java_test_helper_library creates a java library and makes sure that it is added to the appropriate test suite.
  1057. func TestHelperLibraryFactory() android.Module {
  1058. module := &TestHelperLibrary{}
  1059. module.addHostAndDeviceProperties()
  1060. module.AddProperties(&module.testHelperLibraryProperties)
  1061. module.Module.properties.Installable = proptools.BoolPtr(true)
  1062. module.Module.dexpreopter.isTest = true
  1063. module.Module.linter.properties.Lint.Test = proptools.BoolPtr(true)
  1064. InitJavaModule(module, android.HostAndDeviceSupported)
  1065. return module
  1066. }
  1067. // java_test_import imports one or more `.jar` files into the build graph as if they were built by a java_test module
  1068. // and makes sure that it is added to the appropriate test suite.
  1069. //
  1070. // By default, a java_test_import has a single variant that expects a `.jar` file containing `.class` files that were
  1071. // compiled against an Android classpath.
  1072. //
  1073. // Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
  1074. // for host modules.
  1075. func JavaTestImportFactory() android.Module {
  1076. module := &JavaTestImport{}
  1077. module.AddProperties(
  1078. &module.Import.properties,
  1079. &module.prebuiltTestProperties)
  1080. module.Import.properties.Installable = proptools.BoolPtr(true)
  1081. android.InitPrebuiltModule(module, &module.properties.Jars)
  1082. android.InitApexModule(module)
  1083. android.InitSdkAwareModule(module)
  1084. InitJavaModule(module, android.HostAndDeviceSupported)
  1085. return module
  1086. }
  1087. // java_test_host builds a and links sources into a `.jar` file for the host, and creates an `AndroidTest.xml` file to
  1088. // allow running the test with `atest` or a `TEST_MAPPING` file.
  1089. //
  1090. // A java_test_host has a single variant that produces a `.jar` file containing `.class` files that were
  1091. // compiled against the host bootclasspath.
  1092. func TestHostFactory() android.Module {
  1093. module := &TestHost{}
  1094. module.addHostProperties()
  1095. module.AddProperties(&module.testProperties)
  1096. module.AddProperties(&module.testHostProperties)
  1097. InitTestHost(
  1098. module,
  1099. proptools.BoolPtr(true),
  1100. nil,
  1101. nil)
  1102. InitJavaModuleMultiTargets(module, android.HostSupported)
  1103. return module
  1104. }
  1105. func InitTestHost(th *TestHost, installable *bool, testSuites []string, autoGenConfig *bool) {
  1106. th.properties.Installable = installable
  1107. th.testProperties.Auto_gen_config = autoGenConfig
  1108. th.testProperties.Test_suites = testSuites
  1109. }
  1110. //
  1111. // Java Binaries (.jar file plus wrapper script)
  1112. //
  1113. type binaryProperties struct {
  1114. // installable script to execute the resulting jar
  1115. Wrapper *string `android:"path,arch_variant"`
  1116. // Name of the class containing main to be inserted into the manifest as Main-Class.
  1117. Main_class *string
  1118. // Names of modules containing JNI libraries that should be installed alongside the host
  1119. // variant of the binary.
  1120. Jni_libs []string `android:"arch_variant"`
  1121. }
  1122. type Binary struct {
  1123. Library
  1124. binaryProperties binaryProperties
  1125. isWrapperVariant bool
  1126. wrapperFile android.Path
  1127. binaryFile android.InstallPath
  1128. }
  1129. func (j *Binary) HostToolPath() android.OptionalPath {
  1130. return android.OptionalPathForPath(j.binaryFile)
  1131. }
  1132. func (j *Binary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  1133. if ctx.Arch().ArchType == android.Common {
  1134. // Compile the jar
  1135. if j.binaryProperties.Main_class != nil {
  1136. if j.properties.Manifest != nil {
  1137. ctx.PropertyErrorf("main_class", "main_class cannot be used when manifest is set")
  1138. }
  1139. manifestFile := android.PathForModuleOut(ctx, "manifest.txt")
  1140. GenerateMainClassManifest(ctx, manifestFile, String(j.binaryProperties.Main_class))
  1141. j.overrideManifest = android.OptionalPathForPath(manifestFile)
  1142. }
  1143. j.Library.GenerateAndroidBuildActions(ctx)
  1144. } else {
  1145. // Handle the binary wrapper
  1146. j.isWrapperVariant = true
  1147. if j.binaryProperties.Wrapper != nil {
  1148. j.wrapperFile = android.PathForModuleSrc(ctx, *j.binaryProperties.Wrapper)
  1149. } else {
  1150. if ctx.Windows() {
  1151. ctx.PropertyErrorf("wrapper", "wrapper is required for Windows")
  1152. }
  1153. j.wrapperFile = android.PathForSource(ctx, "build/soong/scripts/jar-wrapper.sh")
  1154. }
  1155. ext := ""
  1156. if ctx.Windows() {
  1157. ext = ".bat"
  1158. }
  1159. // The host installation rules make the installed wrapper depend on all the dependencies
  1160. // of the wrapper variant, which will include the common variant's jar file and any JNI
  1161. // libraries. This is verified by TestBinary.
  1162. j.binaryFile = ctx.InstallExecutable(android.PathForModuleInstall(ctx, "bin"),
  1163. ctx.ModuleName()+ext, j.wrapperFile)
  1164. }
  1165. }
  1166. func (j *Binary) DepsMutator(ctx android.BottomUpMutatorContext) {
  1167. if ctx.Arch().ArchType == android.Common {
  1168. j.deps(ctx)
  1169. }
  1170. if ctx.Arch().ArchType != android.Common {
  1171. // These dependencies ensure the host installation rules will install the jar file and
  1172. // the jni libraries when the wrapper is installed.
  1173. ctx.AddVariationDependencies(nil, jniInstallTag, j.binaryProperties.Jni_libs...)
  1174. ctx.AddVariationDependencies(
  1175. []blueprint.Variation{{Mutator: "arch", Variation: android.CommonArch.String()}},
  1176. binaryInstallTag, ctx.ModuleName())
  1177. }
  1178. }
  1179. // java_binary builds a `.jar` file and a shell script that executes it for the device, and possibly for the host
  1180. // as well.
  1181. //
  1182. // By default, a java_binary has a single variant that produces a `.jar` file containing `classes.dex` files that were
  1183. // compiled against the device bootclasspath.
  1184. //
  1185. // Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
  1186. // compiled against the host bootclasspath.
  1187. func BinaryFactory() android.Module {
  1188. module := &Binary{}
  1189. module.addHostAndDeviceProperties()
  1190. module.AddProperties(&module.binaryProperties)
  1191. module.Module.properties.Installable = proptools.BoolPtr(true)
  1192. android.InitAndroidArchModule(module, android.HostAndDeviceSupported, android.MultilibCommonFirst)
  1193. android.InitDefaultableModule(module)
  1194. android.InitBazelModule(module)
  1195. return module
  1196. }
  1197. // java_binary_host builds a `.jar` file and a shell script that executes it for the host.
  1198. //
  1199. // A java_binary_host has a single variant that produces a `.jar` file containing `.class` files that were
  1200. // compiled against the host bootclasspath.
  1201. func BinaryHostFactory() android.Module {
  1202. module := &Binary{}
  1203. module.addHostProperties()
  1204. module.AddProperties(&module.binaryProperties)
  1205. module.Module.properties.Installable = proptools.BoolPtr(true)
  1206. android.InitAndroidArchModule(module, android.HostSupported, android.MultilibCommonFirst)
  1207. android.InitDefaultableModule(module)
  1208. android.InitBazelModule(module)
  1209. return module
  1210. }
  1211. //
  1212. // Java prebuilts
  1213. //
  1214. type ImportProperties struct {
  1215. Jars []string `android:"path,arch_variant"`
  1216. // The version of the SDK that the source prebuilt file was built against. Defaults to the
  1217. // current version if not specified.
  1218. Sdk_version *string
  1219. // The minimum version of the SDK that this module supports. Defaults to sdk_version if not
  1220. // specified.
  1221. Min_sdk_version *string
  1222. // The max sdk version placeholder used to replace maxSdkVersion attributes on permission
  1223. // and uses-permission tags in manifest_fixer.
  1224. Replace_max_sdk_version_placeholder *string
  1225. Installable *bool
  1226. // If not empty, classes are restricted to the specified packages and their sub-packages.
  1227. Permitted_packages []string
  1228. // List of shared java libs that this module has dependencies to
  1229. Libs []string
  1230. // List of files to remove from the jar file(s)
  1231. Exclude_files []string
  1232. // List of directories to remove from the jar file(s)
  1233. Exclude_dirs []string
  1234. // if set to true, run Jetifier against .jar file. Defaults to false.
  1235. Jetifier *bool
  1236. // set the name of the output
  1237. Stem *string
  1238. Aidl struct {
  1239. // directories that should be added as include directories for any aidl sources of modules
  1240. // that depend on this module, as well as to aidl for this module.
  1241. Export_include_dirs []string
  1242. }
  1243. }
  1244. type Import struct {
  1245. android.ModuleBase
  1246. android.DefaultableModuleBase
  1247. android.ApexModuleBase
  1248. android.BazelModuleBase
  1249. prebuilt android.Prebuilt
  1250. android.SdkBase
  1251. // Functionality common to Module and Import.
  1252. embeddableInModuleAndImport
  1253. hiddenAPI
  1254. dexer
  1255. dexpreopter
  1256. properties ImportProperties
  1257. // output file containing classes.dex and resources
  1258. dexJarFile OptionalDexJarPath
  1259. dexJarInstallFile android.Path
  1260. combinedClasspathFile android.Path
  1261. classLoaderContexts dexpreopt.ClassLoaderContextMap
  1262. exportAidlIncludeDirs android.Paths
  1263. hideApexVariantFromMake bool
  1264. sdkVersion android.SdkSpec
  1265. minSdkVersion android.SdkSpec
  1266. }
  1267. var _ PermittedPackagesForUpdatableBootJars = (*Import)(nil)
  1268. func (j *Import) PermittedPackagesForUpdatableBootJars() []string {
  1269. return j.properties.Permitted_packages
  1270. }
  1271. func (j *Import) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
  1272. return android.SdkSpecFrom(ctx, String(j.properties.Sdk_version))
  1273. }
  1274. func (j *Import) SystemModules() string {
  1275. return "none"
  1276. }
  1277. func (j *Import) MinSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
  1278. if j.properties.Min_sdk_version != nil {
  1279. return android.SdkSpecFrom(ctx, *j.properties.Min_sdk_version)
  1280. }
  1281. return j.SdkVersion(ctx)
  1282. }
  1283. func (j *Import) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.SdkSpec {
  1284. if j.properties.Replace_max_sdk_version_placeholder != nil {
  1285. return android.SdkSpecFrom(ctx, *j.properties.Replace_max_sdk_version_placeholder)
  1286. }
  1287. return android.SdkSpecFrom(ctx, "")
  1288. }
  1289. func (j *Import) TargetSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
  1290. return j.SdkVersion(ctx)
  1291. }
  1292. func (j *Import) Prebuilt() *android.Prebuilt {
  1293. return &j.prebuilt
  1294. }
  1295. func (j *Import) PrebuiltSrcs() []string {
  1296. return j.properties.Jars
  1297. }
  1298. func (j *Import) Name() string {
  1299. return j.prebuilt.Name(j.ModuleBase.Name())
  1300. }
  1301. func (j *Import) Stem() string {
  1302. return proptools.StringDefault(j.properties.Stem, j.ModuleBase.Name())
  1303. }
  1304. func (a *Import) JacocoReportClassesFile() android.Path {
  1305. return nil
  1306. }
  1307. func (j *Import) LintDepSets() LintDepSets {
  1308. return LintDepSets{}
  1309. }
  1310. func (j *Import) getStrictUpdatabilityLinting() bool {
  1311. return false
  1312. }
  1313. func (j *Import) setStrictUpdatabilityLinting(bool) {
  1314. }
  1315. func (j *Import) DepsMutator(ctx android.BottomUpMutatorContext) {
  1316. ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
  1317. if ctx.Device() && Bool(j.dexProperties.Compile_dex) {
  1318. sdkDeps(ctx, android.SdkContext(j), j.dexer)
  1319. }
  1320. }
  1321. func (j *Import) commonBuildActions(ctx android.ModuleContext) {
  1322. //TODO(b/231322772) these should come from Bazel once available
  1323. j.sdkVersion = j.SdkVersion(ctx)
  1324. j.minSdkVersion = j.MinSdkVersion(ctx)
  1325. if !ctx.Provider(android.ApexInfoProvider).(android.ApexInfo).IsForPlatform() {
  1326. j.hideApexVariantFromMake = true
  1327. }
  1328. if ctx.Windows() {
  1329. j.HideFromMake()
  1330. }
  1331. }
  1332. func (j *Import) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  1333. j.commonBuildActions(ctx)
  1334. jars := android.PathsForModuleSrc(ctx, j.properties.Jars)
  1335. jarName := j.Stem() + ".jar"
  1336. outputFile := android.PathForModuleOut(ctx, "combined", jarName)
  1337. TransformJarsToJar(ctx, outputFile, "for prebuilts", jars, android.OptionalPath{},
  1338. false, j.properties.Exclude_files, j.properties.Exclude_dirs)
  1339. if Bool(j.properties.Jetifier) {
  1340. inputFile := outputFile
  1341. outputFile = android.PathForModuleOut(ctx, "jetifier", jarName)
  1342. TransformJetifier(ctx, outputFile, inputFile)
  1343. }
  1344. j.combinedClasspathFile = outputFile
  1345. j.classLoaderContexts = make(dexpreopt.ClassLoaderContextMap)
  1346. var flags javaBuilderFlags
  1347. ctx.VisitDirectDeps(func(module android.Module) {
  1348. tag := ctx.OtherModuleDependencyTag(module)
  1349. if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
  1350. dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
  1351. switch tag {
  1352. case libTag:
  1353. flags.classpath = append(flags.classpath, dep.HeaderJars...)
  1354. flags.dexClasspath = append(flags.dexClasspath, dep.HeaderJars...)
  1355. case staticLibTag:
  1356. flags.classpath = append(flags.classpath, dep.HeaderJars...)
  1357. case bootClasspathTag:
  1358. flags.bootClasspath = append(flags.bootClasspath, dep.HeaderJars...)
  1359. }
  1360. } else if dep, ok := module.(SdkLibraryDependency); ok {
  1361. switch tag {
  1362. case libTag:
  1363. flags.classpath = append(flags.classpath, dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))...)
  1364. }
  1365. }
  1366. addCLCFromDep(ctx, module, j.classLoaderContexts)
  1367. })
  1368. j.maybeInstall(ctx, jarName, outputFile)
  1369. j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.properties.Aidl.Export_include_dirs)
  1370. if ctx.Device() {
  1371. // If this is a variant created for a prebuilt_apex then use the dex implementation jar
  1372. // obtained from the associated deapexer module.
  1373. ai := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
  1374. if ai.ForPrebuiltApex {
  1375. // Get the path of the dex implementation jar from the `deapexer` module.
  1376. di := android.FindDeapexerProviderForModule(ctx)
  1377. if di == nil {
  1378. return // An error has been reported by FindDeapexerProviderForModule.
  1379. }
  1380. if dexOutputPath := di.PrebuiltExportPath(apexRootRelativePathToJavaLib(j.BaseModuleName())); dexOutputPath != nil {
  1381. dexJarFile := makeDexJarPathFromPath(dexOutputPath)
  1382. j.dexJarFile = dexJarFile
  1383. installPath := android.PathForModuleInPartitionInstall(ctx, "apex", ai.ApexVariationName, apexRootRelativePathToJavaLib(j.BaseModuleName()))
  1384. j.dexJarInstallFile = installPath
  1385. j.dexpreopter.installPath = j.dexpreopter.getInstallPath(ctx, installPath)
  1386. setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
  1387. j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
  1388. j.dexpreopt(ctx, dexOutputPath)
  1389. // Initialize the hiddenapi structure.
  1390. j.initHiddenAPI(ctx, dexJarFile, outputFile, j.dexProperties.Uncompress_dex)
  1391. } else {
  1392. // This should never happen as a variant for a prebuilt_apex is only created if the
  1393. // prebuilt_apex has been configured to export the java library dex file.
  1394. ctx.ModuleErrorf("internal error: no dex implementation jar available from prebuilt APEX %s", di.ApexModuleName())
  1395. }
  1396. } else if Bool(j.dexProperties.Compile_dex) {
  1397. sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
  1398. if sdkDep.invalidVersion {
  1399. ctx.AddMissingDependencies(sdkDep.bootclasspath)
  1400. ctx.AddMissingDependencies(sdkDep.java9Classpath)
  1401. } else if sdkDep.useFiles {
  1402. // sdkDep.jar is actually equivalent to turbine header.jar.
  1403. flags.classpath = append(flags.classpath, sdkDep.jars...)
  1404. }
  1405. // Dex compilation
  1406. j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
  1407. ctx, android.PathForModuleInstall(ctx, "framework", jarName))
  1408. setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
  1409. j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
  1410. var dexOutputFile android.OutputPath
  1411. dexOutputFile = j.dexer.compileDex(ctx, flags, j.MinSdkVersion(ctx), outputFile, jarName)
  1412. if ctx.Failed() {
  1413. return
  1414. }
  1415. // Initialize the hiddenapi structure.
  1416. j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), outputFile, j.dexProperties.Uncompress_dex)
  1417. // Encode hidden API flags in dex file.
  1418. dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
  1419. j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
  1420. j.dexJarInstallFile = android.PathForModuleInstall(ctx, "framework", jarName)
  1421. }
  1422. }
  1423. ctx.SetProvider(JavaInfoProvider, JavaInfo{
  1424. HeaderJars: android.PathsIfNonNil(j.combinedClasspathFile),
  1425. ImplementationAndResourcesJars: android.PathsIfNonNil(j.combinedClasspathFile),
  1426. ImplementationJars: android.PathsIfNonNil(j.combinedClasspathFile),
  1427. AidlIncludeDirs: j.exportAidlIncludeDirs,
  1428. })
  1429. }
  1430. func (j *Import) maybeInstall(ctx android.ModuleContext, jarName string, outputFile android.Path) {
  1431. if !Bool(j.properties.Installable) {
  1432. return
  1433. }
  1434. var installDir android.InstallPath
  1435. if ctx.InstallInTestcases() {
  1436. var archDir string
  1437. if !ctx.Host() {
  1438. archDir = ctx.DeviceConfig().DeviceArch()
  1439. }
  1440. installDir = android.PathForModuleInstall(ctx, ctx.ModuleName(), archDir)
  1441. } else {
  1442. installDir = android.PathForModuleInstall(ctx, "framework")
  1443. }
  1444. ctx.InstallFile(installDir, jarName, outputFile)
  1445. }
  1446. func (j *Import) OutputFiles(tag string) (android.Paths, error) {
  1447. switch tag {
  1448. case "", ".jar":
  1449. return android.Paths{j.combinedClasspathFile}, nil
  1450. default:
  1451. return nil, fmt.Errorf("unsupported module reference tag %q", tag)
  1452. }
  1453. }
  1454. var _ android.OutputFileProducer = (*Import)(nil)
  1455. func (j *Import) HeaderJars() android.Paths {
  1456. if j.combinedClasspathFile == nil {
  1457. return nil
  1458. }
  1459. return android.Paths{j.combinedClasspathFile}
  1460. }
  1461. func (j *Import) ImplementationAndResourcesJars() android.Paths {
  1462. if j.combinedClasspathFile == nil {
  1463. return nil
  1464. }
  1465. return android.Paths{j.combinedClasspathFile}
  1466. }
  1467. func (j *Import) DexJarBuildPath() OptionalDexJarPath {
  1468. return j.dexJarFile
  1469. }
  1470. func (j *Import) DexJarInstallPath() android.Path {
  1471. return j.dexJarInstallFile
  1472. }
  1473. func (j *Import) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
  1474. return j.classLoaderContexts
  1475. }
  1476. var _ android.ApexModule = (*Import)(nil)
  1477. // Implements android.ApexModule
  1478. func (j *Import) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
  1479. return j.depIsInSameApex(ctx, dep)
  1480. }
  1481. // Implements android.ApexModule
  1482. func (j *Import) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
  1483. sdkVersion android.ApiLevel) error {
  1484. sdkSpec := j.MinSdkVersion(ctx)
  1485. if !sdkSpec.Specified() {
  1486. return fmt.Errorf("min_sdk_version is not specified")
  1487. }
  1488. if sdkSpec.Kind == android.SdkCore {
  1489. return nil
  1490. }
  1491. if sdkSpec.ApiLevel.GreaterThan(sdkVersion) {
  1492. return fmt.Errorf("newer SDK(%v)", sdkSpec.ApiLevel)
  1493. }
  1494. return nil
  1495. }
  1496. // requiredFilesFromPrebuiltApexForImport returns information about the files that a java_import or
  1497. // java_sdk_library_import with the specified base module name requires to be exported from a
  1498. // prebuilt_apex/apex_set.
  1499. func requiredFilesFromPrebuiltApexForImport(name string) []string {
  1500. // Add the dex implementation jar to the set of exported files.
  1501. return []string{
  1502. apexRootRelativePathToJavaLib(name),
  1503. }
  1504. }
  1505. // apexRootRelativePathToJavaLib returns the path, relative to the root of the apex's contents, for
  1506. // the java library with the specified name.
  1507. func apexRootRelativePathToJavaLib(name string) string {
  1508. return filepath.Join("javalib", name+".jar")
  1509. }
  1510. var _ android.RequiredFilesFromPrebuiltApex = (*Import)(nil)
  1511. func (j *Import) RequiredFilesFromPrebuiltApex(_ android.BaseModuleContext) []string {
  1512. name := j.BaseModuleName()
  1513. return requiredFilesFromPrebuiltApexForImport(name)
  1514. }
  1515. // Add compile time check for interface implementation
  1516. var _ android.IDEInfo = (*Import)(nil)
  1517. var _ android.IDECustomizedModuleName = (*Import)(nil)
  1518. // Collect information for opening IDE project files in java/jdeps.go.
  1519. func (j *Import) IDEInfo(dpInfo *android.IdeInfo) {
  1520. dpInfo.Jars = append(dpInfo.Jars, j.PrebuiltSrcs()...)
  1521. }
  1522. func (j *Import) IDECustomizedModuleName() string {
  1523. // TODO(b/113562217): Extract the base module name from the Import name, often the Import name
  1524. // has a prefix "prebuilt_". Remove the prefix explicitly if needed until we find a better
  1525. // solution to get the Import name.
  1526. return android.RemoveOptionalPrebuiltPrefix(j.Name())
  1527. }
  1528. var _ android.PrebuiltInterface = (*Import)(nil)
  1529. func (j *Import) IsInstallable() bool {
  1530. return Bool(j.properties.Installable)
  1531. }
  1532. var _ DexpreopterInterface = (*Import)(nil)
  1533. // java_import imports one or more `.jar` files into the build graph as if they were built by a java_library module.
  1534. //
  1535. // By default, a java_import has a single variant that expects a `.jar` file containing `.class` files that were
  1536. // compiled against an Android classpath.
  1537. //
  1538. // Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
  1539. // for host modules.
  1540. func ImportFactory() android.Module {
  1541. module := &Import{}
  1542. module.AddProperties(
  1543. &module.properties,
  1544. &module.dexer.dexProperties,
  1545. )
  1546. module.initModuleAndImport(module)
  1547. module.dexProperties.Optimize.EnabledByDefault = false
  1548. android.InitPrebuiltModule(module, &module.properties.Jars)
  1549. android.InitApexModule(module)
  1550. android.InitSdkAwareModule(module)
  1551. android.InitBazelModule(module)
  1552. InitJavaModule(module, android.HostAndDeviceSupported)
  1553. return module
  1554. }
  1555. // java_import imports one or more `.jar` files into the build graph as if they were built by a java_library_host
  1556. // module.
  1557. //
  1558. // A java_import_host has a single variant that expects a `.jar` file containing `.class` files that were
  1559. // compiled against a host bootclasspath.
  1560. func ImportFactoryHost() android.Module {
  1561. module := &Import{}
  1562. module.AddProperties(&module.properties)
  1563. android.InitPrebuiltModule(module, &module.properties.Jars)
  1564. android.InitApexModule(module)
  1565. android.InitBazelModule(module)
  1566. InitJavaModule(module, android.HostSupported)
  1567. return module
  1568. }
  1569. // dex_import module
  1570. type DexImportProperties struct {
  1571. Jars []string `android:"path"`
  1572. // set the name of the output
  1573. Stem *string
  1574. }
  1575. type DexImport struct {
  1576. android.ModuleBase
  1577. android.DefaultableModuleBase
  1578. android.ApexModuleBase
  1579. prebuilt android.Prebuilt
  1580. properties DexImportProperties
  1581. dexJarFile OptionalDexJarPath
  1582. dexpreopter
  1583. hideApexVariantFromMake bool
  1584. }
  1585. func (j *DexImport) Prebuilt() *android.Prebuilt {
  1586. return &j.prebuilt
  1587. }
  1588. func (j *DexImport) PrebuiltSrcs() []string {
  1589. return j.properties.Jars
  1590. }
  1591. func (j *DexImport) Name() string {
  1592. return j.prebuilt.Name(j.ModuleBase.Name())
  1593. }
  1594. func (j *DexImport) Stem() string {
  1595. return proptools.StringDefault(j.properties.Stem, j.ModuleBase.Name())
  1596. }
  1597. func (a *DexImport) JacocoReportClassesFile() android.Path {
  1598. return nil
  1599. }
  1600. func (a *DexImport) LintDepSets() LintDepSets {
  1601. return LintDepSets{}
  1602. }
  1603. func (j *DexImport) IsInstallable() bool {
  1604. return true
  1605. }
  1606. func (j *DexImport) getStrictUpdatabilityLinting() bool {
  1607. return false
  1608. }
  1609. func (j *DexImport) setStrictUpdatabilityLinting(bool) {
  1610. }
  1611. func (j *DexImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  1612. if len(j.properties.Jars) != 1 {
  1613. ctx.PropertyErrorf("jars", "exactly one jar must be provided")
  1614. }
  1615. apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
  1616. if !apexInfo.IsForPlatform() {
  1617. j.hideApexVariantFromMake = true
  1618. }
  1619. j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
  1620. ctx, android.PathForModuleInstall(ctx, "framework", j.Stem()+".jar"))
  1621. j.dexpreopter.uncompressedDex = shouldUncompressDex(ctx, &j.dexpreopter)
  1622. inputJar := ctx.ExpandSource(j.properties.Jars[0], "jars")
  1623. dexOutputFile := android.PathForModuleOut(ctx, ctx.ModuleName()+".jar")
  1624. if j.dexpreopter.uncompressedDex {
  1625. rule := android.NewRuleBuilder(pctx, ctx)
  1626. temporary := android.PathForModuleOut(ctx, ctx.ModuleName()+".jar.unaligned")
  1627. rule.Temporary(temporary)
  1628. // use zip2zip to uncompress classes*.dex files
  1629. rule.Command().
  1630. BuiltTool("zip2zip").
  1631. FlagWithInput("-i ", inputJar).
  1632. FlagWithOutput("-o ", temporary).
  1633. FlagWithArg("-0 ", "'classes*.dex'")
  1634. // use zipalign to align uncompressed classes*.dex files
  1635. rule.Command().
  1636. BuiltTool("zipalign").
  1637. Flag("-f").
  1638. Text("4").
  1639. Input(temporary).
  1640. Output(dexOutputFile)
  1641. rule.DeleteTemporaryFiles()
  1642. rule.Build("uncompress_dex", "uncompress dex")
  1643. } else {
  1644. ctx.Build(pctx, android.BuildParams{
  1645. Rule: android.Cp,
  1646. Input: inputJar,
  1647. Output: dexOutputFile,
  1648. })
  1649. }
  1650. j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
  1651. j.dexpreopt(ctx, dexOutputFile)
  1652. if apexInfo.IsForPlatform() {
  1653. ctx.InstallFile(android.PathForModuleInstall(ctx, "framework"),
  1654. j.Stem()+".jar", dexOutputFile)
  1655. }
  1656. }
  1657. func (j *DexImport) DexJarBuildPath() OptionalDexJarPath {
  1658. return j.dexJarFile
  1659. }
  1660. var _ android.ApexModule = (*DexImport)(nil)
  1661. // Implements android.ApexModule
  1662. func (j *DexImport) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
  1663. sdkVersion android.ApiLevel) error {
  1664. // we don't check prebuilt modules for sdk_version
  1665. return nil
  1666. }
  1667. // dex_import imports a `.jar` file containing classes.dex files.
  1668. //
  1669. // A dex_import module cannot be used as a dependency of a java_* or android_* module, it can only be installed
  1670. // to the device.
  1671. func DexImportFactory() android.Module {
  1672. module := &DexImport{}
  1673. module.AddProperties(&module.properties)
  1674. android.InitPrebuiltModule(module, &module.properties.Jars)
  1675. android.InitApexModule(module)
  1676. InitJavaModule(module, android.DeviceSupported)
  1677. return module
  1678. }
  1679. // Defaults
  1680. type Defaults struct {
  1681. android.ModuleBase
  1682. android.DefaultsModuleBase
  1683. android.ApexModuleBase
  1684. }
  1685. // java_defaults provides a set of properties that can be inherited by other java or android modules.
  1686. //
  1687. // A module can use the properties from a java_defaults module using `defaults: ["defaults_module_name"]`. Each
  1688. // property in the defaults module that exists in the depending module will be prepended to the depending module's
  1689. // value for that property.
  1690. //
  1691. // Example:
  1692. //
  1693. // java_defaults {
  1694. // name: "example_defaults",
  1695. // srcs: ["common/**/*.java"],
  1696. // javacflags: ["-Xlint:all"],
  1697. // aaptflags: ["--auto-add-overlay"],
  1698. // }
  1699. //
  1700. // java_library {
  1701. // name: "example",
  1702. // defaults: ["example_defaults"],
  1703. // srcs: ["example/**/*.java"],
  1704. // }
  1705. //
  1706. // is functionally identical to:
  1707. //
  1708. // java_library {
  1709. // name: "example",
  1710. // srcs: [
  1711. // "common/**/*.java",
  1712. // "example/**/*.java",
  1713. // ],
  1714. // javacflags: ["-Xlint:all"],
  1715. // }
  1716. func DefaultsFactory() android.Module {
  1717. module := &Defaults{}
  1718. module.AddProperties(
  1719. &CommonProperties{},
  1720. &DeviceProperties{},
  1721. &OverridableDeviceProperties{},
  1722. &DexProperties{},
  1723. &DexpreoptProperties{},
  1724. &android.ProtoProperties{},
  1725. &aaptProperties{},
  1726. &androidLibraryProperties{},
  1727. &appProperties{},
  1728. &appTestProperties{},
  1729. &overridableAppProperties{},
  1730. &testProperties{},
  1731. &ImportProperties{},
  1732. &AARImportProperties{},
  1733. &sdkLibraryProperties{},
  1734. &commonToSdkLibraryAndImportProperties{},
  1735. &DexImportProperties{},
  1736. &android.ApexProperties{},
  1737. &RuntimeResourceOverlayProperties{},
  1738. &LintProperties{},
  1739. &appTestHelperAppProperties{},
  1740. )
  1741. android.InitDefaultsModule(module)
  1742. return module
  1743. }
  1744. func kytheExtractJavaFactory() android.Singleton {
  1745. return &kytheExtractJavaSingleton{}
  1746. }
  1747. type kytheExtractJavaSingleton struct {
  1748. }
  1749. func (ks *kytheExtractJavaSingleton) GenerateBuildActions(ctx android.SingletonContext) {
  1750. var xrefTargets android.Paths
  1751. ctx.VisitAllModules(func(module android.Module) {
  1752. if javaModule, ok := module.(xref); ok {
  1753. xrefTargets = append(xrefTargets, javaModule.XrefJavaFiles()...)
  1754. }
  1755. })
  1756. // TODO(asmundak): perhaps emit a rule to output a warning if there were no xrefTargets
  1757. if len(xrefTargets) > 0 {
  1758. ctx.Phony("xref_java", xrefTargets...)
  1759. }
  1760. }
  1761. var Bool = proptools.Bool
  1762. var BoolDefault = proptools.BoolDefault
  1763. var String = proptools.String
  1764. var inList = android.InList
  1765. // Add class loader context (CLC) of a given dependency to the current CLC.
  1766. func addCLCFromDep(ctx android.ModuleContext, depModule android.Module,
  1767. clcMap dexpreopt.ClassLoaderContextMap) {
  1768. dep, ok := depModule.(UsesLibraryDependency)
  1769. if !ok {
  1770. return
  1771. }
  1772. depName := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(depModule))
  1773. var sdkLib *string
  1774. if lib, ok := depModule.(SdkLibraryDependency); ok && lib.sharedLibrary() {
  1775. // A shared SDK library. This should be added as a top-level CLC element.
  1776. sdkLib = &depName
  1777. } else if ulib, ok := depModule.(ProvidesUsesLib); ok {
  1778. // A non-SDK library disguised as an SDK library by the means of `provides_uses_lib`
  1779. // property. This should be handled in the same way as a shared SDK library.
  1780. sdkLib = ulib.ProvidesUsesLib()
  1781. }
  1782. depTag := ctx.OtherModuleDependencyTag(depModule)
  1783. if depTag == libTag {
  1784. // Ok, propagate <uses-library> through non-static library dependencies.
  1785. } else if tag, ok := depTag.(usesLibraryDependencyTag); ok && tag.sdkVersion == dexpreopt.AnySdkVersion {
  1786. // Ok, propagate <uses-library> through non-compatibility <uses-library> dependencies.
  1787. } else if depTag == staticLibTag {
  1788. // Propagate <uses-library> through static library dependencies, unless it is a component
  1789. // library (such as stubs). Component libraries have a dependency on their SDK library,
  1790. // which should not be pulled just because of a static component library.
  1791. if sdkLib != nil {
  1792. return
  1793. }
  1794. } else {
  1795. // Don't propagate <uses-library> for other dependency tags.
  1796. return
  1797. }
  1798. // If this is an SDK (or SDK-like) library, then it should be added as a node in the CLC tree,
  1799. // and its CLC should be added as subtree of that node. Otherwise the library is not a
  1800. // <uses_library> and should not be added to CLC, but the transitive <uses-library> dependencies
  1801. // from its CLC should be added to the current CLC.
  1802. if sdkLib != nil {
  1803. clcMap.AddContext(ctx, dexpreopt.AnySdkVersion, *sdkLib, false,
  1804. dep.DexJarBuildPath().PathOrNil(), dep.DexJarInstallPath(), dep.ClassLoaderContexts())
  1805. } else {
  1806. clcMap.AddContextMap(dep.ClassLoaderContexts(), depName)
  1807. }
  1808. }
  1809. type javaResourcesAttributes struct {
  1810. Resources bazel.LabelListAttribute
  1811. Resource_strip_prefix *string
  1812. }
  1813. func (m *Library) convertJavaResourcesAttributes(ctx android.TopDownMutatorContext) *javaResourcesAttributes {
  1814. var resources bazel.LabelList
  1815. var resourceStripPrefix *string
  1816. if m.properties.Java_resources != nil {
  1817. resources.Append(android.BazelLabelForModuleSrc(ctx, m.properties.Java_resources))
  1818. }
  1819. //TODO(b/179889880) handle case where glob includes files outside package
  1820. resDeps := ResourceDirsToFiles(
  1821. ctx,
  1822. m.properties.Java_resource_dirs,
  1823. m.properties.Exclude_java_resource_dirs,
  1824. m.properties.Exclude_java_resources,
  1825. )
  1826. for i, resDep := range resDeps {
  1827. dir, files := resDep.dir, resDep.files
  1828. resources.Append(bazel.MakeLabelList(android.RootToModuleRelativePaths(ctx, files)))
  1829. // Bazel includes the relative path from the WORKSPACE root when placing the resource
  1830. // inside the JAR file, so we need to remove that prefix
  1831. resourceStripPrefix = proptools.StringPtr(dir.String())
  1832. if i > 0 {
  1833. // TODO(b/226423379) allow multiple resource prefixes
  1834. ctx.ModuleErrorf("bp2build does not support more than one directory in java_resource_dirs (b/226423379)")
  1835. }
  1836. }
  1837. return &javaResourcesAttributes{
  1838. Resources: bazel.MakeLabelListAttribute(resources),
  1839. Resource_strip_prefix: resourceStripPrefix,
  1840. }
  1841. }
  1842. type javaCommonAttributes struct {
  1843. *javaResourcesAttributes
  1844. Srcs bazel.LabelListAttribute
  1845. Plugins bazel.LabelListAttribute
  1846. Javacopts bazel.StringListAttribute
  1847. }
  1848. type javaDependencyLabels struct {
  1849. // Dependencies which DO NOT contribute to the API visible to upstream dependencies.
  1850. Deps bazel.LabelListAttribute
  1851. // Dependencies which DO contribute to the API visible to upstream dependencies.
  1852. StaticDeps bazel.LabelListAttribute
  1853. }
  1854. type eventLogTagsAttributes struct {
  1855. Srcs bazel.LabelListAttribute
  1856. }
  1857. type aidlLibraryAttributes struct {
  1858. Srcs bazel.LabelListAttribute
  1859. }
  1860. type javaAidlLibraryAttributes struct {
  1861. Deps bazel.LabelListAttribute
  1862. }
  1863. // convertLibraryAttrsBp2Build converts a few shared attributes from java_* modules
  1864. // and also separates dependencies into dynamic dependencies and static dependencies.
  1865. // Each corresponding Bazel target type, can have a different method for handling
  1866. // dynamic vs. static dependencies, and so these are returned to the calling function.
  1867. func (m *Library) convertLibraryAttrsBp2Build(ctx android.TopDownMutatorContext) (*javaCommonAttributes, *javaDependencyLabels) {
  1868. var srcs bazel.LabelListAttribute
  1869. var deps bazel.LabelList
  1870. var staticDeps bazel.LabelList
  1871. archVariantProps := m.GetArchVariantProperties(ctx, &CommonProperties{})
  1872. for axis, configToProps := range archVariantProps {
  1873. for config, _props := range configToProps {
  1874. if archProps, ok := _props.(*CommonProperties); ok {
  1875. archSrcs := android.BazelLabelForModuleSrcExcludes(ctx, archProps.Srcs, archProps.Exclude_srcs)
  1876. srcs.SetSelectValue(axis, config, archSrcs)
  1877. }
  1878. }
  1879. }
  1880. javaSrcPartition := "java"
  1881. protoSrcPartition := "proto"
  1882. logtagSrcPartition := "logtag"
  1883. aidlSrcPartition := "aidl"
  1884. srcPartitions := bazel.PartitionLabelListAttribute(ctx, &srcs, bazel.LabelPartitions{
  1885. javaSrcPartition: bazel.LabelPartition{Extensions: []string{".java"}, Keep_remainder: true},
  1886. logtagSrcPartition: bazel.LabelPartition{Extensions: []string{".logtags", ".logtag"}},
  1887. protoSrcPartition: android.ProtoSrcLabelPartition,
  1888. aidlSrcPartition: android.AidlSrcLabelPartition,
  1889. })
  1890. javaSrcs := srcPartitions[javaSrcPartition]
  1891. if !srcPartitions[logtagSrcPartition].IsEmpty() {
  1892. logtagsLibName := m.Name() + "_logtags"
  1893. ctx.CreateBazelTargetModule(
  1894. bazel.BazelTargetModuleProperties{
  1895. Rule_class: "event_log_tags",
  1896. Bzl_load_location: "//build/make/tools:event_log_tags.bzl",
  1897. },
  1898. android.CommonAttributes{Name: logtagsLibName},
  1899. &eventLogTagsAttributes{
  1900. Srcs: srcPartitions[logtagSrcPartition],
  1901. },
  1902. )
  1903. logtagsSrcs := bazel.MakeLabelList([]bazel.Label{{Label: ":" + logtagsLibName}})
  1904. javaSrcs.Append(bazel.MakeLabelListAttribute(logtagsSrcs))
  1905. }
  1906. if !srcPartitions[aidlSrcPartition].IsEmpty() {
  1907. aidlLibs, aidlSrcs := srcPartitions[aidlSrcPartition].Partition(func(src bazel.Label) bool {
  1908. return android.IsConvertedToAidlLibrary(ctx, src.OriginalModuleName)
  1909. })
  1910. if !aidlSrcs.IsEmpty() {
  1911. aidlLibName := m.Name() + "_aidl_library"
  1912. ctx.CreateBazelTargetModule(
  1913. bazel.BazelTargetModuleProperties{
  1914. Rule_class: "aidl_library",
  1915. Bzl_load_location: "//build/bazel/rules/aidl:library.bzl",
  1916. },
  1917. android.CommonAttributes{Name: aidlLibName},
  1918. &aidlLibraryAttributes{
  1919. Srcs: aidlSrcs,
  1920. },
  1921. )
  1922. aidlLibs.Add(&bazel.LabelAttribute{Value: &bazel.Label{Label: ":" + aidlLibName}})
  1923. }
  1924. javaAidlLibName := m.Name() + "_java_aidl_library"
  1925. ctx.CreateBazelTargetModule(
  1926. bazel.BazelTargetModuleProperties{
  1927. Rule_class: "java_aidl_library",
  1928. Bzl_load_location: "//build/bazel/rules/java:aidl_library.bzl",
  1929. },
  1930. android.CommonAttributes{Name: javaAidlLibName},
  1931. &javaAidlLibraryAttributes{
  1932. Deps: aidlLibs,
  1933. },
  1934. )
  1935. staticDeps.Add(&bazel.Label{Label: ":" + javaAidlLibName})
  1936. }
  1937. var javacopts []string
  1938. if m.properties.Javacflags != nil {
  1939. javacopts = append(javacopts, m.properties.Javacflags...)
  1940. }
  1941. if m.properties.Java_version != nil {
  1942. javaVersion := normalizeJavaVersion(ctx, *m.properties.Java_version).String()
  1943. javacopts = append(javacopts, fmt.Sprintf("-source %s -target %s", javaVersion, javaVersion))
  1944. }
  1945. epEnabled := m.properties.Errorprone.Enabled
  1946. //TODO(b/227504307) add configuration that depends on RUN_ERROR_PRONE environment variable
  1947. if Bool(epEnabled) {
  1948. javacopts = append(javacopts, m.properties.Errorprone.Javacflags...)
  1949. }
  1950. commonAttrs := &javaCommonAttributes{
  1951. Srcs: javaSrcs,
  1952. javaResourcesAttributes: m.convertJavaResourcesAttributes(ctx),
  1953. Plugins: bazel.MakeLabelListAttribute(
  1954. android.BazelLabelForModuleDeps(ctx, m.properties.Plugins),
  1955. ),
  1956. Javacopts: bazel.MakeStringListAttribute(javacopts),
  1957. }
  1958. if m.properties.Libs != nil {
  1959. deps.Append(android.BazelLabelForModuleDeps(ctx, android.LastUniqueStrings(android.CopyOf(m.properties.Libs))))
  1960. }
  1961. if m.properties.Static_libs != nil {
  1962. staticDeps.Append(android.BazelLabelForModuleDeps(ctx, android.LastUniqueStrings(android.CopyOf(m.properties.Static_libs))))
  1963. }
  1964. protoDepLabel := bp2buildProto(ctx, &m.Module, srcPartitions[protoSrcPartition])
  1965. // Soong does not differentiate between a java_library and the Bazel equivalent of
  1966. // a java_proto_library + proto_library pair. Instead, in Soong proto sources are
  1967. // listed directly in the srcs of a java_library, and the classes produced
  1968. // by protoc are included directly in the resulting JAR. Thus upstream dependencies
  1969. // that depend on a java_library with proto sources can link directly to the protobuf API,
  1970. // and so this should be a static dependency.
  1971. staticDeps.Add(protoDepLabel)
  1972. depLabels := &javaDependencyLabels{}
  1973. depLabels.Deps = bazel.MakeLabelListAttribute(deps)
  1974. depLabels.StaticDeps = bazel.MakeLabelListAttribute(staticDeps)
  1975. return commonAttrs, depLabels
  1976. }
  1977. type javaLibraryAttributes struct {
  1978. *javaCommonAttributes
  1979. Deps bazel.LabelListAttribute
  1980. Exports bazel.LabelListAttribute
  1981. }
  1982. func javaLibraryBp2Build(ctx android.TopDownMutatorContext, m *Library) {
  1983. commonAttrs, depLabels := m.convertLibraryAttrsBp2Build(ctx)
  1984. deps := depLabels.Deps
  1985. if !commonAttrs.Srcs.IsEmpty() {
  1986. deps.Append(depLabels.StaticDeps) // we should only append these if there are sources to use them
  1987. sdkVersion := m.SdkVersion(ctx)
  1988. if sdkVersion.Kind == android.SdkPublic && sdkVersion.ApiLevel == android.FutureApiLevel {
  1989. // TODO(b/220869005) remove forced dependency on current public android.jar
  1990. deps.Add(bazel.MakeLabelAttribute("//prebuilts/sdk:public_current_android_sdk_java_import"))
  1991. }
  1992. } else if !deps.IsEmpty() {
  1993. ctx.ModuleErrorf("Module has direct dependencies but no sources. Bazel will not allow this.")
  1994. }
  1995. attrs := &javaLibraryAttributes{
  1996. javaCommonAttributes: commonAttrs,
  1997. Deps: deps,
  1998. Exports: depLabels.StaticDeps,
  1999. }
  2000. props := bazel.BazelTargetModuleProperties{
  2001. Rule_class: "java_library",
  2002. Bzl_load_location: "//build/bazel/rules/java:library.bzl",
  2003. }
  2004. ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, attrs)
  2005. }
  2006. type javaBinaryHostAttributes struct {
  2007. *javaCommonAttributes
  2008. Deps bazel.LabelListAttribute
  2009. Runtime_deps bazel.LabelListAttribute
  2010. Main_class string
  2011. Jvm_flags bazel.StringListAttribute
  2012. }
  2013. // JavaBinaryHostBp2Build is for java_binary_host bp2build.
  2014. func javaBinaryHostBp2Build(ctx android.TopDownMutatorContext, m *Binary) {
  2015. commonAttrs, depLabels := m.convertLibraryAttrsBp2Build(ctx)
  2016. deps := depLabels.Deps
  2017. deps.Append(depLabels.StaticDeps)
  2018. if m.binaryProperties.Jni_libs != nil {
  2019. deps.Append(bazel.MakeLabelListAttribute(android.BazelLabelForModuleDeps(ctx, m.binaryProperties.Jni_libs)))
  2020. }
  2021. var runtimeDeps bazel.LabelListAttribute
  2022. if commonAttrs.Srcs.IsEmpty() {
  2023. // if there are no sources, then the dependencies can only be used at runtime
  2024. runtimeDeps = deps
  2025. deps = bazel.LabelListAttribute{}
  2026. }
  2027. mainClass := ""
  2028. if m.binaryProperties.Main_class != nil {
  2029. mainClass = *m.binaryProperties.Main_class
  2030. }
  2031. if m.properties.Manifest != nil {
  2032. mainClassInManifest, err := android.GetMainClassInManifest(ctx.Config(), android.PathForModuleSrc(ctx, *m.properties.Manifest).String())
  2033. if err != nil {
  2034. return
  2035. }
  2036. mainClass = mainClassInManifest
  2037. }
  2038. attrs := &javaBinaryHostAttributes{
  2039. javaCommonAttributes: commonAttrs,
  2040. Deps: deps,
  2041. Runtime_deps: runtimeDeps,
  2042. Main_class: mainClass,
  2043. }
  2044. // Attribute jvm_flags
  2045. if m.binaryProperties.Jni_libs != nil {
  2046. jniLibPackages := map[string]bool{}
  2047. for _, jniLibLabel := range android.BazelLabelForModuleDeps(ctx, m.binaryProperties.Jni_libs).Includes {
  2048. jniLibPackage := jniLibLabel.Label
  2049. indexOfColon := strings.Index(jniLibLabel.Label, ":")
  2050. if indexOfColon > 0 {
  2051. // JNI lib from other package
  2052. jniLibPackage = jniLibLabel.Label[2:indexOfColon]
  2053. } else if indexOfColon == 0 {
  2054. // JNI lib in the same package of java_binary
  2055. packageOfCurrentModule := m.GetBazelLabel(ctx, m)
  2056. jniLibPackage = packageOfCurrentModule[2:strings.Index(packageOfCurrentModule, ":")]
  2057. }
  2058. if _, inMap := jniLibPackages[jniLibPackage]; !inMap {
  2059. jniLibPackages[jniLibPackage] = true
  2060. }
  2061. }
  2062. jniLibPaths := []string{}
  2063. for jniLibPackage, _ := range jniLibPackages {
  2064. // See cs/f:.*/third_party/bazel/.*java_stub_template.txt for the use of RUNPATH
  2065. jniLibPaths = append(jniLibPaths, "$${RUNPATH}"+jniLibPackage)
  2066. }
  2067. attrs.Jvm_flags = bazel.MakeStringListAttribute([]string{"-Djava.library.path=" + strings.Join(jniLibPaths, ":")})
  2068. }
  2069. props := bazel.BazelTargetModuleProperties{
  2070. Rule_class: "java_binary",
  2071. }
  2072. // Create the BazelTargetModule.
  2073. ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, attrs)
  2074. }
  2075. type bazelJavaImportAttributes struct {
  2076. Jars bazel.LabelListAttribute
  2077. }
  2078. // java_import bp2Build converter.
  2079. func (i *Import) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
  2080. var jars bazel.LabelListAttribute
  2081. archVariantProps := i.GetArchVariantProperties(ctx, &ImportProperties{})
  2082. for axis, configToProps := range archVariantProps {
  2083. for config, _props := range configToProps {
  2084. if archProps, ok := _props.(*ImportProperties); ok {
  2085. archJars := android.BazelLabelForModuleSrcExcludes(ctx, archProps.Jars, []string(nil))
  2086. jars.SetSelectValue(axis, config, archJars)
  2087. }
  2088. }
  2089. }
  2090. attrs := &bazelJavaImportAttributes{
  2091. Jars: jars,
  2092. }
  2093. props := bazel.BazelTargetModuleProperties{Rule_class: "java_import"}
  2094. ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: android.RemoveOptionalPrebuiltPrefix(i.Name())}, attrs)
  2095. }
  2096. var _ android.MixedBuildBuildable = (*Import)(nil)
  2097. func (i *Import) getBazelModuleLabel(ctx android.BaseModuleContext) string {
  2098. return android.RemoveOptionalPrebuiltPrefixFromBazelLabel(i.GetBazelLabel(ctx, i))
  2099. }
  2100. func (i *Import) ProcessBazelQueryResponse(ctx android.ModuleContext) {
  2101. i.commonBuildActions(ctx)
  2102. bazelCtx := ctx.Config().BazelContext
  2103. filePaths, err := bazelCtx.GetOutputFiles(i.getBazelModuleLabel(ctx), android.GetConfigKey(ctx))
  2104. if err != nil {
  2105. ctx.ModuleErrorf(err.Error())
  2106. return
  2107. }
  2108. bazelJars := android.Paths{}
  2109. for _, bazelOutputFile := range filePaths {
  2110. bazelJars = append(bazelJars, android.PathForBazelOut(ctx, bazelOutputFile))
  2111. }
  2112. jarName := android.RemoveOptionalPrebuiltPrefix(i.Name()) + ".jar"
  2113. outputFile := android.PathForModuleOut(ctx, "bazelCombined", jarName)
  2114. TransformJarsToJar(ctx, outputFile, "combine prebuilt jars", bazelJars,
  2115. android.OptionalPath{}, // manifest
  2116. false, // stripDirEntries
  2117. []string{}, // filesToStrip
  2118. []string{}, // dirsToStrip
  2119. )
  2120. i.combinedClasspathFile = outputFile
  2121. ctx.SetProvider(JavaInfoProvider, JavaInfo{
  2122. HeaderJars: android.PathsIfNonNil(i.combinedClasspathFile),
  2123. ImplementationAndResourcesJars: android.PathsIfNonNil(i.combinedClasspathFile),
  2124. ImplementationJars: android.PathsIfNonNil(i.combinedClasspathFile),
  2125. //TODO(b/240308299) include AIDL information from Bazel
  2126. })
  2127. i.maybeInstall(ctx, jarName, outputFile)
  2128. }
  2129. func (i *Import) QueueBazelCall(ctx android.BaseModuleContext) {
  2130. bazelCtx := ctx.Config().BazelContext
  2131. bazelCtx.QueueBazelRequest(i.getBazelModuleLabel(ctx), cquery.GetOutputFiles, android.GetConfigKey(ctx))
  2132. }
  2133. func (i *Import) IsMixedBuildSupported(ctx android.BaseModuleContext) bool {
  2134. return true
  2135. }