java.go 103 KB

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