java.go 111 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316
  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.RegisterParallelSingletonType("logtags", LogtagsSingleton)
  65. ctx.RegisterParallelSingletonType("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. javaApiContributionTag = dependencyTag{name: "java-api-contribution"}
  335. depApiSrcsTag = dependencyTag{name: "dep-api-srcs"}
  336. jniInstallTag = installDependencyTag{name: "jni install"}
  337. binaryInstallTag = installDependencyTag{name: "binary install"}
  338. usesLibReqTag = makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, false)
  339. usesLibOptTag = makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, true)
  340. usesLibCompat28OptTag = makeUsesLibraryDependencyTag(28, true)
  341. usesLibCompat29ReqTag = makeUsesLibraryDependencyTag(29, false)
  342. usesLibCompat30OptTag = makeUsesLibraryDependencyTag(30, true)
  343. )
  344. func IsLibDepTag(depTag blueprint.DependencyTag) bool {
  345. return depTag == libTag || depTag == sdkLibTag
  346. }
  347. func IsStaticLibDepTag(depTag blueprint.DependencyTag) bool {
  348. return depTag == staticLibTag
  349. }
  350. type sdkDep struct {
  351. useModule, useFiles, invalidVersion bool
  352. // The modules that will be added to the bootclasspath when targeting 1.8 or lower
  353. bootclasspath []string
  354. // The default system modules to use. Will be an empty string if no system
  355. // modules are to be used.
  356. systemModules string
  357. // The modules that will be added to the classpath regardless of the Java language level targeted
  358. classpath []string
  359. // The modules that will be added ot the classpath when targeting 1.9 or higher
  360. // (normally these will be on the bootclasspath when targeting 1.8 or lower)
  361. java9Classpath []string
  362. frameworkResModule string
  363. jars android.Paths
  364. aidl android.OptionalPath
  365. noStandardLibs, noFrameworksLibs bool
  366. }
  367. func (s sdkDep) hasStandardLibs() bool {
  368. return !s.noStandardLibs
  369. }
  370. func (s sdkDep) hasFrameworkLibs() bool {
  371. return !s.noStandardLibs && !s.noFrameworksLibs
  372. }
  373. type jniLib struct {
  374. name string
  375. path android.Path
  376. target android.Target
  377. coverageFile android.OptionalPath
  378. unstrippedFile android.Path
  379. partition string
  380. }
  381. func sdkDeps(ctx android.BottomUpMutatorContext, sdkContext android.SdkContext, d dexer) {
  382. sdkDep := decodeSdkDep(ctx, sdkContext)
  383. if sdkDep.useModule {
  384. ctx.AddVariationDependencies(nil, bootClasspathTag, sdkDep.bootclasspath...)
  385. ctx.AddVariationDependencies(nil, java9LibTag, sdkDep.java9Classpath...)
  386. ctx.AddVariationDependencies(nil, sdkLibTag, sdkDep.classpath...)
  387. if d.effectiveOptimizeEnabled() && sdkDep.hasStandardLibs() {
  388. ctx.AddVariationDependencies(nil, proguardRaiseTag,
  389. android.JavaApiLibraryNames(ctx.Config(), config.LegacyCorePlatformBootclasspathLibraries)...,
  390. )
  391. }
  392. if d.effectiveOptimizeEnabled() && sdkDep.hasFrameworkLibs() {
  393. ctx.AddVariationDependencies(nil, proguardRaiseTag, config.FrameworkLibraries...)
  394. }
  395. }
  396. if sdkDep.systemModules != "" {
  397. ctx.AddVariationDependencies(nil, systemModulesTag, sdkDep.systemModules)
  398. }
  399. }
  400. type deps struct {
  401. // bootClasspath is the list of jars that form the boot classpath (generally the java.* and
  402. // android.* classes) for tools that still use it. javac targeting 1.9 or higher uses
  403. // systemModules and java9Classpath instead.
  404. bootClasspath classpath
  405. // classpath is the list of jars that form the classpath for javac and kotlinc rules. It
  406. // contains header jars for all static and non-static dependencies.
  407. classpath classpath
  408. // dexClasspath is the list of jars that form the classpath for d8 and r8 rules. It contains
  409. // header jars for all non-static dependencies. Static dependencies have already been
  410. // combined into the program jar.
  411. dexClasspath classpath
  412. // java9Classpath is the list of jars that will be added to the classpath when targeting
  413. // 1.9 or higher. It generally contains the android.* classes, while the java.* classes
  414. // are provided by systemModules.
  415. java9Classpath classpath
  416. processorPath classpath
  417. errorProneProcessorPath classpath
  418. processorClasses []string
  419. staticJars android.Paths
  420. staticHeaderJars android.Paths
  421. staticResourceJars android.Paths
  422. aidlIncludeDirs android.Paths
  423. srcs android.Paths
  424. srcJars android.Paths
  425. systemModules *systemModules
  426. aidlPreprocess android.OptionalPath
  427. kotlinStdlib android.Paths
  428. kotlinAnnotations android.Paths
  429. kotlinPlugins android.Paths
  430. disableTurbine bool
  431. }
  432. func checkProducesJars(ctx android.ModuleContext, dep android.SourceFileProducer) {
  433. for _, f := range dep.Srcs() {
  434. if f.Ext() != ".jar" {
  435. ctx.ModuleErrorf("genrule %q must generate files ending with .jar to be used as a libs or static_libs dependency",
  436. ctx.OtherModuleName(dep.(blueprint.Module)))
  437. }
  438. }
  439. }
  440. func getJavaVersion(ctx android.ModuleContext, javaVersion string, sdkContext android.SdkContext) javaVersion {
  441. if javaVersion != "" {
  442. return normalizeJavaVersion(ctx, javaVersion)
  443. } else if ctx.Device() {
  444. return defaultJavaLanguageVersion(ctx, sdkContext.SdkVersion(ctx))
  445. } else {
  446. return JAVA_VERSION_17
  447. }
  448. }
  449. // Java version for stubs generation
  450. func getStubsJavaVersion() javaVersion {
  451. return JAVA_VERSION_8
  452. }
  453. type javaVersion int
  454. const (
  455. JAVA_VERSION_UNSUPPORTED = 0
  456. JAVA_VERSION_6 = 6
  457. JAVA_VERSION_7 = 7
  458. JAVA_VERSION_8 = 8
  459. JAVA_VERSION_9 = 9
  460. JAVA_VERSION_11 = 11
  461. JAVA_VERSION_17 = 17
  462. )
  463. func (v javaVersion) String() string {
  464. switch v {
  465. case JAVA_VERSION_6:
  466. return "1.6"
  467. case JAVA_VERSION_7:
  468. return "1.7"
  469. case JAVA_VERSION_8:
  470. return "1.8"
  471. case JAVA_VERSION_9:
  472. return "1.9"
  473. case JAVA_VERSION_11:
  474. return "11"
  475. case JAVA_VERSION_17:
  476. return "17"
  477. default:
  478. return "unsupported"
  479. }
  480. }
  481. func (v javaVersion) StringForKotlinc() string {
  482. // $ ./external/kotlinc/bin/kotlinc -jvm-target foo
  483. // error: unknown JVM target version: foo
  484. // Supported versions: 1.6, 1.8, 9, 10, 11, 12, 13, 14, 15, 16, 17
  485. switch v {
  486. case JAVA_VERSION_7:
  487. return "1.6"
  488. case JAVA_VERSION_9:
  489. return "9"
  490. default:
  491. return v.String()
  492. }
  493. }
  494. // Returns true if javac targeting this version uses system modules instead of a bootclasspath.
  495. func (v javaVersion) usesJavaModules() bool {
  496. return v >= 9
  497. }
  498. func normalizeJavaVersion(ctx android.BaseModuleContext, javaVersion string) javaVersion {
  499. switch javaVersion {
  500. case "1.6", "6":
  501. return JAVA_VERSION_6
  502. case "1.7", "7":
  503. return JAVA_VERSION_7
  504. case "1.8", "8":
  505. return JAVA_VERSION_8
  506. case "1.9", "9":
  507. return JAVA_VERSION_9
  508. case "11":
  509. return JAVA_VERSION_11
  510. case "17":
  511. return JAVA_VERSION_17
  512. case "10", "12", "13", "14", "15", "16":
  513. ctx.PropertyErrorf("java_version", "Java language level %s is not supported", javaVersion)
  514. return JAVA_VERSION_UNSUPPORTED
  515. default:
  516. ctx.PropertyErrorf("java_version", "Unrecognized Java language level")
  517. return JAVA_VERSION_UNSUPPORTED
  518. }
  519. }
  520. //
  521. // Java libraries (.jar file)
  522. //
  523. type Library struct {
  524. Module
  525. exportedProguardFlagFiles android.Paths
  526. InstallMixin func(ctx android.ModuleContext, installPath android.Path) (extraInstallDeps android.Paths)
  527. }
  528. var _ LibraryDependency = (*Library)(nil)
  529. func (j *Library) ExportedProguardFlagFiles() android.Paths {
  530. return j.exportedProguardFlagFiles
  531. }
  532. var _ android.ApexModule = (*Library)(nil)
  533. // Provides access to the list of permitted packages from apex boot jars.
  534. type PermittedPackagesForUpdatableBootJars interface {
  535. PermittedPackagesForUpdatableBootJars() []string
  536. }
  537. var _ PermittedPackagesForUpdatableBootJars = (*Library)(nil)
  538. func (j *Library) PermittedPackagesForUpdatableBootJars() []string {
  539. return j.properties.Permitted_packages
  540. }
  541. func shouldUncompressDex(ctx android.ModuleContext, dexpreopter *dexpreopter) bool {
  542. // Store uncompressed (and aligned) any dex files from jars in APEXes.
  543. if apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo); !apexInfo.IsForPlatform() {
  544. return true
  545. }
  546. // Store uncompressed (and do not strip) dex files from boot class path jars.
  547. if inList(ctx.ModuleName(), ctx.Config().BootJars()) {
  548. return true
  549. }
  550. // Store uncompressed dex files that are preopted on /system.
  551. if !dexpreopter.dexpreoptDisabled(ctx) && (ctx.Host() || !dexpreopter.odexOnSystemOther(ctx, dexpreopter.installPath)) {
  552. return true
  553. }
  554. if ctx.Config().UncompressPrivAppDex() &&
  555. inList(ctx.ModuleName(), ctx.Config().ModulesLoadedByPrivilegedModules()) {
  556. return true
  557. }
  558. return false
  559. }
  560. // Sets `dexer.dexProperties.Uncompress_dex` to the proper value.
  561. func setUncompressDex(ctx android.ModuleContext, dexpreopter *dexpreopter, dexer *dexer) {
  562. if dexer.dexProperties.Uncompress_dex == nil {
  563. // If the value was not force-set by the user, use reasonable default based on the module.
  564. dexer.dexProperties.Uncompress_dex = proptools.BoolPtr(shouldUncompressDex(ctx, dexpreopter))
  565. }
  566. }
  567. func (j *Library) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  568. j.provideHiddenAPIPropertyInfo(ctx)
  569. j.sdkVersion = j.SdkVersion(ctx)
  570. j.minSdkVersion = j.MinSdkVersion(ctx)
  571. j.maxSdkVersion = j.MaxSdkVersion(ctx)
  572. apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
  573. if !apexInfo.IsForPlatform() {
  574. j.hideApexVariantFromMake = true
  575. }
  576. j.checkSdkVersions(ctx)
  577. if ctx.Device() {
  578. j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
  579. ctx, android.PathForModuleInstall(ctx, "framework", j.Stem()+".jar"))
  580. j.dexpreopter.isSDKLibrary = j.deviceProperties.IsSDKLibrary
  581. setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
  582. j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
  583. j.classLoaderContexts = j.usesLibrary.classLoaderContextForUsesLibDeps(ctx)
  584. }
  585. j.compile(ctx, nil)
  586. // Collect the module directory for IDE info in java/jdeps.go.
  587. j.modulePaths = append(j.modulePaths, ctx.ModuleDir())
  588. exclusivelyForApex := !apexInfo.IsForPlatform()
  589. if (Bool(j.properties.Installable) || ctx.Host()) && !exclusivelyForApex {
  590. var extraInstallDeps android.Paths
  591. if j.InstallMixin != nil {
  592. extraInstallDeps = j.InstallMixin(ctx, j.outputFile)
  593. }
  594. hostDexNeeded := Bool(j.deviceProperties.Hostdex) && !ctx.Host()
  595. if hostDexNeeded {
  596. j.hostdexInstallFile = ctx.InstallFile(
  597. android.PathForHostDexInstall(ctx, "framework"),
  598. j.Stem()+"-hostdex.jar", j.outputFile)
  599. }
  600. var installDir android.InstallPath
  601. if ctx.InstallInTestcases() {
  602. var archDir string
  603. if !ctx.Host() {
  604. archDir = ctx.DeviceConfig().DeviceArch()
  605. }
  606. installDir = android.PathForModuleInstall(ctx, ctx.ModuleName(), archDir)
  607. } else {
  608. installDir = android.PathForModuleInstall(ctx, "framework")
  609. }
  610. j.installFile = ctx.InstallFile(installDir, j.Stem()+".jar", j.outputFile, extraInstallDeps...)
  611. }
  612. j.exportedProguardFlagFiles = append(j.exportedProguardFlagFiles,
  613. android.PathsForModuleSrc(ctx, j.dexProperties.Optimize.Proguard_flags_files)...)
  614. ctx.VisitDirectDeps(func(m android.Module) {
  615. if lib, ok := m.(LibraryDependency); ok && ctx.OtherModuleDependencyTag(m) == staticLibTag {
  616. j.exportedProguardFlagFiles = append(j.exportedProguardFlagFiles, lib.ExportedProguardFlagFiles()...)
  617. }
  618. })
  619. j.exportedProguardFlagFiles = android.FirstUniquePaths(j.exportedProguardFlagFiles)
  620. }
  621. func (j *Library) DepsMutator(ctx android.BottomUpMutatorContext) {
  622. j.deps(ctx)
  623. j.usesLibrary.deps(ctx, false)
  624. }
  625. const (
  626. aidlIncludeDir = "aidl"
  627. javaDir = "java"
  628. jarFileSuffix = ".jar"
  629. testConfigSuffix = "-AndroidTest.xml"
  630. )
  631. // path to the jar file of a java library. Relative to <sdk_root>/<api_dir>
  632. func sdkSnapshotFilePathForJar(_ android.SdkMemberContext, osPrefix, name string) string {
  633. return sdkSnapshotFilePathForMember(osPrefix, name, jarFileSuffix)
  634. }
  635. func sdkSnapshotFilePathForMember(osPrefix, name string, suffix string) string {
  636. return filepath.Join(javaDir, osPrefix, name+suffix)
  637. }
  638. type librarySdkMemberType struct {
  639. android.SdkMemberTypeBase
  640. // Function to retrieve the appropriate output jar (implementation or header) from
  641. // the library.
  642. jarToExportGetter func(ctx android.SdkMemberContext, j *Library) android.Path
  643. // Function to compute the snapshot relative path to which the named library's
  644. // jar should be copied.
  645. snapshotPathGetter func(ctx android.SdkMemberContext, osPrefix, name string) string
  646. // True if only the jar should be copied to the snapshot, false if the jar plus any additional
  647. // files like aidl files should also be copied.
  648. onlyCopyJarToSnapshot bool
  649. }
  650. const (
  651. onlyCopyJarToSnapshot = true
  652. copyEverythingToSnapshot = false
  653. )
  654. func (mt *librarySdkMemberType) AddDependencies(ctx android.SdkDependencyContext, dependencyTag blueprint.DependencyTag, names []string) {
  655. ctx.AddVariationDependencies(nil, dependencyTag, names...)
  656. }
  657. func (mt *librarySdkMemberType) IsInstance(module android.Module) bool {
  658. _, ok := module.(*Library)
  659. return ok
  660. }
  661. func (mt *librarySdkMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
  662. return ctx.SnapshotBuilder().AddPrebuiltModule(member, "java_import")
  663. }
  664. func (mt *librarySdkMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
  665. return &librarySdkMemberProperties{}
  666. }
  667. type librarySdkMemberProperties struct {
  668. android.SdkMemberPropertiesBase
  669. JarToExport android.Path `android:"arch_variant"`
  670. AidlIncludeDirs android.Paths
  671. // The list of permitted packages that need to be passed to the prebuilts as they are used to
  672. // create the updatable-bcp-packages.txt file.
  673. PermittedPackages []string
  674. // The value of the min_sdk_version property, translated into a number where possible.
  675. MinSdkVersion *string `supported_build_releases:"Tiramisu+"`
  676. DexPreoptProfileGuided *bool `supported_build_releases:"UpsideDownCake+"`
  677. }
  678. func (p *librarySdkMemberProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
  679. j := variant.(*Library)
  680. p.JarToExport = ctx.MemberType().(*librarySdkMemberType).jarToExportGetter(ctx, j)
  681. p.AidlIncludeDirs = j.AidlIncludeDirs()
  682. p.PermittedPackages = j.PermittedPackagesForUpdatableBootJars()
  683. // If the min_sdk_version was set then add the canonical representation of the API level to the
  684. // snapshot.
  685. if j.deviceProperties.Min_sdk_version != nil {
  686. canonical, err := android.ReplaceFinalizedCodenames(ctx.SdkModuleContext().Config(), j.minSdkVersion.String())
  687. if err != nil {
  688. ctx.ModuleErrorf("%s", err)
  689. }
  690. p.MinSdkVersion = proptools.StringPtr(canonical)
  691. }
  692. if j.dexpreopter.dexpreoptProperties.Dex_preopt_result.Profile_guided {
  693. p.DexPreoptProfileGuided = proptools.BoolPtr(true)
  694. }
  695. }
  696. func (p *librarySdkMemberProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
  697. builder := ctx.SnapshotBuilder()
  698. memberType := ctx.MemberType().(*librarySdkMemberType)
  699. exportedJar := p.JarToExport
  700. if exportedJar != nil {
  701. // Delegate the creation of the snapshot relative path to the member type.
  702. snapshotRelativeJavaLibPath := memberType.snapshotPathGetter(ctx, p.OsPrefix(), ctx.Name())
  703. // Copy the exported jar to the snapshot.
  704. builder.CopyToSnapshot(exportedJar, snapshotRelativeJavaLibPath)
  705. propertySet.AddProperty("jars", []string{snapshotRelativeJavaLibPath})
  706. }
  707. if p.MinSdkVersion != nil {
  708. propertySet.AddProperty("min_sdk_version", *p.MinSdkVersion)
  709. }
  710. if len(p.PermittedPackages) > 0 {
  711. propertySet.AddProperty("permitted_packages", p.PermittedPackages)
  712. }
  713. dexPreoptSet := propertySet.AddPropertySet("dex_preopt")
  714. if p.DexPreoptProfileGuided != nil {
  715. dexPreoptSet.AddProperty("profile_guided", proptools.Bool(p.DexPreoptProfileGuided))
  716. }
  717. // Do not copy anything else to the snapshot.
  718. if memberType.onlyCopyJarToSnapshot {
  719. return
  720. }
  721. aidlIncludeDirs := p.AidlIncludeDirs
  722. if len(aidlIncludeDirs) != 0 {
  723. sdkModuleContext := ctx.SdkModuleContext()
  724. for _, dir := range aidlIncludeDirs {
  725. // TODO(jiyong): copy parcelable declarations only
  726. aidlFiles, _ := sdkModuleContext.GlobWithDeps(dir.String()+"/**/*.aidl", nil)
  727. for _, file := range aidlFiles {
  728. builder.CopyToSnapshot(android.PathForSource(sdkModuleContext, file), filepath.Join(aidlIncludeDir, file))
  729. }
  730. }
  731. // TODO(b/151933053) - add aidl include dirs property
  732. }
  733. }
  734. // java_library builds and links sources into a `.jar` file for the device, and possibly for the host as well.
  735. //
  736. // By default, a java_library has a single variant that produces a `.jar` file containing `.class` files that were
  737. // compiled against the device bootclasspath. This jar is not suitable for installing on a device, but can be used
  738. // as a `static_libs` dependency of another module.
  739. //
  740. // Specifying `installable: true` will product a `.jar` file containing `classes.dex` files, suitable for installing on
  741. // a device.
  742. //
  743. // Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
  744. // compiled against the host bootclasspath.
  745. func LibraryFactory() android.Module {
  746. module := &Library{}
  747. module.addHostAndDeviceProperties()
  748. module.initModuleAndImport(module)
  749. android.InitApexModule(module)
  750. android.InitBazelModule(module)
  751. InitJavaModule(module, android.HostAndDeviceSupported)
  752. return module
  753. }
  754. // java_library_static is an obsolete alias for java_library.
  755. func LibraryStaticFactory() android.Module {
  756. return LibraryFactory()
  757. }
  758. // java_library_host builds and links sources into a `.jar` file for the host.
  759. //
  760. // A java_library_host has a single variant that produces a `.jar` file containing `.class` files that were
  761. // compiled against the host bootclasspath.
  762. func LibraryHostFactory() android.Module {
  763. module := &Library{}
  764. module.addHostProperties()
  765. module.Module.properties.Installable = proptools.BoolPtr(true)
  766. android.InitApexModule(module)
  767. android.InitBazelModule(module)
  768. InitJavaModule(module, android.HostSupported)
  769. return module
  770. }
  771. //
  772. // Java Tests
  773. //
  774. // Test option struct.
  775. type TestOptions struct {
  776. android.CommonTestOptions
  777. // a list of extra test configuration files that should be installed with the module.
  778. Extra_test_configs []string `android:"path,arch_variant"`
  779. // Extra <option> tags to add to the auto generated test xml file. The "key"
  780. // is optional in each of these.
  781. Tradefed_options []tradefed.Option
  782. // Extra <option> tags to add to the auto generated test xml file under the test runner, e.g., AndroidJunitTest.
  783. // The "key" is optional in each of these.
  784. Test_runner_options []tradefed.Option
  785. }
  786. type testProperties struct {
  787. // list of compatibility suites (for example "cts", "vts") that the module should be
  788. // installed into.
  789. Test_suites []string `android:"arch_variant"`
  790. // the name of the test configuration (for example "AndroidTest.xml") that should be
  791. // installed with the module.
  792. Test_config *string `android:"path,arch_variant"`
  793. // the name of the test configuration template (for example "AndroidTestTemplate.xml") that
  794. // should be installed with the module.
  795. Test_config_template *string `android:"path,arch_variant"`
  796. // list of files or filegroup modules that provide data that should be installed alongside
  797. // the test
  798. Data []string `android:"path"`
  799. // Flag to indicate whether or not to create test config automatically. If AndroidTest.xml
  800. // doesn't exist next to the Android.bp, this attribute doesn't need to be set to true
  801. // explicitly.
  802. Auto_gen_config *bool
  803. // Add parameterized mainline modules to auto generated test config. The options will be
  804. // handled by TradeFed to do downloading and installing the specified modules on the device.
  805. Test_mainline_modules []string
  806. // Test options.
  807. Test_options TestOptions
  808. // Names of modules containing JNI libraries that should be installed alongside the test.
  809. Jni_libs []string
  810. // Install the test into a folder named for the module in all test suites.
  811. Per_testcase_directory *bool
  812. }
  813. type hostTestProperties struct {
  814. // list of native binary modules that should be installed alongside the test
  815. Data_native_bins []string `android:"arch_variant"`
  816. // list of device binary modules that should be installed alongside the test
  817. // This property only adds the first variant of the dependency
  818. Data_device_bins_first []string `android:"arch_variant"`
  819. // list of device binary modules that should be installed alongside the test
  820. // This property adds 64bit AND 32bit variants of the dependency
  821. Data_device_bins_both []string `android:"arch_variant"`
  822. // list of device binary modules that should be installed alongside the test
  823. // This property only adds 64bit variants of the dependency
  824. Data_device_bins_64 []string `android:"arch_variant"`
  825. // list of device binary modules that should be installed alongside the test
  826. // This property adds 32bit variants of the dependency if available, or else
  827. // defaults to the 64bit variant
  828. Data_device_bins_prefer32 []string `android:"arch_variant"`
  829. // list of device binary modules that should be installed alongside the test
  830. // This property only adds 32bit variants of the dependency
  831. Data_device_bins_32 []string `android:"arch_variant"`
  832. }
  833. type testHelperLibraryProperties struct {
  834. // list of compatibility suites (for example "cts", "vts") that the module should be
  835. // installed into.
  836. Test_suites []string `android:"arch_variant"`
  837. // Install the test into a folder named for the module in all test suites.
  838. Per_testcase_directory *bool
  839. }
  840. type prebuiltTestProperties struct {
  841. // list of compatibility suites (for example "cts", "vts") that the module should be
  842. // installed into.
  843. Test_suites []string `android:"arch_variant"`
  844. // the name of the test configuration (for example "AndroidTest.xml") that should be
  845. // installed with the module.
  846. Test_config *string `android:"path,arch_variant"`
  847. }
  848. type Test struct {
  849. Library
  850. testProperties testProperties
  851. testConfig android.Path
  852. extraTestConfigs android.Paths
  853. data android.Paths
  854. }
  855. type TestHost struct {
  856. Test
  857. testHostProperties hostTestProperties
  858. }
  859. type TestHelperLibrary struct {
  860. Library
  861. testHelperLibraryProperties testHelperLibraryProperties
  862. }
  863. type JavaTestImport struct {
  864. Import
  865. prebuiltTestProperties prebuiltTestProperties
  866. testConfig android.Path
  867. dexJarFile android.Path
  868. }
  869. func (j *Test) InstallInTestcases() bool {
  870. // Host java tests install into $(HOST_OUT_JAVA_LIBRARIES), and then are copied into
  871. // testcases by base_rules.mk.
  872. return !j.Host()
  873. }
  874. func (j *TestHelperLibrary) InstallInTestcases() bool {
  875. return true
  876. }
  877. func (j *JavaTestImport) InstallInTestcases() bool {
  878. return true
  879. }
  880. func (j *TestHost) addDataDeviceBinsDeps(ctx android.BottomUpMutatorContext) {
  881. if len(j.testHostProperties.Data_device_bins_first) > 0 {
  882. deviceVariations := ctx.Config().AndroidFirstDeviceTarget.Variations()
  883. ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_first...)
  884. }
  885. var maybeAndroid32Target *android.Target
  886. var maybeAndroid64Target *android.Target
  887. android32TargetList := android.FirstTarget(ctx.Config().Targets[android.Android], "lib32")
  888. android64TargetList := android.FirstTarget(ctx.Config().Targets[android.Android], "lib64")
  889. if len(android32TargetList) > 0 {
  890. maybeAndroid32Target = &android32TargetList[0]
  891. }
  892. if len(android64TargetList) > 0 {
  893. maybeAndroid64Target = &android64TargetList[0]
  894. }
  895. if len(j.testHostProperties.Data_device_bins_both) > 0 {
  896. if maybeAndroid32Target == nil && maybeAndroid64Target == nil {
  897. ctx.PropertyErrorf("data_device_bins_both", "no device targets available. Targets: %q", ctx.Config().Targets)
  898. return
  899. }
  900. if maybeAndroid32Target != nil {
  901. ctx.AddFarVariationDependencies(
  902. maybeAndroid32Target.Variations(),
  903. dataDeviceBinsTag,
  904. j.testHostProperties.Data_device_bins_both...,
  905. )
  906. }
  907. if maybeAndroid64Target != nil {
  908. ctx.AddFarVariationDependencies(
  909. maybeAndroid64Target.Variations(),
  910. dataDeviceBinsTag,
  911. j.testHostProperties.Data_device_bins_both...,
  912. )
  913. }
  914. }
  915. if len(j.testHostProperties.Data_device_bins_prefer32) > 0 {
  916. if maybeAndroid32Target != nil {
  917. ctx.AddFarVariationDependencies(
  918. maybeAndroid32Target.Variations(),
  919. dataDeviceBinsTag,
  920. j.testHostProperties.Data_device_bins_prefer32...,
  921. )
  922. } else {
  923. if maybeAndroid64Target == nil {
  924. ctx.PropertyErrorf("data_device_bins_prefer32", "no device targets available. Targets: %q", ctx.Config().Targets)
  925. return
  926. }
  927. ctx.AddFarVariationDependencies(
  928. maybeAndroid64Target.Variations(),
  929. dataDeviceBinsTag,
  930. j.testHostProperties.Data_device_bins_prefer32...,
  931. )
  932. }
  933. }
  934. if len(j.testHostProperties.Data_device_bins_32) > 0 {
  935. if maybeAndroid32Target == nil {
  936. ctx.PropertyErrorf("data_device_bins_32", "cannot find 32bit device target. Targets: %q", ctx.Config().Targets)
  937. return
  938. }
  939. deviceVariations := maybeAndroid32Target.Variations()
  940. ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_32...)
  941. }
  942. if len(j.testHostProperties.Data_device_bins_64) > 0 {
  943. if maybeAndroid64Target == nil {
  944. ctx.PropertyErrorf("data_device_bins_64", "cannot find 64bit device target. Targets: %q", ctx.Config().Targets)
  945. return
  946. }
  947. deviceVariations := maybeAndroid64Target.Variations()
  948. ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_64...)
  949. }
  950. }
  951. func (j *TestHost) DepsMutator(ctx android.BottomUpMutatorContext) {
  952. if len(j.testHostProperties.Data_native_bins) > 0 {
  953. for _, target := range ctx.MultiTargets() {
  954. ctx.AddVariationDependencies(target.Variations(), dataNativeBinsTag, j.testHostProperties.Data_native_bins...)
  955. }
  956. }
  957. if len(j.testProperties.Jni_libs) > 0 {
  958. for _, target := range ctx.MultiTargets() {
  959. sharedLibVariations := append(target.Variations(), blueprint.Variation{Mutator: "link", Variation: "shared"})
  960. ctx.AddFarVariationDependencies(sharedLibVariations, jniLibTag, j.testProperties.Jni_libs...)
  961. }
  962. }
  963. j.addDataDeviceBinsDeps(ctx)
  964. j.deps(ctx)
  965. }
  966. func (j *TestHost) AddExtraResource(p android.Path) {
  967. j.extraResources = append(j.extraResources, p)
  968. }
  969. func (j *TestHost) dataDeviceBins() []string {
  970. ret := make([]string, 0,
  971. len(j.testHostProperties.Data_device_bins_first)+
  972. len(j.testHostProperties.Data_device_bins_both)+
  973. len(j.testHostProperties.Data_device_bins_prefer32)+
  974. len(j.testHostProperties.Data_device_bins_32)+
  975. len(j.testHostProperties.Data_device_bins_64),
  976. )
  977. ret = append(ret, j.testHostProperties.Data_device_bins_first...)
  978. ret = append(ret, j.testHostProperties.Data_device_bins_both...)
  979. ret = append(ret, j.testHostProperties.Data_device_bins_prefer32...)
  980. ret = append(ret, j.testHostProperties.Data_device_bins_32...)
  981. ret = append(ret, j.testHostProperties.Data_device_bins_64...)
  982. return ret
  983. }
  984. func (j *TestHost) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  985. var configs []tradefed.Config
  986. dataDeviceBins := j.dataDeviceBins()
  987. if len(dataDeviceBins) > 0 {
  988. // add Tradefed configuration to push device bins to device for testing
  989. remoteDir := filepath.Join("/data/local/tests/unrestricted/", j.Name())
  990. options := []tradefed.Option{{Name: "cleanup", Value: "true"}}
  991. for _, bin := range dataDeviceBins {
  992. fullPath := filepath.Join(remoteDir, bin)
  993. options = append(options, tradefed.Option{Name: "push-file", Key: bin, Value: fullPath})
  994. }
  995. configs = append(configs, tradefed.Object{
  996. Type: "target_preparer",
  997. Class: "com.android.tradefed.targetprep.PushFilePreparer",
  998. Options: options,
  999. })
  1000. }
  1001. j.Test.generateAndroidBuildActionsWithConfig(ctx, configs)
  1002. }
  1003. func (j *Test) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  1004. j.generateAndroidBuildActionsWithConfig(ctx, nil)
  1005. }
  1006. func (j *Test) generateAndroidBuildActionsWithConfig(ctx android.ModuleContext, configs []tradefed.Config) {
  1007. if j.testProperties.Test_options.Unit_test == nil && ctx.Host() {
  1008. // TODO(b/): Clean temporary heuristic to avoid unexpected onboarding.
  1009. defaultUnitTest := !inList("tradefed", j.properties.Libs) && !inList("cts", j.testProperties.Test_suites)
  1010. j.testProperties.Test_options.Unit_test = proptools.BoolPtr(defaultUnitTest)
  1011. }
  1012. j.testConfig = tradefed.AutoGenTestConfig(ctx, tradefed.AutoGenTestConfigOptions{
  1013. TestConfigProp: j.testProperties.Test_config,
  1014. TestConfigTemplateProp: j.testProperties.Test_config_template,
  1015. TestSuites: j.testProperties.Test_suites,
  1016. Config: configs,
  1017. OptionsForAutogenerated: j.testProperties.Test_options.Tradefed_options,
  1018. TestRunnerOptions: j.testProperties.Test_options.Test_runner_options,
  1019. AutoGenConfig: j.testProperties.Auto_gen_config,
  1020. UnitTest: j.testProperties.Test_options.Unit_test,
  1021. DeviceTemplate: "${JavaTestConfigTemplate}",
  1022. HostTemplate: "${JavaHostTestConfigTemplate}",
  1023. HostUnitTestTemplate: "${JavaHostUnitTestConfigTemplate}",
  1024. })
  1025. j.data = android.PathsForModuleSrc(ctx, j.testProperties.Data)
  1026. j.extraTestConfigs = android.PathsForModuleSrc(ctx, j.testProperties.Test_options.Extra_test_configs)
  1027. ctx.VisitDirectDepsWithTag(dataNativeBinsTag, func(dep android.Module) {
  1028. j.data = append(j.data, android.OutputFileForModule(ctx, dep, ""))
  1029. })
  1030. ctx.VisitDirectDepsWithTag(dataDeviceBinsTag, func(dep android.Module) {
  1031. j.data = append(j.data, android.OutputFileForModule(ctx, dep, ""))
  1032. })
  1033. ctx.VisitDirectDepsWithTag(jniLibTag, func(dep android.Module) {
  1034. sharedLibInfo := ctx.OtherModuleProvider(dep, cc.SharedLibraryInfoProvider).(cc.SharedLibraryInfo)
  1035. if sharedLibInfo.SharedLibrary != nil {
  1036. // Copy to an intermediate output directory to append "lib[64]" to the path,
  1037. // so that it's compatible with the default rpath values.
  1038. var relPath string
  1039. if sharedLibInfo.Target.Arch.ArchType.Multilib == "lib64" {
  1040. relPath = filepath.Join("lib64", sharedLibInfo.SharedLibrary.Base())
  1041. } else {
  1042. relPath = filepath.Join("lib", sharedLibInfo.SharedLibrary.Base())
  1043. }
  1044. relocatedLib := android.PathForModuleOut(ctx, "relocated").Join(ctx, relPath)
  1045. ctx.Build(pctx, android.BuildParams{
  1046. Rule: android.Cp,
  1047. Input: sharedLibInfo.SharedLibrary,
  1048. Output: relocatedLib,
  1049. })
  1050. j.data = append(j.data, relocatedLib)
  1051. } else {
  1052. ctx.PropertyErrorf("jni_libs", "%q of type %q is not supported", dep.Name(), ctx.OtherModuleType(dep))
  1053. }
  1054. })
  1055. j.Library.GenerateAndroidBuildActions(ctx)
  1056. }
  1057. func (j *TestHelperLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  1058. j.Library.GenerateAndroidBuildActions(ctx)
  1059. }
  1060. func (j *JavaTestImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  1061. j.testConfig = tradefed.AutoGenTestConfig(ctx, tradefed.AutoGenTestConfigOptions{
  1062. TestConfigProp: j.prebuiltTestProperties.Test_config,
  1063. TestSuites: j.prebuiltTestProperties.Test_suites,
  1064. DeviceTemplate: "${JavaTestConfigTemplate}",
  1065. HostTemplate: "${JavaHostTestConfigTemplate}",
  1066. HostUnitTestTemplate: "${JavaHostUnitTestConfigTemplate}",
  1067. })
  1068. j.Import.GenerateAndroidBuildActions(ctx)
  1069. }
  1070. type testSdkMemberType struct {
  1071. android.SdkMemberTypeBase
  1072. }
  1073. func (mt *testSdkMemberType) AddDependencies(ctx android.SdkDependencyContext, dependencyTag blueprint.DependencyTag, names []string) {
  1074. ctx.AddVariationDependencies(nil, dependencyTag, names...)
  1075. }
  1076. func (mt *testSdkMemberType) IsInstance(module android.Module) bool {
  1077. _, ok := module.(*Test)
  1078. return ok
  1079. }
  1080. func (mt *testSdkMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
  1081. return ctx.SnapshotBuilder().AddPrebuiltModule(member, "java_test_import")
  1082. }
  1083. func (mt *testSdkMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
  1084. return &testSdkMemberProperties{}
  1085. }
  1086. type testSdkMemberProperties struct {
  1087. android.SdkMemberPropertiesBase
  1088. JarToExport android.Path
  1089. TestConfig android.Path
  1090. }
  1091. func (p *testSdkMemberProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
  1092. test := variant.(*Test)
  1093. implementationJars := test.ImplementationJars()
  1094. if len(implementationJars) != 1 {
  1095. panic(fmt.Errorf("there must be only one implementation jar from %q", test.Name()))
  1096. }
  1097. p.JarToExport = implementationJars[0]
  1098. p.TestConfig = test.testConfig
  1099. }
  1100. func (p *testSdkMemberProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
  1101. builder := ctx.SnapshotBuilder()
  1102. exportedJar := p.JarToExport
  1103. if exportedJar != nil {
  1104. snapshotRelativeJavaLibPath := sdkSnapshotFilePathForJar(ctx, p.OsPrefix(), ctx.Name())
  1105. builder.CopyToSnapshot(exportedJar, snapshotRelativeJavaLibPath)
  1106. propertySet.AddProperty("jars", []string{snapshotRelativeJavaLibPath})
  1107. }
  1108. testConfig := p.TestConfig
  1109. if testConfig != nil {
  1110. snapshotRelativeTestConfigPath := sdkSnapshotFilePathForMember(p.OsPrefix(), ctx.Name(), testConfigSuffix)
  1111. builder.CopyToSnapshot(testConfig, snapshotRelativeTestConfigPath)
  1112. propertySet.AddProperty("test_config", snapshotRelativeTestConfigPath)
  1113. }
  1114. }
  1115. // java_test builds a and links sources into a `.jar` file for the device, and possibly for the host as well, and
  1116. // creates an `AndroidTest.xml` file to allow running the test with `atest` or a `TEST_MAPPING` file.
  1117. //
  1118. // By default, a java_test has a single variant that produces a `.jar` file containing `classes.dex` files that were
  1119. // compiled against the device bootclasspath.
  1120. //
  1121. // Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
  1122. // compiled against the host bootclasspath.
  1123. func TestFactory() android.Module {
  1124. module := &Test{}
  1125. module.addHostAndDeviceProperties()
  1126. module.AddProperties(&module.testProperties)
  1127. module.Module.properties.Installable = proptools.BoolPtr(true)
  1128. module.Module.dexpreopter.isTest = true
  1129. module.Module.linter.properties.Lint.Test = proptools.BoolPtr(true)
  1130. InitJavaModule(module, android.HostAndDeviceSupported)
  1131. return module
  1132. }
  1133. // java_test_helper_library creates a java library and makes sure that it is added to the appropriate test suite.
  1134. func TestHelperLibraryFactory() android.Module {
  1135. module := &TestHelperLibrary{}
  1136. module.addHostAndDeviceProperties()
  1137. module.AddProperties(&module.testHelperLibraryProperties)
  1138. module.Module.properties.Installable = proptools.BoolPtr(true)
  1139. module.Module.dexpreopter.isTest = true
  1140. module.Module.linter.properties.Lint.Test = proptools.BoolPtr(true)
  1141. InitJavaModule(module, android.HostAndDeviceSupported)
  1142. return module
  1143. }
  1144. // java_test_import imports one or more `.jar` files into the build graph as if they were built by a java_test module
  1145. // and makes sure that it is added to the appropriate test suite.
  1146. //
  1147. // By default, a java_test_import has a single variant that expects a `.jar` file containing `.class` files that were
  1148. // compiled against an Android classpath.
  1149. //
  1150. // Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
  1151. // for host modules.
  1152. func JavaTestImportFactory() android.Module {
  1153. module := &JavaTestImport{}
  1154. module.AddProperties(
  1155. &module.Import.properties,
  1156. &module.prebuiltTestProperties)
  1157. module.Import.properties.Installable = proptools.BoolPtr(true)
  1158. android.InitPrebuiltModule(module, &module.properties.Jars)
  1159. android.InitApexModule(module)
  1160. InitJavaModule(module, android.HostAndDeviceSupported)
  1161. return module
  1162. }
  1163. // java_test_host builds a and links sources into a `.jar` file for the host, and creates an `AndroidTest.xml` file to
  1164. // allow running the test with `atest` or a `TEST_MAPPING` file.
  1165. //
  1166. // A java_test_host has a single variant that produces a `.jar` file containing `.class` files that were
  1167. // compiled against the host bootclasspath.
  1168. func TestHostFactory() android.Module {
  1169. module := &TestHost{}
  1170. module.addHostProperties()
  1171. module.AddProperties(&module.testProperties)
  1172. module.AddProperties(&module.testHostProperties)
  1173. InitTestHost(
  1174. module,
  1175. proptools.BoolPtr(true),
  1176. nil,
  1177. nil)
  1178. android.InitBazelModule(module)
  1179. InitJavaModuleMultiTargets(module, android.HostSupported)
  1180. return module
  1181. }
  1182. func InitTestHost(th *TestHost, installable *bool, testSuites []string, autoGenConfig *bool) {
  1183. th.properties.Installable = installable
  1184. th.testProperties.Auto_gen_config = autoGenConfig
  1185. th.testProperties.Test_suites = testSuites
  1186. }
  1187. //
  1188. // Java Binaries (.jar file plus wrapper script)
  1189. //
  1190. type binaryProperties struct {
  1191. // installable script to execute the resulting jar
  1192. Wrapper *string `android:"path,arch_variant"`
  1193. // Name of the class containing main to be inserted into the manifest as Main-Class.
  1194. Main_class *string
  1195. // Names of modules containing JNI libraries that should be installed alongside the host
  1196. // variant of the binary.
  1197. Jni_libs []string `android:"arch_variant"`
  1198. }
  1199. type Binary struct {
  1200. Library
  1201. binaryProperties binaryProperties
  1202. isWrapperVariant bool
  1203. wrapperFile android.Path
  1204. binaryFile android.InstallPath
  1205. }
  1206. func (j *Binary) HostToolPath() android.OptionalPath {
  1207. return android.OptionalPathForPath(j.binaryFile)
  1208. }
  1209. func (j *Binary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  1210. if ctx.Arch().ArchType == android.Common {
  1211. // Compile the jar
  1212. if j.binaryProperties.Main_class != nil {
  1213. if j.properties.Manifest != nil {
  1214. ctx.PropertyErrorf("main_class", "main_class cannot be used when manifest is set")
  1215. }
  1216. manifestFile := android.PathForModuleOut(ctx, "manifest.txt")
  1217. GenerateMainClassManifest(ctx, manifestFile, String(j.binaryProperties.Main_class))
  1218. j.overrideManifest = android.OptionalPathForPath(manifestFile)
  1219. }
  1220. j.Library.GenerateAndroidBuildActions(ctx)
  1221. } else {
  1222. // Handle the binary wrapper
  1223. j.isWrapperVariant = true
  1224. if j.binaryProperties.Wrapper != nil {
  1225. j.wrapperFile = android.PathForModuleSrc(ctx, *j.binaryProperties.Wrapper)
  1226. } else {
  1227. if ctx.Windows() {
  1228. ctx.PropertyErrorf("wrapper", "wrapper is required for Windows")
  1229. }
  1230. if ctx.Device() {
  1231. // device binary should have a main_class property if it does not
  1232. // have a specific wrapper, so that a default wrapper can
  1233. // be generated for it.
  1234. if j.binaryProperties.Main_class == nil {
  1235. ctx.PropertyErrorf("main_class", "main_class property "+
  1236. "is required for device binary if no default wrapper is assigned")
  1237. } else {
  1238. wrapper := android.PathForModuleOut(ctx, ctx.ModuleName()+".sh")
  1239. jarName := j.Stem() + ".jar"
  1240. partition := j.PartitionTag(ctx.DeviceConfig())
  1241. ctx.Build(pctx, android.BuildParams{
  1242. Rule: deviceBinaryWrapper,
  1243. Output: wrapper,
  1244. Args: map[string]string{
  1245. "jar_name": jarName,
  1246. "partition": partition,
  1247. "main_class": String(j.binaryProperties.Main_class),
  1248. },
  1249. })
  1250. j.wrapperFile = wrapper
  1251. }
  1252. } else {
  1253. j.wrapperFile = android.PathForSource(ctx, "build/soong/scripts/jar-wrapper.sh")
  1254. }
  1255. }
  1256. ext := ""
  1257. if ctx.Windows() {
  1258. ext = ".bat"
  1259. }
  1260. // The host installation rules make the installed wrapper depend on all the dependencies
  1261. // of the wrapper variant, which will include the common variant's jar file and any JNI
  1262. // libraries. This is verified by TestBinary.
  1263. j.binaryFile = ctx.InstallExecutable(android.PathForModuleInstall(ctx, "bin"),
  1264. ctx.ModuleName()+ext, j.wrapperFile)
  1265. }
  1266. }
  1267. func (j *Binary) DepsMutator(ctx android.BottomUpMutatorContext) {
  1268. if ctx.Arch().ArchType == android.Common {
  1269. j.deps(ctx)
  1270. }
  1271. if ctx.Arch().ArchType != android.Common {
  1272. // These dependencies ensure the host installation rules will install the jar file and
  1273. // the jni libraries when the wrapper is installed.
  1274. ctx.AddVariationDependencies(nil, jniInstallTag, j.binaryProperties.Jni_libs...)
  1275. ctx.AddVariationDependencies(
  1276. []blueprint.Variation{{Mutator: "arch", Variation: android.CommonArch.String()}},
  1277. binaryInstallTag, ctx.ModuleName())
  1278. }
  1279. }
  1280. // java_binary builds a `.jar` file and a shell script that executes it for the device, and possibly for the host
  1281. // as well.
  1282. //
  1283. // By default, a java_binary has a single variant that produces a `.jar` file containing `classes.dex` files that were
  1284. // compiled against the device bootclasspath.
  1285. //
  1286. // Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
  1287. // compiled against the host bootclasspath.
  1288. func BinaryFactory() android.Module {
  1289. module := &Binary{}
  1290. module.addHostAndDeviceProperties()
  1291. module.AddProperties(&module.binaryProperties)
  1292. module.Module.properties.Installable = proptools.BoolPtr(true)
  1293. android.InitAndroidArchModule(module, android.HostAndDeviceSupported, android.MultilibCommonFirst)
  1294. android.InitDefaultableModule(module)
  1295. android.InitBazelModule(module)
  1296. return module
  1297. }
  1298. // java_binary_host builds a `.jar` file and a shell script that executes it for the host.
  1299. //
  1300. // A java_binary_host has a single variant that produces a `.jar` file containing `.class` files that were
  1301. // compiled against the host bootclasspath.
  1302. func BinaryHostFactory() android.Module {
  1303. module := &Binary{}
  1304. module.addHostProperties()
  1305. module.AddProperties(&module.binaryProperties)
  1306. module.Module.properties.Installable = proptools.BoolPtr(true)
  1307. android.InitAndroidArchModule(module, android.HostSupported, android.MultilibCommonFirst)
  1308. android.InitDefaultableModule(module)
  1309. android.InitBazelModule(module)
  1310. return module
  1311. }
  1312. type JavaApiContribution struct {
  1313. android.ModuleBase
  1314. android.DefaultableModuleBase
  1315. properties struct {
  1316. // name of the API surface
  1317. Api_surface *string
  1318. // relative path to the API signature text file
  1319. Api_file *string `android:"path"`
  1320. }
  1321. }
  1322. func ApiContributionFactory() android.Module {
  1323. module := &JavaApiContribution{}
  1324. android.InitAndroidModule(module)
  1325. android.InitDefaultableModule(module)
  1326. module.AddProperties(&module.properties)
  1327. return module
  1328. }
  1329. type JavaApiImportInfo struct {
  1330. ApiFile android.Path
  1331. }
  1332. var JavaApiImportProvider = blueprint.NewProvider(JavaApiImportInfo{})
  1333. func (ap *JavaApiContribution) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  1334. var apiFile android.Path = nil
  1335. if apiFileString := ap.properties.Api_file; apiFileString != nil {
  1336. apiFile = android.PathForModuleSrc(ctx, String(apiFileString))
  1337. }
  1338. ctx.SetProvider(JavaApiImportProvider, JavaApiImportInfo{
  1339. ApiFile: apiFile,
  1340. })
  1341. }
  1342. type JavaApiLibraryDepsInfo struct {
  1343. JavaInfo
  1344. StubsSrcJar android.Path
  1345. }
  1346. var JavaApiLibraryDepsProvider = blueprint.NewProvider(JavaApiLibraryDepsInfo{})
  1347. type ApiLibrary struct {
  1348. android.ModuleBase
  1349. android.DefaultableModuleBase
  1350. hiddenAPI
  1351. dexer
  1352. properties JavaApiLibraryProperties
  1353. stubsSrcJar android.WritablePath
  1354. stubsJar android.WritablePath
  1355. stubsJarWithoutStaticLibs android.WritablePath
  1356. extractedSrcJar android.WritablePath
  1357. // .dex of stubs, used for hiddenapi processing
  1358. dexJarFile OptionalDexJarPath
  1359. }
  1360. type JavaApiLibraryProperties struct {
  1361. // name of the API surface
  1362. Api_surface *string
  1363. // list of Java API contribution modules that consists this API surface
  1364. // This is a list of Soong modules
  1365. Api_contributions []string
  1366. // list of api.txt files relative to this directory that contribute to the
  1367. // API surface.
  1368. // This is a list of relative paths
  1369. Api_files []string `android:"path"`
  1370. // List of flags to be passed to the javac compiler to generate jar file
  1371. Javacflags []string
  1372. // List of shared java libs that this module has dependencies to and
  1373. // should be passed as classpath in javac invocation
  1374. Libs []string
  1375. // List of java libs that this module has static dependencies to and will be
  1376. // merge zipped after metalava invocation
  1377. Static_libs []string
  1378. // Java Api library to provide the full API surface text files and jar file.
  1379. // If this property is set, the provided full API surface text files and
  1380. // jar file are passed to metalava invocation.
  1381. Dep_api_srcs *string
  1382. }
  1383. func ApiLibraryFactory() android.Module {
  1384. module := &ApiLibrary{}
  1385. android.InitAndroidArchModule(module, android.DeviceSupported, android.MultilibCommon)
  1386. module.AddProperties(&module.properties)
  1387. android.InitDefaultableModule(module)
  1388. return module
  1389. }
  1390. func (al *ApiLibrary) ApiSurface() *string {
  1391. return al.properties.Api_surface
  1392. }
  1393. func (al *ApiLibrary) StubsJar() android.Path {
  1394. return al.stubsJar
  1395. }
  1396. func metalavaStubCmd(ctx android.ModuleContext, rule *android.RuleBuilder,
  1397. srcs android.Paths, homeDir android.WritablePath) *android.RuleBuilderCommand {
  1398. rule.Command().Text("rm -rf").Flag(homeDir.String())
  1399. rule.Command().Text("mkdir -p").Flag(homeDir.String())
  1400. cmd := rule.Command()
  1401. cmd.FlagWithArg("ANDROID_PREFS_ROOT=", homeDir.String())
  1402. if metalavaUseRbe(ctx) {
  1403. rule.Remoteable(android.RemoteRuleSupports{RBE: true})
  1404. execStrategy := ctx.Config().GetenvWithDefault("RBE_METALAVA_EXEC_STRATEGY", remoteexec.LocalExecStrategy)
  1405. labels := map[string]string{"type": "tool", "name": "metalava"}
  1406. pool := ctx.Config().GetenvWithDefault("RBE_METALAVA_POOL", "java16")
  1407. rule.Rewrapper(&remoteexec.REParams{
  1408. Labels: labels,
  1409. ExecStrategy: execStrategy,
  1410. ToolchainInputs: []string{config.JavaCmd(ctx).String()},
  1411. Platform: map[string]string{remoteexec.PoolKey: pool},
  1412. })
  1413. }
  1414. cmd.BuiltTool("metalava").ImplicitTool(ctx.Config().HostJavaToolPath(ctx, "metalava.jar")).
  1415. Flag(config.JavacVmFlags).
  1416. Flag("-J--add-opens=java.base/java.util=ALL-UNNAMED").
  1417. FlagWithArg("-encoding ", "UTF-8").
  1418. FlagWithInputList("--source-files ", srcs, " ")
  1419. cmd.Flag("--no-banner").
  1420. Flag("--color").
  1421. Flag("--quiet").
  1422. Flag("--format=v2").
  1423. Flag("--include-annotations").
  1424. // The flag makes nullability issues as warnings rather than errors by replacing
  1425. // @Nullable/@NonNull in the listed packages APIs with @RecentlyNullable/@RecentlyNonNull,
  1426. // and these packages are meant to have everything annotated
  1427. // @RecentlyNullable/@RecentlyNonNull.
  1428. FlagWithArg("--force-convert-to-warning-nullability-annotations ", "+*:-android.*:+android.icu.*:-dalvik.*").
  1429. FlagWithArg("--repeat-errors-max ", "10").
  1430. FlagWithArg("--hide ", "UnresolvedImport").
  1431. FlagWithArg("--hide ", "InvalidNullabilityOverride").
  1432. FlagWithArg("--hide ", "ChangedDefault")
  1433. // Force metalava to ignore classes on the classpath when an API file contains missing classes.
  1434. // See b/285140653 for more information.
  1435. cmd.FlagWithArg("--api-class-resolution ", "api")
  1436. // Force metalava to sort overloaded methods by their order in the source code.
  1437. // See b/285312164 for more information.
  1438. cmd.FlagWithArg("--api-overloaded-method-order ", "source")
  1439. return cmd
  1440. }
  1441. func (al *ApiLibrary) HeaderJars() android.Paths {
  1442. return android.Paths{al.stubsJar}
  1443. }
  1444. func (al *ApiLibrary) OutputDirAndDeps() (android.Path, android.Paths) {
  1445. return nil, nil
  1446. }
  1447. func (al *ApiLibrary) stubsFlags(ctx android.ModuleContext, cmd *android.RuleBuilderCommand, stubsDir android.OptionalPath) {
  1448. if stubsDir.Valid() {
  1449. cmd.FlagWithArg("--stubs ", stubsDir.String())
  1450. }
  1451. }
  1452. // This method extracts the stub java files from the srcjar file provided from dep_api_srcs module
  1453. // and replaces the java stubs generated by invoking metalava in this module.
  1454. // This method is used because metalava can generate compilable from-text stubs only when
  1455. // the codebase encompasses all classes listed in the input API text file, but a class can extend
  1456. // a class that is not within the same API domain.
  1457. func (al *ApiLibrary) extractApiSrcs(ctx android.ModuleContext, rule *android.RuleBuilder, stubsDir android.OptionalPath, depApiSrcsSrcJar android.Path) {
  1458. generatedStubsList := android.PathForModuleOut(ctx, "metalava", "sources.txt")
  1459. unzippedSrcJarDir := android.PathForModuleOut(ctx, "metalava", "unzipDir")
  1460. rule.Command().
  1461. BuiltTool("list_files").
  1462. Text(stubsDir.String()).
  1463. FlagWithOutput("--out ", generatedStubsList).
  1464. FlagWithArg("--extensions ", ".java").
  1465. FlagWithArg("--root ", unzippedSrcJarDir.String())
  1466. rule.Command().
  1467. Text("unzip").
  1468. Flag("-q").
  1469. Input(depApiSrcsSrcJar).
  1470. FlagWithArg("-d ", unzippedSrcJarDir.String())
  1471. rule.Command().
  1472. BuiltTool("soong_zip").
  1473. Flag("-srcjar").
  1474. Flag("-write_if_changed").
  1475. FlagWithArg("-C ", unzippedSrcJarDir.String()).
  1476. FlagWithInput("-l ", generatedStubsList).
  1477. FlagWithOutput("-o ", al.stubsSrcJar)
  1478. }
  1479. func (al *ApiLibrary) DepsMutator(ctx android.BottomUpMutatorContext) {
  1480. apiContributions := al.properties.Api_contributions
  1481. for _, apiContributionName := range apiContributions {
  1482. ctx.AddDependency(ctx.Module(), javaApiContributionTag, apiContributionName)
  1483. }
  1484. ctx.AddVariationDependencies(nil, libTag, al.properties.Libs...)
  1485. ctx.AddVariationDependencies(nil, staticLibTag, al.properties.Static_libs...)
  1486. if al.properties.Dep_api_srcs != nil {
  1487. ctx.AddVariationDependencies(nil, depApiSrcsTag, String(al.properties.Dep_api_srcs))
  1488. }
  1489. }
  1490. func (al *ApiLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  1491. rule := android.NewRuleBuilder(pctx, ctx)
  1492. rule.Sbox(android.PathForModuleOut(ctx, "metalava"),
  1493. android.PathForModuleOut(ctx, "metalava.sbox.textproto")).
  1494. SandboxInputs()
  1495. var stubsDir android.OptionalPath
  1496. stubsDir = android.OptionalPathForPath(android.PathForModuleOut(ctx, "metalava", "stubsDir"))
  1497. rule.Command().Text("rm -rf").Text(stubsDir.String())
  1498. rule.Command().Text("mkdir -p").Text(stubsDir.String())
  1499. homeDir := android.PathForModuleOut(ctx, "metalava", "home")
  1500. var srcFiles android.Paths
  1501. var classPaths android.Paths
  1502. var staticLibs android.Paths
  1503. var depApiSrcsStubsSrcJar android.Path
  1504. ctx.VisitDirectDeps(func(dep android.Module) {
  1505. tag := ctx.OtherModuleDependencyTag(dep)
  1506. switch tag {
  1507. case javaApiContributionTag:
  1508. provider := ctx.OtherModuleProvider(dep, JavaApiImportProvider).(JavaApiImportInfo)
  1509. providerApiFile := provider.ApiFile
  1510. if providerApiFile == nil && !ctx.Config().AllowMissingDependencies() {
  1511. ctx.ModuleErrorf("Error: %s has an empty api file.", dep.Name())
  1512. }
  1513. srcFiles = append(srcFiles, android.PathForSource(ctx, providerApiFile.String()))
  1514. case libTag:
  1515. provider := ctx.OtherModuleProvider(dep, JavaInfoProvider).(JavaInfo)
  1516. classPaths = append(classPaths, provider.HeaderJars...)
  1517. case staticLibTag:
  1518. provider := ctx.OtherModuleProvider(dep, JavaInfoProvider).(JavaInfo)
  1519. staticLibs = append(staticLibs, provider.HeaderJars...)
  1520. case depApiSrcsTag:
  1521. provider := ctx.OtherModuleProvider(dep, JavaApiLibraryDepsProvider).(JavaApiLibraryDepsInfo)
  1522. classPaths = append(classPaths, provider.HeaderJars...)
  1523. depApiSrcsStubsSrcJar = provider.StubsSrcJar
  1524. }
  1525. })
  1526. // Add the api_files inputs
  1527. for _, api := range al.properties.Api_files {
  1528. srcFiles = append(srcFiles, android.PathForModuleSrc(ctx, api))
  1529. }
  1530. if srcFiles == nil && !ctx.Config().AllowMissingDependencies() {
  1531. ctx.ModuleErrorf("Error: %s has an empty api file.", ctx.ModuleName())
  1532. }
  1533. cmd := metalavaStubCmd(ctx, rule, srcFiles, homeDir)
  1534. al.stubsFlags(ctx, cmd, stubsDir)
  1535. al.stubsSrcJar = android.PathForModuleOut(ctx, "metalava", ctx.ModuleName()+"-"+"stubs.srcjar")
  1536. if depApiSrcsStubsSrcJar != nil {
  1537. al.extractApiSrcs(ctx, rule, stubsDir, depApiSrcsStubsSrcJar)
  1538. } else {
  1539. rule.Command().
  1540. BuiltTool("soong_zip").
  1541. Flag("-write_if_changed").
  1542. Flag("-jar").
  1543. FlagWithOutput("-o ", al.stubsSrcJar).
  1544. FlagWithArg("-C ", stubsDir.String()).
  1545. FlagWithArg("-D ", stubsDir.String())
  1546. }
  1547. rule.Build("metalava", "metalava merged")
  1548. al.stubsJarWithoutStaticLibs = android.PathForModuleOut(ctx, ctx.ModuleName(), "stubs.jar")
  1549. al.stubsJar = android.PathForModuleOut(ctx, ctx.ModuleName(), fmt.Sprintf("%s.jar", ctx.ModuleName()))
  1550. var flags javaBuilderFlags
  1551. flags.javaVersion = getStubsJavaVersion()
  1552. flags.javacFlags = strings.Join(al.properties.Javacflags, " ")
  1553. flags.classpath = classpath(classPaths)
  1554. TransformJavaToClasses(ctx, al.stubsJarWithoutStaticLibs, 0, android.Paths{},
  1555. android.Paths{al.stubsSrcJar}, flags, android.Paths{})
  1556. builder := android.NewRuleBuilder(pctx, ctx)
  1557. builder.Command().
  1558. BuiltTool("merge_zips").
  1559. Output(al.stubsJar).
  1560. Inputs(android.Paths{al.stubsJarWithoutStaticLibs}).
  1561. Inputs(staticLibs)
  1562. builder.Build("merge_zips", "merge jar files")
  1563. // compile stubs to .dex for hiddenapi processing
  1564. dexParams := &compileDexParams{
  1565. flags: javaBuilderFlags{},
  1566. sdkVersion: al.SdkVersion(ctx),
  1567. minSdkVersion: al.MinSdkVersion(ctx),
  1568. classesJar: al.stubsJar,
  1569. jarName: ctx.ModuleName() + ".jar",
  1570. }
  1571. dexOutputFile := al.dexer.compileDex(ctx, dexParams)
  1572. uncompressed := true
  1573. al.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), al.stubsJar, &uncompressed)
  1574. dexOutputFile = al.hiddenAPIEncodeDex(ctx, dexOutputFile)
  1575. al.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
  1576. ctx.Phony(ctx.ModuleName(), al.stubsJar)
  1577. ctx.SetProvider(JavaInfoProvider, JavaInfo{
  1578. HeaderJars: android.PathsIfNonNil(al.stubsJar),
  1579. ImplementationAndResourcesJars: android.PathsIfNonNil(al.stubsJar),
  1580. ImplementationJars: android.PathsIfNonNil(al.stubsJar),
  1581. AidlIncludeDirs: android.Paths{},
  1582. })
  1583. ctx.SetProvider(JavaApiLibraryDepsProvider, JavaApiLibraryDepsInfo{
  1584. JavaInfo: JavaInfo{
  1585. HeaderJars: android.PathsIfNonNil(al.stubsJar),
  1586. },
  1587. StubsSrcJar: al.stubsSrcJar,
  1588. })
  1589. }
  1590. func (al *ApiLibrary) DexJarBuildPath() OptionalDexJarPath {
  1591. return al.dexJarFile
  1592. }
  1593. func (al *ApiLibrary) DexJarInstallPath() android.Path {
  1594. return al.dexJarFile.Path()
  1595. }
  1596. func (al *ApiLibrary) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
  1597. return nil
  1598. }
  1599. // java_api_library constitutes the sdk, and does not build against one
  1600. func (al *ApiLibrary) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
  1601. return android.SdkSpecNone
  1602. }
  1603. // java_api_library is always at "current". Return FutureApiLevel
  1604. func (al *ApiLibrary) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
  1605. return android.FutureApiLevel
  1606. }
  1607. // implement the following interfaces for hiddenapi processing
  1608. var _ hiddenAPIModule = (*ApiLibrary)(nil)
  1609. var _ UsesLibraryDependency = (*ApiLibrary)(nil)
  1610. //
  1611. // Java prebuilts
  1612. //
  1613. type ImportProperties struct {
  1614. Jars []string `android:"path,arch_variant"`
  1615. // The version of the SDK that the source prebuilt file was built against. Defaults to the
  1616. // current version if not specified.
  1617. Sdk_version *string
  1618. // The minimum version of the SDK that this module supports. Defaults to sdk_version if not
  1619. // specified.
  1620. Min_sdk_version *string
  1621. // The max sdk version placeholder used to replace maxSdkVersion attributes on permission
  1622. // and uses-permission tags in manifest_fixer.
  1623. Replace_max_sdk_version_placeholder *string
  1624. Installable *bool
  1625. // If not empty, classes are restricted to the specified packages and their sub-packages.
  1626. Permitted_packages []string
  1627. // List of shared java libs that this module has dependencies to
  1628. Libs []string
  1629. // List of files to remove from the jar file(s)
  1630. Exclude_files []string
  1631. // List of directories to remove from the jar file(s)
  1632. Exclude_dirs []string
  1633. // if set to true, run Jetifier against .jar file. Defaults to false.
  1634. Jetifier *bool
  1635. // set the name of the output
  1636. Stem *string
  1637. Aidl struct {
  1638. // directories that should be added as include directories for any aidl sources of modules
  1639. // that depend on this module, as well as to aidl for this module.
  1640. Export_include_dirs []string
  1641. }
  1642. }
  1643. type Import struct {
  1644. android.ModuleBase
  1645. android.DefaultableModuleBase
  1646. android.ApexModuleBase
  1647. android.BazelModuleBase
  1648. prebuilt android.Prebuilt
  1649. // Functionality common to Module and Import.
  1650. embeddableInModuleAndImport
  1651. hiddenAPI
  1652. dexer
  1653. dexpreopter
  1654. properties ImportProperties
  1655. // output file containing classes.dex and resources
  1656. dexJarFile OptionalDexJarPath
  1657. dexJarInstallFile android.Path
  1658. combinedClasspathFile android.Path
  1659. classLoaderContexts dexpreopt.ClassLoaderContextMap
  1660. exportAidlIncludeDirs android.Paths
  1661. hideApexVariantFromMake bool
  1662. sdkVersion android.SdkSpec
  1663. minSdkVersion android.ApiLevel
  1664. }
  1665. var _ PermittedPackagesForUpdatableBootJars = (*Import)(nil)
  1666. func (j *Import) PermittedPackagesForUpdatableBootJars() []string {
  1667. return j.properties.Permitted_packages
  1668. }
  1669. func (j *Import) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
  1670. return android.SdkSpecFrom(ctx, String(j.properties.Sdk_version))
  1671. }
  1672. func (j *Import) SystemModules() string {
  1673. return "none"
  1674. }
  1675. func (j *Import) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
  1676. if j.properties.Min_sdk_version != nil {
  1677. return android.ApiLevelFrom(ctx, *j.properties.Min_sdk_version)
  1678. }
  1679. return j.SdkVersion(ctx).ApiLevel
  1680. }
  1681. func (j *Import) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.ApiLevel {
  1682. if j.properties.Replace_max_sdk_version_placeholder != nil {
  1683. return android.ApiLevelFrom(ctx, *j.properties.Replace_max_sdk_version_placeholder)
  1684. }
  1685. // Default is PrivateApiLevel
  1686. return android.SdkSpecPrivate.ApiLevel
  1687. }
  1688. func (j *Import) TargetSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
  1689. return j.SdkVersion(ctx).ApiLevel
  1690. }
  1691. func (j *Import) Prebuilt() *android.Prebuilt {
  1692. return &j.prebuilt
  1693. }
  1694. func (j *Import) PrebuiltSrcs() []string {
  1695. return j.properties.Jars
  1696. }
  1697. func (j *Import) Name() string {
  1698. return j.prebuilt.Name(j.ModuleBase.Name())
  1699. }
  1700. func (j *Import) Stem() string {
  1701. return proptools.StringDefault(j.properties.Stem, j.ModuleBase.Name())
  1702. }
  1703. func (a *Import) JacocoReportClassesFile() android.Path {
  1704. return nil
  1705. }
  1706. func (j *Import) LintDepSets() LintDepSets {
  1707. return LintDepSets{}
  1708. }
  1709. func (j *Import) getStrictUpdatabilityLinting() bool {
  1710. return false
  1711. }
  1712. func (j *Import) setStrictUpdatabilityLinting(bool) {
  1713. }
  1714. func (j *Import) DepsMutator(ctx android.BottomUpMutatorContext) {
  1715. ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
  1716. if ctx.Device() && Bool(j.dexProperties.Compile_dex) {
  1717. sdkDeps(ctx, android.SdkContext(j), j.dexer)
  1718. }
  1719. }
  1720. func (j *Import) commonBuildActions(ctx android.ModuleContext) {
  1721. //TODO(b/231322772) these should come from Bazel once available
  1722. j.sdkVersion = j.SdkVersion(ctx)
  1723. j.minSdkVersion = j.MinSdkVersion(ctx)
  1724. if !ctx.Provider(android.ApexInfoProvider).(android.ApexInfo).IsForPlatform() {
  1725. j.hideApexVariantFromMake = true
  1726. }
  1727. if ctx.Windows() {
  1728. j.HideFromMake()
  1729. }
  1730. }
  1731. func (j *Import) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  1732. j.commonBuildActions(ctx)
  1733. jars := android.PathsForModuleSrc(ctx, j.properties.Jars)
  1734. jarName := j.Stem() + ".jar"
  1735. outputFile := android.PathForModuleOut(ctx, "combined", jarName)
  1736. TransformJarsToJar(ctx, outputFile, "for prebuilts", jars, android.OptionalPath{},
  1737. false, j.properties.Exclude_files, j.properties.Exclude_dirs)
  1738. if Bool(j.properties.Jetifier) {
  1739. inputFile := outputFile
  1740. outputFile = android.PathForModuleOut(ctx, "jetifier", jarName)
  1741. TransformJetifier(ctx, outputFile, inputFile)
  1742. }
  1743. j.combinedClasspathFile = outputFile
  1744. j.classLoaderContexts = make(dexpreopt.ClassLoaderContextMap)
  1745. var flags javaBuilderFlags
  1746. j.collectTransitiveHeaderJars(ctx)
  1747. ctx.VisitDirectDeps(func(module android.Module) {
  1748. tag := ctx.OtherModuleDependencyTag(module)
  1749. if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
  1750. dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
  1751. switch tag {
  1752. case libTag, sdkLibTag:
  1753. flags.classpath = append(flags.classpath, dep.HeaderJars...)
  1754. flags.dexClasspath = append(flags.dexClasspath, dep.HeaderJars...)
  1755. case staticLibTag:
  1756. flags.classpath = append(flags.classpath, dep.HeaderJars...)
  1757. case bootClasspathTag:
  1758. flags.bootClasspath = append(flags.bootClasspath, dep.HeaderJars...)
  1759. }
  1760. } else if dep, ok := module.(SdkLibraryDependency); ok {
  1761. switch tag {
  1762. case libTag, sdkLibTag:
  1763. flags.classpath = append(flags.classpath, dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))...)
  1764. }
  1765. }
  1766. addCLCFromDep(ctx, module, j.classLoaderContexts)
  1767. })
  1768. j.maybeInstall(ctx, jarName, outputFile)
  1769. j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.properties.Aidl.Export_include_dirs)
  1770. if ctx.Device() {
  1771. // If this is a variant created for a prebuilt_apex then use the dex implementation jar
  1772. // obtained from the associated deapexer module.
  1773. ai := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
  1774. if ai.ForPrebuiltApex {
  1775. // Get the path of the dex implementation jar from the `deapexer` module.
  1776. di := android.FindDeapexerProviderForModule(ctx)
  1777. if di == nil {
  1778. return // An error has been reported by FindDeapexerProviderForModule.
  1779. }
  1780. dexJarFileApexRootRelative := apexRootRelativePathToJavaLib(j.BaseModuleName())
  1781. if dexOutputPath := di.PrebuiltExportPath(dexJarFileApexRootRelative); dexOutputPath != nil {
  1782. dexJarFile := makeDexJarPathFromPath(dexOutputPath)
  1783. j.dexJarFile = dexJarFile
  1784. installPath := android.PathForModuleInPartitionInstall(ctx, "apex", ai.ApexVariationName, apexRootRelativePathToJavaLib(j.BaseModuleName()))
  1785. j.dexJarInstallFile = installPath
  1786. j.dexpreopter.installPath = j.dexpreopter.getInstallPath(ctx, installPath)
  1787. setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
  1788. j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
  1789. if profilePath := di.PrebuiltExportPath(dexJarFileApexRootRelative + ".prof"); profilePath != nil {
  1790. j.dexpreopter.inputProfilePathOnHost = profilePath
  1791. }
  1792. j.dexpreopt(ctx, dexOutputPath)
  1793. // Initialize the hiddenapi structure.
  1794. j.initHiddenAPI(ctx, dexJarFile, outputFile, j.dexProperties.Uncompress_dex)
  1795. } else {
  1796. // This should never happen as a variant for a prebuilt_apex is only created if the
  1797. // prebuilt_apex has been configured to export the java library dex file.
  1798. ctx.ModuleErrorf("internal error: no dex implementation jar available from prebuilt APEX %s", di.ApexModuleName())
  1799. }
  1800. } else if Bool(j.dexProperties.Compile_dex) {
  1801. sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
  1802. if sdkDep.invalidVersion {
  1803. ctx.AddMissingDependencies(sdkDep.bootclasspath)
  1804. ctx.AddMissingDependencies(sdkDep.java9Classpath)
  1805. } else if sdkDep.useFiles {
  1806. // sdkDep.jar is actually equivalent to turbine header.jar.
  1807. flags.classpath = append(flags.classpath, sdkDep.jars...)
  1808. }
  1809. // Dex compilation
  1810. j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
  1811. ctx, android.PathForModuleInstall(ctx, "framework", jarName))
  1812. setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
  1813. j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
  1814. var dexOutputFile android.OutputPath
  1815. dexParams := &compileDexParams{
  1816. flags: flags,
  1817. sdkVersion: j.SdkVersion(ctx),
  1818. minSdkVersion: j.MinSdkVersion(ctx),
  1819. classesJar: outputFile,
  1820. jarName: jarName,
  1821. }
  1822. dexOutputFile = j.dexer.compileDex(ctx, dexParams)
  1823. if ctx.Failed() {
  1824. return
  1825. }
  1826. // Initialize the hiddenapi structure.
  1827. j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), outputFile, j.dexProperties.Uncompress_dex)
  1828. // Encode hidden API flags in dex file.
  1829. dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
  1830. j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
  1831. j.dexJarInstallFile = android.PathForModuleInstall(ctx, "framework", jarName)
  1832. }
  1833. }
  1834. ctx.SetProvider(JavaInfoProvider, JavaInfo{
  1835. HeaderJars: android.PathsIfNonNil(j.combinedClasspathFile),
  1836. TransitiveLibsHeaderJars: j.transitiveLibsHeaderJars,
  1837. TransitiveStaticLibsHeaderJars: j.transitiveStaticLibsHeaderJars,
  1838. ImplementationAndResourcesJars: android.PathsIfNonNil(j.combinedClasspathFile),
  1839. ImplementationJars: android.PathsIfNonNil(j.combinedClasspathFile),
  1840. AidlIncludeDirs: j.exportAidlIncludeDirs,
  1841. })
  1842. }
  1843. func (j *Import) maybeInstall(ctx android.ModuleContext, jarName string, outputFile android.Path) {
  1844. if !Bool(j.properties.Installable) {
  1845. return
  1846. }
  1847. var installDir android.InstallPath
  1848. if ctx.InstallInTestcases() {
  1849. var archDir string
  1850. if !ctx.Host() {
  1851. archDir = ctx.DeviceConfig().DeviceArch()
  1852. }
  1853. installDir = android.PathForModuleInstall(ctx, ctx.ModuleName(), archDir)
  1854. } else {
  1855. installDir = android.PathForModuleInstall(ctx, "framework")
  1856. }
  1857. ctx.InstallFile(installDir, jarName, outputFile)
  1858. }
  1859. func (j *Import) OutputFiles(tag string) (android.Paths, error) {
  1860. switch tag {
  1861. case "", ".jar":
  1862. return android.Paths{j.combinedClasspathFile}, nil
  1863. default:
  1864. return nil, fmt.Errorf("unsupported module reference tag %q", tag)
  1865. }
  1866. }
  1867. var _ android.OutputFileProducer = (*Import)(nil)
  1868. func (j *Import) HeaderJars() android.Paths {
  1869. if j.combinedClasspathFile == nil {
  1870. return nil
  1871. }
  1872. return android.Paths{j.combinedClasspathFile}
  1873. }
  1874. func (j *Import) ImplementationAndResourcesJars() android.Paths {
  1875. if j.combinedClasspathFile == nil {
  1876. return nil
  1877. }
  1878. return android.Paths{j.combinedClasspathFile}
  1879. }
  1880. func (j *Import) DexJarBuildPath() OptionalDexJarPath {
  1881. return j.dexJarFile
  1882. }
  1883. func (j *Import) DexJarInstallPath() android.Path {
  1884. return j.dexJarInstallFile
  1885. }
  1886. func (j *Import) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
  1887. return j.classLoaderContexts
  1888. }
  1889. var _ android.ApexModule = (*Import)(nil)
  1890. // Implements android.ApexModule
  1891. func (j *Import) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
  1892. return j.depIsInSameApex(ctx, dep)
  1893. }
  1894. // Implements android.ApexModule
  1895. func (j *Import) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
  1896. sdkVersion android.ApiLevel) error {
  1897. sdkVersionSpec := j.SdkVersion(ctx)
  1898. minSdkVersion := j.MinSdkVersion(ctx)
  1899. if !minSdkVersion.Specified() {
  1900. return fmt.Errorf("min_sdk_version is not specified")
  1901. }
  1902. // If the module is compiling against core (via sdk_version), skip comparison check.
  1903. if sdkVersionSpec.Kind == android.SdkCore {
  1904. return nil
  1905. }
  1906. if minSdkVersion.GreaterThan(sdkVersion) {
  1907. return fmt.Errorf("newer SDK(%v)", minSdkVersion)
  1908. }
  1909. return nil
  1910. }
  1911. // requiredFilesFromPrebuiltApexForImport returns information about the files that a java_import or
  1912. // java_sdk_library_import with the specified base module name requires to be exported from a
  1913. // prebuilt_apex/apex_set.
  1914. func requiredFilesFromPrebuiltApexForImport(name string, d *dexpreopter) []string {
  1915. dexJarFileApexRootRelative := apexRootRelativePathToJavaLib(name)
  1916. // Add the dex implementation jar to the set of exported files.
  1917. files := []string{
  1918. dexJarFileApexRootRelative,
  1919. }
  1920. if BoolDefault(d.importDexpreoptProperties.Dex_preopt.Profile_guided, false) {
  1921. files = append(files, dexJarFileApexRootRelative+".prof")
  1922. }
  1923. return files
  1924. }
  1925. // apexRootRelativePathToJavaLib returns the path, relative to the root of the apex's contents, for
  1926. // the java library with the specified name.
  1927. func apexRootRelativePathToJavaLib(name string) string {
  1928. return filepath.Join("javalib", name+".jar")
  1929. }
  1930. var _ android.RequiredFilesFromPrebuiltApex = (*Import)(nil)
  1931. func (j *Import) RequiredFilesFromPrebuiltApex(_ android.BaseModuleContext) []string {
  1932. name := j.BaseModuleName()
  1933. return requiredFilesFromPrebuiltApexForImport(name, &j.dexpreopter)
  1934. }
  1935. // Add compile time check for interface implementation
  1936. var _ android.IDEInfo = (*Import)(nil)
  1937. var _ android.IDECustomizedModuleName = (*Import)(nil)
  1938. // Collect information for opening IDE project files in java/jdeps.go.
  1939. func (j *Import) IDEInfo(dpInfo *android.IdeInfo) {
  1940. dpInfo.Jars = append(dpInfo.Jars, j.PrebuiltSrcs()...)
  1941. }
  1942. func (j *Import) IDECustomizedModuleName() string {
  1943. // TODO(b/113562217): Extract the base module name from the Import name, often the Import name
  1944. // has a prefix "prebuilt_". Remove the prefix explicitly if needed until we find a better
  1945. // solution to get the Import name.
  1946. return android.RemoveOptionalPrebuiltPrefix(j.Name())
  1947. }
  1948. var _ android.PrebuiltInterface = (*Import)(nil)
  1949. func (j *Import) IsInstallable() bool {
  1950. return Bool(j.properties.Installable)
  1951. }
  1952. var _ DexpreopterInterface = (*Import)(nil)
  1953. // java_import imports one or more `.jar` files into the build graph as if they were built by a java_library module.
  1954. //
  1955. // By default, a java_import has a single variant that expects a `.jar` file containing `.class` files that were
  1956. // compiled against an Android classpath.
  1957. //
  1958. // Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
  1959. // for host modules.
  1960. func ImportFactory() android.Module {
  1961. module := &Import{}
  1962. module.AddProperties(
  1963. &module.properties,
  1964. &module.dexer.dexProperties,
  1965. &module.importDexpreoptProperties,
  1966. )
  1967. module.initModuleAndImport(module)
  1968. module.dexProperties.Optimize.EnabledByDefault = false
  1969. android.InitPrebuiltModule(module, &module.properties.Jars)
  1970. android.InitApexModule(module)
  1971. android.InitBazelModule(module)
  1972. InitJavaModule(module, android.HostAndDeviceSupported)
  1973. return module
  1974. }
  1975. // java_import imports one or more `.jar` files into the build graph as if they were built by a java_library_host
  1976. // module.
  1977. //
  1978. // A java_import_host has a single variant that expects a `.jar` file containing `.class` files that were
  1979. // compiled against a host bootclasspath.
  1980. func ImportFactoryHost() android.Module {
  1981. module := &Import{}
  1982. module.AddProperties(&module.properties)
  1983. android.InitPrebuiltModule(module, &module.properties.Jars)
  1984. android.InitApexModule(module)
  1985. android.InitBazelModule(module)
  1986. InitJavaModule(module, android.HostSupported)
  1987. return module
  1988. }
  1989. // dex_import module
  1990. type DexImportProperties struct {
  1991. Jars []string `android:"path"`
  1992. // set the name of the output
  1993. Stem *string
  1994. }
  1995. type DexImport struct {
  1996. android.ModuleBase
  1997. android.DefaultableModuleBase
  1998. android.ApexModuleBase
  1999. prebuilt android.Prebuilt
  2000. properties DexImportProperties
  2001. dexJarFile OptionalDexJarPath
  2002. dexpreopter
  2003. hideApexVariantFromMake bool
  2004. }
  2005. func (j *DexImport) Prebuilt() *android.Prebuilt {
  2006. return &j.prebuilt
  2007. }
  2008. func (j *DexImport) PrebuiltSrcs() []string {
  2009. return j.properties.Jars
  2010. }
  2011. func (j *DexImport) Name() string {
  2012. return j.prebuilt.Name(j.ModuleBase.Name())
  2013. }
  2014. func (j *DexImport) Stem() string {
  2015. return proptools.StringDefault(j.properties.Stem, j.ModuleBase.Name())
  2016. }
  2017. func (a *DexImport) JacocoReportClassesFile() android.Path {
  2018. return nil
  2019. }
  2020. func (a *DexImport) LintDepSets() LintDepSets {
  2021. return LintDepSets{}
  2022. }
  2023. func (j *DexImport) IsInstallable() bool {
  2024. return true
  2025. }
  2026. func (j *DexImport) getStrictUpdatabilityLinting() bool {
  2027. return false
  2028. }
  2029. func (j *DexImport) setStrictUpdatabilityLinting(bool) {
  2030. }
  2031. func (j *DexImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  2032. if len(j.properties.Jars) != 1 {
  2033. ctx.PropertyErrorf("jars", "exactly one jar must be provided")
  2034. }
  2035. apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
  2036. if !apexInfo.IsForPlatform() {
  2037. j.hideApexVariantFromMake = true
  2038. }
  2039. j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
  2040. ctx, android.PathForModuleInstall(ctx, "framework", j.Stem()+".jar"))
  2041. j.dexpreopter.uncompressedDex = shouldUncompressDex(ctx, &j.dexpreopter)
  2042. inputJar := ctx.ExpandSource(j.properties.Jars[0], "jars")
  2043. dexOutputFile := android.PathForModuleOut(ctx, ctx.ModuleName()+".jar")
  2044. if j.dexpreopter.uncompressedDex {
  2045. rule := android.NewRuleBuilder(pctx, ctx)
  2046. temporary := android.PathForModuleOut(ctx, ctx.ModuleName()+".jar.unaligned")
  2047. rule.Temporary(temporary)
  2048. // use zip2zip to uncompress classes*.dex files
  2049. rule.Command().
  2050. BuiltTool("zip2zip").
  2051. FlagWithInput("-i ", inputJar).
  2052. FlagWithOutput("-o ", temporary).
  2053. FlagWithArg("-0 ", "'classes*.dex'")
  2054. // use zipalign to align uncompressed classes*.dex files
  2055. rule.Command().
  2056. BuiltTool("zipalign").
  2057. Flag("-f").
  2058. Text("4").
  2059. Input(temporary).
  2060. Output(dexOutputFile)
  2061. rule.DeleteTemporaryFiles()
  2062. rule.Build("uncompress_dex", "uncompress dex")
  2063. } else {
  2064. ctx.Build(pctx, android.BuildParams{
  2065. Rule: android.Cp,
  2066. Input: inputJar,
  2067. Output: dexOutputFile,
  2068. })
  2069. }
  2070. j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
  2071. j.dexpreopt(ctx, dexOutputFile)
  2072. if apexInfo.IsForPlatform() {
  2073. ctx.InstallFile(android.PathForModuleInstall(ctx, "framework"),
  2074. j.Stem()+".jar", dexOutputFile)
  2075. }
  2076. }
  2077. func (j *DexImport) DexJarBuildPath() OptionalDexJarPath {
  2078. return j.dexJarFile
  2079. }
  2080. var _ android.ApexModule = (*DexImport)(nil)
  2081. // Implements android.ApexModule
  2082. func (j *DexImport) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
  2083. sdkVersion android.ApiLevel) error {
  2084. // we don't check prebuilt modules for sdk_version
  2085. return nil
  2086. }
  2087. // dex_import imports a `.jar` file containing classes.dex files.
  2088. //
  2089. // A dex_import module cannot be used as a dependency of a java_* or android_* module, it can only be installed
  2090. // to the device.
  2091. func DexImportFactory() android.Module {
  2092. module := &DexImport{}
  2093. module.AddProperties(&module.properties)
  2094. android.InitPrebuiltModule(module, &module.properties.Jars)
  2095. android.InitApexModule(module)
  2096. InitJavaModule(module, android.DeviceSupported)
  2097. return module
  2098. }
  2099. // Defaults
  2100. type Defaults struct {
  2101. android.ModuleBase
  2102. android.DefaultsModuleBase
  2103. android.ApexModuleBase
  2104. }
  2105. // java_defaults provides a set of properties that can be inherited by other java or android modules.
  2106. //
  2107. // A module can use the properties from a java_defaults module using `defaults: ["defaults_module_name"]`. Each
  2108. // property in the defaults module that exists in the depending module will be prepended to the depending module's
  2109. // value for that property.
  2110. //
  2111. // Example:
  2112. //
  2113. // java_defaults {
  2114. // name: "example_defaults",
  2115. // srcs: ["common/**/*.java"],
  2116. // javacflags: ["-Xlint:all"],
  2117. // aaptflags: ["--auto-add-overlay"],
  2118. // }
  2119. //
  2120. // java_library {
  2121. // name: "example",
  2122. // defaults: ["example_defaults"],
  2123. // srcs: ["example/**/*.java"],
  2124. // }
  2125. //
  2126. // is functionally identical to:
  2127. //
  2128. // java_library {
  2129. // name: "example",
  2130. // srcs: [
  2131. // "common/**/*.java",
  2132. // "example/**/*.java",
  2133. // ],
  2134. // javacflags: ["-Xlint:all"],
  2135. // }
  2136. func DefaultsFactory() android.Module {
  2137. module := &Defaults{}
  2138. module.AddProperties(
  2139. &CommonProperties{},
  2140. &DeviceProperties{},
  2141. &OverridableDeviceProperties{},
  2142. &DexProperties{},
  2143. &DexpreoptProperties{},
  2144. &android.ProtoProperties{},
  2145. &aaptProperties{},
  2146. &androidLibraryProperties{},
  2147. &appProperties{},
  2148. &appTestProperties{},
  2149. &overridableAppProperties{},
  2150. &hostTestProperties{},
  2151. &testProperties{},
  2152. &ImportProperties{},
  2153. &AARImportProperties{},
  2154. &sdkLibraryProperties{},
  2155. &commonToSdkLibraryAndImportProperties{},
  2156. &DexImportProperties{},
  2157. &android.ApexProperties{},
  2158. &RuntimeResourceOverlayProperties{},
  2159. &LintProperties{},
  2160. &appTestHelperAppProperties{},
  2161. &JavaApiLibraryProperties{},
  2162. )
  2163. android.InitDefaultsModule(module)
  2164. return module
  2165. }
  2166. func kytheExtractJavaFactory() android.Singleton {
  2167. return &kytheExtractJavaSingleton{}
  2168. }
  2169. type kytheExtractJavaSingleton struct {
  2170. }
  2171. func (ks *kytheExtractJavaSingleton) GenerateBuildActions(ctx android.SingletonContext) {
  2172. var xrefTargets android.Paths
  2173. ctx.VisitAllModules(func(module android.Module) {
  2174. if javaModule, ok := module.(xref); ok {
  2175. xrefTargets = append(xrefTargets, javaModule.XrefJavaFiles()...)
  2176. }
  2177. })
  2178. // TODO(asmundak): perhaps emit a rule to output a warning if there were no xrefTargets
  2179. if len(xrefTargets) > 0 {
  2180. ctx.Phony("xref_java", xrefTargets...)
  2181. }
  2182. }
  2183. var Bool = proptools.Bool
  2184. var BoolDefault = proptools.BoolDefault
  2185. var String = proptools.String
  2186. var inList = android.InList
  2187. // Add class loader context (CLC) of a given dependency to the current CLC.
  2188. func addCLCFromDep(ctx android.ModuleContext, depModule android.Module,
  2189. clcMap dexpreopt.ClassLoaderContextMap) {
  2190. dep, ok := depModule.(UsesLibraryDependency)
  2191. if !ok {
  2192. return
  2193. }
  2194. depName := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(depModule))
  2195. var sdkLib *string
  2196. if lib, ok := depModule.(SdkLibraryDependency); ok && lib.sharedLibrary() {
  2197. // A shared SDK library. This should be added as a top-level CLC element.
  2198. sdkLib = &depName
  2199. } else if ulib, ok := depModule.(ProvidesUsesLib); ok {
  2200. // A non-SDK library disguised as an SDK library by the means of `provides_uses_lib`
  2201. // property. This should be handled in the same way as a shared SDK library.
  2202. sdkLib = ulib.ProvidesUsesLib()
  2203. }
  2204. depTag := ctx.OtherModuleDependencyTag(depModule)
  2205. if IsLibDepTag(depTag) {
  2206. // Ok, propagate <uses-library> through non-static library dependencies.
  2207. } else if tag, ok := depTag.(usesLibraryDependencyTag); ok && tag.sdkVersion == dexpreopt.AnySdkVersion {
  2208. // Ok, propagate <uses-library> through non-compatibility <uses-library> dependencies.
  2209. } else if depTag == staticLibTag {
  2210. // Propagate <uses-library> through static library dependencies, unless it is a component
  2211. // library (such as stubs). Component libraries have a dependency on their SDK library,
  2212. // which should not be pulled just because of a static component library.
  2213. if sdkLib != nil {
  2214. return
  2215. }
  2216. } else {
  2217. // Don't propagate <uses-library> for other dependency tags.
  2218. return
  2219. }
  2220. // If this is an SDK (or SDK-like) library, then it should be added as a node in the CLC tree,
  2221. // and its CLC should be added as subtree of that node. Otherwise the library is not a
  2222. // <uses_library> and should not be added to CLC, but the transitive <uses-library> dependencies
  2223. // from its CLC should be added to the current CLC.
  2224. if sdkLib != nil {
  2225. clcMap.AddContext(ctx, dexpreopt.AnySdkVersion, *sdkLib, false,
  2226. dep.DexJarBuildPath().PathOrNil(), dep.DexJarInstallPath(), dep.ClassLoaderContexts())
  2227. } else {
  2228. clcMap.AddContextMap(dep.ClassLoaderContexts(), depName)
  2229. }
  2230. }
  2231. type javaResourcesAttributes struct {
  2232. Resources bazel.LabelListAttribute
  2233. Resource_strip_prefix *string
  2234. }
  2235. func (m *Library) javaResourcesGetSingleFilegroupStripPrefix(ctx android.TopDownMutatorContext) (string, bool) {
  2236. if otherM, ok := ctx.ModuleFromName(m.properties.Java_resources[0]); ok && len(m.properties.Java_resources) == 1 {
  2237. if fg, isFilegroup := otherM.(android.FileGroupPath); isFilegroup {
  2238. return filepath.Join(ctx.OtherModuleDir(otherM), fg.GetPath(ctx)), true
  2239. }
  2240. }
  2241. return "", false
  2242. }
  2243. func (m *Library) convertJavaResourcesAttributes(ctx android.TopDownMutatorContext) *javaResourcesAttributes {
  2244. var resources bazel.LabelList
  2245. var resourceStripPrefix *string
  2246. if m.properties.Java_resources != nil && len(m.properties.Java_resource_dirs) > 0 {
  2247. ctx.ModuleErrorf("bp2build doesn't support both java_resources and java_resource_dirs being set on the same module.")
  2248. }
  2249. if m.properties.Java_resources != nil {
  2250. if prefix, ok := m.javaResourcesGetSingleFilegroupStripPrefix(ctx); ok {
  2251. resourceStripPrefix = proptools.StringPtr(prefix)
  2252. } else {
  2253. resourceStripPrefix = proptools.StringPtr(ctx.ModuleDir())
  2254. }
  2255. resources.Append(android.BazelLabelForModuleSrc(ctx, m.properties.Java_resources))
  2256. }
  2257. //TODO(b/179889880) handle case where glob includes files outside package
  2258. resDeps := ResourceDirsToFiles(
  2259. ctx,
  2260. m.properties.Java_resource_dirs,
  2261. m.properties.Exclude_java_resource_dirs,
  2262. m.properties.Exclude_java_resources,
  2263. )
  2264. for i, resDep := range resDeps {
  2265. dir, files := resDep.dir, resDep.files
  2266. resources.Append(bazel.MakeLabelList(android.RootToModuleRelativePaths(ctx, files)))
  2267. // Bazel includes the relative path from the WORKSPACE root when placing the resource
  2268. // inside the JAR file, so we need to remove that prefix
  2269. resourceStripPrefix = proptools.StringPtr(dir.String())
  2270. if i > 0 {
  2271. // TODO(b/226423379) allow multiple resource prefixes
  2272. ctx.ModuleErrorf("bp2build does not support more than one directory in java_resource_dirs (b/226423379)")
  2273. }
  2274. }
  2275. return &javaResourcesAttributes{
  2276. Resources: bazel.MakeLabelListAttribute(resources),
  2277. Resource_strip_prefix: resourceStripPrefix,
  2278. }
  2279. }
  2280. type javaCommonAttributes struct {
  2281. *javaResourcesAttributes
  2282. *kotlinAttributes
  2283. Srcs bazel.LabelListAttribute
  2284. Plugins bazel.LabelListAttribute
  2285. Javacopts bazel.StringListAttribute
  2286. Sdk_version bazel.StringAttribute
  2287. Java_version bazel.StringAttribute
  2288. }
  2289. type javaDependencyLabels struct {
  2290. // Dependencies which DO NOT contribute to the API visible to upstream dependencies.
  2291. Deps bazel.LabelListAttribute
  2292. // Dependencies which DO contribute to the API visible to upstream dependencies.
  2293. StaticDeps bazel.LabelListAttribute
  2294. }
  2295. type eventLogTagsAttributes struct {
  2296. Srcs bazel.LabelListAttribute
  2297. }
  2298. type aidlLibraryAttributes struct {
  2299. Srcs bazel.LabelListAttribute
  2300. Tags bazel.StringListAttribute
  2301. }
  2302. type javaAidlLibraryAttributes struct {
  2303. Deps bazel.LabelListAttribute
  2304. Tags bazel.StringListAttribute
  2305. }
  2306. // bp2BuildJavaInfo has information needed for the conversion of java*_modules
  2307. // that is needed bor Bp2Build conversion but that requires different handling
  2308. // depending on the module type.
  2309. type bp2BuildJavaInfo struct {
  2310. // separates dependencies into dynamic dependencies and static dependencies.
  2311. DepLabels *javaDependencyLabels
  2312. hasKotlin bool
  2313. }
  2314. // Replaces //a/b/my_xsd_config with //a/b/my_xsd_config-java
  2315. func xsdConfigJavaTarget(ctx android.BazelConversionPathContext, mod blueprint.Module) string {
  2316. callback := func(xsd android.XsdConfigBp2buildTargets) string {
  2317. return xsd.JavaBp2buildTargetName()
  2318. }
  2319. return android.XsdConfigBp2buildTarget(ctx, mod, callback)
  2320. }
  2321. // convertLibraryAttrsBp2Build returns a javaCommonAttributes struct with
  2322. // converted attributes shared across java_* modules and a bp2BuildJavaInfo struct
  2323. // which has other non-attribute information needed for bp2build conversion
  2324. // that needs different handling depending on the module types, and thus needs
  2325. // to be returned to the calling function.
  2326. func (m *Library) convertLibraryAttrsBp2Build(ctx android.TopDownMutatorContext) (*javaCommonAttributes, *bp2BuildJavaInfo) {
  2327. var srcs bazel.LabelListAttribute
  2328. var deps bazel.LabelListAttribute
  2329. var staticDeps bazel.LabelList
  2330. archVariantProps := m.GetArchVariantProperties(ctx, &CommonProperties{})
  2331. for axis, configToProps := range archVariantProps {
  2332. for config, _props := range configToProps {
  2333. if archProps, ok := _props.(*CommonProperties); ok {
  2334. srcsNonXsd, srcsXsd := android.PartitionXsdSrcs(ctx, archProps.Srcs)
  2335. excludeSrcsNonXsd, _ := android.PartitionXsdSrcs(ctx, archProps.Exclude_srcs)
  2336. archSrcs := android.BazelLabelForModuleSrcExcludes(ctx, srcsNonXsd, excludeSrcsNonXsd)
  2337. srcs.SetSelectValue(axis, config, archSrcs)
  2338. // Add to static deps
  2339. xsdJavaConfigLibraryLabels := android.BazelLabelForModuleDepsWithFn(ctx, srcsXsd, xsdConfigJavaTarget)
  2340. staticDeps.Append(xsdJavaConfigLibraryLabels)
  2341. }
  2342. }
  2343. }
  2344. srcs.ResolveExcludes()
  2345. javaSrcPartition := "java"
  2346. protoSrcPartition := "proto"
  2347. logtagSrcPartition := "logtag"
  2348. aidlSrcPartition := "aidl"
  2349. kotlinPartition := "kotlin"
  2350. srcPartitions := bazel.PartitionLabelListAttribute(ctx, &srcs, bazel.LabelPartitions{
  2351. javaSrcPartition: bazel.LabelPartition{Extensions: []string{".java"}, Keep_remainder: true},
  2352. logtagSrcPartition: bazel.LabelPartition{Extensions: []string{".logtags", ".logtag"}},
  2353. protoSrcPartition: android.ProtoSrcLabelPartition,
  2354. aidlSrcPartition: android.AidlSrcLabelPartition,
  2355. kotlinPartition: bazel.LabelPartition{Extensions: []string{".kt"}},
  2356. })
  2357. javaSrcs := srcPartitions[javaSrcPartition]
  2358. kotlinSrcs := srcPartitions[kotlinPartition]
  2359. javaSrcs.Append(kotlinSrcs)
  2360. if !srcPartitions[logtagSrcPartition].IsEmpty() {
  2361. logtagsLibName := m.Name() + "_logtags"
  2362. ctx.CreateBazelTargetModule(
  2363. bazel.BazelTargetModuleProperties{
  2364. Rule_class: "event_log_tags",
  2365. Bzl_load_location: "//build/bazel/rules/java:event_log_tags.bzl",
  2366. },
  2367. android.CommonAttributes{Name: logtagsLibName},
  2368. &eventLogTagsAttributes{
  2369. Srcs: srcPartitions[logtagSrcPartition],
  2370. },
  2371. )
  2372. logtagsSrcs := bazel.MakeLabelList([]bazel.Label{{Label: ":" + logtagsLibName}})
  2373. javaSrcs.Append(bazel.MakeLabelListAttribute(logtagsSrcs))
  2374. }
  2375. if !srcPartitions[aidlSrcPartition].IsEmpty() {
  2376. aidlLibs, aidlSrcs := srcPartitions[aidlSrcPartition].Partition(func(src bazel.Label) bool {
  2377. return android.IsConvertedToAidlLibrary(ctx, src.OriginalModuleName)
  2378. })
  2379. apexAvailableTags := android.ApexAvailableTagsWithoutTestApexes(ctx, ctx.Module())
  2380. if !aidlSrcs.IsEmpty() {
  2381. aidlLibName := m.Name() + "_aidl_library"
  2382. ctx.CreateBazelTargetModule(
  2383. bazel.BazelTargetModuleProperties{
  2384. Rule_class: "aidl_library",
  2385. Bzl_load_location: "//build/bazel/rules/aidl:aidl_library.bzl",
  2386. },
  2387. android.CommonAttributes{Name: aidlLibName},
  2388. &aidlLibraryAttributes{
  2389. Srcs: aidlSrcs,
  2390. Tags: apexAvailableTags,
  2391. },
  2392. )
  2393. aidlLibs.Add(&bazel.LabelAttribute{Value: &bazel.Label{Label: ":" + aidlLibName}})
  2394. }
  2395. javaAidlLibName := m.Name() + "_java_aidl_library"
  2396. ctx.CreateBazelTargetModule(
  2397. bazel.BazelTargetModuleProperties{
  2398. Rule_class: "java_aidl_library",
  2399. Bzl_load_location: "//build/bazel/rules/java:java_aidl_library.bzl",
  2400. },
  2401. android.CommonAttributes{Name: javaAidlLibName},
  2402. &javaAidlLibraryAttributes{
  2403. Deps: aidlLibs,
  2404. Tags: apexAvailableTags,
  2405. },
  2406. )
  2407. staticDeps.Add(&bazel.Label{Label: ":" + javaAidlLibName})
  2408. }
  2409. var javacopts []string
  2410. if m.properties.Javacflags != nil {
  2411. javacopts = append(javacopts, m.properties.Javacflags...)
  2412. }
  2413. epEnabled := m.properties.Errorprone.Enabled
  2414. //TODO(b/227504307) add configuration that depends on RUN_ERROR_PRONE environment variable
  2415. if Bool(epEnabled) {
  2416. javacopts = append(javacopts, m.properties.Errorprone.Javacflags...)
  2417. }
  2418. commonAttrs := &javaCommonAttributes{
  2419. Srcs: javaSrcs,
  2420. javaResourcesAttributes: m.convertJavaResourcesAttributes(ctx),
  2421. Plugins: bazel.MakeLabelListAttribute(
  2422. android.BazelLabelForModuleDeps(ctx, m.properties.Plugins),
  2423. ),
  2424. Javacopts: bazel.MakeStringListAttribute(javacopts),
  2425. Java_version: bazel.StringAttribute{Value: m.properties.Java_version},
  2426. Sdk_version: bazel.StringAttribute{Value: m.deviceProperties.Sdk_version},
  2427. }
  2428. for axis, configToProps := range archVariantProps {
  2429. for config, _props := range configToProps {
  2430. if archProps, ok := _props.(*CommonProperties); ok {
  2431. var libLabels []bazel.Label
  2432. for _, d := range archProps.Libs {
  2433. neverlinkLabel := android.BazelLabelForModuleDepSingle(ctx, d)
  2434. neverlinkLabel.Label = neverlinkLabel.Label + "-neverlink"
  2435. libLabels = append(libLabels, neverlinkLabel)
  2436. }
  2437. deps.SetSelectValue(axis, config, bazel.MakeLabelList(libLabels))
  2438. }
  2439. }
  2440. }
  2441. protoDepLabel := bp2buildProto(ctx, &m.Module, srcPartitions[protoSrcPartition])
  2442. // Soong does not differentiate between a java_library and the Bazel equivalent of
  2443. // a java_proto_library + proto_library pair. Instead, in Soong proto sources are
  2444. // listed directly in the srcs of a java_library, and the classes produced
  2445. // by protoc are included directly in the resulting JAR. Thus upstream dependencies
  2446. // that depend on a java_library with proto sources can link directly to the protobuf API,
  2447. // and so this should be a static dependency.
  2448. staticDeps.Add(protoDepLabel)
  2449. depLabels := &javaDependencyLabels{}
  2450. depLabels.Deps = deps
  2451. for axis, configToProps := range archVariantProps {
  2452. for config, _props := range configToProps {
  2453. if archProps, ok := _props.(*CommonProperties); ok {
  2454. archStaticLibs := android.BazelLabelForModuleDeps(
  2455. ctx,
  2456. android.LastUniqueStrings(android.CopyOf(archProps.Static_libs)))
  2457. depLabels.StaticDeps.SetSelectValue(axis, config, archStaticLibs)
  2458. }
  2459. }
  2460. }
  2461. depLabels.StaticDeps.Value.Append(staticDeps)
  2462. hasKotlin := !kotlinSrcs.IsEmpty()
  2463. commonAttrs.kotlinAttributes = &kotlinAttributes{
  2464. Kotlincflags: &m.properties.Kotlincflags,
  2465. }
  2466. if len(m.properties.Common_srcs) != 0 {
  2467. hasKotlin = true
  2468. commonAttrs.kotlinAttributes.Common_srcs = bazel.MakeLabelListAttribute(android.BazelLabelForModuleSrc(ctx, m.properties.Common_srcs))
  2469. }
  2470. bp2BuildInfo := &bp2BuildJavaInfo{
  2471. DepLabels: depLabels,
  2472. hasKotlin: hasKotlin,
  2473. }
  2474. return commonAttrs, bp2BuildInfo
  2475. }
  2476. type javaLibraryAttributes struct {
  2477. *javaCommonAttributes
  2478. Deps bazel.LabelListAttribute
  2479. Exports bazel.LabelListAttribute
  2480. Neverlink bazel.BoolAttribute
  2481. }
  2482. type kotlinAttributes struct {
  2483. Common_srcs bazel.LabelListAttribute
  2484. Kotlincflags *[]string
  2485. }
  2486. func ktJvmLibraryBazelTargetModuleProperties() bazel.BazelTargetModuleProperties {
  2487. return bazel.BazelTargetModuleProperties{
  2488. Rule_class: "kt_jvm_library",
  2489. Bzl_load_location: "//build/bazel/rules/kotlin:kt_jvm_library.bzl",
  2490. }
  2491. }
  2492. func javaLibraryBazelTargetModuleProperties() bazel.BazelTargetModuleProperties {
  2493. return bazel.BazelTargetModuleProperties{
  2494. Rule_class: "java_library",
  2495. Bzl_load_location: "//build/bazel/rules/java:library.bzl",
  2496. }
  2497. }
  2498. func javaLibraryBp2Build(ctx android.TopDownMutatorContext, m *Library) {
  2499. commonAttrs, bp2BuildInfo := m.convertLibraryAttrsBp2Build(ctx)
  2500. depLabels := bp2BuildInfo.DepLabels
  2501. deps := depLabels.Deps
  2502. if !commonAttrs.Srcs.IsEmpty() {
  2503. deps.Append(depLabels.StaticDeps) // we should only append these if there are sources to use them
  2504. } else if !deps.IsEmpty() {
  2505. ctx.ModuleErrorf("Module has direct dependencies but no sources. Bazel will not allow this.")
  2506. }
  2507. var props bazel.BazelTargetModuleProperties
  2508. attrs := &javaLibraryAttributes{
  2509. javaCommonAttributes: commonAttrs,
  2510. Deps: deps,
  2511. Exports: depLabels.StaticDeps,
  2512. }
  2513. name := m.Name()
  2514. if !bp2BuildInfo.hasKotlin {
  2515. props = javaLibraryBazelTargetModuleProperties()
  2516. } else {
  2517. props = ktJvmLibraryBazelTargetModuleProperties()
  2518. }
  2519. ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: name}, attrs)
  2520. neverlinkProp := true
  2521. neverLinkAttrs := &javaLibraryAttributes{
  2522. Exports: bazel.MakeSingleLabelListAttribute(bazel.Label{Label: ":" + name}),
  2523. Neverlink: bazel.BoolAttribute{Value: &neverlinkProp},
  2524. javaCommonAttributes: &javaCommonAttributes{
  2525. Sdk_version: bazel.StringAttribute{Value: m.deviceProperties.Sdk_version},
  2526. Java_version: bazel.StringAttribute{Value: m.properties.Java_version},
  2527. },
  2528. }
  2529. ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: name + "-neverlink"}, neverLinkAttrs)
  2530. }
  2531. type javaBinaryHostAttributes struct {
  2532. *javaCommonAttributes
  2533. Deps bazel.LabelListAttribute
  2534. Runtime_deps bazel.LabelListAttribute
  2535. Main_class string
  2536. Jvm_flags bazel.StringListAttribute
  2537. }
  2538. // JavaBinaryHostBp2Build is for java_binary_host bp2build.
  2539. func javaBinaryHostBp2Build(ctx android.TopDownMutatorContext, m *Binary) {
  2540. commonAttrs, bp2BuildInfo := m.convertLibraryAttrsBp2Build(ctx)
  2541. depLabels := bp2BuildInfo.DepLabels
  2542. deps := depLabels.Deps
  2543. deps.Append(depLabels.StaticDeps)
  2544. if m.binaryProperties.Jni_libs != nil {
  2545. deps.Append(bazel.MakeLabelListAttribute(android.BazelLabelForModuleDeps(ctx, m.binaryProperties.Jni_libs)))
  2546. }
  2547. var runtimeDeps bazel.LabelListAttribute
  2548. if commonAttrs.Srcs.IsEmpty() {
  2549. // if there are no sources, then the dependencies can only be used at runtime
  2550. runtimeDeps = deps
  2551. deps = bazel.LabelListAttribute{}
  2552. }
  2553. mainClass := ""
  2554. if m.binaryProperties.Main_class != nil {
  2555. mainClass = *m.binaryProperties.Main_class
  2556. }
  2557. if m.properties.Manifest != nil {
  2558. mainClassInManifest, err := android.GetMainClassInManifest(ctx.Config(), android.PathForModuleSrc(ctx, *m.properties.Manifest).String())
  2559. if err != nil {
  2560. return
  2561. }
  2562. mainClass = mainClassInManifest
  2563. }
  2564. // Attribute jvm_flags
  2565. var jvmFlags bazel.StringListAttribute
  2566. if m.binaryProperties.Jni_libs != nil {
  2567. jniLibPackages := []string{}
  2568. for _, jniLib := range m.binaryProperties.Jni_libs {
  2569. if jniLibModule, exists := ctx.ModuleFromName(jniLib); exists {
  2570. otherDir := ctx.OtherModuleDir(jniLibModule)
  2571. jniLibPackages = append(jniLibPackages, filepath.Join(otherDir, jniLib))
  2572. }
  2573. }
  2574. jniLibPaths := []string{}
  2575. for _, jniLibPackage := range jniLibPackages {
  2576. // See cs/f:.*/third_party/bazel/.*java_stub_template.txt for the use of RUNPATH
  2577. jniLibPaths = append(jniLibPaths, "$${RUNPATH}"+jniLibPackage)
  2578. }
  2579. jvmFlags = bazel.MakeStringListAttribute([]string{"-Djava.library.path=" + strings.Join(jniLibPaths, ":")})
  2580. }
  2581. props := bazel.BazelTargetModuleProperties{
  2582. Rule_class: "java_binary",
  2583. Bzl_load_location: "@rules_java//java:defs.bzl",
  2584. }
  2585. binAttrs := &javaBinaryHostAttributes{
  2586. Runtime_deps: runtimeDeps,
  2587. Main_class: mainClass,
  2588. Jvm_flags: jvmFlags,
  2589. }
  2590. if commonAttrs.Srcs.IsEmpty() {
  2591. binAttrs.javaCommonAttributes = commonAttrs
  2592. ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, binAttrs)
  2593. return
  2594. }
  2595. libInfo := libraryCreationInfo{
  2596. deps: deps,
  2597. attrs: commonAttrs,
  2598. baseName: m.Name(),
  2599. hasKotlin: bp2BuildInfo.hasKotlin,
  2600. }
  2601. libName := createLibraryTarget(ctx, libInfo)
  2602. binAttrs.Runtime_deps.Add(&bazel.LabelAttribute{Value: &bazel.Label{Label: ":" + libName}})
  2603. // Create the BazelTargetModule.
  2604. ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, binAttrs)
  2605. }
  2606. type javaTestHostAttributes struct {
  2607. *javaCommonAttributes
  2608. Deps bazel.LabelListAttribute
  2609. Runtime_deps bazel.LabelListAttribute
  2610. }
  2611. // javaTestHostBp2Build is for java_test_host bp2build.
  2612. func javaTestHostBp2Build(ctx android.TopDownMutatorContext, m *TestHost) {
  2613. commonAttrs, bp2BuildInfo := m.convertLibraryAttrsBp2Build(ctx)
  2614. depLabels := bp2BuildInfo.DepLabels
  2615. deps := depLabels.Deps
  2616. deps.Append(depLabels.StaticDeps)
  2617. var runtimeDeps bazel.LabelListAttribute
  2618. attrs := &javaTestHostAttributes{
  2619. Runtime_deps: runtimeDeps,
  2620. }
  2621. props := bazel.BazelTargetModuleProperties{
  2622. Rule_class: "java_test",
  2623. Bzl_load_location: "//build/bazel/rules/java:test.bzl",
  2624. }
  2625. if commonAttrs.Srcs.IsEmpty() {
  2626. // if there are no sources, then the dependencies can only be used at runtime
  2627. attrs.Runtime_deps = deps
  2628. attrs.javaCommonAttributes = commonAttrs
  2629. ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, attrs)
  2630. return
  2631. }
  2632. libInfo := libraryCreationInfo{
  2633. deps: deps,
  2634. attrs: commonAttrs,
  2635. baseName: m.Name(),
  2636. hasKotlin: bp2BuildInfo.hasKotlin,
  2637. }
  2638. libName := createLibraryTarget(ctx, libInfo)
  2639. attrs.Runtime_deps.Add(&bazel.LabelAttribute{Value: &bazel.Label{Label: ":" + libName}})
  2640. // Create the BazelTargetModule.
  2641. ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, attrs)
  2642. }
  2643. // libraryCreationInfo encapsulates the info needed to create java_library target from
  2644. // java_binary_host or java_test_host.
  2645. type libraryCreationInfo struct {
  2646. deps bazel.LabelListAttribute
  2647. attrs *javaCommonAttributes
  2648. baseName string
  2649. hasKotlin bool
  2650. }
  2651. // helper function that creates java_library target from java_binary_host or java_test_host,
  2652. // and returns the library target name,
  2653. func createLibraryTarget(ctx android.TopDownMutatorContext, libInfo libraryCreationInfo) string {
  2654. libName := libInfo.baseName + "_lib"
  2655. var libProps bazel.BazelTargetModuleProperties
  2656. if libInfo.hasKotlin {
  2657. libProps = ktJvmLibraryBazelTargetModuleProperties()
  2658. } else {
  2659. libProps = javaLibraryBazelTargetModuleProperties()
  2660. }
  2661. libAttrs := &javaLibraryAttributes{
  2662. Deps: libInfo.deps,
  2663. javaCommonAttributes: libInfo.attrs,
  2664. }
  2665. ctx.CreateBazelTargetModule(libProps, android.CommonAttributes{Name: libName}, libAttrs)
  2666. return libName
  2667. }
  2668. type bazelJavaImportAttributes struct {
  2669. Jars bazel.LabelListAttribute
  2670. Exports bazel.LabelListAttribute
  2671. }
  2672. // java_import bp2Build converter.
  2673. func (i *Import) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
  2674. var jars bazel.LabelListAttribute
  2675. archVariantProps := i.GetArchVariantProperties(ctx, &ImportProperties{})
  2676. for axis, configToProps := range archVariantProps {
  2677. for config, _props := range configToProps {
  2678. if archProps, ok := _props.(*ImportProperties); ok {
  2679. archJars := android.BazelLabelForModuleSrcExcludes(ctx, archProps.Jars, []string(nil))
  2680. jars.SetSelectValue(axis, config, archJars)
  2681. }
  2682. }
  2683. }
  2684. attrs := &bazelJavaImportAttributes{
  2685. Jars: jars,
  2686. }
  2687. props := bazel.BazelTargetModuleProperties{
  2688. Rule_class: "java_import",
  2689. Bzl_load_location: "//build/bazel/rules/java:import.bzl",
  2690. }
  2691. name := android.RemoveOptionalPrebuiltPrefix(i.Name())
  2692. ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: name}, attrs)
  2693. neverlink := true
  2694. neverlinkAttrs := &javaLibraryAttributes{
  2695. Neverlink: bazel.BoolAttribute{Value: &neverlink},
  2696. Exports: bazel.MakeSingleLabelListAttribute(bazel.Label{Label: ":" + name}),
  2697. javaCommonAttributes: &javaCommonAttributes{
  2698. Sdk_version: bazel.StringAttribute{Value: proptools.StringPtr("none")},
  2699. },
  2700. }
  2701. ctx.CreateBazelTargetModule(
  2702. javaLibraryBazelTargetModuleProperties(),
  2703. android.CommonAttributes{Name: name + "-neverlink"},
  2704. neverlinkAttrs)
  2705. }
  2706. var _ android.MixedBuildBuildable = (*Import)(nil)
  2707. func (i *Import) getBazelModuleLabel(ctx android.BaseModuleContext) string {
  2708. return android.RemoveOptionalPrebuiltPrefixFromBazelLabel(i.GetBazelLabel(ctx, i))
  2709. }
  2710. func (i *Import) ProcessBazelQueryResponse(ctx android.ModuleContext) {
  2711. i.commonBuildActions(ctx)
  2712. bazelCtx := ctx.Config().BazelContext
  2713. filePaths, err := bazelCtx.GetOutputFiles(i.getBazelModuleLabel(ctx), android.GetConfigKey(ctx))
  2714. if err != nil {
  2715. ctx.ModuleErrorf(err.Error())
  2716. return
  2717. }
  2718. bazelJars := android.Paths{}
  2719. for _, bazelOutputFile := range filePaths {
  2720. bazelJars = append(bazelJars, android.PathForBazelOut(ctx, bazelOutputFile))
  2721. }
  2722. jarName := android.RemoveOptionalPrebuiltPrefix(i.Name()) + ".jar"
  2723. outputFile := android.PathForModuleOut(ctx, "bazelCombined", jarName)
  2724. TransformJarsToJar(ctx, outputFile, "combine prebuilt jars", bazelJars,
  2725. android.OptionalPath{}, // manifest
  2726. false, // stripDirEntries
  2727. []string{}, // filesToStrip
  2728. []string{}, // dirsToStrip
  2729. )
  2730. i.combinedClasspathFile = outputFile
  2731. ctx.SetProvider(JavaInfoProvider, JavaInfo{
  2732. HeaderJars: android.PathsIfNonNil(i.combinedClasspathFile),
  2733. ImplementationAndResourcesJars: android.PathsIfNonNil(i.combinedClasspathFile),
  2734. ImplementationJars: android.PathsIfNonNil(i.combinedClasspathFile),
  2735. //TODO(b/240308299) include AIDL information from Bazel
  2736. })
  2737. i.maybeInstall(ctx, jarName, outputFile)
  2738. }
  2739. func (i *Import) QueueBazelCall(ctx android.BaseModuleContext) {
  2740. bazelCtx := ctx.Config().BazelContext
  2741. bazelCtx.QueueBazelRequest(i.getBazelModuleLabel(ctx), cquery.GetOutputFiles, android.GetConfigKey(ctx))
  2742. }
  2743. func (i *Import) IsMixedBuildSupported(ctx android.BaseModuleContext) bool {
  2744. return true
  2745. }