java.go 111 KB

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