java.go 99 KB

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