java.go 112 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318
  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. android.JavaApiLibraryNames(ctx.Config(), 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 JavaApiLibraryDepsInfo struct {
  1344. JavaInfo
  1345. StubsSrcJar android.Path
  1346. }
  1347. var JavaApiLibraryDepsProvider = blueprint.NewProvider(JavaApiLibraryDepsInfo{})
  1348. type ApiLibrary struct {
  1349. android.ModuleBase
  1350. android.DefaultableModuleBase
  1351. hiddenAPI
  1352. dexer
  1353. properties JavaApiLibraryProperties
  1354. stubsSrcJar android.WritablePath
  1355. stubsJar android.WritablePath
  1356. stubsJarWithoutStaticLibs android.WritablePath
  1357. extractedSrcJar android.WritablePath
  1358. // .dex of stubs, used for hiddenapi processing
  1359. dexJarFile OptionalDexJarPath
  1360. }
  1361. type JavaApiLibraryProperties struct {
  1362. // name of the API surface
  1363. Api_surface *string
  1364. // list of Java API contribution modules that consists this API surface
  1365. // This is a list of Soong modules
  1366. Api_contributions []string
  1367. // list of api.txt files relative to this directory that contribute to the
  1368. // API surface.
  1369. // This is a list of relative paths
  1370. Api_files []string `android:"path"`
  1371. // List of flags to be passed to the javac compiler to generate jar file
  1372. Javacflags []string
  1373. // List of shared java libs that this module has dependencies to and
  1374. // should be passed as classpath in javac invocation
  1375. Libs []string
  1376. // List of java libs that this module has static dependencies to and will be
  1377. // merge zipped after metalava invocation
  1378. Static_libs []string
  1379. // Java Api library to provide the full API surface text files and jar file.
  1380. // If this property is set, the provided full API surface text files and
  1381. // jar file are passed to metalava invocation.
  1382. Dep_api_srcs *string
  1383. }
  1384. func ApiLibraryFactory() android.Module {
  1385. module := &ApiLibrary{}
  1386. android.InitAndroidArchModule(module, android.DeviceSupported, android.MultilibCommon)
  1387. module.AddProperties(&module.properties)
  1388. android.InitDefaultableModule(module)
  1389. return module
  1390. }
  1391. func (al *ApiLibrary) ApiSurface() *string {
  1392. return al.properties.Api_surface
  1393. }
  1394. func (al *ApiLibrary) StubsJar() android.Path {
  1395. return al.stubsJar
  1396. }
  1397. func metalavaStubCmd(ctx android.ModuleContext, rule *android.RuleBuilder,
  1398. srcs android.Paths, homeDir android.WritablePath) *android.RuleBuilderCommand {
  1399. rule.Command().Text("rm -rf").Flag(homeDir.String())
  1400. rule.Command().Text("mkdir -p").Flag(homeDir.String())
  1401. cmd := rule.Command()
  1402. cmd.FlagWithArg("ANDROID_PREFS_ROOT=", homeDir.String())
  1403. if metalavaUseRbe(ctx) {
  1404. rule.Remoteable(android.RemoteRuleSupports{RBE: true})
  1405. execStrategy := ctx.Config().GetenvWithDefault("RBE_METALAVA_EXEC_STRATEGY", remoteexec.LocalExecStrategy)
  1406. labels := map[string]string{"type": "tool", "name": "metalava"}
  1407. pool := ctx.Config().GetenvWithDefault("RBE_METALAVA_POOL", "java16")
  1408. rule.Rewrapper(&remoteexec.REParams{
  1409. Labels: labels,
  1410. ExecStrategy: execStrategy,
  1411. ToolchainInputs: []string{config.JavaCmd(ctx).String()},
  1412. Platform: map[string]string{remoteexec.PoolKey: pool},
  1413. })
  1414. }
  1415. cmd.BuiltTool("metalava").ImplicitTool(ctx.Config().HostJavaToolPath(ctx, "metalava.jar")).
  1416. Flag(config.JavacVmFlags).
  1417. Flag("-J--add-opens=java.base/java.util=ALL-UNNAMED").
  1418. FlagWithArg("-encoding ", "UTF-8").
  1419. FlagWithInputList("--source-files ", srcs, " ")
  1420. cmd.Flag("--no-banner").
  1421. Flag("--color").
  1422. Flag("--quiet").
  1423. Flag("--format=v2").
  1424. Flag("--include-annotations").
  1425. // The flag makes nullability issues as warnings rather than errors by replacing
  1426. // @Nullable/@NonNull in the listed packages APIs with @RecentlyNullable/@RecentlyNonNull,
  1427. // and these packages are meant to have everything annotated
  1428. // @RecentlyNullable/@RecentlyNonNull.
  1429. FlagWithArg("--force-convert-to-warning-nullability-annotations ", "+*:-android.*:+android.icu.*:-dalvik.*").
  1430. FlagWithArg("--repeat-errors-max ", "10").
  1431. FlagWithArg("--hide ", "UnresolvedImport").
  1432. FlagWithArg("--hide ", "InvalidNullabilityOverride").
  1433. FlagWithArg("--hide ", "ChangedDefault")
  1434. // Force metalava to ignore classes on the classpath when an API file contains missing classes.
  1435. // See b/285140653 for more information.
  1436. cmd.FlagWithArg("--api-class-resolution ", "api")
  1437. // Force metalava to sort overloaded methods by their order in the source code.
  1438. // See b/285312164 for more information.
  1439. cmd.FlagWithArg("--api-overloaded-method-order ", "source")
  1440. return cmd
  1441. }
  1442. func (al *ApiLibrary) HeaderJars() android.Paths {
  1443. return android.Paths{al.stubsJar}
  1444. }
  1445. func (al *ApiLibrary) OutputDirAndDeps() (android.Path, android.Paths) {
  1446. return nil, nil
  1447. }
  1448. func (al *ApiLibrary) stubsFlags(ctx android.ModuleContext, cmd *android.RuleBuilderCommand, stubsDir android.OptionalPath) {
  1449. if stubsDir.Valid() {
  1450. cmd.FlagWithArg("--stubs ", stubsDir.String())
  1451. }
  1452. }
  1453. // This method extracts the stub java files from the srcjar file provided from dep_api_srcs module
  1454. // and replaces the java stubs generated by invoking metalava in this module.
  1455. // This method is used because metalava can generate compilable from-text stubs only when
  1456. // the codebase encompasses all classes listed in the input API text file, but a class can extend
  1457. // a class that is not within the same API domain.
  1458. func (al *ApiLibrary) extractApiSrcs(ctx android.ModuleContext, rule *android.RuleBuilder, stubsDir android.OptionalPath, depApiSrcsSrcJar android.Path) {
  1459. generatedStubsList := android.PathForModuleOut(ctx, "metalava", "sources.txt")
  1460. unzippedSrcJarDir := android.PathForModuleOut(ctx, "metalava", "unzipDir")
  1461. rule.Command().
  1462. BuiltTool("list_files").
  1463. Text(stubsDir.String()).
  1464. FlagWithOutput("--out ", generatedStubsList).
  1465. FlagWithArg("--extensions ", ".java").
  1466. FlagWithArg("--root ", unzippedSrcJarDir.String())
  1467. rule.Command().
  1468. Text("unzip").
  1469. Flag("-q").
  1470. Input(depApiSrcsSrcJar).
  1471. FlagWithArg("-d ", unzippedSrcJarDir.String())
  1472. rule.Command().
  1473. BuiltTool("soong_zip").
  1474. Flag("-srcjar").
  1475. Flag("-write_if_changed").
  1476. FlagWithArg("-C ", unzippedSrcJarDir.String()).
  1477. FlagWithInput("-l ", generatedStubsList).
  1478. FlagWithOutput("-o ", al.stubsSrcJar)
  1479. }
  1480. func (al *ApiLibrary) DepsMutator(ctx android.BottomUpMutatorContext) {
  1481. apiContributions := al.properties.Api_contributions
  1482. for _, apiContributionName := range apiContributions {
  1483. ctx.AddDependency(ctx.Module(), javaApiContributionTag, apiContributionName)
  1484. }
  1485. ctx.AddVariationDependencies(nil, libTag, al.properties.Libs...)
  1486. ctx.AddVariationDependencies(nil, staticLibTag, al.properties.Static_libs...)
  1487. if al.properties.Dep_api_srcs != nil {
  1488. ctx.AddVariationDependencies(nil, depApiSrcsTag, String(al.properties.Dep_api_srcs))
  1489. }
  1490. }
  1491. func (al *ApiLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  1492. rule := android.NewRuleBuilder(pctx, ctx)
  1493. rule.Sbox(android.PathForModuleOut(ctx, "metalava"),
  1494. android.PathForModuleOut(ctx, "metalava.sbox.textproto")).
  1495. SandboxInputs()
  1496. var stubsDir android.OptionalPath
  1497. stubsDir = android.OptionalPathForPath(android.PathForModuleOut(ctx, "metalava", "stubsDir"))
  1498. rule.Command().Text("rm -rf").Text(stubsDir.String())
  1499. rule.Command().Text("mkdir -p").Text(stubsDir.String())
  1500. homeDir := android.PathForModuleOut(ctx, "metalava", "home")
  1501. var srcFiles android.Paths
  1502. var classPaths android.Paths
  1503. var staticLibs android.Paths
  1504. var depApiSrcsStubsSrcJar android.Path
  1505. ctx.VisitDirectDeps(func(dep android.Module) {
  1506. tag := ctx.OtherModuleDependencyTag(dep)
  1507. switch tag {
  1508. case javaApiContributionTag:
  1509. provider := ctx.OtherModuleProvider(dep, JavaApiImportProvider).(JavaApiImportInfo)
  1510. providerApiFile := provider.ApiFile
  1511. if providerApiFile == nil && !ctx.Config().AllowMissingDependencies() {
  1512. ctx.ModuleErrorf("Error: %s has an empty api file.", dep.Name())
  1513. }
  1514. srcFiles = append(srcFiles, android.PathForSource(ctx, providerApiFile.String()))
  1515. case libTag:
  1516. provider := ctx.OtherModuleProvider(dep, JavaInfoProvider).(JavaInfo)
  1517. classPaths = append(classPaths, provider.HeaderJars...)
  1518. case staticLibTag:
  1519. provider := ctx.OtherModuleProvider(dep, JavaInfoProvider).(JavaInfo)
  1520. staticLibs = append(staticLibs, provider.HeaderJars...)
  1521. case depApiSrcsTag:
  1522. provider := ctx.OtherModuleProvider(dep, JavaApiLibraryDepsProvider).(JavaApiLibraryDepsInfo)
  1523. classPaths = append(classPaths, provider.HeaderJars...)
  1524. depApiSrcsStubsSrcJar = provider.StubsSrcJar
  1525. }
  1526. })
  1527. // Add the api_files inputs
  1528. for _, api := range al.properties.Api_files {
  1529. srcFiles = append(srcFiles, android.PathForModuleSrc(ctx, api))
  1530. }
  1531. if srcFiles == nil && !ctx.Config().AllowMissingDependencies() {
  1532. ctx.ModuleErrorf("Error: %s has an empty api file.", ctx.ModuleName())
  1533. }
  1534. cmd := metalavaStubCmd(ctx, rule, srcFiles, homeDir)
  1535. al.stubsFlags(ctx, cmd, stubsDir)
  1536. al.stubsSrcJar = android.PathForModuleOut(ctx, "metalava", ctx.ModuleName()+"-"+"stubs.srcjar")
  1537. if depApiSrcsStubsSrcJar != nil {
  1538. al.extractApiSrcs(ctx, rule, stubsDir, depApiSrcsStubsSrcJar)
  1539. } else {
  1540. rule.Command().
  1541. BuiltTool("soong_zip").
  1542. Flag("-write_if_changed").
  1543. Flag("-jar").
  1544. FlagWithOutput("-o ", al.stubsSrcJar).
  1545. FlagWithArg("-C ", stubsDir.String()).
  1546. FlagWithArg("-D ", stubsDir.String())
  1547. }
  1548. rule.Build("metalava", "metalava merged")
  1549. al.stubsJarWithoutStaticLibs = android.PathForModuleOut(ctx, ctx.ModuleName(), "stubs.jar")
  1550. al.stubsJar = android.PathForModuleOut(ctx, ctx.ModuleName(), fmt.Sprintf("%s.jar", ctx.ModuleName()))
  1551. var flags javaBuilderFlags
  1552. flags.javaVersion = getStubsJavaVersion()
  1553. flags.javacFlags = strings.Join(al.properties.Javacflags, " ")
  1554. flags.classpath = classpath(classPaths)
  1555. TransformJavaToClasses(ctx, al.stubsJarWithoutStaticLibs, 0, android.Paths{},
  1556. android.Paths{al.stubsSrcJar}, flags, android.Paths{})
  1557. builder := android.NewRuleBuilder(pctx, ctx)
  1558. builder.Command().
  1559. BuiltTool("merge_zips").
  1560. Output(al.stubsJar).
  1561. Inputs(android.Paths{al.stubsJarWithoutStaticLibs}).
  1562. Inputs(staticLibs)
  1563. builder.Build("merge_zips", "merge jar files")
  1564. // compile stubs to .dex for hiddenapi processing
  1565. dexParams := &compileDexParams{
  1566. flags: javaBuilderFlags{},
  1567. sdkVersion: al.SdkVersion(ctx),
  1568. minSdkVersion: al.MinSdkVersion(ctx),
  1569. classesJar: al.stubsJar,
  1570. jarName: ctx.ModuleName() + ".jar",
  1571. }
  1572. dexOutputFile := al.dexer.compileDex(ctx, dexParams)
  1573. uncompressed := true
  1574. al.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), al.stubsJar, &uncompressed)
  1575. dexOutputFile = al.hiddenAPIEncodeDex(ctx, dexOutputFile)
  1576. al.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
  1577. ctx.Phony(ctx.ModuleName(), al.stubsJar)
  1578. ctx.SetProvider(JavaInfoProvider, JavaInfo{
  1579. HeaderJars: android.PathsIfNonNil(al.stubsJar),
  1580. ImplementationAndResourcesJars: android.PathsIfNonNil(al.stubsJar),
  1581. ImplementationJars: android.PathsIfNonNil(al.stubsJar),
  1582. AidlIncludeDirs: android.Paths{},
  1583. })
  1584. ctx.SetProvider(JavaApiLibraryDepsProvider, JavaApiLibraryDepsInfo{
  1585. JavaInfo: JavaInfo{
  1586. HeaderJars: android.PathsIfNonNil(al.stubsJar),
  1587. },
  1588. StubsSrcJar: al.stubsSrcJar,
  1589. })
  1590. }
  1591. func (al *ApiLibrary) DexJarBuildPath() OptionalDexJarPath {
  1592. return al.dexJarFile
  1593. }
  1594. func (al *ApiLibrary) DexJarInstallPath() android.Path {
  1595. return al.dexJarFile.Path()
  1596. }
  1597. func (al *ApiLibrary) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
  1598. return nil
  1599. }
  1600. // java_api_library constitutes the sdk, and does not build against one
  1601. func (al *ApiLibrary) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
  1602. return android.SdkSpecNone
  1603. }
  1604. // java_api_library is always at "current". Return FutureApiLevel
  1605. func (al *ApiLibrary) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
  1606. return android.FutureApiLevel
  1607. }
  1608. // implement the following interfaces for hiddenapi processing
  1609. var _ hiddenAPIModule = (*ApiLibrary)(nil)
  1610. var _ UsesLibraryDependency = (*ApiLibrary)(nil)
  1611. //
  1612. // Java prebuilts
  1613. //
  1614. type ImportProperties struct {
  1615. Jars []string `android:"path,arch_variant"`
  1616. // The version of the SDK that the source prebuilt file was built against. Defaults to the
  1617. // current version if not specified.
  1618. Sdk_version *string
  1619. // The minimum version of the SDK that this module supports. Defaults to sdk_version if not
  1620. // specified.
  1621. Min_sdk_version *string
  1622. // The max sdk version placeholder used to replace maxSdkVersion attributes on permission
  1623. // and uses-permission tags in manifest_fixer.
  1624. Replace_max_sdk_version_placeholder *string
  1625. Installable *bool
  1626. // If not empty, classes are restricted to the specified packages and their sub-packages.
  1627. Permitted_packages []string
  1628. // List of shared java libs that this module has dependencies to
  1629. Libs []string
  1630. // List of files to remove from the jar file(s)
  1631. Exclude_files []string
  1632. // List of directories to remove from the jar file(s)
  1633. Exclude_dirs []string
  1634. // if set to true, run Jetifier against .jar file. Defaults to false.
  1635. Jetifier *bool
  1636. // set the name of the output
  1637. Stem *string
  1638. Aidl struct {
  1639. // directories that should be added as include directories for any aidl sources of modules
  1640. // that depend on this module, as well as to aidl for this module.
  1641. Export_include_dirs []string
  1642. }
  1643. }
  1644. type Import struct {
  1645. android.ModuleBase
  1646. android.DefaultableModuleBase
  1647. android.ApexModuleBase
  1648. android.BazelModuleBase
  1649. prebuilt android.Prebuilt
  1650. // Functionality common to Module and Import.
  1651. embeddableInModuleAndImport
  1652. hiddenAPI
  1653. dexer
  1654. dexpreopter
  1655. properties ImportProperties
  1656. // output file containing classes.dex and resources
  1657. dexJarFile OptionalDexJarPath
  1658. dexJarInstallFile android.Path
  1659. combinedClasspathFile android.Path
  1660. classLoaderContexts dexpreopt.ClassLoaderContextMap
  1661. exportAidlIncludeDirs android.Paths
  1662. hideApexVariantFromMake bool
  1663. sdkVersion android.SdkSpec
  1664. minSdkVersion android.ApiLevel
  1665. }
  1666. var _ PermittedPackagesForUpdatableBootJars = (*Import)(nil)
  1667. func (j *Import) PermittedPackagesForUpdatableBootJars() []string {
  1668. return j.properties.Permitted_packages
  1669. }
  1670. func (j *Import) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
  1671. return android.SdkSpecFrom(ctx, String(j.properties.Sdk_version))
  1672. }
  1673. func (j *Import) SystemModules() string {
  1674. return "none"
  1675. }
  1676. func (j *Import) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
  1677. if j.properties.Min_sdk_version != nil {
  1678. return android.ApiLevelFrom(ctx, *j.properties.Min_sdk_version)
  1679. }
  1680. return j.SdkVersion(ctx).ApiLevel
  1681. }
  1682. func (j *Import) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.ApiLevel {
  1683. if j.properties.Replace_max_sdk_version_placeholder != nil {
  1684. return android.ApiLevelFrom(ctx, *j.properties.Replace_max_sdk_version_placeholder)
  1685. }
  1686. // Default is PrivateApiLevel
  1687. return android.SdkSpecPrivate.ApiLevel
  1688. }
  1689. func (j *Import) TargetSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
  1690. return j.SdkVersion(ctx).ApiLevel
  1691. }
  1692. func (j *Import) Prebuilt() *android.Prebuilt {
  1693. return &j.prebuilt
  1694. }
  1695. func (j *Import) PrebuiltSrcs() []string {
  1696. return j.properties.Jars
  1697. }
  1698. func (j *Import) Name() string {
  1699. return j.prebuilt.Name(j.ModuleBase.Name())
  1700. }
  1701. func (j *Import) Stem() string {
  1702. return proptools.StringDefault(j.properties.Stem, j.ModuleBase.Name())
  1703. }
  1704. func (a *Import) JacocoReportClassesFile() android.Path {
  1705. return nil
  1706. }
  1707. func (j *Import) LintDepSets() LintDepSets {
  1708. return LintDepSets{}
  1709. }
  1710. func (j *Import) getStrictUpdatabilityLinting() bool {
  1711. return false
  1712. }
  1713. func (j *Import) setStrictUpdatabilityLinting(bool) {
  1714. }
  1715. func (j *Import) DepsMutator(ctx android.BottomUpMutatorContext) {
  1716. ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
  1717. if ctx.Device() && Bool(j.dexProperties.Compile_dex) {
  1718. sdkDeps(ctx, android.SdkContext(j), j.dexer)
  1719. }
  1720. }
  1721. func (j *Import) commonBuildActions(ctx android.ModuleContext) {
  1722. //TODO(b/231322772) these should come from Bazel once available
  1723. j.sdkVersion = j.SdkVersion(ctx)
  1724. j.minSdkVersion = j.MinSdkVersion(ctx)
  1725. if !ctx.Provider(android.ApexInfoProvider).(android.ApexInfo).IsForPlatform() {
  1726. j.hideApexVariantFromMake = true
  1727. }
  1728. if ctx.Windows() {
  1729. j.HideFromMake()
  1730. }
  1731. }
  1732. func (j *Import) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  1733. j.commonBuildActions(ctx)
  1734. jars := android.PathsForModuleSrc(ctx, j.properties.Jars)
  1735. jarName := j.Stem() + ".jar"
  1736. outputFile := android.PathForModuleOut(ctx, "combined", jarName)
  1737. TransformJarsToJar(ctx, outputFile, "for prebuilts", jars, android.OptionalPath{},
  1738. false, j.properties.Exclude_files, j.properties.Exclude_dirs)
  1739. if Bool(j.properties.Jetifier) {
  1740. inputFile := outputFile
  1741. outputFile = android.PathForModuleOut(ctx, "jetifier", jarName)
  1742. TransformJetifier(ctx, outputFile, inputFile)
  1743. }
  1744. j.combinedClasspathFile = outputFile
  1745. j.classLoaderContexts = make(dexpreopt.ClassLoaderContextMap)
  1746. var flags javaBuilderFlags
  1747. j.collectTransitiveHeaderJars(ctx)
  1748. ctx.VisitDirectDeps(func(module android.Module) {
  1749. tag := ctx.OtherModuleDependencyTag(module)
  1750. if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
  1751. dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
  1752. switch tag {
  1753. case libTag, sdkLibTag:
  1754. flags.classpath = append(flags.classpath, dep.HeaderJars...)
  1755. flags.dexClasspath = append(flags.dexClasspath, dep.HeaderJars...)
  1756. case staticLibTag:
  1757. flags.classpath = append(flags.classpath, dep.HeaderJars...)
  1758. case bootClasspathTag:
  1759. flags.bootClasspath = append(flags.bootClasspath, dep.HeaderJars...)
  1760. }
  1761. } else if dep, ok := module.(SdkLibraryDependency); ok {
  1762. switch tag {
  1763. case libTag, sdkLibTag:
  1764. flags.classpath = append(flags.classpath, dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))...)
  1765. }
  1766. }
  1767. addCLCFromDep(ctx, module, j.classLoaderContexts)
  1768. })
  1769. j.maybeInstall(ctx, jarName, outputFile)
  1770. j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.properties.Aidl.Export_include_dirs)
  1771. if ctx.Device() {
  1772. // If this is a variant created for a prebuilt_apex then use the dex implementation jar
  1773. // obtained from the associated deapexer module.
  1774. ai := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
  1775. if ai.ForPrebuiltApex {
  1776. // Get the path of the dex implementation jar from the `deapexer` module.
  1777. di := android.FindDeapexerProviderForModule(ctx)
  1778. if di == nil {
  1779. return // An error has been reported by FindDeapexerProviderForModule.
  1780. }
  1781. dexJarFileApexRootRelative := apexRootRelativePathToJavaLib(j.BaseModuleName())
  1782. if dexOutputPath := di.PrebuiltExportPath(dexJarFileApexRootRelative); dexOutputPath != nil {
  1783. dexJarFile := makeDexJarPathFromPath(dexOutputPath)
  1784. j.dexJarFile = dexJarFile
  1785. installPath := android.PathForModuleInPartitionInstall(ctx, "apex", ai.ApexVariationName, apexRootRelativePathToJavaLib(j.BaseModuleName()))
  1786. j.dexJarInstallFile = installPath
  1787. j.dexpreopter.installPath = j.dexpreopter.getInstallPath(ctx, installPath)
  1788. setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
  1789. j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
  1790. if profilePath := di.PrebuiltExportPath(dexJarFileApexRootRelative + ".prof"); profilePath != nil {
  1791. j.dexpreopter.inputProfilePathOnHost = profilePath
  1792. }
  1793. j.dexpreopt(ctx, dexOutputPath)
  1794. // Initialize the hiddenapi structure.
  1795. j.initHiddenAPI(ctx, dexJarFile, outputFile, j.dexProperties.Uncompress_dex)
  1796. } else {
  1797. // This should never happen as a variant for a prebuilt_apex is only created if the
  1798. // prebuilt_apex has been configured to export the java library dex file.
  1799. ctx.ModuleErrorf("internal error: no dex implementation jar available from prebuilt APEX %s", di.ApexModuleName())
  1800. }
  1801. } else if Bool(j.dexProperties.Compile_dex) {
  1802. sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
  1803. if sdkDep.invalidVersion {
  1804. ctx.AddMissingDependencies(sdkDep.bootclasspath)
  1805. ctx.AddMissingDependencies(sdkDep.java9Classpath)
  1806. } else if sdkDep.useFiles {
  1807. // sdkDep.jar is actually equivalent to turbine header.jar.
  1808. flags.classpath = append(flags.classpath, sdkDep.jars...)
  1809. }
  1810. // Dex compilation
  1811. j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
  1812. ctx, android.PathForModuleInstall(ctx, "framework", jarName))
  1813. setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
  1814. j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
  1815. var dexOutputFile android.OutputPath
  1816. dexParams := &compileDexParams{
  1817. flags: flags,
  1818. sdkVersion: j.SdkVersion(ctx),
  1819. minSdkVersion: j.MinSdkVersion(ctx),
  1820. classesJar: outputFile,
  1821. jarName: jarName,
  1822. }
  1823. dexOutputFile = j.dexer.compileDex(ctx, dexParams)
  1824. if ctx.Failed() {
  1825. return
  1826. }
  1827. // Initialize the hiddenapi structure.
  1828. j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), outputFile, j.dexProperties.Uncompress_dex)
  1829. // Encode hidden API flags in dex file.
  1830. dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
  1831. j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
  1832. j.dexJarInstallFile = android.PathForModuleInstall(ctx, "framework", jarName)
  1833. }
  1834. }
  1835. ctx.SetProvider(JavaInfoProvider, JavaInfo{
  1836. HeaderJars: android.PathsIfNonNil(j.combinedClasspathFile),
  1837. TransitiveLibsHeaderJars: j.transitiveLibsHeaderJars,
  1838. TransitiveStaticLibsHeaderJars: j.transitiveStaticLibsHeaderJars,
  1839. ImplementationAndResourcesJars: android.PathsIfNonNil(j.combinedClasspathFile),
  1840. ImplementationJars: android.PathsIfNonNil(j.combinedClasspathFile),
  1841. AidlIncludeDirs: j.exportAidlIncludeDirs,
  1842. })
  1843. }
  1844. func (j *Import) maybeInstall(ctx android.ModuleContext, jarName string, outputFile android.Path) {
  1845. if !Bool(j.properties.Installable) {
  1846. return
  1847. }
  1848. var installDir android.InstallPath
  1849. if ctx.InstallInTestcases() {
  1850. var archDir string
  1851. if !ctx.Host() {
  1852. archDir = ctx.DeviceConfig().DeviceArch()
  1853. }
  1854. installDir = android.PathForModuleInstall(ctx, ctx.ModuleName(), archDir)
  1855. } else {
  1856. installDir = android.PathForModuleInstall(ctx, "framework")
  1857. }
  1858. ctx.InstallFile(installDir, jarName, outputFile)
  1859. }
  1860. func (j *Import) OutputFiles(tag string) (android.Paths, error) {
  1861. switch tag {
  1862. case "", ".jar":
  1863. return android.Paths{j.combinedClasspathFile}, nil
  1864. default:
  1865. return nil, fmt.Errorf("unsupported module reference tag %q", tag)
  1866. }
  1867. }
  1868. var _ android.OutputFileProducer = (*Import)(nil)
  1869. func (j *Import) HeaderJars() android.Paths {
  1870. if j.combinedClasspathFile == nil {
  1871. return nil
  1872. }
  1873. return android.Paths{j.combinedClasspathFile}
  1874. }
  1875. func (j *Import) ImplementationAndResourcesJars() android.Paths {
  1876. if j.combinedClasspathFile == nil {
  1877. return nil
  1878. }
  1879. return android.Paths{j.combinedClasspathFile}
  1880. }
  1881. func (j *Import) DexJarBuildPath() OptionalDexJarPath {
  1882. return j.dexJarFile
  1883. }
  1884. func (j *Import) DexJarInstallPath() android.Path {
  1885. return j.dexJarInstallFile
  1886. }
  1887. func (j *Import) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
  1888. return j.classLoaderContexts
  1889. }
  1890. var _ android.ApexModule = (*Import)(nil)
  1891. // Implements android.ApexModule
  1892. func (j *Import) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
  1893. return j.depIsInSameApex(ctx, dep)
  1894. }
  1895. // Implements android.ApexModule
  1896. func (j *Import) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
  1897. sdkVersion android.ApiLevel) error {
  1898. sdkVersionSpec := j.SdkVersion(ctx)
  1899. minSdkVersion := j.MinSdkVersion(ctx)
  1900. if !minSdkVersion.Specified() {
  1901. return fmt.Errorf("min_sdk_version is not specified")
  1902. }
  1903. // If the module is compiling against core (via sdk_version), skip comparison check.
  1904. if sdkVersionSpec.Kind == android.SdkCore {
  1905. return nil
  1906. }
  1907. if minSdkVersion.GreaterThan(sdkVersion) {
  1908. return fmt.Errorf("newer SDK(%v)", minSdkVersion)
  1909. }
  1910. return nil
  1911. }
  1912. // requiredFilesFromPrebuiltApexForImport returns information about the files that a java_import or
  1913. // java_sdk_library_import with the specified base module name requires to be exported from a
  1914. // prebuilt_apex/apex_set.
  1915. func requiredFilesFromPrebuiltApexForImport(name string, d *dexpreopter) []string {
  1916. dexJarFileApexRootRelative := apexRootRelativePathToJavaLib(name)
  1917. // Add the dex implementation jar to the set of exported files.
  1918. files := []string{
  1919. dexJarFileApexRootRelative,
  1920. }
  1921. if BoolDefault(d.importDexpreoptProperties.Dex_preopt.Profile_guided, false) {
  1922. files = append(files, dexJarFileApexRootRelative+".prof")
  1923. }
  1924. return files
  1925. }
  1926. // apexRootRelativePathToJavaLib returns the path, relative to the root of the apex's contents, for
  1927. // the java library with the specified name.
  1928. func apexRootRelativePathToJavaLib(name string) string {
  1929. return filepath.Join("javalib", name+".jar")
  1930. }
  1931. var _ android.RequiredFilesFromPrebuiltApex = (*Import)(nil)
  1932. func (j *Import) RequiredFilesFromPrebuiltApex(_ android.BaseModuleContext) []string {
  1933. name := j.BaseModuleName()
  1934. return requiredFilesFromPrebuiltApexForImport(name, &j.dexpreopter)
  1935. }
  1936. // Add compile time check for interface implementation
  1937. var _ android.IDEInfo = (*Import)(nil)
  1938. var _ android.IDECustomizedModuleName = (*Import)(nil)
  1939. // Collect information for opening IDE project files in java/jdeps.go.
  1940. func (j *Import) IDEInfo(dpInfo *android.IdeInfo) {
  1941. dpInfo.Jars = append(dpInfo.Jars, j.PrebuiltSrcs()...)
  1942. }
  1943. func (j *Import) IDECustomizedModuleName() string {
  1944. // TODO(b/113562217): Extract the base module name from the Import name, often the Import name
  1945. // has a prefix "prebuilt_". Remove the prefix explicitly if needed until we find a better
  1946. // solution to get the Import name.
  1947. return android.RemoveOptionalPrebuiltPrefix(j.Name())
  1948. }
  1949. var _ android.PrebuiltInterface = (*Import)(nil)
  1950. func (j *Import) IsInstallable() bool {
  1951. return Bool(j.properties.Installable)
  1952. }
  1953. var _ DexpreopterInterface = (*Import)(nil)
  1954. // java_import imports one or more `.jar` files into the build graph as if they were built by a java_library module.
  1955. //
  1956. // By default, a java_import has a single variant that expects a `.jar` file containing `.class` files that were
  1957. // compiled against an Android classpath.
  1958. //
  1959. // Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
  1960. // for host modules.
  1961. func ImportFactory() android.Module {
  1962. module := &Import{}
  1963. module.AddProperties(
  1964. &module.properties,
  1965. &module.dexer.dexProperties,
  1966. &module.importDexpreoptProperties,
  1967. )
  1968. module.initModuleAndImport(module)
  1969. module.dexProperties.Optimize.EnabledByDefault = false
  1970. android.InitPrebuiltModule(module, &module.properties.Jars)
  1971. android.InitApexModule(module)
  1972. android.InitBazelModule(module)
  1973. InitJavaModule(module, android.HostAndDeviceSupported)
  1974. return module
  1975. }
  1976. // java_import imports one or more `.jar` files into the build graph as if they were built by a java_library_host
  1977. // module.
  1978. //
  1979. // A java_import_host has a single variant that expects a `.jar` file containing `.class` files that were
  1980. // compiled against a host bootclasspath.
  1981. func ImportFactoryHost() android.Module {
  1982. module := &Import{}
  1983. module.AddProperties(&module.properties)
  1984. android.InitPrebuiltModule(module, &module.properties.Jars)
  1985. android.InitApexModule(module)
  1986. android.InitBazelModule(module)
  1987. InitJavaModule(module, android.HostSupported)
  1988. return module
  1989. }
  1990. // dex_import module
  1991. type DexImportProperties struct {
  1992. Jars []string `android:"path"`
  1993. // set the name of the output
  1994. Stem *string
  1995. }
  1996. type DexImport struct {
  1997. android.ModuleBase
  1998. android.DefaultableModuleBase
  1999. android.ApexModuleBase
  2000. prebuilt android.Prebuilt
  2001. properties DexImportProperties
  2002. dexJarFile OptionalDexJarPath
  2003. dexpreopter
  2004. hideApexVariantFromMake bool
  2005. }
  2006. func (j *DexImport) Prebuilt() *android.Prebuilt {
  2007. return &j.prebuilt
  2008. }
  2009. func (j *DexImport) PrebuiltSrcs() []string {
  2010. return j.properties.Jars
  2011. }
  2012. func (j *DexImport) Name() string {
  2013. return j.prebuilt.Name(j.ModuleBase.Name())
  2014. }
  2015. func (j *DexImport) Stem() string {
  2016. return proptools.StringDefault(j.properties.Stem, j.ModuleBase.Name())
  2017. }
  2018. func (a *DexImport) JacocoReportClassesFile() android.Path {
  2019. return nil
  2020. }
  2021. func (a *DexImport) LintDepSets() LintDepSets {
  2022. return LintDepSets{}
  2023. }
  2024. func (j *DexImport) IsInstallable() bool {
  2025. return true
  2026. }
  2027. func (j *DexImport) getStrictUpdatabilityLinting() bool {
  2028. return false
  2029. }
  2030. func (j *DexImport) setStrictUpdatabilityLinting(bool) {
  2031. }
  2032. func (j *DexImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  2033. if len(j.properties.Jars) != 1 {
  2034. ctx.PropertyErrorf("jars", "exactly one jar must be provided")
  2035. }
  2036. apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
  2037. if !apexInfo.IsForPlatform() {
  2038. j.hideApexVariantFromMake = true
  2039. }
  2040. j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
  2041. ctx, android.PathForModuleInstall(ctx, "framework", j.Stem()+".jar"))
  2042. j.dexpreopter.uncompressedDex = shouldUncompressDex(ctx, &j.dexpreopter)
  2043. inputJar := ctx.ExpandSource(j.properties.Jars[0], "jars")
  2044. dexOutputFile := android.PathForModuleOut(ctx, ctx.ModuleName()+".jar")
  2045. if j.dexpreopter.uncompressedDex {
  2046. rule := android.NewRuleBuilder(pctx, ctx)
  2047. temporary := android.PathForModuleOut(ctx, ctx.ModuleName()+".jar.unaligned")
  2048. rule.Temporary(temporary)
  2049. // use zip2zip to uncompress classes*.dex files
  2050. rule.Command().
  2051. BuiltTool("zip2zip").
  2052. FlagWithInput("-i ", inputJar).
  2053. FlagWithOutput("-o ", temporary).
  2054. FlagWithArg("-0 ", "'classes*.dex'")
  2055. // use zipalign to align uncompressed classes*.dex files
  2056. rule.Command().
  2057. BuiltTool("zipalign").
  2058. Flag("-f").
  2059. Text("4").
  2060. Input(temporary).
  2061. Output(dexOutputFile)
  2062. rule.DeleteTemporaryFiles()
  2063. rule.Build("uncompress_dex", "uncompress dex")
  2064. } else {
  2065. ctx.Build(pctx, android.BuildParams{
  2066. Rule: android.Cp,
  2067. Input: inputJar,
  2068. Output: dexOutputFile,
  2069. })
  2070. }
  2071. j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
  2072. j.dexpreopt(ctx, dexOutputFile)
  2073. if apexInfo.IsForPlatform() {
  2074. ctx.InstallFile(android.PathForModuleInstall(ctx, "framework"),
  2075. j.Stem()+".jar", dexOutputFile)
  2076. }
  2077. }
  2078. func (j *DexImport) DexJarBuildPath() OptionalDexJarPath {
  2079. return j.dexJarFile
  2080. }
  2081. var _ android.ApexModule = (*DexImport)(nil)
  2082. // Implements android.ApexModule
  2083. func (j *DexImport) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
  2084. sdkVersion android.ApiLevel) error {
  2085. // we don't check prebuilt modules for sdk_version
  2086. return nil
  2087. }
  2088. // dex_import imports a `.jar` file containing classes.dex files.
  2089. //
  2090. // A dex_import module cannot be used as a dependency of a java_* or android_* module, it can only be installed
  2091. // to the device.
  2092. func DexImportFactory() android.Module {
  2093. module := &DexImport{}
  2094. module.AddProperties(&module.properties)
  2095. android.InitPrebuiltModule(module, &module.properties.Jars)
  2096. android.InitApexModule(module)
  2097. InitJavaModule(module, android.DeviceSupported)
  2098. return module
  2099. }
  2100. // Defaults
  2101. type Defaults struct {
  2102. android.ModuleBase
  2103. android.DefaultsModuleBase
  2104. android.ApexModuleBase
  2105. }
  2106. // java_defaults provides a set of properties that can be inherited by other java or android modules.
  2107. //
  2108. // A module can use the properties from a java_defaults module using `defaults: ["defaults_module_name"]`. Each
  2109. // property in the defaults module that exists in the depending module will be prepended to the depending module's
  2110. // value for that property.
  2111. //
  2112. // Example:
  2113. //
  2114. // java_defaults {
  2115. // name: "example_defaults",
  2116. // srcs: ["common/**/*.java"],
  2117. // javacflags: ["-Xlint:all"],
  2118. // aaptflags: ["--auto-add-overlay"],
  2119. // }
  2120. //
  2121. // java_library {
  2122. // name: "example",
  2123. // defaults: ["example_defaults"],
  2124. // srcs: ["example/**/*.java"],
  2125. // }
  2126. //
  2127. // is functionally identical to:
  2128. //
  2129. // java_library {
  2130. // name: "example",
  2131. // srcs: [
  2132. // "common/**/*.java",
  2133. // "example/**/*.java",
  2134. // ],
  2135. // javacflags: ["-Xlint:all"],
  2136. // }
  2137. func DefaultsFactory() android.Module {
  2138. module := &Defaults{}
  2139. module.AddProperties(
  2140. &CommonProperties{},
  2141. &DeviceProperties{},
  2142. &OverridableDeviceProperties{},
  2143. &DexProperties{},
  2144. &DexpreoptProperties{},
  2145. &android.ProtoProperties{},
  2146. &aaptProperties{},
  2147. &androidLibraryProperties{},
  2148. &appProperties{},
  2149. &appTestProperties{},
  2150. &overridableAppProperties{},
  2151. &hostTestProperties{},
  2152. &testProperties{},
  2153. &ImportProperties{},
  2154. &AARImportProperties{},
  2155. &sdkLibraryProperties{},
  2156. &commonToSdkLibraryAndImportProperties{},
  2157. &DexImportProperties{},
  2158. &android.ApexProperties{},
  2159. &RuntimeResourceOverlayProperties{},
  2160. &LintProperties{},
  2161. &appTestHelperAppProperties{},
  2162. &JavaApiLibraryProperties{},
  2163. )
  2164. android.InitDefaultsModule(module)
  2165. return module
  2166. }
  2167. func kytheExtractJavaFactory() android.Singleton {
  2168. return &kytheExtractJavaSingleton{}
  2169. }
  2170. type kytheExtractJavaSingleton struct {
  2171. }
  2172. func (ks *kytheExtractJavaSingleton) GenerateBuildActions(ctx android.SingletonContext) {
  2173. var xrefTargets android.Paths
  2174. ctx.VisitAllModules(func(module android.Module) {
  2175. if javaModule, ok := module.(xref); ok {
  2176. xrefTargets = append(xrefTargets, javaModule.XrefJavaFiles()...)
  2177. }
  2178. })
  2179. // TODO(asmundak): perhaps emit a rule to output a warning if there were no xrefTargets
  2180. if len(xrefTargets) > 0 {
  2181. ctx.Phony("xref_java", xrefTargets...)
  2182. }
  2183. }
  2184. var Bool = proptools.Bool
  2185. var BoolDefault = proptools.BoolDefault
  2186. var String = proptools.String
  2187. var inList = android.InList
  2188. // Add class loader context (CLC) of a given dependency to the current CLC.
  2189. func addCLCFromDep(ctx android.ModuleContext, depModule android.Module,
  2190. clcMap dexpreopt.ClassLoaderContextMap) {
  2191. dep, ok := depModule.(UsesLibraryDependency)
  2192. if !ok {
  2193. return
  2194. }
  2195. depName := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(depModule))
  2196. var sdkLib *string
  2197. if lib, ok := depModule.(SdkLibraryDependency); ok && lib.sharedLibrary() {
  2198. // A shared SDK library. This should be added as a top-level CLC element.
  2199. sdkLib = &depName
  2200. } else if ulib, ok := depModule.(ProvidesUsesLib); ok {
  2201. // A non-SDK library disguised as an SDK library by the means of `provides_uses_lib`
  2202. // property. This should be handled in the same way as a shared SDK library.
  2203. sdkLib = ulib.ProvidesUsesLib()
  2204. }
  2205. depTag := ctx.OtherModuleDependencyTag(depModule)
  2206. if IsLibDepTag(depTag) {
  2207. // Ok, propagate <uses-library> through non-static library dependencies.
  2208. } else if tag, ok := depTag.(usesLibraryDependencyTag); ok && tag.sdkVersion == dexpreopt.AnySdkVersion {
  2209. // Ok, propagate <uses-library> through non-compatibility <uses-library> dependencies.
  2210. } else if depTag == staticLibTag {
  2211. // Propagate <uses-library> through static library dependencies, unless it is a component
  2212. // library (such as stubs). Component libraries have a dependency on their SDK library,
  2213. // which should not be pulled just because of a static component library.
  2214. if sdkLib != nil {
  2215. return
  2216. }
  2217. } else {
  2218. // Don't propagate <uses-library> for other dependency tags.
  2219. return
  2220. }
  2221. // If this is an SDK (or SDK-like) library, then it should be added as a node in the CLC tree,
  2222. // and its CLC should be added as subtree of that node. Otherwise the library is not a
  2223. // <uses_library> and should not be added to CLC, but the transitive <uses-library> dependencies
  2224. // from its CLC should be added to the current CLC.
  2225. if sdkLib != nil {
  2226. clcMap.AddContext(ctx, dexpreopt.AnySdkVersion, *sdkLib, false,
  2227. dep.DexJarBuildPath().PathOrNil(), dep.DexJarInstallPath(), dep.ClassLoaderContexts())
  2228. } else {
  2229. clcMap.AddContextMap(dep.ClassLoaderContexts(), depName)
  2230. }
  2231. }
  2232. type javaResourcesAttributes struct {
  2233. Resources bazel.LabelListAttribute
  2234. Resource_strip_prefix *string
  2235. }
  2236. func (m *Library) javaResourcesGetSingleFilegroupStripPrefix(ctx android.TopDownMutatorContext) (string, bool) {
  2237. if otherM, ok := ctx.ModuleFromName(m.properties.Java_resources[0]); ok && len(m.properties.Java_resources) == 1 {
  2238. if fg, isFilegroup := otherM.(android.FileGroupPath); isFilegroup {
  2239. return filepath.Join(ctx.OtherModuleDir(otherM), fg.GetPath(ctx)), true
  2240. }
  2241. }
  2242. return "", false
  2243. }
  2244. func (m *Library) convertJavaResourcesAttributes(ctx android.TopDownMutatorContext) *javaResourcesAttributes {
  2245. var resources bazel.LabelList
  2246. var resourceStripPrefix *string
  2247. if m.properties.Java_resources != nil && len(m.properties.Java_resource_dirs) > 0 {
  2248. ctx.ModuleErrorf("bp2build doesn't support both java_resources and java_resource_dirs being set on the same module.")
  2249. }
  2250. if m.properties.Java_resources != nil {
  2251. if prefix, ok := m.javaResourcesGetSingleFilegroupStripPrefix(ctx); ok {
  2252. resourceStripPrefix = proptools.StringPtr(prefix)
  2253. } else {
  2254. resourceStripPrefix = proptools.StringPtr(ctx.ModuleDir())
  2255. }
  2256. resources.Append(android.BazelLabelForModuleSrc(ctx, m.properties.Java_resources))
  2257. }
  2258. //TODO(b/179889880) handle case where glob includes files outside package
  2259. resDeps := ResourceDirsToFiles(
  2260. ctx,
  2261. m.properties.Java_resource_dirs,
  2262. m.properties.Exclude_java_resource_dirs,
  2263. m.properties.Exclude_java_resources,
  2264. )
  2265. for i, resDep := range resDeps {
  2266. dir, files := resDep.dir, resDep.files
  2267. resources.Append(bazel.MakeLabelList(android.RootToModuleRelativePaths(ctx, files)))
  2268. // Bazel includes the relative path from the WORKSPACE root when placing the resource
  2269. // inside the JAR file, so we need to remove that prefix
  2270. resourceStripPrefix = proptools.StringPtr(dir.String())
  2271. if i > 0 {
  2272. // TODO(b/226423379) allow multiple resource prefixes
  2273. ctx.ModuleErrorf("bp2build does not support more than one directory in java_resource_dirs (b/226423379)")
  2274. }
  2275. }
  2276. return &javaResourcesAttributes{
  2277. Resources: bazel.MakeLabelListAttribute(resources),
  2278. Resource_strip_prefix: resourceStripPrefix,
  2279. }
  2280. }
  2281. type javaCommonAttributes struct {
  2282. *javaResourcesAttributes
  2283. *kotlinAttributes
  2284. Srcs bazel.LabelListAttribute
  2285. Plugins bazel.LabelListAttribute
  2286. Javacopts bazel.StringListAttribute
  2287. Sdk_version bazel.StringAttribute
  2288. Java_version bazel.StringAttribute
  2289. }
  2290. type javaDependencyLabels struct {
  2291. // Dependencies which DO NOT contribute to the API visible to upstream dependencies.
  2292. Deps bazel.LabelListAttribute
  2293. // Dependencies which DO contribute to the API visible to upstream dependencies.
  2294. StaticDeps bazel.LabelListAttribute
  2295. }
  2296. type eventLogTagsAttributes struct {
  2297. Srcs bazel.LabelListAttribute
  2298. }
  2299. type aidlLibraryAttributes struct {
  2300. Srcs bazel.LabelListAttribute
  2301. Tags bazel.StringListAttribute
  2302. }
  2303. type javaAidlLibraryAttributes struct {
  2304. Deps bazel.LabelListAttribute
  2305. Tags bazel.StringListAttribute
  2306. }
  2307. // bp2BuildJavaInfo has information needed for the conversion of java*_modules
  2308. // that is needed bor Bp2Build conversion but that requires different handling
  2309. // depending on the module type.
  2310. type bp2BuildJavaInfo struct {
  2311. // separates dependencies into dynamic dependencies and static dependencies.
  2312. DepLabels *javaDependencyLabels
  2313. hasKotlin bool
  2314. }
  2315. // Replaces //a/b/my_xsd_config with //a/b/my_xsd_config-java
  2316. func xsdConfigJavaTarget(ctx android.BazelConversionPathContext, mod blueprint.Module) string {
  2317. callback := func(xsd android.XsdConfigBp2buildTargets) string {
  2318. return xsd.JavaBp2buildTargetName()
  2319. }
  2320. return android.XsdConfigBp2buildTarget(ctx, mod, callback)
  2321. }
  2322. // convertLibraryAttrsBp2Build returns a javaCommonAttributes struct with
  2323. // converted attributes shared across java_* modules and a bp2BuildJavaInfo struct
  2324. // which has other non-attribute information needed for bp2build conversion
  2325. // that needs different handling depending on the module types, and thus needs
  2326. // to be returned to the calling function.
  2327. func (m *Library) convertLibraryAttrsBp2Build(ctx android.TopDownMutatorContext) (*javaCommonAttributes, *bp2BuildJavaInfo) {
  2328. var srcs bazel.LabelListAttribute
  2329. var deps bazel.LabelListAttribute
  2330. var staticDeps bazel.LabelList
  2331. archVariantProps := m.GetArchVariantProperties(ctx, &CommonProperties{})
  2332. for axis, configToProps := range archVariantProps {
  2333. for config, _props := range configToProps {
  2334. if archProps, ok := _props.(*CommonProperties); ok {
  2335. srcsNonXsd, srcsXsd := android.PartitionXsdSrcs(ctx, archProps.Srcs)
  2336. excludeSrcsNonXsd, _ := android.PartitionXsdSrcs(ctx, archProps.Exclude_srcs)
  2337. archSrcs := android.BazelLabelForModuleSrcExcludes(ctx, srcsNonXsd, excludeSrcsNonXsd)
  2338. srcs.SetSelectValue(axis, config, archSrcs)
  2339. // Add to static deps
  2340. xsdJavaConfigLibraryLabels := android.BazelLabelForModuleDepsWithFn(ctx, srcsXsd, xsdConfigJavaTarget)
  2341. staticDeps.Append(xsdJavaConfigLibraryLabels)
  2342. }
  2343. }
  2344. }
  2345. srcs.ResolveExcludes()
  2346. javaSrcPartition := "java"
  2347. protoSrcPartition := "proto"
  2348. logtagSrcPartition := "logtag"
  2349. aidlSrcPartition := "aidl"
  2350. kotlinPartition := "kotlin"
  2351. srcPartitions := bazel.PartitionLabelListAttribute(ctx, &srcs, bazel.LabelPartitions{
  2352. javaSrcPartition: bazel.LabelPartition{Extensions: []string{".java"}, Keep_remainder: true},
  2353. logtagSrcPartition: bazel.LabelPartition{Extensions: []string{".logtags", ".logtag"}},
  2354. protoSrcPartition: android.ProtoSrcLabelPartition,
  2355. aidlSrcPartition: android.AidlSrcLabelPartition,
  2356. kotlinPartition: bazel.LabelPartition{Extensions: []string{".kt"}},
  2357. })
  2358. javaSrcs := srcPartitions[javaSrcPartition]
  2359. kotlinSrcs := srcPartitions[kotlinPartition]
  2360. javaSrcs.Append(kotlinSrcs)
  2361. if !srcPartitions[logtagSrcPartition].IsEmpty() {
  2362. logtagsLibName := m.Name() + "_logtags"
  2363. ctx.CreateBazelTargetModule(
  2364. bazel.BazelTargetModuleProperties{
  2365. Rule_class: "event_log_tags",
  2366. Bzl_load_location: "//build/bazel/rules/java:event_log_tags.bzl",
  2367. },
  2368. android.CommonAttributes{Name: logtagsLibName},
  2369. &eventLogTagsAttributes{
  2370. Srcs: srcPartitions[logtagSrcPartition],
  2371. },
  2372. )
  2373. logtagsSrcs := bazel.MakeLabelList([]bazel.Label{{Label: ":" + logtagsLibName}})
  2374. javaSrcs.Append(bazel.MakeLabelListAttribute(logtagsSrcs))
  2375. }
  2376. if !srcPartitions[aidlSrcPartition].IsEmpty() {
  2377. aidlLibs, aidlSrcs := srcPartitions[aidlSrcPartition].Partition(func(src bazel.Label) bool {
  2378. return android.IsConvertedToAidlLibrary(ctx, src.OriginalModuleName)
  2379. })
  2380. apexAvailableTags := android.ApexAvailableTagsWithoutTestApexes(ctx, ctx.Module())
  2381. if !aidlSrcs.IsEmpty() {
  2382. aidlLibName := m.Name() + "_aidl_library"
  2383. ctx.CreateBazelTargetModule(
  2384. bazel.BazelTargetModuleProperties{
  2385. Rule_class: "aidl_library",
  2386. Bzl_load_location: "//build/bazel/rules/aidl:aidl_library.bzl",
  2387. },
  2388. android.CommonAttributes{Name: aidlLibName},
  2389. &aidlLibraryAttributes{
  2390. Srcs: aidlSrcs,
  2391. Tags: apexAvailableTags,
  2392. },
  2393. )
  2394. aidlLibs.Add(&bazel.LabelAttribute{Value: &bazel.Label{Label: ":" + aidlLibName}})
  2395. }
  2396. javaAidlLibName := m.Name() + "_java_aidl_library"
  2397. ctx.CreateBazelTargetModule(
  2398. bazel.BazelTargetModuleProperties{
  2399. Rule_class: "java_aidl_library",
  2400. Bzl_load_location: "//build/bazel/rules/java:java_aidl_library.bzl",
  2401. },
  2402. android.CommonAttributes{Name: javaAidlLibName},
  2403. &javaAidlLibraryAttributes{
  2404. Deps: aidlLibs,
  2405. Tags: apexAvailableTags,
  2406. },
  2407. )
  2408. staticDeps.Add(&bazel.Label{Label: ":" + javaAidlLibName})
  2409. }
  2410. var javacopts []string
  2411. if m.properties.Javacflags != nil {
  2412. javacopts = append(javacopts, m.properties.Javacflags...)
  2413. }
  2414. epEnabled := m.properties.Errorprone.Enabled
  2415. //TODO(b/227504307) add configuration that depends on RUN_ERROR_PRONE environment variable
  2416. if Bool(epEnabled) {
  2417. javacopts = append(javacopts, m.properties.Errorprone.Javacflags...)
  2418. }
  2419. commonAttrs := &javaCommonAttributes{
  2420. Srcs: javaSrcs,
  2421. javaResourcesAttributes: m.convertJavaResourcesAttributes(ctx),
  2422. Plugins: bazel.MakeLabelListAttribute(
  2423. android.BazelLabelForModuleDeps(ctx, m.properties.Plugins),
  2424. ),
  2425. Javacopts: bazel.MakeStringListAttribute(javacopts),
  2426. Java_version: bazel.StringAttribute{Value: m.properties.Java_version},
  2427. Sdk_version: bazel.StringAttribute{Value: m.deviceProperties.Sdk_version},
  2428. }
  2429. for axis, configToProps := range archVariantProps {
  2430. for config, _props := range configToProps {
  2431. if archProps, ok := _props.(*CommonProperties); ok {
  2432. var libLabels []bazel.Label
  2433. for _, d := range archProps.Libs {
  2434. neverlinkLabel := android.BazelLabelForModuleDepSingle(ctx, d)
  2435. neverlinkLabel.Label = neverlinkLabel.Label + "-neverlink"
  2436. libLabels = append(libLabels, neverlinkLabel)
  2437. }
  2438. deps.SetSelectValue(axis, config, bazel.MakeLabelList(libLabels))
  2439. }
  2440. }
  2441. }
  2442. protoDepLabel := bp2buildProto(ctx, &m.Module, srcPartitions[protoSrcPartition])
  2443. // Soong does not differentiate between a java_library and the Bazel equivalent of
  2444. // a java_proto_library + proto_library pair. Instead, in Soong proto sources are
  2445. // listed directly in the srcs of a java_library, and the classes produced
  2446. // by protoc are included directly in the resulting JAR. Thus upstream dependencies
  2447. // that depend on a java_library with proto sources can link directly to the protobuf API,
  2448. // and so this should be a static dependency.
  2449. staticDeps.Add(protoDepLabel)
  2450. depLabels := &javaDependencyLabels{}
  2451. depLabels.Deps = deps
  2452. for axis, configToProps := range archVariantProps {
  2453. for config, _props := range configToProps {
  2454. if archProps, ok := _props.(*CommonProperties); ok {
  2455. archStaticLibs := android.BazelLabelForModuleDeps(
  2456. ctx,
  2457. android.LastUniqueStrings(android.CopyOf(archProps.Static_libs)))
  2458. depLabels.StaticDeps.SetSelectValue(axis, config, archStaticLibs)
  2459. }
  2460. }
  2461. }
  2462. depLabels.StaticDeps.Value.Append(staticDeps)
  2463. hasKotlin := !kotlinSrcs.IsEmpty()
  2464. commonAttrs.kotlinAttributes = &kotlinAttributes{
  2465. Kotlincflags: &m.properties.Kotlincflags,
  2466. }
  2467. if len(m.properties.Common_srcs) != 0 {
  2468. hasKotlin = true
  2469. commonAttrs.kotlinAttributes.Common_srcs = bazel.MakeLabelListAttribute(android.BazelLabelForModuleSrc(ctx, m.properties.Common_srcs))
  2470. }
  2471. bp2BuildInfo := &bp2BuildJavaInfo{
  2472. DepLabels: depLabels,
  2473. hasKotlin: hasKotlin,
  2474. }
  2475. return commonAttrs, bp2BuildInfo
  2476. }
  2477. type javaLibraryAttributes struct {
  2478. *javaCommonAttributes
  2479. Deps bazel.LabelListAttribute
  2480. Exports bazel.LabelListAttribute
  2481. Neverlink bazel.BoolAttribute
  2482. }
  2483. type kotlinAttributes struct {
  2484. Common_srcs bazel.LabelListAttribute
  2485. Kotlincflags *[]string
  2486. }
  2487. func ktJvmLibraryBazelTargetModuleProperties() bazel.BazelTargetModuleProperties {
  2488. return bazel.BazelTargetModuleProperties{
  2489. Rule_class: "kt_jvm_library",
  2490. Bzl_load_location: "//build/bazel/rules/kotlin:kt_jvm_library.bzl",
  2491. }
  2492. }
  2493. func javaLibraryBazelTargetModuleProperties() bazel.BazelTargetModuleProperties {
  2494. return bazel.BazelTargetModuleProperties{
  2495. Rule_class: "java_library",
  2496. Bzl_load_location: "//build/bazel/rules/java:library.bzl",
  2497. }
  2498. }
  2499. func javaLibraryBp2Build(ctx android.TopDownMutatorContext, m *Library) {
  2500. commonAttrs, bp2BuildInfo := m.convertLibraryAttrsBp2Build(ctx)
  2501. depLabels := bp2BuildInfo.DepLabels
  2502. deps := depLabels.Deps
  2503. if !commonAttrs.Srcs.IsEmpty() {
  2504. deps.Append(depLabels.StaticDeps) // we should only append these if there are sources to use them
  2505. } else if !deps.IsEmpty() {
  2506. ctx.ModuleErrorf("Module has direct dependencies but no sources. Bazel will not allow this.")
  2507. }
  2508. var props bazel.BazelTargetModuleProperties
  2509. attrs := &javaLibraryAttributes{
  2510. javaCommonAttributes: commonAttrs,
  2511. Deps: deps,
  2512. Exports: depLabels.StaticDeps,
  2513. }
  2514. name := m.Name()
  2515. if !bp2BuildInfo.hasKotlin {
  2516. props = javaLibraryBazelTargetModuleProperties()
  2517. } else {
  2518. props = ktJvmLibraryBazelTargetModuleProperties()
  2519. }
  2520. ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: name}, attrs)
  2521. neverlinkProp := true
  2522. neverLinkAttrs := &javaLibraryAttributes{
  2523. Exports: bazel.MakeSingleLabelListAttribute(bazel.Label{Label: ":" + name}),
  2524. Neverlink: bazel.BoolAttribute{Value: &neverlinkProp},
  2525. javaCommonAttributes: &javaCommonAttributes{
  2526. Sdk_version: bazel.StringAttribute{Value: m.deviceProperties.Sdk_version},
  2527. Java_version: bazel.StringAttribute{Value: m.properties.Java_version},
  2528. },
  2529. }
  2530. ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: name + "-neverlink"}, neverLinkAttrs)
  2531. }
  2532. type javaBinaryHostAttributes struct {
  2533. *javaCommonAttributes
  2534. Deps bazel.LabelListAttribute
  2535. Runtime_deps bazel.LabelListAttribute
  2536. Main_class string
  2537. Jvm_flags bazel.StringListAttribute
  2538. }
  2539. // JavaBinaryHostBp2Build is for java_binary_host bp2build.
  2540. func javaBinaryHostBp2Build(ctx android.TopDownMutatorContext, m *Binary) {
  2541. commonAttrs, bp2BuildInfo := m.convertLibraryAttrsBp2Build(ctx)
  2542. depLabels := bp2BuildInfo.DepLabels
  2543. deps := depLabels.Deps
  2544. deps.Append(depLabels.StaticDeps)
  2545. if m.binaryProperties.Jni_libs != nil {
  2546. deps.Append(bazel.MakeLabelListAttribute(android.BazelLabelForModuleDeps(ctx, m.binaryProperties.Jni_libs)))
  2547. }
  2548. var runtimeDeps bazel.LabelListAttribute
  2549. if commonAttrs.Srcs.IsEmpty() {
  2550. // if there are no sources, then the dependencies can only be used at runtime
  2551. runtimeDeps = deps
  2552. deps = bazel.LabelListAttribute{}
  2553. }
  2554. mainClass := ""
  2555. if m.binaryProperties.Main_class != nil {
  2556. mainClass = *m.binaryProperties.Main_class
  2557. }
  2558. if m.properties.Manifest != nil {
  2559. mainClassInManifest, err := android.GetMainClassInManifest(ctx.Config(), android.PathForModuleSrc(ctx, *m.properties.Manifest).String())
  2560. if err != nil {
  2561. return
  2562. }
  2563. mainClass = mainClassInManifest
  2564. }
  2565. // Attribute jvm_flags
  2566. var jvmFlags bazel.StringListAttribute
  2567. if m.binaryProperties.Jni_libs != nil {
  2568. jniLibPackages := []string{}
  2569. for _, jniLib := range m.binaryProperties.Jni_libs {
  2570. if jniLibModule, exists := ctx.ModuleFromName(jniLib); exists {
  2571. otherDir := ctx.OtherModuleDir(jniLibModule)
  2572. jniLibPackages = append(jniLibPackages, filepath.Join(otherDir, jniLib))
  2573. }
  2574. }
  2575. jniLibPaths := []string{}
  2576. for _, jniLibPackage := range jniLibPackages {
  2577. // See cs/f:.*/third_party/bazel/.*java_stub_template.txt for the use of RUNPATH
  2578. jniLibPaths = append(jniLibPaths, "$${RUNPATH}"+jniLibPackage)
  2579. }
  2580. jvmFlags = bazel.MakeStringListAttribute([]string{"-Djava.library.path=" + strings.Join(jniLibPaths, ":")})
  2581. }
  2582. props := bazel.BazelTargetModuleProperties{
  2583. Rule_class: "java_binary",
  2584. Bzl_load_location: "@rules_java//java:defs.bzl",
  2585. }
  2586. binAttrs := &javaBinaryHostAttributes{
  2587. Runtime_deps: runtimeDeps,
  2588. Main_class: mainClass,
  2589. Jvm_flags: jvmFlags,
  2590. }
  2591. if commonAttrs.Srcs.IsEmpty() {
  2592. binAttrs.javaCommonAttributes = commonAttrs
  2593. ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, binAttrs)
  2594. return
  2595. }
  2596. libInfo := libraryCreationInfo{
  2597. deps: deps,
  2598. attrs: commonAttrs,
  2599. baseName: m.Name(),
  2600. hasKotlin: bp2BuildInfo.hasKotlin,
  2601. }
  2602. libName := createLibraryTarget(ctx, libInfo)
  2603. binAttrs.Runtime_deps.Add(&bazel.LabelAttribute{Value: &bazel.Label{Label: ":" + libName}})
  2604. // Create the BazelTargetModule.
  2605. ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, binAttrs)
  2606. }
  2607. type javaTestHostAttributes struct {
  2608. *javaCommonAttributes
  2609. Deps bazel.LabelListAttribute
  2610. Runtime_deps bazel.LabelListAttribute
  2611. }
  2612. // javaTestHostBp2Build is for java_test_host bp2build.
  2613. func javaTestHostBp2Build(ctx android.TopDownMutatorContext, m *TestHost) {
  2614. commonAttrs, bp2BuildInfo := m.convertLibraryAttrsBp2Build(ctx)
  2615. depLabels := bp2BuildInfo.DepLabels
  2616. deps := depLabels.Deps
  2617. deps.Append(depLabels.StaticDeps)
  2618. var runtimeDeps bazel.LabelListAttribute
  2619. attrs := &javaTestHostAttributes{
  2620. Runtime_deps: runtimeDeps,
  2621. }
  2622. props := bazel.BazelTargetModuleProperties{
  2623. Rule_class: "java_test",
  2624. Bzl_load_location: "//build/bazel/rules/java:test.bzl",
  2625. }
  2626. if commonAttrs.Srcs.IsEmpty() {
  2627. // if there are no sources, then the dependencies can only be used at runtime
  2628. attrs.Runtime_deps = deps
  2629. attrs.javaCommonAttributes = commonAttrs
  2630. ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, attrs)
  2631. return
  2632. }
  2633. libInfo := libraryCreationInfo{
  2634. deps: deps,
  2635. attrs: commonAttrs,
  2636. baseName: m.Name(),
  2637. hasKotlin: bp2BuildInfo.hasKotlin,
  2638. }
  2639. libName := createLibraryTarget(ctx, libInfo)
  2640. attrs.Runtime_deps.Add(&bazel.LabelAttribute{Value: &bazel.Label{Label: ":" + libName}})
  2641. // Create the BazelTargetModule.
  2642. ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, attrs)
  2643. }
  2644. // libraryCreationInfo encapsulates the info needed to create java_library target from
  2645. // java_binary_host or java_test_host.
  2646. type libraryCreationInfo struct {
  2647. deps bazel.LabelListAttribute
  2648. attrs *javaCommonAttributes
  2649. baseName string
  2650. hasKotlin bool
  2651. }
  2652. // helper function that creates java_library target from java_binary_host or java_test_host,
  2653. // and returns the library target name,
  2654. func createLibraryTarget(ctx android.TopDownMutatorContext, libInfo libraryCreationInfo) string {
  2655. libName := libInfo.baseName + "_lib"
  2656. var libProps bazel.BazelTargetModuleProperties
  2657. if libInfo.hasKotlin {
  2658. libProps = ktJvmLibraryBazelTargetModuleProperties()
  2659. } else {
  2660. libProps = javaLibraryBazelTargetModuleProperties()
  2661. }
  2662. libAttrs := &javaLibraryAttributes{
  2663. Deps: libInfo.deps,
  2664. javaCommonAttributes: libInfo.attrs,
  2665. }
  2666. ctx.CreateBazelTargetModule(libProps, android.CommonAttributes{Name: libName}, libAttrs)
  2667. return libName
  2668. }
  2669. type bazelJavaImportAttributes struct {
  2670. Jars bazel.LabelListAttribute
  2671. Exports bazel.LabelListAttribute
  2672. }
  2673. // java_import bp2Build converter.
  2674. func (i *Import) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
  2675. var jars bazel.LabelListAttribute
  2676. archVariantProps := i.GetArchVariantProperties(ctx, &ImportProperties{})
  2677. for axis, configToProps := range archVariantProps {
  2678. for config, _props := range configToProps {
  2679. if archProps, ok := _props.(*ImportProperties); ok {
  2680. archJars := android.BazelLabelForModuleSrcExcludes(ctx, archProps.Jars, []string(nil))
  2681. jars.SetSelectValue(axis, config, archJars)
  2682. }
  2683. }
  2684. }
  2685. attrs := &bazelJavaImportAttributes{
  2686. Jars: jars,
  2687. }
  2688. props := bazel.BazelTargetModuleProperties{
  2689. Rule_class: "java_import",
  2690. Bzl_load_location: "//build/bazel/rules/java:import.bzl",
  2691. }
  2692. name := android.RemoveOptionalPrebuiltPrefix(i.Name())
  2693. ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: name}, attrs)
  2694. neverlink := true
  2695. neverlinkAttrs := &javaLibraryAttributes{
  2696. Neverlink: bazel.BoolAttribute{Value: &neverlink},
  2697. Exports: bazel.MakeSingleLabelListAttribute(bazel.Label{Label: ":" + name}),
  2698. javaCommonAttributes: &javaCommonAttributes{
  2699. Sdk_version: bazel.StringAttribute{Value: proptools.StringPtr("none")},
  2700. },
  2701. }
  2702. ctx.CreateBazelTargetModule(
  2703. javaLibraryBazelTargetModuleProperties(),
  2704. android.CommonAttributes{Name: name + "-neverlink"},
  2705. neverlinkAttrs)
  2706. }
  2707. var _ android.MixedBuildBuildable = (*Import)(nil)
  2708. func (i *Import) getBazelModuleLabel(ctx android.BaseModuleContext) string {
  2709. return android.RemoveOptionalPrebuiltPrefixFromBazelLabel(i.GetBazelLabel(ctx, i))
  2710. }
  2711. func (i *Import) ProcessBazelQueryResponse(ctx android.ModuleContext) {
  2712. i.commonBuildActions(ctx)
  2713. bazelCtx := ctx.Config().BazelContext
  2714. filePaths, err := bazelCtx.GetOutputFiles(i.getBazelModuleLabel(ctx), android.GetConfigKey(ctx))
  2715. if err != nil {
  2716. ctx.ModuleErrorf(err.Error())
  2717. return
  2718. }
  2719. bazelJars := android.Paths{}
  2720. for _, bazelOutputFile := range filePaths {
  2721. bazelJars = append(bazelJars, android.PathForBazelOut(ctx, bazelOutputFile))
  2722. }
  2723. jarName := android.RemoveOptionalPrebuiltPrefix(i.Name()) + ".jar"
  2724. outputFile := android.PathForModuleOut(ctx, "bazelCombined", jarName)
  2725. TransformJarsToJar(ctx, outputFile, "combine prebuilt jars", bazelJars,
  2726. android.OptionalPath{}, // manifest
  2727. false, // stripDirEntries
  2728. []string{}, // filesToStrip
  2729. []string{}, // dirsToStrip
  2730. )
  2731. i.combinedClasspathFile = outputFile
  2732. ctx.SetProvider(JavaInfoProvider, JavaInfo{
  2733. HeaderJars: android.PathsIfNonNil(i.combinedClasspathFile),
  2734. ImplementationAndResourcesJars: android.PathsIfNonNil(i.combinedClasspathFile),
  2735. ImplementationJars: android.PathsIfNonNil(i.combinedClasspathFile),
  2736. //TODO(b/240308299) include AIDL information from Bazel
  2737. })
  2738. i.maybeInstall(ctx, jarName, outputFile)
  2739. }
  2740. func (i *Import) QueueBazelCall(ctx android.BaseModuleContext) {
  2741. bazelCtx := ctx.Config().BazelContext
  2742. bazelCtx.QueueBazelRequest(i.getBazelModuleLabel(ctx), cquery.GetOutputFiles, android.GetConfigKey(ctx))
  2743. }
  2744. func (i *Import) IsMixedBuildSupported(ctx android.BaseModuleContext) bool {
  2745. return true
  2746. }