java.go 97 KB

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