java.go 108 KB

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