java.go 114 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434
  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. "strconv"
  22. "strings"
  23. "github.com/google/blueprint"
  24. "github.com/google/blueprint/pathtools"
  25. "github.com/google/blueprint/proptools"
  26. "android/soong/android"
  27. "android/soong/dexpreopt"
  28. "android/soong/java/config"
  29. "android/soong/tradefed"
  30. )
  31. func init() {
  32. RegisterJavaBuildComponents(android.InitRegistrationContext)
  33. // Register sdk member types.
  34. android.RegisterSdkMemberType(javaHeaderLibsSdkMemberType)
  35. // Export implementation classes jar as part of the sdk.
  36. exportImplementationClassesJar := func(_ android.SdkMemberContext, j *Library) android.Path {
  37. implementationJars := j.ImplementationAndResourcesJars()
  38. if len(implementationJars) != 1 {
  39. panic(fmt.Errorf("there must be only one implementation jar from %q", j.Name()))
  40. }
  41. return implementationJars[0]
  42. }
  43. // Register java implementation libraries for use only in module_exports (not sdk).
  44. android.RegisterSdkMemberType(&librarySdkMemberType{
  45. android.SdkMemberTypeBase{
  46. PropertyName: "java_libs",
  47. },
  48. exportImplementationClassesJar,
  49. sdkSnapshotFilePathForJar,
  50. copyEverythingToSnapshot,
  51. })
  52. // Register java boot libraries for use in sdk.
  53. //
  54. // The build has some implicit dependencies (via the boot jars configuration) on a number of
  55. // modules, e.g. core-oj, apache-xml, that are part of the java boot class path and which are
  56. // provided by mainline modules (e.g. art, conscrypt, runtime-i18n) but which are not otherwise
  57. // used outside those mainline modules.
  58. //
  59. // As they are not needed outside the mainline modules adding them to the sdk/module-exports as
  60. // either java_libs, or java_header_libs would end up exporting more information than was strictly
  61. // necessary. The java_boot_libs property to allow those modules to be exported as part of the
  62. // sdk/module_exports without exposing any unnecessary information.
  63. android.RegisterSdkMemberType(&librarySdkMemberType{
  64. android.SdkMemberTypeBase{
  65. PropertyName: "java_boot_libs",
  66. SupportsSdk: true,
  67. },
  68. // Temporarily export implementation classes jar for java_boot_libs as it is required for the
  69. // hiddenapi processing.
  70. // TODO(b/179354495): Revert once hiddenapi processing has been modularized.
  71. exportImplementationClassesJar,
  72. sdkSnapshotFilePathForJar,
  73. onlyCopyJarToSnapshot,
  74. })
  75. // Register java test libraries for use only in module_exports (not sdk).
  76. android.RegisterSdkMemberType(&testSdkMemberType{
  77. SdkMemberTypeBase: android.SdkMemberTypeBase{
  78. PropertyName: "java_tests",
  79. },
  80. })
  81. }
  82. func RegisterJavaBuildComponents(ctx android.RegistrationContext) {
  83. ctx.RegisterModuleType("java_defaults", DefaultsFactory)
  84. ctx.RegisterModuleType("java_library", LibraryFactory)
  85. ctx.RegisterModuleType("java_library_static", LibraryStaticFactory)
  86. ctx.RegisterModuleType("java_library_host", LibraryHostFactory)
  87. ctx.RegisterModuleType("java_binary", BinaryFactory)
  88. ctx.RegisterModuleType("java_binary_host", BinaryHostFactory)
  89. ctx.RegisterModuleType("java_test", TestFactory)
  90. ctx.RegisterModuleType("java_test_helper_library", TestHelperLibraryFactory)
  91. ctx.RegisterModuleType("java_test_host", TestHostFactory)
  92. ctx.RegisterModuleType("java_test_import", JavaTestImportFactory)
  93. ctx.RegisterModuleType("java_import", ImportFactory)
  94. ctx.RegisterModuleType("java_import_host", ImportFactoryHost)
  95. ctx.RegisterModuleType("java_device_for_host", DeviceForHostFactory)
  96. ctx.RegisterModuleType("java_host_for_device", HostForDeviceFactory)
  97. ctx.RegisterModuleType("dex_import", DexImportFactory)
  98. ctx.FinalDepsMutators(func(ctx android.RegisterMutatorsContext) {
  99. ctx.BottomUp("dexpreopt_tool_deps", dexpreoptToolDepsMutator).Parallel()
  100. })
  101. ctx.RegisterSingletonType("logtags", LogtagsSingleton)
  102. ctx.RegisterSingletonType("kythe_java_extract", kytheExtractJavaFactory)
  103. }
  104. func (j *Module) CheckStableSdkVersion() error {
  105. sdkVersion := j.sdkVersion()
  106. if sdkVersion.stable() {
  107. return nil
  108. }
  109. return fmt.Errorf("non stable SDK %v", sdkVersion)
  110. }
  111. func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
  112. if j.RequiresStableAPIs(ctx) {
  113. if sc, ok := ctx.Module().(sdkContext); ok {
  114. if !sc.sdkVersion().specified() {
  115. ctx.PropertyErrorf("sdk_version",
  116. "sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
  117. }
  118. }
  119. }
  120. ctx.VisitDirectDeps(func(module android.Module) {
  121. tag := ctx.OtherModuleDependencyTag(module)
  122. switch module.(type) {
  123. // TODO(satayev): cover other types as well, e.g. imports
  124. case *Library, *AndroidLibrary:
  125. switch tag {
  126. case bootClasspathTag, libTag, staticLibTag, java9LibTag:
  127. checkLinkType(ctx, j, module.(linkTypeContext), tag.(dependencyTag))
  128. }
  129. }
  130. })
  131. }
  132. func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
  133. if sc, ok := ctx.Module().(sdkContext); ok {
  134. usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
  135. sdkVersionSpecified := sc.sdkVersion().specified()
  136. if usePlatformAPI && sdkVersionSpecified {
  137. ctx.PropertyErrorf("platform_apis", "platform_apis must be false when sdk_version is not empty.")
  138. } else if !usePlatformAPI && !sdkVersionSpecified {
  139. ctx.PropertyErrorf("platform_apis", "platform_apis must be true when sdk_version is empty.")
  140. }
  141. }
  142. }
  143. // TODO:
  144. // Autogenerated files:
  145. // Renderscript
  146. // Post-jar passes:
  147. // Proguard
  148. // Rmtypedefs
  149. // DroidDoc
  150. // Findbugs
  151. type CompilerProperties struct {
  152. // list of source files used to compile the Java module. May be .java, .kt, .logtags, .proto,
  153. // or .aidl files.
  154. Srcs []string `android:"path,arch_variant"`
  155. // list Kotlin of source files containing Kotlin code that should be treated as common code in
  156. // a codebase that supports Kotlin multiplatform. See
  157. // https://kotlinlang.org/docs/reference/multiplatform.html. May be only be .kt files.
  158. Common_srcs []string `android:"path,arch_variant"`
  159. // list of source files that should not be used to build the Java module.
  160. // This is most useful in the arch/multilib variants to remove non-common files
  161. Exclude_srcs []string `android:"path,arch_variant"`
  162. // list of directories containing Java resources
  163. Java_resource_dirs []string `android:"arch_variant"`
  164. // list of directories that should be excluded from java_resource_dirs
  165. Exclude_java_resource_dirs []string `android:"arch_variant"`
  166. // list of files to use as Java resources
  167. Java_resources []string `android:"path,arch_variant"`
  168. // list of files that should be excluded from java_resources and java_resource_dirs
  169. Exclude_java_resources []string `android:"path,arch_variant"`
  170. // list of module-specific flags that will be used for javac compiles
  171. Javacflags []string `android:"arch_variant"`
  172. // list of module-specific flags that will be used for kotlinc compiles
  173. Kotlincflags []string `android:"arch_variant"`
  174. // list of of java libraries that will be in the classpath
  175. Libs []string `android:"arch_variant"`
  176. // list of java libraries that will be compiled into the resulting jar
  177. Static_libs []string `android:"arch_variant"`
  178. // manifest file to be included in resulting jar
  179. Manifest *string `android:"path"`
  180. // if not blank, run jarjar using the specified rules file
  181. Jarjar_rules *string `android:"path,arch_variant"`
  182. // If not blank, set the java version passed to javac as -source and -target
  183. Java_version *string
  184. // If set to true, allow this module to be dexed and installed on devices. Has no
  185. // effect on host modules, which are always considered installable.
  186. Installable *bool
  187. // If set to true, include sources used to compile the module in to the final jar
  188. Include_srcs *bool
  189. // If not empty, classes are restricted to the specified packages and their sub-packages.
  190. // This restriction is checked after applying jarjar rules and including static libs.
  191. Permitted_packages []string
  192. // List of modules to use as annotation processors
  193. Plugins []string
  194. // List of modules to export to libraries that directly depend on this library as annotation
  195. // processors. Note that if the plugins set generates_api: true this will disable the turbine
  196. // optimization on modules that depend on this module, which will reduce parallelism and cause
  197. // more recompilation.
  198. Exported_plugins []string
  199. // The number of Java source entries each Javac instance can process
  200. Javac_shard_size *int64
  201. // Add host jdk tools.jar to bootclasspath
  202. Use_tools_jar *bool
  203. Openjdk9 struct {
  204. // List of source files that should only be used when passing -source 1.9 or higher
  205. Srcs []string `android:"path"`
  206. // List of javac flags that should only be used when passing -source 1.9 or higher
  207. Javacflags []string
  208. }
  209. // When compiling language level 9+ .java code in packages that are part of
  210. // a system module, patch_module names the module that your sources and
  211. // dependencies should be patched into. The Android runtime currently
  212. // doesn't implement the JEP 261 module system so this option is only
  213. // supported at compile time. It should only be needed to compile tests in
  214. // packages that exist in libcore and which are inconvenient to move
  215. // elsewhere.
  216. Patch_module *string `android:"arch_variant"`
  217. Jacoco struct {
  218. // List of classes to include for instrumentation with jacoco to collect coverage
  219. // information at runtime when building with coverage enabled. If unset defaults to all
  220. // classes.
  221. // Supports '*' as the last character of an entry in the list as a wildcard match.
  222. // If preceded by '.' it matches all classes in the package and subpackages, otherwise
  223. // it matches classes in the package that have the class name as a prefix.
  224. Include_filter []string
  225. // List of classes to exclude from instrumentation with jacoco to collect coverage
  226. // information at runtime when building with coverage enabled. Overrides classes selected
  227. // by the include_filter property.
  228. // Supports '*' as the last character of an entry in the list as a wildcard match.
  229. // If preceded by '.' it matches all classes in the package and subpackages, otherwise
  230. // it matches classes in the package that have the class name as a prefix.
  231. Exclude_filter []string
  232. }
  233. Errorprone struct {
  234. // List of javac flags that should only be used when running errorprone.
  235. Javacflags []string
  236. // List of java_plugin modules that provide extra errorprone checks.
  237. Extra_check_modules []string
  238. }
  239. Proto struct {
  240. // List of extra options that will be passed to the proto generator.
  241. Output_params []string
  242. }
  243. Instrument bool `blueprint:"mutated"`
  244. // List of files to include in the META-INF/services folder of the resulting jar.
  245. Services []string `android:"path,arch_variant"`
  246. // If true, package the kotlin stdlib into the jar. Defaults to true.
  247. Static_kotlin_stdlib *bool `android:"arch_variant"`
  248. // A list of java_library instances that provide additional hiddenapi annotations for the library.
  249. Hiddenapi_additional_annotations []string
  250. }
  251. type CompilerDeviceProperties struct {
  252. // if not blank, set to the version of the sdk to compile against.
  253. // Defaults to compiling against the current platform.
  254. Sdk_version *string
  255. // if not blank, set the minimum version of the sdk that the compiled artifacts will run against.
  256. // Defaults to sdk_version if not set.
  257. Min_sdk_version *string
  258. // if not blank, set the targetSdkVersion in the AndroidManifest.xml.
  259. // Defaults to sdk_version if not set.
  260. Target_sdk_version *string
  261. // Whether to compile against the platform APIs instead of an SDK.
  262. // If true, then sdk_version must be empty. The value of this field
  263. // is ignored when module's type isn't android_app.
  264. Platform_apis *bool
  265. Aidl struct {
  266. // Top level directories to pass to aidl tool
  267. Include_dirs []string
  268. // Directories rooted at the Android.bp file to pass to aidl tool
  269. Local_include_dirs []string
  270. // directories that should be added as include directories for any aidl sources of modules
  271. // that depend on this module, as well as to aidl for this module.
  272. Export_include_dirs []string
  273. // whether to generate traces (for systrace) for this interface
  274. Generate_traces *bool
  275. // whether to generate Binder#GetTransaction name method.
  276. Generate_get_transaction_name *bool
  277. // list of flags that will be passed to the AIDL compiler
  278. Flags []string
  279. }
  280. // If true, export a copy of the module as a -hostdex module for host testing.
  281. Hostdex *bool
  282. Target struct {
  283. Hostdex struct {
  284. // Additional required dependencies to add to -hostdex modules.
  285. Required []string
  286. }
  287. }
  288. // When targeting 1.9 and above, override the modules to use with --system,
  289. // otherwise provides defaults libraries to add to the bootclasspath.
  290. System_modules *string
  291. // The name of the module as used in build configuration.
  292. //
  293. // Allows a library to separate its actual name from the name used in
  294. // build configuration, e.g.ctx.Config().BootJars().
  295. ConfigurationName *string `blueprint:"mutated"`
  296. // set the name of the output
  297. Stem *string
  298. IsSDKLibrary bool `blueprint:"mutated"`
  299. // If true, generate the signature file of APK Signing Scheme V4, along side the signed APK file.
  300. // Defaults to false.
  301. V4_signature *bool
  302. // Only for libraries created by a sysprop_library module, SyspropPublicStub is the name of the
  303. // public stubs library.
  304. SyspropPublicStub string `blueprint:"mutated"`
  305. }
  306. // Functionality common to Module and Import
  307. //
  308. // It is embedded in Module so its functionality can be used by methods in Module
  309. // but it is currently only initialized by Import and Library.
  310. type embeddableInModuleAndImport struct {
  311. // Functionality related to this being used as a component of a java_sdk_library.
  312. EmbeddableSdkLibraryComponent
  313. }
  314. func (e *embeddableInModuleAndImport) initModuleAndImport(moduleBase *android.ModuleBase) {
  315. e.initSdkLibraryComponent(moduleBase)
  316. }
  317. // Module/Import's DepIsInSameApex(...) delegates to this method.
  318. //
  319. // This cannot implement DepIsInSameApex(...) directly as that leads to ambiguity with
  320. // the one provided by ApexModuleBase.
  321. func (e *embeddableInModuleAndImport) depIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
  322. // dependencies other than the static linkage are all considered crossing APEX boundary
  323. if staticLibTag == ctx.OtherModuleDependencyTag(dep) {
  324. return true
  325. }
  326. return false
  327. }
  328. // Module contains the properties and members used by all java module types
  329. type Module struct {
  330. android.ModuleBase
  331. android.DefaultableModuleBase
  332. android.ApexModuleBase
  333. android.SdkBase
  334. // Functionality common to Module and Import.
  335. embeddableInModuleAndImport
  336. properties CompilerProperties
  337. protoProperties android.ProtoProperties
  338. deviceProperties CompilerDeviceProperties
  339. // jar file containing header classes including static library dependencies, suitable for
  340. // inserting into the bootclasspath/classpath of another compile
  341. headerJarFile android.Path
  342. // jar file containing implementation classes including static library dependencies but no
  343. // resources
  344. implementationJarFile android.Path
  345. // jar file containing only resources including from static library dependencies
  346. resourceJar android.Path
  347. // args and dependencies to package source files into a srcjar
  348. srcJarArgs []string
  349. srcJarDeps android.Paths
  350. // jar file containing implementation classes and resources including static library
  351. // dependencies
  352. implementationAndResourcesJar android.Path
  353. // output file containing classes.dex and resources
  354. dexJarFile android.Path
  355. // output file containing uninstrumented classes that will be instrumented by jacoco
  356. jacocoReportClassesFile android.Path
  357. // output file of the module, which may be a classes jar or a dex jar
  358. outputFile android.Path
  359. extraOutputFiles android.Paths
  360. exportAidlIncludeDirs android.Paths
  361. logtagsSrcs android.Paths
  362. // installed file for binary dependency
  363. installFile android.Path
  364. // list of .java files and srcjars that was passed to javac
  365. compiledJavaSrcs android.Paths
  366. compiledSrcJars android.Paths
  367. // manifest file to use instead of properties.Manifest
  368. overrideManifest android.OptionalPath
  369. // map of SDK version to class loader context
  370. classLoaderContexts dexpreopt.ClassLoaderContextMap
  371. // list of plugins that this java module is exporting
  372. exportedPluginJars android.Paths
  373. // list of plugins that this java module is exporting
  374. exportedPluginClasses []string
  375. // if true, the exported plugins generate API and require disabling turbine.
  376. exportedDisableTurbine bool
  377. // list of source files, collected from srcFiles with unique java and all kt files,
  378. // will be used by android.IDEInfo struct
  379. expandIDEInfoCompiledSrcs []string
  380. // expanded Jarjar_rules
  381. expandJarjarRules android.Path
  382. // list of additional targets for checkbuild
  383. additionalCheckedModules android.Paths
  384. // Extra files generated by the module type to be added as java resources.
  385. extraResources android.Paths
  386. hiddenAPI
  387. dexer
  388. dexpreopter
  389. usesLibrary
  390. linter
  391. // list of the xref extraction files
  392. kytheFiles android.Paths
  393. // Collect the module directory for IDE info in java/jdeps.go.
  394. modulePaths []string
  395. hideApexVariantFromMake bool
  396. }
  397. func (j *Module) addHostProperties() {
  398. j.AddProperties(
  399. &j.properties,
  400. &j.protoProperties,
  401. &j.usesLibraryProperties,
  402. )
  403. }
  404. func (j *Module) addHostAndDeviceProperties() {
  405. j.addHostProperties()
  406. j.AddProperties(
  407. &j.deviceProperties,
  408. &j.dexer.dexProperties,
  409. &j.dexpreoptProperties,
  410. &j.linter.properties,
  411. )
  412. }
  413. func (j *Module) OutputFiles(tag string) (android.Paths, error) {
  414. switch tag {
  415. case "":
  416. return append(android.Paths{j.outputFile}, j.extraOutputFiles...), nil
  417. case android.DefaultDistTag:
  418. return android.Paths{j.outputFile}, nil
  419. case ".jar":
  420. return android.Paths{j.implementationAndResourcesJar}, nil
  421. case ".proguard_map":
  422. if j.dexer.proguardDictionary.Valid() {
  423. return android.Paths{j.dexer.proguardDictionary.Path()}, nil
  424. }
  425. return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
  426. default:
  427. return nil, fmt.Errorf("unsupported module reference tag %q", tag)
  428. }
  429. }
  430. var _ android.OutputFileProducer = (*Module)(nil)
  431. // JavaInfo contains information about a java module for use by modules that depend on it.
  432. type JavaInfo struct {
  433. // HeaderJars is a list of jars that can be passed as the javac classpath in order to link
  434. // against this module. If empty, ImplementationJars should be used instead.
  435. HeaderJars android.Paths
  436. // ImplementationAndResourceJars is a list of jars that contain the implementations of classes
  437. // in the module as well as any resources included in the module.
  438. ImplementationAndResourcesJars android.Paths
  439. // ImplementationJars is a list of jars that contain the implementations of classes in the
  440. //module.
  441. ImplementationJars android.Paths
  442. // ResourceJars is a list of jars that contain the resources included in the module.
  443. ResourceJars android.Paths
  444. // AidlIncludeDirs is a list of directories that should be passed to the aidl tool when
  445. // depending on this module.
  446. AidlIncludeDirs android.Paths
  447. // SrcJarArgs is a list of arguments to pass to soong_zip to package the sources of this
  448. // module.
  449. SrcJarArgs []string
  450. // SrcJarDeps is a list of paths to depend on when packaging the sources of this module.
  451. SrcJarDeps android.Paths
  452. // ExportedPlugins is a list of paths that should be used as annotation processors for any
  453. // module that depends on this module.
  454. ExportedPlugins android.Paths
  455. // ExportedPluginClasses is a list of classes that should be run as annotation processors for
  456. // any module that depends on this module.
  457. ExportedPluginClasses []string
  458. // ExportedPluginDisableTurbine is true if this module's annotation processors generate APIs,
  459. // requiring disbling turbine for any modules that depend on it.
  460. ExportedPluginDisableTurbine bool
  461. // JacocoReportClassesFile is the path to a jar containing uninstrumented classes that will be
  462. // instrumented by jacoco.
  463. JacocoReportClassesFile android.Path
  464. }
  465. var JavaInfoProvider = blueprint.NewProvider(JavaInfo{})
  466. // SyspropPublicStubInfo contains info about the sysprop public stub library that corresponds to
  467. // the sysprop implementation library.
  468. type SyspropPublicStubInfo struct {
  469. // JavaInfo is the JavaInfoProvider of the sysprop public stub library that corresponds to
  470. // the sysprop implementation library.
  471. JavaInfo JavaInfo
  472. }
  473. var SyspropPublicStubInfoProvider = blueprint.NewProvider(SyspropPublicStubInfo{})
  474. // Methods that need to be implemented for a module that is added to apex java_libs property.
  475. type ApexDependency interface {
  476. HeaderJars() android.Paths
  477. ImplementationAndResourcesJars() android.Paths
  478. }
  479. // Provides build path and install path to DEX jars.
  480. type UsesLibraryDependency interface {
  481. DexJarBuildPath() android.Path
  482. DexJarInstallPath() android.Path
  483. ClassLoaderContexts() dexpreopt.ClassLoaderContextMap
  484. }
  485. type xref interface {
  486. XrefJavaFiles() android.Paths
  487. }
  488. func (j *Module) XrefJavaFiles() android.Paths {
  489. return j.kytheFiles
  490. }
  491. func InitJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
  492. initJavaModule(module, hod, false)
  493. }
  494. func InitJavaModuleMultiTargets(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
  495. initJavaModule(module, hod, true)
  496. }
  497. func initJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported, multiTargets bool) {
  498. multilib := android.MultilibCommon
  499. if multiTargets {
  500. android.InitAndroidMultiTargetsArchModule(module, hod, multilib)
  501. } else {
  502. android.InitAndroidArchModule(module, hod, multilib)
  503. }
  504. android.InitDefaultableModule(module)
  505. }
  506. type dependencyTag struct {
  507. blueprint.BaseDependencyTag
  508. name string
  509. }
  510. // installDependencyTag is a dependency tag that is annotated to cause the installed files of the
  511. // dependency to be installed when the parent module is installed.
  512. type installDependencyTag struct {
  513. blueprint.BaseDependencyTag
  514. android.InstallAlwaysNeededDependencyTag
  515. name string
  516. }
  517. type usesLibraryDependencyTag struct {
  518. dependencyTag
  519. sdkVersion int // SDK version in which the library appared as a standalone library.
  520. }
  521. func makeUsesLibraryDependencyTag(sdkVersion int) usesLibraryDependencyTag {
  522. return usesLibraryDependencyTag{
  523. dependencyTag: dependencyTag{name: fmt.Sprintf("uses-library-%d", sdkVersion)},
  524. sdkVersion: sdkVersion,
  525. }
  526. }
  527. func IsJniDepTag(depTag blueprint.DependencyTag) bool {
  528. return depTag == jniLibTag
  529. }
  530. var (
  531. dataNativeBinsTag = dependencyTag{name: "dataNativeBins"}
  532. staticLibTag = dependencyTag{name: "staticlib"}
  533. libTag = dependencyTag{name: "javalib"}
  534. java9LibTag = dependencyTag{name: "java9lib"}
  535. pluginTag = dependencyTag{name: "plugin"}
  536. errorpronePluginTag = dependencyTag{name: "errorprone-plugin"}
  537. exportedPluginTag = dependencyTag{name: "exported-plugin"}
  538. bootClasspathTag = dependencyTag{name: "bootclasspath"}
  539. systemModulesTag = dependencyTag{name: "system modules"}
  540. frameworkResTag = dependencyTag{name: "framework-res"}
  541. kotlinStdlibTag = dependencyTag{name: "kotlin-stdlib"}
  542. kotlinAnnotationsTag = dependencyTag{name: "kotlin-annotations"}
  543. proguardRaiseTag = dependencyTag{name: "proguard-raise"}
  544. certificateTag = dependencyTag{name: "certificate"}
  545. instrumentationForTag = dependencyTag{name: "instrumentation_for"}
  546. extraLintCheckTag = dependencyTag{name: "extra-lint-check"}
  547. jniLibTag = dependencyTag{name: "jnilib"}
  548. syspropPublicStubDepTag = dependencyTag{name: "sysprop public stub"}
  549. jniInstallTag = installDependencyTag{name: "jni install"}
  550. binaryInstallTag = installDependencyTag{name: "binary install"}
  551. usesLibTag = makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion)
  552. usesLibCompat28Tag = makeUsesLibraryDependencyTag(28)
  553. usesLibCompat29Tag = makeUsesLibraryDependencyTag(29)
  554. usesLibCompat30Tag = makeUsesLibraryDependencyTag(30)
  555. )
  556. func IsLibDepTag(depTag blueprint.DependencyTag) bool {
  557. return depTag == libTag
  558. }
  559. func IsStaticLibDepTag(depTag blueprint.DependencyTag) bool {
  560. return depTag == staticLibTag
  561. }
  562. type sdkDep struct {
  563. useModule, useFiles, invalidVersion bool
  564. // The modules that will be added to the bootclasspath when targeting 1.8 or lower
  565. bootclasspath []string
  566. // The default system modules to use. Will be an empty string if no system
  567. // modules are to be used.
  568. systemModules string
  569. // The modules that will be added to the classpath regardless of the Java language level targeted
  570. classpath []string
  571. // The modules that will be added ot the classpath when targeting 1.9 or higher
  572. // (normally these will be on the bootclasspath when targeting 1.8 or lower)
  573. java9Classpath []string
  574. frameworkResModule string
  575. jars android.Paths
  576. aidl android.OptionalPath
  577. noStandardLibs, noFrameworksLibs bool
  578. }
  579. func (s sdkDep) hasStandardLibs() bool {
  580. return !s.noStandardLibs
  581. }
  582. func (s sdkDep) hasFrameworkLibs() bool {
  583. return !s.noStandardLibs && !s.noFrameworksLibs
  584. }
  585. type jniLib struct {
  586. name string
  587. path android.Path
  588. target android.Target
  589. coverageFile android.OptionalPath
  590. unstrippedFile android.Path
  591. }
  592. func (j *Module) shouldInstrument(ctx android.BaseModuleContext) bool {
  593. return j.properties.Instrument &&
  594. ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") &&
  595. ctx.DeviceConfig().JavaCoverageEnabledForPath(ctx.ModuleDir())
  596. }
  597. func (j *Module) shouldInstrumentStatic(ctx android.BaseModuleContext) bool {
  598. return j.shouldInstrument(ctx) &&
  599. (ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_STATIC") ||
  600. ctx.Config().UnbundledBuild())
  601. }
  602. func (j *Module) shouldInstrumentInApex(ctx android.BaseModuleContext) bool {
  603. // Force enable the instrumentation for java code that is built for APEXes ...
  604. // except for the jacocoagent itself (because instrumenting jacocoagent using jacocoagent
  605. // doesn't make sense) or framework libraries (e.g. libraries found in the InstrumentFrameworkModules list) unless EMMA_INSTRUMENT_FRAMEWORK is true.
  606. apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
  607. isJacocoAgent := ctx.ModuleName() == "jacocoagent"
  608. if j.DirectlyInAnyApex() && !isJacocoAgent && !apexInfo.IsForPlatform() {
  609. if !inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
  610. return true
  611. } else if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
  612. return true
  613. }
  614. }
  615. return false
  616. }
  617. func (j *Module) sdkVersion() sdkSpec {
  618. return sdkSpecFrom(String(j.deviceProperties.Sdk_version))
  619. }
  620. func (j *Module) systemModules() string {
  621. return proptools.String(j.deviceProperties.System_modules)
  622. }
  623. func (j *Module) minSdkVersion() sdkSpec {
  624. if j.deviceProperties.Min_sdk_version != nil {
  625. return sdkSpecFrom(*j.deviceProperties.Min_sdk_version)
  626. }
  627. return j.sdkVersion()
  628. }
  629. func (j *Module) targetSdkVersion() sdkSpec {
  630. if j.deviceProperties.Target_sdk_version != nil {
  631. return sdkSpecFrom(*j.deviceProperties.Target_sdk_version)
  632. }
  633. return j.sdkVersion()
  634. }
  635. func (j *Module) MinSdkVersion() string {
  636. return j.minSdkVersion().version.String()
  637. }
  638. func (j *Module) AvailableFor(what string) bool {
  639. if what == android.AvailableToPlatform && Bool(j.deviceProperties.Hostdex) {
  640. // Exception: for hostdex: true libraries, the platform variant is created
  641. // even if it's not marked as available to platform. In that case, the platform
  642. // variant is used only for the hostdex and not installed to the device.
  643. return true
  644. }
  645. return j.ApexModuleBase.AvailableFor(what)
  646. }
  647. func sdkDeps(ctx android.BottomUpMutatorContext, sdkContext sdkContext, d dexer) {
  648. sdkDep := decodeSdkDep(ctx, sdkContext)
  649. if sdkDep.useModule {
  650. ctx.AddVariationDependencies(nil, bootClasspathTag, sdkDep.bootclasspath...)
  651. ctx.AddVariationDependencies(nil, java9LibTag, sdkDep.java9Classpath...)
  652. ctx.AddVariationDependencies(nil, libTag, sdkDep.classpath...)
  653. if d.effectiveOptimizeEnabled() && sdkDep.hasStandardLibs() {
  654. ctx.AddVariationDependencies(nil, proguardRaiseTag, config.LegacyCorePlatformBootclasspathLibraries...)
  655. }
  656. if d.effectiveOptimizeEnabled() && sdkDep.hasFrameworkLibs() {
  657. ctx.AddVariationDependencies(nil, proguardRaiseTag, config.FrameworkLibraries...)
  658. }
  659. }
  660. if sdkDep.systemModules != "" {
  661. ctx.AddVariationDependencies(nil, systemModulesTag, sdkDep.systemModules)
  662. }
  663. }
  664. func (j *Module) deps(ctx android.BottomUpMutatorContext) {
  665. if ctx.Device() {
  666. j.linter.deps(ctx)
  667. sdkDeps(ctx, sdkContext(j), j.dexer)
  668. if j.deviceProperties.SyspropPublicStub != "" {
  669. // This is a sysprop implementation library that has a corresponding sysprop public
  670. // stubs library, and a dependency on it so that dependencies on the implementation can
  671. // be forwarded to the public stubs library when necessary.
  672. ctx.AddVariationDependencies(nil, syspropPublicStubDepTag, j.deviceProperties.SyspropPublicStub)
  673. }
  674. }
  675. libDeps := ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
  676. ctx.AddVariationDependencies(nil, staticLibTag, j.properties.Static_libs...)
  677. // Add dependency on libraries that provide additional hidden api annotations.
  678. ctx.AddVariationDependencies(nil, hiddenApiAnnotationsTag, j.properties.Hiddenapi_additional_annotations...)
  679. if ctx.DeviceConfig().VndkVersion() != "" && ctx.Config().EnforceInterPartitionJavaSdkLibrary() {
  680. // Require java_sdk_library at inter-partition java dependency to ensure stable
  681. // interface between partitions. If inter-partition java_library dependency is detected,
  682. // raise build error because java_library doesn't have a stable interface.
  683. //
  684. // Inputs:
  685. // PRODUCT_ENFORCE_INTER_PARTITION_JAVA_SDK_LIBRARY
  686. // if true, enable enforcement
  687. // PRODUCT_INTER_PARTITION_JAVA_LIBRARY_ALLOWLIST
  688. // exception list of java_library names to allow inter-partition dependency
  689. for idx := range j.properties.Libs {
  690. if libDeps[idx] == nil {
  691. continue
  692. }
  693. if javaDep, ok := libDeps[idx].(javaSdkLibraryEnforceContext); ok {
  694. // java_sdk_library is always allowed at inter-partition dependency.
  695. // So, skip check.
  696. if _, ok := javaDep.(*SdkLibrary); ok {
  697. continue
  698. }
  699. j.checkPartitionsForJavaDependency(ctx, "libs", javaDep)
  700. }
  701. }
  702. }
  703. // For library dependencies that are component libraries (like stubs), add the implementation
  704. // as a dependency (dexpreopt needs to be against the implementation library, not stubs).
  705. for _, dep := range libDeps {
  706. if dep != nil {
  707. if component, ok := dep.(SdkLibraryComponentDependency); ok {
  708. if lib := component.OptionalSdkLibraryImplementation(); lib != nil {
  709. ctx.AddVariationDependencies(nil, usesLibTag, *lib)
  710. }
  711. }
  712. }
  713. }
  714. ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
  715. ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
  716. ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
  717. android.ProtoDeps(ctx, &j.protoProperties)
  718. if j.hasSrcExt(".proto") {
  719. protoDeps(ctx, &j.protoProperties)
  720. }
  721. if j.hasSrcExt(".kt") {
  722. // TODO(ccross): move this to a mutator pass that can tell if generated sources contain
  723. // Kotlin files
  724. ctx.AddVariationDependencies(nil, kotlinStdlibTag,
  725. "kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8")
  726. if len(j.properties.Plugins) > 0 {
  727. ctx.AddVariationDependencies(nil, kotlinAnnotationsTag, "kotlin-annotations")
  728. }
  729. }
  730. // Framework libraries need special handling in static coverage builds: they should not have
  731. // static dependency on jacoco, otherwise there would be multiple conflicting definitions of
  732. // the same jacoco classes coming from different bootclasspath jars.
  733. if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
  734. if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
  735. j.properties.Instrument = true
  736. }
  737. } else if j.shouldInstrumentStatic(ctx) {
  738. ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
  739. }
  740. }
  741. func hasSrcExt(srcs []string, ext string) bool {
  742. for _, src := range srcs {
  743. if filepath.Ext(src) == ext {
  744. return true
  745. }
  746. }
  747. return false
  748. }
  749. func (j *Module) hasSrcExt(ext string) bool {
  750. return hasSrcExt(j.properties.Srcs, ext)
  751. }
  752. func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
  753. aidlIncludeDirs android.Paths) (string, android.Paths) {
  754. aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
  755. aidlIncludes = append(aidlIncludes,
  756. android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
  757. aidlIncludes = append(aidlIncludes,
  758. android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
  759. var flags []string
  760. var deps android.Paths
  761. flags = append(flags, j.deviceProperties.Aidl.Flags...)
  762. if aidlPreprocess.Valid() {
  763. flags = append(flags, "-p"+aidlPreprocess.String())
  764. deps = append(deps, aidlPreprocess.Path())
  765. } else if len(aidlIncludeDirs) > 0 {
  766. flags = append(flags, android.JoinWithPrefix(aidlIncludeDirs.Strings(), "-I"))
  767. }
  768. if len(j.exportAidlIncludeDirs) > 0 {
  769. flags = append(flags, android.JoinWithPrefix(j.exportAidlIncludeDirs.Strings(), "-I"))
  770. }
  771. if len(aidlIncludes) > 0 {
  772. flags = append(flags, android.JoinWithPrefix(aidlIncludes.Strings(), "-I"))
  773. }
  774. flags = append(flags, "-I"+android.PathForModuleSrc(ctx).String())
  775. if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
  776. flags = append(flags, "-I"+src.String())
  777. }
  778. if Bool(j.deviceProperties.Aidl.Generate_traces) {
  779. flags = append(flags, "-t")
  780. }
  781. if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
  782. flags = append(flags, "--transaction_names")
  783. }
  784. return strings.Join(flags, " "), deps
  785. }
  786. type deps struct {
  787. classpath classpath
  788. java9Classpath classpath
  789. bootClasspath classpath
  790. processorPath classpath
  791. errorProneProcessorPath classpath
  792. processorClasses []string
  793. staticJars android.Paths
  794. staticHeaderJars android.Paths
  795. staticResourceJars android.Paths
  796. aidlIncludeDirs android.Paths
  797. srcs android.Paths
  798. srcJars android.Paths
  799. systemModules *systemModules
  800. aidlPreprocess android.OptionalPath
  801. kotlinStdlib android.Paths
  802. kotlinAnnotations android.Paths
  803. disableTurbine bool
  804. }
  805. func checkProducesJars(ctx android.ModuleContext, dep android.SourceFileProducer) {
  806. for _, f := range dep.Srcs() {
  807. if f.Ext() != ".jar" {
  808. ctx.ModuleErrorf("genrule %q must generate files ending with .jar to be used as a libs or static_libs dependency",
  809. ctx.OtherModuleName(dep.(blueprint.Module)))
  810. }
  811. }
  812. }
  813. type linkType int
  814. const (
  815. // TODO(jiyong) rename these for better readability. Make the allowed
  816. // and disallowed link types explicit
  817. // order is important here. See rank()
  818. javaCore linkType = iota
  819. javaSdk
  820. javaSystem
  821. javaModule
  822. javaSystemServer
  823. javaPlatform
  824. )
  825. func (lt linkType) String() string {
  826. switch lt {
  827. case javaCore:
  828. return "core Java API"
  829. case javaSdk:
  830. return "Android API"
  831. case javaSystem:
  832. return "system API"
  833. case javaModule:
  834. return "module API"
  835. case javaSystemServer:
  836. return "system server API"
  837. case javaPlatform:
  838. return "private API"
  839. default:
  840. panic(fmt.Errorf("unrecognized linktype: %d", lt))
  841. }
  842. }
  843. // rank determins the total order among linkTypes. A link type of rank A can link to another link
  844. // type of rank B only when B <= A
  845. func (lt linkType) rank() int {
  846. return int(lt)
  847. }
  848. type linkTypeContext interface {
  849. android.Module
  850. getLinkType(name string) (ret linkType, stubs bool)
  851. }
  852. func (m *Module) getLinkType(name string) (ret linkType, stubs bool) {
  853. switch name {
  854. case "core.current.stubs", "legacy.core.platform.api.stubs", "stable.core.platform.api.stubs",
  855. "stub-annotations", "private-stub-annotations-jar",
  856. "core-lambda-stubs", "core-generated-annotation-stubs":
  857. return javaCore, true
  858. case "android_stubs_current":
  859. return javaSdk, true
  860. case "android_system_stubs_current":
  861. return javaSystem, true
  862. case "android_module_lib_stubs_current":
  863. return javaModule, true
  864. case "android_system_server_stubs_current":
  865. return javaSystemServer, true
  866. case "android_test_stubs_current":
  867. return javaSystem, true
  868. }
  869. if stub, linkType := moduleStubLinkType(name); stub {
  870. return linkType, true
  871. }
  872. ver := m.sdkVersion()
  873. switch ver.kind {
  874. case sdkCore:
  875. return javaCore, false
  876. case sdkSystem:
  877. return javaSystem, false
  878. case sdkPublic:
  879. return javaSdk, false
  880. case sdkModule:
  881. return javaModule, false
  882. case sdkSystemServer:
  883. return javaSystemServer, false
  884. case sdkPrivate, sdkNone, sdkCorePlatform, sdkTest:
  885. return javaPlatform, false
  886. }
  887. if !ver.valid() {
  888. panic(fmt.Errorf("sdk_version is invalid. got %q", ver.raw))
  889. }
  890. return javaSdk, false
  891. }
  892. func checkLinkType(ctx android.ModuleContext, from *Module, to linkTypeContext, tag dependencyTag) {
  893. if ctx.Host() {
  894. return
  895. }
  896. myLinkType, stubs := from.getLinkType(ctx.ModuleName())
  897. if stubs {
  898. return
  899. }
  900. otherLinkType, _ := to.getLinkType(ctx.OtherModuleName(to))
  901. if myLinkType.rank() < otherLinkType.rank() {
  902. ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
  903. "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
  904. "property of the source or target module so that target module is built "+
  905. "with the same or smaller API set when compared to the source.",
  906. myLinkType, ctx.OtherModuleName(to), otherLinkType)
  907. }
  908. }
  909. func (j *Module) collectDeps(ctx android.ModuleContext) deps {
  910. var deps deps
  911. if ctx.Device() {
  912. sdkDep := decodeSdkDep(ctx, sdkContext(j))
  913. if sdkDep.invalidVersion {
  914. ctx.AddMissingDependencies(sdkDep.bootclasspath)
  915. ctx.AddMissingDependencies(sdkDep.java9Classpath)
  916. } else if sdkDep.useFiles {
  917. // sdkDep.jar is actually equivalent to turbine header.jar.
  918. deps.classpath = append(deps.classpath, sdkDep.jars...)
  919. deps.aidlPreprocess = sdkDep.aidl
  920. } else {
  921. deps.aidlPreprocess = sdkDep.aidl
  922. }
  923. }
  924. linkType, _ := j.getLinkType(ctx.ModuleName())
  925. ctx.VisitDirectDeps(func(module android.Module) {
  926. otherName := ctx.OtherModuleName(module)
  927. tag := ctx.OtherModuleDependencyTag(module)
  928. if IsJniDepTag(tag) {
  929. // Handled by AndroidApp.collectAppDeps
  930. return
  931. }
  932. if tag == certificateTag {
  933. // Handled by AndroidApp.collectAppDeps
  934. return
  935. }
  936. if dep, ok := module.(SdkLibraryDependency); ok {
  937. switch tag {
  938. case libTag:
  939. deps.classpath = append(deps.classpath, dep.SdkHeaderJars(ctx, j.sdkVersion())...)
  940. case staticLibTag:
  941. ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
  942. }
  943. } else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
  944. dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
  945. if linkType != javaPlatform &&
  946. ctx.OtherModuleHasProvider(module, SyspropPublicStubInfoProvider) {
  947. // dep is a sysprop implementation library, but this module is not linking against
  948. // the platform, so it gets the sysprop public stubs library instead. Replace
  949. // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
  950. syspropDep := ctx.OtherModuleProvider(module, SyspropPublicStubInfoProvider).(SyspropPublicStubInfo)
  951. dep = syspropDep.JavaInfo
  952. }
  953. switch tag {
  954. case bootClasspathTag:
  955. deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
  956. case libTag, instrumentationForTag:
  957. deps.classpath = append(deps.classpath, dep.HeaderJars...)
  958. deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
  959. addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
  960. deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
  961. case java9LibTag:
  962. deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
  963. case staticLibTag:
  964. deps.classpath = append(deps.classpath, dep.HeaderJars...)
  965. deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
  966. deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
  967. deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
  968. deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
  969. addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
  970. // Turbine doesn't run annotation processors, so any module that uses an
  971. // annotation processor that generates API is incompatible with the turbine
  972. // optimization.
  973. deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
  974. case pluginTag:
  975. if plugin, ok := module.(*Plugin); ok {
  976. if plugin.pluginProperties.Processor_class != nil {
  977. addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
  978. } else {
  979. addPlugins(&deps, dep.ImplementationAndResourcesJars)
  980. }
  981. // Turbine doesn't run annotation processors, so any module that uses an
  982. // annotation processor that generates API is incompatible with the turbine
  983. // optimization.
  984. deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
  985. } else {
  986. ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
  987. }
  988. case errorpronePluginTag:
  989. if _, ok := module.(*Plugin); ok {
  990. deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
  991. } else {
  992. ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
  993. }
  994. case exportedPluginTag:
  995. if plugin, ok := module.(*Plugin); ok {
  996. j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
  997. if plugin.pluginProperties.Processor_class != nil {
  998. j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
  999. }
  1000. // Turbine doesn't run annotation processors, so any module that uses an
  1001. // annotation processor that generates API is incompatible with the turbine
  1002. // optimization.
  1003. j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
  1004. } else {
  1005. ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
  1006. }
  1007. case kotlinStdlibTag:
  1008. deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
  1009. case kotlinAnnotationsTag:
  1010. deps.kotlinAnnotations = dep.HeaderJars
  1011. case syspropPublicStubDepTag:
  1012. // This is a sysprop implementation library, forward the JavaInfoProvider from
  1013. // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
  1014. ctx.SetProvider(SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
  1015. JavaInfo: dep,
  1016. })
  1017. }
  1018. } else if dep, ok := module.(android.SourceFileProducer); ok {
  1019. switch tag {
  1020. case libTag:
  1021. checkProducesJars(ctx, dep)
  1022. deps.classpath = append(deps.classpath, dep.Srcs()...)
  1023. case staticLibTag:
  1024. checkProducesJars(ctx, dep)
  1025. deps.classpath = append(deps.classpath, dep.Srcs()...)
  1026. deps.staticJars = append(deps.staticJars, dep.Srcs()...)
  1027. deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
  1028. }
  1029. } else {
  1030. switch tag {
  1031. case bootClasspathTag:
  1032. // If a system modules dependency has been added to the bootclasspath
  1033. // then add its libs to the bootclasspath.
  1034. sm := module.(SystemModulesProvider)
  1035. deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
  1036. case systemModulesTag:
  1037. if deps.systemModules != nil {
  1038. panic("Found two system module dependencies")
  1039. }
  1040. sm := module.(SystemModulesProvider)
  1041. outputDir, outputDeps := sm.OutputDirAndDeps()
  1042. deps.systemModules = &systemModules{outputDir, outputDeps}
  1043. }
  1044. }
  1045. addCLCFromDep(ctx, module, j.classLoaderContexts)
  1046. })
  1047. return deps
  1048. }
  1049. func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
  1050. deps.processorPath = append(deps.processorPath, pluginJars...)
  1051. deps.processorClasses = append(deps.processorClasses, pluginClasses...)
  1052. }
  1053. func getJavaVersion(ctx android.ModuleContext, javaVersion string, sdkContext sdkContext) javaVersion {
  1054. if javaVersion != "" {
  1055. return normalizeJavaVersion(ctx, javaVersion)
  1056. } else if ctx.Device() {
  1057. return sdkContext.sdkVersion().defaultJavaLanguageVersion(ctx)
  1058. } else {
  1059. return JAVA_VERSION_9
  1060. }
  1061. }
  1062. type javaVersion int
  1063. const (
  1064. JAVA_VERSION_UNSUPPORTED = 0
  1065. JAVA_VERSION_6 = 6
  1066. JAVA_VERSION_7 = 7
  1067. JAVA_VERSION_8 = 8
  1068. JAVA_VERSION_9 = 9
  1069. )
  1070. func (v javaVersion) String() string {
  1071. switch v {
  1072. case JAVA_VERSION_6:
  1073. return "1.6"
  1074. case JAVA_VERSION_7:
  1075. return "1.7"
  1076. case JAVA_VERSION_8:
  1077. return "1.8"
  1078. case JAVA_VERSION_9:
  1079. return "1.9"
  1080. default:
  1081. return "unsupported"
  1082. }
  1083. }
  1084. // Returns true if javac targeting this version uses system modules instead of a bootclasspath.
  1085. func (v javaVersion) usesJavaModules() bool {
  1086. return v >= 9
  1087. }
  1088. func normalizeJavaVersion(ctx android.BaseModuleContext, javaVersion string) javaVersion {
  1089. switch javaVersion {
  1090. case "1.6", "6":
  1091. return JAVA_VERSION_6
  1092. case "1.7", "7":
  1093. return JAVA_VERSION_7
  1094. case "1.8", "8":
  1095. return JAVA_VERSION_8
  1096. case "1.9", "9":
  1097. return JAVA_VERSION_9
  1098. case "10", "11":
  1099. ctx.PropertyErrorf("java_version", "Java language levels above 9 are not supported")
  1100. return JAVA_VERSION_UNSUPPORTED
  1101. default:
  1102. ctx.PropertyErrorf("java_version", "Unrecognized Java language level")
  1103. return JAVA_VERSION_UNSUPPORTED
  1104. }
  1105. }
  1106. func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
  1107. var flags javaBuilderFlags
  1108. // javaVersion flag.
  1109. flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), sdkContext(j))
  1110. if ctx.Config().RunErrorProne() {
  1111. if config.ErrorProneClasspath == nil && ctx.Config().TestProductVariables == nil {
  1112. ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
  1113. }
  1114. errorProneFlags := []string{
  1115. "-Xplugin:ErrorProne",
  1116. "${config.ErrorProneChecks}",
  1117. }
  1118. errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
  1119. flags.errorProneExtraJavacFlags = "${config.ErrorProneFlags} " +
  1120. "'" + strings.Join(errorProneFlags, " ") + "'"
  1121. flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
  1122. }
  1123. // classpath
  1124. flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
  1125. flags.classpath = append(flags.classpath, deps.classpath...)
  1126. flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
  1127. flags.processorPath = append(flags.processorPath, deps.processorPath...)
  1128. flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
  1129. flags.processors = append(flags.processors, deps.processorClasses...)
  1130. flags.processors = android.FirstUniqueStrings(flags.processors)
  1131. if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
  1132. decodeSdkDep(ctx, sdkContext(j)).hasStandardLibs() {
  1133. // Give host-side tools a version of OpenJDK's standard libraries
  1134. // close to what they're targeting. As of Dec 2017, AOSP is only
  1135. // bundling OpenJDK 8 and 9, so nothing < 8 is available.
  1136. //
  1137. // When building with OpenJDK 8, the following should have no
  1138. // effect since those jars would be available by default.
  1139. //
  1140. // When building with OpenJDK 9 but targeting a version < 1.8,
  1141. // putting them on the bootclasspath means that:
  1142. // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
  1143. // b) references to existing APIs are not reinterpreted in an
  1144. // OpenJDK 9-specific way, eg. calls to subclasses of
  1145. // java.nio.Buffer as in http://b/70862583
  1146. java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
  1147. flags.bootClasspath = append(flags.bootClasspath,
  1148. android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
  1149. android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
  1150. if Bool(j.properties.Use_tools_jar) {
  1151. flags.bootClasspath = append(flags.bootClasspath,
  1152. android.PathForSource(ctx, java8Home, "lib/tools.jar"))
  1153. }
  1154. }
  1155. // systemModules
  1156. flags.systemModules = deps.systemModules
  1157. // aidl flags.
  1158. flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs)
  1159. return flags
  1160. }
  1161. func (j *Module) collectJavacFlags(
  1162. ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
  1163. // javac flags.
  1164. javacFlags := j.properties.Javacflags
  1165. if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() {
  1166. // For non-host binaries, override the -g flag passed globally to remove
  1167. // local variable debug info to reduce disk and memory usage.
  1168. javacFlags = append(javacFlags, "-g:source,lines")
  1169. }
  1170. javacFlags = append(javacFlags, "-Xlint:-dep-ann")
  1171. if flags.javaVersion.usesJavaModules() {
  1172. javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
  1173. if j.properties.Patch_module != nil {
  1174. // Manually specify build directory in case it is not under the repo root.
  1175. // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
  1176. // just adding a symlink under the root doesn't help.)
  1177. patchPaths := []string{".", ctx.Config().BuildDir()}
  1178. // b/150878007
  1179. //
  1180. // Workaround to support *Bazel-executed* JDK9 javac in Bazel's
  1181. // execution root for --patch-module. If this javac command line is
  1182. // invoked within Bazel's execution root working directory, the top
  1183. // level directories (e.g. libcore/, tools/, frameworks/) are all
  1184. // symlinks. JDK9 javac does not traverse into symlinks, which causes
  1185. // --patch-module to fail source file lookups when invoked in the
  1186. // execution root.
  1187. //
  1188. // Short of patching javac or enumerating *all* directories as possible
  1189. // input dirs, manually add the top level dir of the source files to be
  1190. // compiled.
  1191. topLevelDirs := map[string]bool{}
  1192. for _, srcFilePath := range srcFiles {
  1193. srcFileParts := strings.Split(srcFilePath.String(), "/")
  1194. // Ignore source files that are already in the top level directory
  1195. // as well as generated files in the out directory. The out
  1196. // directory may be an absolute path, which means srcFileParts[0] is the
  1197. // empty string, so check that as well. Note that "out" in Bazel's execution
  1198. // root is *not* a symlink, which doesn't cause problems for --patch-modules
  1199. // anyway, so it's fine to not apply this workaround for generated
  1200. // source files.
  1201. if len(srcFileParts) > 1 &&
  1202. srcFileParts[0] != "" &&
  1203. srcFileParts[0] != "out" {
  1204. topLevelDirs[srcFileParts[0]] = true
  1205. }
  1206. }
  1207. patchPaths = append(patchPaths, android.SortedStringKeys(topLevelDirs)...)
  1208. classPath := flags.classpath.FormJavaClassPath("")
  1209. if classPath != "" {
  1210. patchPaths = append(patchPaths, classPath)
  1211. }
  1212. javacFlags = append(
  1213. javacFlags,
  1214. "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
  1215. }
  1216. }
  1217. if len(javacFlags) > 0 {
  1218. // optimization.
  1219. ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
  1220. flags.javacFlags = "$javacFlags"
  1221. }
  1222. return flags
  1223. }
  1224. func (j *Module) compile(ctx android.ModuleContext, aaptSrcJar android.Path) {
  1225. j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
  1226. deps := j.collectDeps(ctx)
  1227. flags := j.collectBuilderFlags(ctx, deps)
  1228. if flags.javaVersion.usesJavaModules() {
  1229. j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
  1230. }
  1231. srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
  1232. if hasSrcExt(srcFiles.Strings(), ".proto") {
  1233. flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
  1234. }
  1235. kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
  1236. if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
  1237. ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
  1238. }
  1239. srcFiles = j.genSources(ctx, srcFiles, flags)
  1240. // Collect javac flags only after computing the full set of srcFiles to
  1241. // ensure that the --patch-module lookup paths are complete.
  1242. flags = j.collectJavacFlags(ctx, flags, srcFiles)
  1243. srcJars := srcFiles.FilterByExt(".srcjar")
  1244. srcJars = append(srcJars, deps.srcJars...)
  1245. if aaptSrcJar != nil {
  1246. srcJars = append(srcJars, aaptSrcJar)
  1247. }
  1248. if j.properties.Jarjar_rules != nil {
  1249. j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
  1250. }
  1251. jarName := ctx.ModuleName() + ".jar"
  1252. javaSrcFiles := srcFiles.FilterByExt(".java")
  1253. var uniqueSrcFiles android.Paths
  1254. set := make(map[string]bool)
  1255. for _, v := range javaSrcFiles {
  1256. if _, found := set[v.String()]; !found {
  1257. set[v.String()] = true
  1258. uniqueSrcFiles = append(uniqueSrcFiles, v)
  1259. }
  1260. }
  1261. // Collect .java files for AIDEGen
  1262. j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
  1263. var kotlinJars android.Paths
  1264. if srcFiles.HasExt(".kt") {
  1265. // user defined kotlin flags.
  1266. kotlincFlags := j.properties.Kotlincflags
  1267. CheckKotlincFlags(ctx, kotlincFlags)
  1268. // Dogfood the JVM_IR backend.
  1269. kotlincFlags = append(kotlincFlags, "-Xuse-ir")
  1270. // If there are kotlin files, compile them first but pass all the kotlin and java files
  1271. // kotlinc will use the java files to resolve types referenced by the kotlin files, but
  1272. // won't emit any classes for them.
  1273. kotlincFlags = append(kotlincFlags, "-no-stdlib")
  1274. if ctx.Device() {
  1275. kotlincFlags = append(kotlincFlags, "-no-jdk")
  1276. }
  1277. if len(kotlincFlags) > 0 {
  1278. // optimization.
  1279. ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
  1280. flags.kotlincFlags += "$kotlincFlags"
  1281. }
  1282. var kotlinSrcFiles android.Paths
  1283. kotlinSrcFiles = append(kotlinSrcFiles, uniqueSrcFiles...)
  1284. kotlinSrcFiles = append(kotlinSrcFiles, srcFiles.FilterByExt(".kt")...)
  1285. // Collect .kt files for AIDEGen
  1286. j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, srcFiles.FilterByExt(".kt").Strings()...)
  1287. j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
  1288. flags.classpath = append(flags.classpath, deps.kotlinStdlib...)
  1289. flags.classpath = append(flags.classpath, deps.kotlinAnnotations...)
  1290. flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
  1291. flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
  1292. if len(flags.processorPath) > 0 {
  1293. // Use kapt for annotation processing
  1294. kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
  1295. kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
  1296. kotlinKapt(ctx, kaptSrcJar, kaptResJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
  1297. srcJars = append(srcJars, kaptSrcJar)
  1298. kotlinJars = append(kotlinJars, kaptResJar)
  1299. // Disable annotation processing in javac, it's already been handled by kapt
  1300. flags.processorPath = nil
  1301. flags.processors = nil
  1302. }
  1303. kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
  1304. kotlinCompile(ctx, kotlinJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
  1305. if ctx.Failed() {
  1306. return
  1307. }
  1308. // Make javac rule depend on the kotlinc rule
  1309. flags.classpath = append(flags.classpath, kotlinJar)
  1310. kotlinJars = append(kotlinJars, kotlinJar)
  1311. // Jar kotlin classes into the final jar after javac
  1312. if BoolDefault(j.properties.Static_kotlin_stdlib, true) {
  1313. kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
  1314. }
  1315. }
  1316. jars := append(android.Paths(nil), kotlinJars...)
  1317. // Store the list of .java files that was passed to javac
  1318. j.compiledJavaSrcs = uniqueSrcFiles
  1319. j.compiledSrcJars = srcJars
  1320. enableSharding := false
  1321. var headerJarFileWithoutJarjar android.Path
  1322. if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !deps.disableTurbine {
  1323. if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
  1324. enableSharding = true
  1325. // Formerly, there was a check here that prevented annotation processors
  1326. // from being used when sharding was enabled, as some annotation processors
  1327. // do not function correctly in sharded environments. It was removed to
  1328. // allow for the use of annotation processors that do function correctly
  1329. // with sharding enabled. See: b/77284273.
  1330. }
  1331. headerJarFileWithoutJarjar, j.headerJarFile =
  1332. j.compileJavaHeader(ctx, uniqueSrcFiles, srcJars, deps, flags, jarName, kotlinJars)
  1333. if ctx.Failed() {
  1334. return
  1335. }
  1336. }
  1337. if len(uniqueSrcFiles) > 0 || len(srcJars) > 0 {
  1338. var extraJarDeps android.Paths
  1339. if ctx.Config().RunErrorProne() {
  1340. // If error-prone is enabled, add an additional rule to compile the java files into
  1341. // a separate set of classes (so that they don't overwrite the normal ones and require
  1342. // a rebuild when error-prone is turned off).
  1343. // TODO(ccross): Once we always compile with javac9 we may be able to conditionally
  1344. // enable error-prone without affecting the output class files.
  1345. errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
  1346. RunErrorProne(ctx, errorprone, uniqueSrcFiles, srcJars, flags)
  1347. extraJarDeps = append(extraJarDeps, errorprone)
  1348. }
  1349. if enableSharding {
  1350. flags.classpath = append(flags.classpath, headerJarFileWithoutJarjar)
  1351. shardSize := int(*(j.properties.Javac_shard_size))
  1352. var shardSrcs []android.Paths
  1353. if len(uniqueSrcFiles) > 0 {
  1354. shardSrcs = android.ShardPaths(uniqueSrcFiles, shardSize)
  1355. for idx, shardSrc := range shardSrcs {
  1356. classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
  1357. nil, flags, extraJarDeps)
  1358. jars = append(jars, classes)
  1359. }
  1360. }
  1361. if len(srcJars) > 0 {
  1362. classes := j.compileJavaClasses(ctx, jarName, len(shardSrcs),
  1363. nil, srcJars, flags, extraJarDeps)
  1364. jars = append(jars, classes)
  1365. }
  1366. } else {
  1367. classes := j.compileJavaClasses(ctx, jarName, -1, uniqueSrcFiles, srcJars, flags, extraJarDeps)
  1368. jars = append(jars, classes)
  1369. }
  1370. if ctx.Failed() {
  1371. return
  1372. }
  1373. }
  1374. j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
  1375. var includeSrcJar android.WritablePath
  1376. if Bool(j.properties.Include_srcs) {
  1377. includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
  1378. TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
  1379. }
  1380. dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
  1381. j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
  1382. fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
  1383. extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
  1384. var resArgs []string
  1385. var resDeps android.Paths
  1386. resArgs = append(resArgs, dirArgs...)
  1387. resDeps = append(resDeps, dirDeps...)
  1388. resArgs = append(resArgs, fileArgs...)
  1389. resDeps = append(resDeps, fileDeps...)
  1390. resArgs = append(resArgs, extraArgs...)
  1391. resDeps = append(resDeps, extraDeps...)
  1392. if len(resArgs) > 0 {
  1393. resourceJar := android.PathForModuleOut(ctx, "res", jarName)
  1394. TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
  1395. j.resourceJar = resourceJar
  1396. if ctx.Failed() {
  1397. return
  1398. }
  1399. }
  1400. var resourceJars android.Paths
  1401. if j.resourceJar != nil {
  1402. resourceJars = append(resourceJars, j.resourceJar)
  1403. }
  1404. if Bool(j.properties.Include_srcs) {
  1405. resourceJars = append(resourceJars, includeSrcJar)
  1406. }
  1407. resourceJars = append(resourceJars, deps.staticResourceJars...)
  1408. if len(resourceJars) > 1 {
  1409. combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
  1410. TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
  1411. false, nil, nil)
  1412. j.resourceJar = combinedJar
  1413. } else if len(resourceJars) == 1 {
  1414. j.resourceJar = resourceJars[0]
  1415. }
  1416. if len(deps.staticJars) > 0 {
  1417. jars = append(jars, deps.staticJars...)
  1418. }
  1419. manifest := j.overrideManifest
  1420. if !manifest.Valid() && j.properties.Manifest != nil {
  1421. manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
  1422. }
  1423. services := android.PathsForModuleSrc(ctx, j.properties.Services)
  1424. if len(services) > 0 {
  1425. servicesJar := android.PathForModuleOut(ctx, "services", jarName)
  1426. var zipargs []string
  1427. for _, file := range services {
  1428. serviceFile := file.String()
  1429. zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
  1430. }
  1431. rule := zip
  1432. args := map[string]string{
  1433. "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
  1434. }
  1435. if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
  1436. rule = zipRE
  1437. args["implicits"] = strings.Join(services.Strings(), ",")
  1438. }
  1439. ctx.Build(pctx, android.BuildParams{
  1440. Rule: rule,
  1441. Output: servicesJar,
  1442. Implicits: services,
  1443. Args: args,
  1444. })
  1445. jars = append(jars, servicesJar)
  1446. }
  1447. // Combine the classes built from sources, any manifests, and any static libraries into
  1448. // classes.jar. If there is only one input jar this step will be skipped.
  1449. var outputFile android.OutputPath
  1450. if len(jars) == 1 && !manifest.Valid() {
  1451. // Optimization: skip the combine step as there is nothing to do
  1452. // TODO(ccross): this leaves any module-info.class files, but those should only come from
  1453. // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
  1454. // any if len(jars) == 1.
  1455. // Transform the single path to the jar into an OutputPath as that is required by the following
  1456. // code.
  1457. if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok {
  1458. // The path contains an embedded OutputPath so reuse that.
  1459. outputFile = moduleOutPath.OutputPath
  1460. } else if outputPath, ok := jars[0].(android.OutputPath); ok {
  1461. // The path is an OutputPath so reuse it directly.
  1462. outputFile = outputPath
  1463. } else {
  1464. // The file is not in the out directory so create an OutputPath into which it can be copied
  1465. // and which the following code can use to refer to it.
  1466. combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
  1467. ctx.Build(pctx, android.BuildParams{
  1468. Rule: android.Cp,
  1469. Input: jars[0],
  1470. Output: combinedJar,
  1471. })
  1472. outputFile = combinedJar.OutputPath
  1473. }
  1474. } else {
  1475. combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
  1476. TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
  1477. false, nil, nil)
  1478. outputFile = combinedJar.OutputPath
  1479. }
  1480. // jarjar implementation jar if necessary
  1481. if j.expandJarjarRules != nil {
  1482. // Transform classes.jar into classes-jarjar.jar
  1483. jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
  1484. TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
  1485. outputFile = jarjarFile
  1486. // jarjar resource jar if necessary
  1487. if j.resourceJar != nil {
  1488. resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
  1489. TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
  1490. j.resourceJar = resourceJarJarFile
  1491. }
  1492. if ctx.Failed() {
  1493. return
  1494. }
  1495. }
  1496. // Check package restrictions if necessary.
  1497. if len(j.properties.Permitted_packages) > 0 {
  1498. // Check packages and copy to package-checked file.
  1499. pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
  1500. CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
  1501. j.additionalCheckedModules = append(j.additionalCheckedModules, pkgckFile)
  1502. if ctx.Failed() {
  1503. return
  1504. }
  1505. }
  1506. j.implementationJarFile = outputFile
  1507. if j.headerJarFile == nil {
  1508. j.headerJarFile = j.implementationJarFile
  1509. }
  1510. if j.shouldInstrumentInApex(ctx) {
  1511. j.properties.Instrument = true
  1512. }
  1513. if j.shouldInstrument(ctx) {
  1514. outputFile = j.instrument(ctx, flags, outputFile, jarName)
  1515. }
  1516. // merge implementation jar with resources if necessary
  1517. implementationAndResourcesJar := outputFile
  1518. if j.resourceJar != nil {
  1519. jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
  1520. combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
  1521. TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
  1522. false, nil, nil)
  1523. implementationAndResourcesJar = combinedJar
  1524. }
  1525. j.implementationAndResourcesJar = implementationAndResourcesJar
  1526. // Enable dex compilation for the APEX variants, unless it is disabled explicitly
  1527. apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
  1528. if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
  1529. if j.dexProperties.Compile_dex == nil {
  1530. j.dexProperties.Compile_dex = proptools.BoolPtr(true)
  1531. }
  1532. if j.deviceProperties.Hostdex == nil {
  1533. j.deviceProperties.Hostdex = proptools.BoolPtr(true)
  1534. }
  1535. }
  1536. if ctx.Device() && (Bool(j.properties.Installable) || Bool(j.dexProperties.Compile_dex)) {
  1537. if j.hasCode(ctx) {
  1538. if j.shouldInstrumentStatic(ctx) {
  1539. j.dexer.extraProguardFlagFiles = append(j.dexer.extraProguardFlagFiles,
  1540. android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
  1541. }
  1542. // Dex compilation
  1543. var dexOutputFile android.OutputPath
  1544. dexOutputFile = j.dexer.compileDex(ctx, flags, j.minSdkVersion(), outputFile, jarName)
  1545. if ctx.Failed() {
  1546. return
  1547. }
  1548. // Hidden API CSV generation and dex encoding
  1549. dexOutputFile = j.hiddenAPIExtractAndEncode(ctx, dexOutputFile, j.implementationJarFile,
  1550. proptools.Bool(j.dexProperties.Uncompress_dex))
  1551. // merge dex jar with resources if necessary
  1552. if j.resourceJar != nil {
  1553. jars := android.Paths{dexOutputFile, j.resourceJar}
  1554. combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
  1555. TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
  1556. false, nil, nil)
  1557. if *j.dexProperties.Uncompress_dex {
  1558. combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
  1559. TransformZipAlign(ctx, combinedAlignedJar, combinedJar)
  1560. dexOutputFile = combinedAlignedJar
  1561. } else {
  1562. dexOutputFile = combinedJar
  1563. }
  1564. }
  1565. j.dexJarFile = dexOutputFile
  1566. // Dexpreopting
  1567. j.dexpreopt(ctx, dexOutputFile)
  1568. outputFile = dexOutputFile
  1569. } else {
  1570. // There is no code to compile into a dex jar, make sure the resources are propagated
  1571. // to the APK if this is an app.
  1572. outputFile = implementationAndResourcesJar
  1573. j.dexJarFile = j.resourceJar
  1574. }
  1575. if ctx.Failed() {
  1576. return
  1577. }
  1578. } else {
  1579. outputFile = implementationAndResourcesJar
  1580. }
  1581. if ctx.Device() {
  1582. lintSDKVersionString := func(sdkSpec sdkSpec) string {
  1583. if v := sdkSpec.version; v.isNumbered() {
  1584. return v.String()
  1585. } else {
  1586. return ctx.Config().DefaultAppTargetSdk(ctx).String()
  1587. }
  1588. }
  1589. j.linter.name = ctx.ModuleName()
  1590. j.linter.srcs = srcFiles
  1591. j.linter.srcJars = srcJars
  1592. j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
  1593. j.linter.classes = j.implementationJarFile
  1594. j.linter.minSdkVersion = lintSDKVersionString(j.minSdkVersion())
  1595. j.linter.targetSdkVersion = lintSDKVersionString(j.targetSdkVersion())
  1596. j.linter.compileSdkVersion = lintSDKVersionString(j.sdkVersion())
  1597. j.linter.javaLanguageLevel = flags.javaVersion.String()
  1598. j.linter.kotlinLanguageLevel = "1.3"
  1599. if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
  1600. j.linter.buildModuleReportZip = true
  1601. }
  1602. j.linter.lint(ctx)
  1603. }
  1604. ctx.CheckbuildFile(outputFile)
  1605. ctx.SetProvider(JavaInfoProvider, JavaInfo{
  1606. HeaderJars: android.PathsIfNonNil(j.headerJarFile),
  1607. ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
  1608. ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
  1609. ResourceJars: android.PathsIfNonNil(j.resourceJar),
  1610. AidlIncludeDirs: j.exportAidlIncludeDirs,
  1611. SrcJarArgs: j.srcJarArgs,
  1612. SrcJarDeps: j.srcJarDeps,
  1613. ExportedPlugins: j.exportedPluginJars,
  1614. ExportedPluginClasses: j.exportedPluginClasses,
  1615. ExportedPluginDisableTurbine: j.exportedDisableTurbine,
  1616. JacocoReportClassesFile: j.jacocoReportClassesFile,
  1617. })
  1618. // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
  1619. j.outputFile = outputFile.WithoutRel()
  1620. }
  1621. func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
  1622. srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
  1623. kzipName := pathtools.ReplaceExtension(jarName, "kzip")
  1624. if idx >= 0 {
  1625. kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
  1626. jarName += strconv.Itoa(idx)
  1627. }
  1628. classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
  1629. TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, flags, extraJarDeps)
  1630. if ctx.Config().EmitXrefRules() {
  1631. extractionFile := android.PathForModuleOut(ctx, kzipName)
  1632. emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
  1633. j.kytheFiles = append(j.kytheFiles, extractionFile)
  1634. }
  1635. return classes
  1636. }
  1637. // Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
  1638. // since some of these flags may be used internally.
  1639. func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
  1640. for _, flag := range flags {
  1641. flag = strings.TrimSpace(flag)
  1642. if !strings.HasPrefix(flag, "-") {
  1643. ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
  1644. } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
  1645. ctx.PropertyErrorf("kotlincflags",
  1646. "Bad flag: `%s`, only use internal compiler for consistency.", flag)
  1647. } else if inList(flag, config.KotlincIllegalFlags) {
  1648. ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
  1649. } else if flag == "-include-runtime" {
  1650. ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
  1651. } else {
  1652. args := strings.Split(flag, " ")
  1653. if args[0] == "-kotlin-home" {
  1654. ctx.PropertyErrorf("kotlincflags",
  1655. "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
  1656. }
  1657. }
  1658. }
  1659. }
  1660. func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
  1661. deps deps, flags javaBuilderFlags, jarName string,
  1662. extraJars android.Paths) (headerJar, jarjarHeaderJar android.Path) {
  1663. var jars android.Paths
  1664. if len(srcFiles) > 0 || len(srcJars) > 0 {
  1665. // Compile java sources into turbine.jar.
  1666. turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
  1667. TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
  1668. if ctx.Failed() {
  1669. return nil, nil
  1670. }
  1671. jars = append(jars, turbineJar)
  1672. }
  1673. jars = append(jars, extraJars...)
  1674. // Combine any static header libraries into classes-header.jar. If there is only
  1675. // one input jar this step will be skipped.
  1676. jars = append(jars, deps.staticHeaderJars...)
  1677. // we cannot skip the combine step for now if there is only one jar
  1678. // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
  1679. combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
  1680. TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
  1681. false, nil, []string{"META-INF/TRANSITIVE"})
  1682. headerJar = combinedJar
  1683. jarjarHeaderJar = combinedJar
  1684. if j.expandJarjarRules != nil {
  1685. // Transform classes.jar into classes-jarjar.jar
  1686. jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
  1687. TransformJarJar(ctx, jarjarFile, headerJar, j.expandJarjarRules)
  1688. jarjarHeaderJar = jarjarFile
  1689. if ctx.Failed() {
  1690. return nil, nil
  1691. }
  1692. }
  1693. return headerJar, jarjarHeaderJar
  1694. }
  1695. func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
  1696. classesJar android.Path, jarName string) android.OutputPath {
  1697. specs := j.jacocoModuleToZipCommand(ctx)
  1698. jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
  1699. instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
  1700. jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
  1701. j.jacocoReportClassesFile = jacocoReportClassesFile
  1702. return instrumentedJar
  1703. }
  1704. func (j *Module) HeaderJars() android.Paths {
  1705. if j.headerJarFile == nil {
  1706. return nil
  1707. }
  1708. return android.Paths{j.headerJarFile}
  1709. }
  1710. func (j *Module) ImplementationJars() android.Paths {
  1711. if j.implementationJarFile == nil {
  1712. return nil
  1713. }
  1714. return android.Paths{j.implementationJarFile}
  1715. }
  1716. func (j *Module) DexJarBuildPath() android.Path {
  1717. return j.dexJarFile
  1718. }
  1719. func (j *Module) DexJarInstallPath() android.Path {
  1720. return j.installFile
  1721. }
  1722. func (j *Module) ImplementationAndResourcesJars() android.Paths {
  1723. if j.implementationAndResourcesJar == nil {
  1724. return nil
  1725. }
  1726. return android.Paths{j.implementationAndResourcesJar}
  1727. }
  1728. func (j *Module) AidlIncludeDirs() android.Paths {
  1729. // exportAidlIncludeDirs is type android.Paths already
  1730. return j.exportAidlIncludeDirs
  1731. }
  1732. func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
  1733. return j.classLoaderContexts
  1734. }
  1735. var _ logtagsProducer = (*Module)(nil)
  1736. func (j *Module) logtags() android.Paths {
  1737. return j.logtagsSrcs
  1738. }
  1739. // Collect information for opening IDE project files in java/jdeps.go.
  1740. func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
  1741. dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
  1742. dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
  1743. dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
  1744. dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
  1745. if j.expandJarjarRules != nil {
  1746. dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
  1747. }
  1748. dpInfo.Paths = append(dpInfo.Paths, j.modulePaths...)
  1749. }
  1750. func (j *Module) CompilerDeps() []string {
  1751. jdeps := []string{}
  1752. jdeps = append(jdeps, j.properties.Libs...)
  1753. jdeps = append(jdeps, j.properties.Static_libs...)
  1754. return jdeps
  1755. }
  1756. func (j *Module) hasCode(ctx android.ModuleContext) bool {
  1757. srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
  1758. return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
  1759. }
  1760. // Implements android.ApexModule
  1761. func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
  1762. return j.depIsInSameApex(ctx, dep)
  1763. }
  1764. // Implements android.ApexModule
  1765. func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
  1766. sdkVersion android.ApiLevel) error {
  1767. sdkSpec := j.minSdkVersion()
  1768. if !sdkSpec.specified() {
  1769. return fmt.Errorf("min_sdk_version is not specified")
  1770. }
  1771. if sdkSpec.kind == sdkCore {
  1772. return nil
  1773. }
  1774. ver, err := sdkSpec.effectiveVersion(ctx)
  1775. if err != nil {
  1776. return err
  1777. }
  1778. if ver.ApiLevel(ctx).GreaterThan(sdkVersion) {
  1779. return fmt.Errorf("newer SDK(%v)", ver)
  1780. }
  1781. return nil
  1782. }
  1783. func (j *Module) Stem() string {
  1784. return proptools.StringDefault(j.deviceProperties.Stem, j.Name())
  1785. }
  1786. // ConfigurationName returns the name of the module as used in build configuration.
  1787. //
  1788. // This is usually the same as BaseModuleName() except for the <x>.impl libraries created by
  1789. // java_sdk_library in which case this is the BaseModuleName() without the ".impl" suffix,
  1790. // i.e. just <x>.
  1791. func (j *Module) ConfigurationName() string {
  1792. return proptools.StringDefault(j.deviceProperties.ConfigurationName, j.BaseModuleName())
  1793. }
  1794. func (j *Module) JacocoReportClassesFile() android.Path {
  1795. return j.jacocoReportClassesFile
  1796. }
  1797. func (j *Module) IsInstallable() bool {
  1798. return Bool(j.properties.Installable)
  1799. }
  1800. //
  1801. // Java libraries (.jar file)
  1802. //
  1803. type Library struct {
  1804. Module
  1805. InstallMixin func(ctx android.ModuleContext, installPath android.Path) (extraInstallDeps android.Paths)
  1806. }
  1807. var _ android.ApexModule = (*Library)(nil)
  1808. // Provides access to the list of permitted packages from updatable boot jars.
  1809. type PermittedPackagesForUpdatableBootJars interface {
  1810. PermittedPackagesForUpdatableBootJars() []string
  1811. }
  1812. var _ PermittedPackagesForUpdatableBootJars = (*Library)(nil)
  1813. func (j *Library) PermittedPackagesForUpdatableBootJars() []string {
  1814. return j.properties.Permitted_packages
  1815. }
  1816. func shouldUncompressDex(ctx android.ModuleContext, dexpreopter *dexpreopter) bool {
  1817. // Store uncompressed (and aligned) any dex files from jars in APEXes.
  1818. if apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo); !apexInfo.IsForPlatform() {
  1819. return true
  1820. }
  1821. // Store uncompressed (and do not strip) dex files from boot class path jars.
  1822. if inList(ctx.ModuleName(), ctx.Config().BootJars()) {
  1823. return true
  1824. }
  1825. // Store uncompressed dex files that are preopted on /system.
  1826. if !dexpreopter.dexpreoptDisabled(ctx) && (ctx.Host() || !odexOnSystemOther(ctx, dexpreopter.installPath)) {
  1827. return true
  1828. }
  1829. if ctx.Config().UncompressPrivAppDex() &&
  1830. inList(ctx.ModuleName(), ctx.Config().ModulesLoadedByPrivilegedModules()) {
  1831. return true
  1832. }
  1833. return false
  1834. }
  1835. func (j *Library) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  1836. // Initialize the hiddenapi structure. Pass in the configuration name rather than the module name
  1837. // so the hidden api will encode the <x>.impl java_ library created by java_sdk_library just as it
  1838. // would the <x> library if <x> was configured as a boot jar.
  1839. j.initHiddenAPI(ctx, j.ConfigurationName())
  1840. apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
  1841. if !apexInfo.IsForPlatform() {
  1842. j.hideApexVariantFromMake = true
  1843. }
  1844. j.checkSdkVersions(ctx)
  1845. j.dexpreopter.installPath = android.PathForModuleInstall(ctx, "framework", j.Stem()+".jar")
  1846. j.dexpreopter.isSDKLibrary = j.deviceProperties.IsSDKLibrary
  1847. if j.dexProperties.Uncompress_dex == nil {
  1848. // If the value was not force-set by the user, use reasonable default based on the module.
  1849. j.dexProperties.Uncompress_dex = proptools.BoolPtr(shouldUncompressDex(ctx, &j.dexpreopter))
  1850. }
  1851. j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
  1852. j.classLoaderContexts = make(dexpreopt.ClassLoaderContextMap)
  1853. j.compile(ctx, nil)
  1854. // Collect the module directory for IDE info in java/jdeps.go.
  1855. j.modulePaths = append(j.modulePaths, ctx.ModuleDir())
  1856. exclusivelyForApex := !apexInfo.IsForPlatform()
  1857. if (Bool(j.properties.Installable) || ctx.Host()) && !exclusivelyForApex {
  1858. var extraInstallDeps android.Paths
  1859. if j.InstallMixin != nil {
  1860. extraInstallDeps = j.InstallMixin(ctx, j.outputFile)
  1861. }
  1862. j.installFile = ctx.InstallFile(android.PathForModuleInstall(ctx, "framework"),
  1863. j.Stem()+".jar", j.outputFile, extraInstallDeps...)
  1864. }
  1865. }
  1866. func (j *Library) DepsMutator(ctx android.BottomUpMutatorContext) {
  1867. j.deps(ctx)
  1868. }
  1869. const (
  1870. aidlIncludeDir = "aidl"
  1871. javaDir = "java"
  1872. jarFileSuffix = ".jar"
  1873. testConfigSuffix = "-AndroidTest.xml"
  1874. )
  1875. // path to the jar file of a java library. Relative to <sdk_root>/<api_dir>
  1876. func sdkSnapshotFilePathForJar(osPrefix, name string) string {
  1877. return sdkSnapshotFilePathForMember(osPrefix, name, jarFileSuffix)
  1878. }
  1879. func sdkSnapshotFilePathForMember(osPrefix, name string, suffix string) string {
  1880. return filepath.Join(javaDir, osPrefix, name+suffix)
  1881. }
  1882. type librarySdkMemberType struct {
  1883. android.SdkMemberTypeBase
  1884. // Function to retrieve the appropriate output jar (implementation or header) from
  1885. // the library.
  1886. jarToExportGetter func(ctx android.SdkMemberContext, j *Library) android.Path
  1887. // Function to compute the snapshot relative path to which the named library's
  1888. // jar should be copied.
  1889. snapshotPathGetter func(osPrefix, name string) string
  1890. // True if only the jar should be copied to the snapshot, false if the jar plus any additional
  1891. // files like aidl files should also be copied.
  1892. onlyCopyJarToSnapshot bool
  1893. }
  1894. const (
  1895. onlyCopyJarToSnapshot = true
  1896. copyEverythingToSnapshot = false
  1897. )
  1898. func (mt *librarySdkMemberType) AddDependencies(mctx android.BottomUpMutatorContext, dependencyTag blueprint.DependencyTag, names []string) {
  1899. mctx.AddVariationDependencies(nil, dependencyTag, names...)
  1900. }
  1901. func (mt *librarySdkMemberType) IsInstance(module android.Module) bool {
  1902. _, ok := module.(*Library)
  1903. return ok
  1904. }
  1905. func (mt *librarySdkMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
  1906. return ctx.SnapshotBuilder().AddPrebuiltModule(member, "java_import")
  1907. }
  1908. func (mt *librarySdkMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
  1909. return &librarySdkMemberProperties{}
  1910. }
  1911. type librarySdkMemberProperties struct {
  1912. android.SdkMemberPropertiesBase
  1913. JarToExport android.Path `android:"arch_variant"`
  1914. AidlIncludeDirs android.Paths
  1915. }
  1916. func (p *librarySdkMemberProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
  1917. j := variant.(*Library)
  1918. p.JarToExport = ctx.MemberType().(*librarySdkMemberType).jarToExportGetter(ctx, j)
  1919. p.AidlIncludeDirs = j.AidlIncludeDirs()
  1920. }
  1921. func (p *librarySdkMemberProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
  1922. builder := ctx.SnapshotBuilder()
  1923. memberType := ctx.MemberType().(*librarySdkMemberType)
  1924. exportedJar := p.JarToExport
  1925. if exportedJar != nil {
  1926. // Delegate the creation of the snapshot relative path to the member type.
  1927. snapshotRelativeJavaLibPath := memberType.snapshotPathGetter(p.OsPrefix(), ctx.Name())
  1928. // Copy the exported jar to the snapshot.
  1929. builder.CopyToSnapshot(exportedJar, snapshotRelativeJavaLibPath)
  1930. propertySet.AddProperty("jars", []string{snapshotRelativeJavaLibPath})
  1931. }
  1932. // Do not copy anything else to the snapshot.
  1933. if memberType.onlyCopyJarToSnapshot {
  1934. return
  1935. }
  1936. aidlIncludeDirs := p.AidlIncludeDirs
  1937. if len(aidlIncludeDirs) != 0 {
  1938. sdkModuleContext := ctx.SdkModuleContext()
  1939. for _, dir := range aidlIncludeDirs {
  1940. // TODO(jiyong): copy parcelable declarations only
  1941. aidlFiles, _ := sdkModuleContext.GlobWithDeps(dir.String()+"/**/*.aidl", nil)
  1942. for _, file := range aidlFiles {
  1943. builder.CopyToSnapshot(android.PathForSource(sdkModuleContext, file), filepath.Join(aidlIncludeDir, file))
  1944. }
  1945. }
  1946. // TODO(b/151933053) - add aidl include dirs property
  1947. }
  1948. }
  1949. var javaHeaderLibsSdkMemberType android.SdkMemberType = &librarySdkMemberType{
  1950. android.SdkMemberTypeBase{
  1951. PropertyName: "java_header_libs",
  1952. SupportsSdk: true,
  1953. },
  1954. func(_ android.SdkMemberContext, j *Library) android.Path {
  1955. headerJars := j.HeaderJars()
  1956. if len(headerJars) != 1 {
  1957. panic(fmt.Errorf("there must be only one header jar from %q", j.Name()))
  1958. }
  1959. return headerJars[0]
  1960. },
  1961. sdkSnapshotFilePathForJar,
  1962. copyEverythingToSnapshot,
  1963. }
  1964. // java_library builds and links sources into a `.jar` file for the device, and possibly for the host as well.
  1965. //
  1966. // By default, a java_library has a single variant that produces a `.jar` file containing `.class` files that were
  1967. // compiled against the device bootclasspath. This jar is not suitable for installing on a device, but can be used
  1968. // as a `static_libs` dependency of another module.
  1969. //
  1970. // Specifying `installable: true` will product a `.jar` file containing `classes.dex` files, suitable for installing on
  1971. // a device.
  1972. //
  1973. // Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
  1974. // compiled against the host bootclasspath.
  1975. func LibraryFactory() android.Module {
  1976. module := &Library{}
  1977. module.addHostAndDeviceProperties()
  1978. module.initModuleAndImport(&module.ModuleBase)
  1979. android.InitApexModule(module)
  1980. android.InitSdkAwareModule(module)
  1981. InitJavaModule(module, android.HostAndDeviceSupported)
  1982. return module
  1983. }
  1984. // java_library_static is an obsolete alias for java_library.
  1985. func LibraryStaticFactory() android.Module {
  1986. return LibraryFactory()
  1987. }
  1988. // java_library_host builds and links sources into a `.jar` file for the host.
  1989. //
  1990. // A java_library_host has a single variant that produces a `.jar` file containing `.class` files that were
  1991. // compiled against the host bootclasspath.
  1992. func LibraryHostFactory() android.Module {
  1993. module := &Library{}
  1994. module.addHostProperties()
  1995. module.Module.properties.Installable = proptools.BoolPtr(true)
  1996. android.InitApexModule(module)
  1997. InitJavaModule(module, android.HostSupported)
  1998. return module
  1999. }
  2000. //
  2001. // Java Tests
  2002. //
  2003. // Test option struct.
  2004. type TestOptions struct {
  2005. // a list of extra test configuration files that should be installed with the module.
  2006. Extra_test_configs []string `android:"path,arch_variant"`
  2007. // If the test is a hostside(no device required) unittest that shall be run during presubmit check.
  2008. Unit_test *bool
  2009. }
  2010. type testProperties struct {
  2011. // list of compatibility suites (for example "cts", "vts") that the module should be
  2012. // installed into.
  2013. Test_suites []string `android:"arch_variant"`
  2014. // the name of the test configuration (for example "AndroidTest.xml") that should be
  2015. // installed with the module.
  2016. Test_config *string `android:"path,arch_variant"`
  2017. // the name of the test configuration template (for example "AndroidTestTemplate.xml") that
  2018. // should be installed with the module.
  2019. Test_config_template *string `android:"path,arch_variant"`
  2020. // list of files or filegroup modules that provide data that should be installed alongside
  2021. // the test
  2022. Data []string `android:"path"`
  2023. // Flag to indicate whether or not to create test config automatically. If AndroidTest.xml
  2024. // doesn't exist next to the Android.bp, this attribute doesn't need to be set to true
  2025. // explicitly.
  2026. Auto_gen_config *bool
  2027. // Add parameterized mainline modules to auto generated test config. The options will be
  2028. // handled by TradeFed to do downloading and installing the specified modules on the device.
  2029. Test_mainline_modules []string
  2030. // Test options.
  2031. Test_options TestOptions
  2032. }
  2033. type hostTestProperties struct {
  2034. // list of native binary modules that should be installed alongside the test
  2035. Data_native_bins []string `android:"arch_variant"`
  2036. }
  2037. type testHelperLibraryProperties struct {
  2038. // list of compatibility suites (for example "cts", "vts") that the module should be
  2039. // installed into.
  2040. Test_suites []string `android:"arch_variant"`
  2041. }
  2042. type prebuiltTestProperties struct {
  2043. // list of compatibility suites (for example "cts", "vts") that the module should be
  2044. // installed into.
  2045. Test_suites []string `android:"arch_variant"`
  2046. // the name of the test configuration (for example "AndroidTest.xml") that should be
  2047. // installed with the module.
  2048. Test_config *string `android:"path,arch_variant"`
  2049. }
  2050. type Test struct {
  2051. Library
  2052. testProperties testProperties
  2053. testConfig android.Path
  2054. extraTestConfigs android.Paths
  2055. data android.Paths
  2056. }
  2057. type TestHost struct {
  2058. Test
  2059. testHostProperties hostTestProperties
  2060. }
  2061. type TestHelperLibrary struct {
  2062. Library
  2063. testHelperLibraryProperties testHelperLibraryProperties
  2064. }
  2065. type JavaTestImport struct {
  2066. Import
  2067. prebuiltTestProperties prebuiltTestProperties
  2068. testConfig android.Path
  2069. dexJarFile android.Path
  2070. }
  2071. func (j *TestHost) DepsMutator(ctx android.BottomUpMutatorContext) {
  2072. if len(j.testHostProperties.Data_native_bins) > 0 {
  2073. for _, target := range ctx.MultiTargets() {
  2074. ctx.AddVariationDependencies(target.Variations(), dataNativeBinsTag, j.testHostProperties.Data_native_bins...)
  2075. }
  2076. }
  2077. j.deps(ctx)
  2078. }
  2079. func (j *Test) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  2080. j.testConfig = tradefed.AutoGenJavaTestConfig(ctx, j.testProperties.Test_config, j.testProperties.Test_config_template,
  2081. j.testProperties.Test_suites, j.testProperties.Auto_gen_config, j.testProperties.Test_options.Unit_test)
  2082. j.data = android.PathsForModuleSrc(ctx, j.testProperties.Data)
  2083. j.extraTestConfigs = android.PathsForModuleSrc(ctx, j.testProperties.Test_options.Extra_test_configs)
  2084. ctx.VisitDirectDepsWithTag(dataNativeBinsTag, func(dep android.Module) {
  2085. j.data = append(j.data, android.OutputFileForModule(ctx, dep, ""))
  2086. })
  2087. j.Library.GenerateAndroidBuildActions(ctx)
  2088. }
  2089. func (j *TestHelperLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  2090. j.Library.GenerateAndroidBuildActions(ctx)
  2091. }
  2092. func (j *JavaTestImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  2093. j.testConfig = tradefed.AutoGenJavaTestConfig(ctx, j.prebuiltTestProperties.Test_config, nil,
  2094. j.prebuiltTestProperties.Test_suites, nil, nil)
  2095. j.Import.GenerateAndroidBuildActions(ctx)
  2096. }
  2097. type testSdkMemberType struct {
  2098. android.SdkMemberTypeBase
  2099. }
  2100. func (mt *testSdkMemberType) AddDependencies(mctx android.BottomUpMutatorContext, dependencyTag blueprint.DependencyTag, names []string) {
  2101. mctx.AddVariationDependencies(nil, dependencyTag, names...)
  2102. }
  2103. func (mt *testSdkMemberType) IsInstance(module android.Module) bool {
  2104. _, ok := module.(*Test)
  2105. return ok
  2106. }
  2107. func (mt *testSdkMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
  2108. return ctx.SnapshotBuilder().AddPrebuiltModule(member, "java_test_import")
  2109. }
  2110. func (mt *testSdkMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
  2111. return &testSdkMemberProperties{}
  2112. }
  2113. type testSdkMemberProperties struct {
  2114. android.SdkMemberPropertiesBase
  2115. JarToExport android.Path
  2116. TestConfig android.Path
  2117. }
  2118. func (p *testSdkMemberProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
  2119. test := variant.(*Test)
  2120. implementationJars := test.ImplementationJars()
  2121. if len(implementationJars) != 1 {
  2122. panic(fmt.Errorf("there must be only one implementation jar from %q", test.Name()))
  2123. }
  2124. p.JarToExport = implementationJars[0]
  2125. p.TestConfig = test.testConfig
  2126. }
  2127. func (p *testSdkMemberProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
  2128. builder := ctx.SnapshotBuilder()
  2129. exportedJar := p.JarToExport
  2130. if exportedJar != nil {
  2131. snapshotRelativeJavaLibPath := sdkSnapshotFilePathForJar(p.OsPrefix(), ctx.Name())
  2132. builder.CopyToSnapshot(exportedJar, snapshotRelativeJavaLibPath)
  2133. propertySet.AddProperty("jars", []string{snapshotRelativeJavaLibPath})
  2134. }
  2135. testConfig := p.TestConfig
  2136. if testConfig != nil {
  2137. snapshotRelativeTestConfigPath := sdkSnapshotFilePathForMember(p.OsPrefix(), ctx.Name(), testConfigSuffix)
  2138. builder.CopyToSnapshot(testConfig, snapshotRelativeTestConfigPath)
  2139. propertySet.AddProperty("test_config", snapshotRelativeTestConfigPath)
  2140. }
  2141. }
  2142. // java_test builds a and links sources into a `.jar` file for the device, and possibly for the host as well, and
  2143. // creates an `AndroidTest.xml` file to allow running the test with `atest` or a `TEST_MAPPING` file.
  2144. //
  2145. // By default, a java_test has a single variant that produces a `.jar` file containing `classes.dex` files that were
  2146. // compiled against the device bootclasspath.
  2147. //
  2148. // Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
  2149. // compiled against the host bootclasspath.
  2150. func TestFactory() android.Module {
  2151. module := &Test{}
  2152. module.addHostAndDeviceProperties()
  2153. module.AddProperties(&module.testProperties)
  2154. module.Module.properties.Installable = proptools.BoolPtr(true)
  2155. module.Module.dexpreopter.isTest = true
  2156. module.Module.linter.test = true
  2157. InitJavaModule(module, android.HostAndDeviceSupported)
  2158. return module
  2159. }
  2160. // java_test_helper_library creates a java library and makes sure that it is added to the appropriate test suite.
  2161. func TestHelperLibraryFactory() android.Module {
  2162. module := &TestHelperLibrary{}
  2163. module.addHostAndDeviceProperties()
  2164. module.AddProperties(&module.testHelperLibraryProperties)
  2165. module.Module.properties.Installable = proptools.BoolPtr(true)
  2166. module.Module.dexpreopter.isTest = true
  2167. module.Module.linter.test = true
  2168. InitJavaModule(module, android.HostAndDeviceSupported)
  2169. return module
  2170. }
  2171. // java_test_import imports one or more `.jar` files into the build graph as if they were built by a java_test module
  2172. // and makes sure that it is added to the appropriate test suite.
  2173. //
  2174. // By default, a java_test_import has a single variant that expects a `.jar` file containing `.class` files that were
  2175. // compiled against an Android classpath.
  2176. //
  2177. // Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
  2178. // for host modules.
  2179. func JavaTestImportFactory() android.Module {
  2180. module := &JavaTestImport{}
  2181. module.AddProperties(
  2182. &module.Import.properties,
  2183. &module.prebuiltTestProperties)
  2184. module.Import.properties.Installable = proptools.BoolPtr(true)
  2185. android.InitPrebuiltModule(module, &module.properties.Jars)
  2186. android.InitApexModule(module)
  2187. android.InitSdkAwareModule(module)
  2188. InitJavaModule(module, android.HostAndDeviceSupported)
  2189. return module
  2190. }
  2191. // java_test_host builds a and links sources into a `.jar` file for the host, and creates an `AndroidTest.xml` file to
  2192. // allow running the test with `atest` or a `TEST_MAPPING` file.
  2193. //
  2194. // A java_test_host has a single variant that produces a `.jar` file containing `.class` files that were
  2195. // compiled against the host bootclasspath.
  2196. func TestHostFactory() android.Module {
  2197. module := &TestHost{}
  2198. module.addHostProperties()
  2199. module.AddProperties(&module.testProperties)
  2200. module.AddProperties(&module.testHostProperties)
  2201. module.Module.properties.Installable = proptools.BoolPtr(true)
  2202. InitJavaModuleMultiTargets(module, android.HostSupported)
  2203. return module
  2204. }
  2205. //
  2206. // Java Binaries (.jar file plus wrapper script)
  2207. //
  2208. type binaryProperties struct {
  2209. // installable script to execute the resulting jar
  2210. Wrapper *string `android:"path"`
  2211. // Name of the class containing main to be inserted into the manifest as Main-Class.
  2212. Main_class *string
  2213. // Names of modules containing JNI libraries that should be installed alongside the host
  2214. // variant of the binary.
  2215. Jni_libs []string
  2216. }
  2217. type Binary struct {
  2218. Library
  2219. binaryProperties binaryProperties
  2220. isWrapperVariant bool
  2221. wrapperFile android.Path
  2222. binaryFile android.InstallPath
  2223. }
  2224. func (j *Binary) HostToolPath() android.OptionalPath {
  2225. return android.OptionalPathForPath(j.binaryFile)
  2226. }
  2227. func (j *Binary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  2228. if ctx.Arch().ArchType == android.Common {
  2229. // Compile the jar
  2230. if j.binaryProperties.Main_class != nil {
  2231. if j.properties.Manifest != nil {
  2232. ctx.PropertyErrorf("main_class", "main_class cannot be used when manifest is set")
  2233. }
  2234. manifestFile := android.PathForModuleOut(ctx, "manifest.txt")
  2235. GenerateMainClassManifest(ctx, manifestFile, String(j.binaryProperties.Main_class))
  2236. j.overrideManifest = android.OptionalPathForPath(manifestFile)
  2237. }
  2238. j.Library.GenerateAndroidBuildActions(ctx)
  2239. } else {
  2240. // Handle the binary wrapper
  2241. j.isWrapperVariant = true
  2242. if j.binaryProperties.Wrapper != nil {
  2243. j.wrapperFile = android.PathForModuleSrc(ctx, *j.binaryProperties.Wrapper)
  2244. } else {
  2245. j.wrapperFile = android.PathForSource(ctx, "build/soong/scripts/jar-wrapper.sh")
  2246. }
  2247. // The host installation rules make the installed wrapper depend on all the dependencies
  2248. // of the wrapper variant, which will include the common variant's jar file and any JNI
  2249. // libraries. This is verified by TestBinary.
  2250. j.binaryFile = ctx.InstallExecutable(android.PathForModuleInstall(ctx, "bin"),
  2251. ctx.ModuleName(), j.wrapperFile)
  2252. }
  2253. }
  2254. func (j *Binary) DepsMutator(ctx android.BottomUpMutatorContext) {
  2255. if ctx.Arch().ArchType == android.Common || ctx.BazelConversionMode() {
  2256. j.deps(ctx)
  2257. }
  2258. if ctx.Arch().ArchType != android.Common || ctx.BazelConversionMode() {
  2259. // These dependencies ensure the host installation rules will install the jar file and
  2260. // the jni libraries when the wrapper is installed.
  2261. ctx.AddVariationDependencies(nil, jniInstallTag, j.binaryProperties.Jni_libs...)
  2262. ctx.AddVariationDependencies(
  2263. []blueprint.Variation{{Mutator: "arch", Variation: android.CommonArch.String()}},
  2264. binaryInstallTag, ctx.ModuleName())
  2265. }
  2266. }
  2267. // java_binary builds a `.jar` file and a shell script that executes it for the device, and possibly for the host
  2268. // as well.
  2269. //
  2270. // By default, a java_binary has a single variant that produces a `.jar` file containing `classes.dex` files that were
  2271. // compiled against the device bootclasspath.
  2272. //
  2273. // Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
  2274. // compiled against the host bootclasspath.
  2275. func BinaryFactory() android.Module {
  2276. module := &Binary{}
  2277. module.addHostAndDeviceProperties()
  2278. module.AddProperties(&module.binaryProperties)
  2279. module.Module.properties.Installable = proptools.BoolPtr(true)
  2280. android.InitAndroidArchModule(module, android.HostAndDeviceSupported, android.MultilibCommonFirst)
  2281. android.InitDefaultableModule(module)
  2282. return module
  2283. }
  2284. // java_binary_host builds a `.jar` file and a shell script that executes it for the host.
  2285. //
  2286. // A java_binary_host has a single variant that produces a `.jar` file containing `.class` files that were
  2287. // compiled against the host bootclasspath.
  2288. func BinaryHostFactory() android.Module {
  2289. module := &Binary{}
  2290. module.addHostProperties()
  2291. module.AddProperties(&module.binaryProperties)
  2292. module.Module.properties.Installable = proptools.BoolPtr(true)
  2293. android.InitAndroidArchModule(module, android.HostSupported, android.MultilibCommonFirst)
  2294. android.InitDefaultableModule(module)
  2295. return module
  2296. }
  2297. //
  2298. // Java prebuilts
  2299. //
  2300. type ImportProperties struct {
  2301. Jars []string `android:"path,arch_variant"`
  2302. Sdk_version *string
  2303. Installable *bool
  2304. // List of shared java libs that this module has dependencies to
  2305. Libs []string
  2306. // List of files to remove from the jar file(s)
  2307. Exclude_files []string
  2308. // List of directories to remove from the jar file(s)
  2309. Exclude_dirs []string
  2310. // if set to true, run Jetifier against .jar file. Defaults to false.
  2311. Jetifier *bool
  2312. // set the name of the output
  2313. Stem *string
  2314. Aidl struct {
  2315. // directories that should be added as include directories for any aidl sources of modules
  2316. // that depend on this module, as well as to aidl for this module.
  2317. Export_include_dirs []string
  2318. }
  2319. }
  2320. type Import struct {
  2321. android.ModuleBase
  2322. android.DefaultableModuleBase
  2323. android.ApexModuleBase
  2324. prebuilt android.Prebuilt
  2325. android.SdkBase
  2326. // Functionality common to Module and Import.
  2327. embeddableInModuleAndImport
  2328. hiddenAPI
  2329. dexer
  2330. dexpreopter
  2331. properties ImportProperties
  2332. // output file containing classes.dex and resources
  2333. dexJarFile android.Path
  2334. combinedClasspathFile android.Path
  2335. classLoaderContexts dexpreopt.ClassLoaderContextMap
  2336. exportAidlIncludeDirs android.Paths
  2337. hideApexVariantFromMake bool
  2338. }
  2339. func (j *Import) sdkVersion() sdkSpec {
  2340. return sdkSpecFrom(String(j.properties.Sdk_version))
  2341. }
  2342. func (j *Import) makeSdkVersion() string {
  2343. return j.sdkVersion().raw
  2344. }
  2345. func (j *Import) systemModules() string {
  2346. return "none"
  2347. }
  2348. func (j *Import) minSdkVersion() sdkSpec {
  2349. return j.sdkVersion()
  2350. }
  2351. func (j *Import) targetSdkVersion() sdkSpec {
  2352. return j.sdkVersion()
  2353. }
  2354. func (j *Import) MinSdkVersion() string {
  2355. return j.minSdkVersion().version.String()
  2356. }
  2357. func (j *Import) Prebuilt() *android.Prebuilt {
  2358. return &j.prebuilt
  2359. }
  2360. func (j *Import) PrebuiltSrcs() []string {
  2361. return j.properties.Jars
  2362. }
  2363. func (j *Import) Name() string {
  2364. return j.prebuilt.Name(j.ModuleBase.Name())
  2365. }
  2366. func (j *Import) Stem() string {
  2367. return proptools.StringDefault(j.properties.Stem, j.ModuleBase.Name())
  2368. }
  2369. func (a *Import) JacocoReportClassesFile() android.Path {
  2370. return nil
  2371. }
  2372. func (j *Import) LintDepSets() LintDepSets {
  2373. return LintDepSets{}
  2374. }
  2375. func (j *Import) DepsMutator(ctx android.BottomUpMutatorContext) {
  2376. ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
  2377. if ctx.Device() && Bool(j.dexProperties.Compile_dex) {
  2378. sdkDeps(ctx, sdkContext(j), j.dexer)
  2379. }
  2380. }
  2381. func (j *Import) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  2382. // Initialize the hiddenapi structure.
  2383. j.initHiddenAPI(ctx, j.BaseModuleName())
  2384. if !ctx.Provider(android.ApexInfoProvider).(android.ApexInfo).IsForPlatform() {
  2385. j.hideApexVariantFromMake = true
  2386. }
  2387. jars := android.PathsForModuleSrc(ctx, j.properties.Jars)
  2388. jarName := j.Stem() + ".jar"
  2389. outputFile := android.PathForModuleOut(ctx, "combined", jarName)
  2390. TransformJarsToJar(ctx, outputFile, "for prebuilts", jars, android.OptionalPath{},
  2391. false, j.properties.Exclude_files, j.properties.Exclude_dirs)
  2392. if Bool(j.properties.Jetifier) {
  2393. inputFile := outputFile
  2394. outputFile = android.PathForModuleOut(ctx, "jetifier", jarName)
  2395. TransformJetifier(ctx, outputFile, inputFile)
  2396. }
  2397. j.combinedClasspathFile = outputFile
  2398. j.classLoaderContexts = make(dexpreopt.ClassLoaderContextMap)
  2399. var flags javaBuilderFlags
  2400. var deapexerModule android.Module
  2401. ctx.VisitDirectDeps(func(module android.Module) {
  2402. tag := ctx.OtherModuleDependencyTag(module)
  2403. if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
  2404. dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
  2405. switch tag {
  2406. case libTag, staticLibTag:
  2407. flags.classpath = append(flags.classpath, dep.HeaderJars...)
  2408. case bootClasspathTag:
  2409. flags.bootClasspath = append(flags.bootClasspath, dep.HeaderJars...)
  2410. }
  2411. } else if dep, ok := module.(SdkLibraryDependency); ok {
  2412. switch tag {
  2413. case libTag:
  2414. flags.classpath = append(flags.classpath, dep.SdkHeaderJars(ctx, j.sdkVersion())...)
  2415. }
  2416. }
  2417. addCLCFromDep(ctx, module, j.classLoaderContexts)
  2418. // Save away the `deapexer` module on which this depends, if any.
  2419. if tag == android.DeapexerTag {
  2420. deapexerModule = module
  2421. }
  2422. })
  2423. if Bool(j.properties.Installable) {
  2424. ctx.InstallFile(android.PathForModuleInstall(ctx, "framework"),
  2425. jarName, outputFile)
  2426. }
  2427. j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.properties.Aidl.Export_include_dirs)
  2428. if ctx.Device() {
  2429. // If this is a variant created for a prebuilt_apex then use the dex implementation jar
  2430. // obtained from the associated deapexer module.
  2431. ai := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
  2432. if ai.ForPrebuiltApex {
  2433. if deapexerModule == nil {
  2434. // This should never happen as a variant for a prebuilt_apex is only created if the
  2435. // deapxer module has been configured to export the dex implementation jar for this module.
  2436. ctx.ModuleErrorf("internal error: module %q does not depend on a `deapexer` module for prebuilt_apex %q",
  2437. j.Name(), ai.ApexVariationName)
  2438. }
  2439. // Get the path of the dex implementation jar from the `deapexer` module.
  2440. di := ctx.OtherModuleProvider(deapexerModule, android.DeapexerProvider).(android.DeapexerInfo)
  2441. if dexOutputPath := di.PrebuiltExportPath(j.BaseModuleName(), ".dexjar"); dexOutputPath != nil {
  2442. j.dexJarFile = dexOutputPath
  2443. j.hiddenAPIExtractInformation(ctx, dexOutputPath, outputFile)
  2444. } else {
  2445. // This should never happen as a variant for a prebuilt_apex is only created if the
  2446. // prebuilt_apex has been configured to export the java library dex file.
  2447. ctx.ModuleErrorf("internal error: no dex implementation jar available from prebuilt_apex %q", deapexerModule.Name())
  2448. }
  2449. } else if Bool(j.dexProperties.Compile_dex) {
  2450. sdkDep := decodeSdkDep(ctx, sdkContext(j))
  2451. if sdkDep.invalidVersion {
  2452. ctx.AddMissingDependencies(sdkDep.bootclasspath)
  2453. ctx.AddMissingDependencies(sdkDep.java9Classpath)
  2454. } else if sdkDep.useFiles {
  2455. // sdkDep.jar is actually equivalent to turbine header.jar.
  2456. flags.classpath = append(flags.classpath, sdkDep.jars...)
  2457. }
  2458. // Dex compilation
  2459. j.dexpreopter.installPath = android.PathForModuleInstall(ctx, "framework", jarName)
  2460. if j.dexProperties.Uncompress_dex == nil {
  2461. // If the value was not force-set by the user, use reasonable default based on the module.
  2462. j.dexProperties.Uncompress_dex = proptools.BoolPtr(shouldUncompressDex(ctx, &j.dexpreopter))
  2463. }
  2464. j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
  2465. var dexOutputFile android.OutputPath
  2466. dexOutputFile = j.dexer.compileDex(ctx, flags, j.minSdkVersion(), outputFile, jarName)
  2467. if ctx.Failed() {
  2468. return
  2469. }
  2470. // Hidden API CSV generation and dex encoding
  2471. dexOutputFile = j.hiddenAPIExtractAndEncode(ctx, dexOutputFile, outputFile,
  2472. proptools.Bool(j.dexProperties.Uncompress_dex))
  2473. j.dexJarFile = dexOutputFile
  2474. }
  2475. }
  2476. ctx.SetProvider(JavaInfoProvider, JavaInfo{
  2477. HeaderJars: android.PathsIfNonNil(j.combinedClasspathFile),
  2478. ImplementationAndResourcesJars: android.PathsIfNonNil(j.combinedClasspathFile),
  2479. ImplementationJars: android.PathsIfNonNil(j.combinedClasspathFile),
  2480. AidlIncludeDirs: j.exportAidlIncludeDirs,
  2481. })
  2482. }
  2483. func (j *Import) OutputFiles(tag string) (android.Paths, error) {
  2484. switch tag {
  2485. case "", ".jar":
  2486. return android.Paths{j.combinedClasspathFile}, nil
  2487. default:
  2488. return nil, fmt.Errorf("unsupported module reference tag %q", tag)
  2489. }
  2490. }
  2491. var _ android.OutputFileProducer = (*Import)(nil)
  2492. func (j *Import) HeaderJars() android.Paths {
  2493. if j.combinedClasspathFile == nil {
  2494. return nil
  2495. }
  2496. return android.Paths{j.combinedClasspathFile}
  2497. }
  2498. func (j *Import) ImplementationAndResourcesJars() android.Paths {
  2499. if j.combinedClasspathFile == nil {
  2500. return nil
  2501. }
  2502. return android.Paths{j.combinedClasspathFile}
  2503. }
  2504. func (j *Import) DexJarBuildPath() android.Path {
  2505. return j.dexJarFile
  2506. }
  2507. func (j *Import) DexJarInstallPath() android.Path {
  2508. return nil
  2509. }
  2510. func (j *Import) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
  2511. return j.classLoaderContexts
  2512. }
  2513. var _ android.ApexModule = (*Import)(nil)
  2514. // Implements android.ApexModule
  2515. func (j *Import) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
  2516. return j.depIsInSameApex(ctx, dep)
  2517. }
  2518. // Implements android.ApexModule
  2519. func (j *Import) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
  2520. sdkVersion android.ApiLevel) error {
  2521. // Do not check for prebuilts against the min_sdk_version of enclosing APEX
  2522. return nil
  2523. }
  2524. // Add compile time check for interface implementation
  2525. var _ android.IDEInfo = (*Import)(nil)
  2526. var _ android.IDECustomizedModuleName = (*Import)(nil)
  2527. // Collect information for opening IDE project files in java/jdeps.go.
  2528. const (
  2529. removedPrefix = "prebuilt_"
  2530. )
  2531. func (j *Import) IDEInfo(dpInfo *android.IdeInfo) {
  2532. dpInfo.Jars = append(dpInfo.Jars, j.PrebuiltSrcs()...)
  2533. }
  2534. func (j *Import) IDECustomizedModuleName() string {
  2535. // TODO(b/113562217): Extract the base module name from the Import name, often the Import name
  2536. // has a prefix "prebuilt_". Remove the prefix explicitly if needed until we find a better
  2537. // solution to get the Import name.
  2538. name := j.Name()
  2539. if strings.HasPrefix(name, removedPrefix) {
  2540. name = strings.TrimPrefix(name, removedPrefix)
  2541. }
  2542. return name
  2543. }
  2544. var _ android.PrebuiltInterface = (*Import)(nil)
  2545. func (j *Import) IsInstallable() bool {
  2546. return Bool(j.properties.Installable)
  2547. }
  2548. var _ dexpreopterInterface = (*Import)(nil)
  2549. // java_import imports one or more `.jar` files into the build graph as if they were built by a java_library module.
  2550. //
  2551. // By default, a java_import has a single variant that expects a `.jar` file containing `.class` files that were
  2552. // compiled against an Android classpath.
  2553. //
  2554. // Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
  2555. // for host modules.
  2556. func ImportFactory() android.Module {
  2557. module := &Import{}
  2558. module.AddProperties(
  2559. &module.properties,
  2560. &module.dexer.dexProperties,
  2561. )
  2562. module.initModuleAndImport(&module.ModuleBase)
  2563. module.dexProperties.Optimize.EnabledByDefault = false
  2564. android.InitPrebuiltModule(module, &module.properties.Jars)
  2565. android.InitApexModule(module)
  2566. android.InitSdkAwareModule(module)
  2567. InitJavaModule(module, android.HostAndDeviceSupported)
  2568. return module
  2569. }
  2570. // java_import imports one or more `.jar` files into the build graph as if they were built by a java_library_host
  2571. // module.
  2572. //
  2573. // A java_import_host has a single variant that expects a `.jar` file containing `.class` files that were
  2574. // compiled against a host bootclasspath.
  2575. func ImportFactoryHost() android.Module {
  2576. module := &Import{}
  2577. module.AddProperties(&module.properties)
  2578. android.InitPrebuiltModule(module, &module.properties.Jars)
  2579. android.InitApexModule(module)
  2580. InitJavaModule(module, android.HostSupported)
  2581. return module
  2582. }
  2583. // dex_import module
  2584. type DexImportProperties struct {
  2585. Jars []string `android:"path"`
  2586. // set the name of the output
  2587. Stem *string
  2588. }
  2589. type DexImport struct {
  2590. android.ModuleBase
  2591. android.DefaultableModuleBase
  2592. android.ApexModuleBase
  2593. prebuilt android.Prebuilt
  2594. properties DexImportProperties
  2595. dexJarFile android.Path
  2596. dexpreopter
  2597. hideApexVariantFromMake bool
  2598. }
  2599. func (j *DexImport) Prebuilt() *android.Prebuilt {
  2600. return &j.prebuilt
  2601. }
  2602. func (j *DexImport) PrebuiltSrcs() []string {
  2603. return j.properties.Jars
  2604. }
  2605. func (j *DexImport) Name() string {
  2606. return j.prebuilt.Name(j.ModuleBase.Name())
  2607. }
  2608. func (j *DexImport) Stem() string {
  2609. return proptools.StringDefault(j.properties.Stem, j.ModuleBase.Name())
  2610. }
  2611. func (a *DexImport) JacocoReportClassesFile() android.Path {
  2612. return nil
  2613. }
  2614. func (a *DexImport) LintDepSets() LintDepSets {
  2615. return LintDepSets{}
  2616. }
  2617. func (j *DexImport) IsInstallable() bool {
  2618. return true
  2619. }
  2620. func (j *DexImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  2621. if len(j.properties.Jars) != 1 {
  2622. ctx.PropertyErrorf("jars", "exactly one jar must be provided")
  2623. }
  2624. apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
  2625. if !apexInfo.IsForPlatform() {
  2626. j.hideApexVariantFromMake = true
  2627. }
  2628. j.dexpreopter.installPath = android.PathForModuleInstall(ctx, "framework", j.Stem()+".jar")
  2629. j.dexpreopter.uncompressedDex = shouldUncompressDex(ctx, &j.dexpreopter)
  2630. inputJar := ctx.ExpandSource(j.properties.Jars[0], "jars")
  2631. dexOutputFile := android.PathForModuleOut(ctx, ctx.ModuleName()+".jar")
  2632. if j.dexpreopter.uncompressedDex {
  2633. rule := android.NewRuleBuilder(pctx, ctx)
  2634. temporary := android.PathForModuleOut(ctx, ctx.ModuleName()+".jar.unaligned")
  2635. rule.Temporary(temporary)
  2636. // use zip2zip to uncompress classes*.dex files
  2637. rule.Command().
  2638. BuiltTool("zip2zip").
  2639. FlagWithInput("-i ", inputJar).
  2640. FlagWithOutput("-o ", temporary).
  2641. FlagWithArg("-0 ", "'classes*.dex'")
  2642. // use zipalign to align uncompressed classes*.dex files
  2643. rule.Command().
  2644. BuiltTool("zipalign").
  2645. Flag("-f").
  2646. Text("4").
  2647. Input(temporary).
  2648. Output(dexOutputFile)
  2649. rule.DeleteTemporaryFiles()
  2650. rule.Build("uncompress_dex", "uncompress dex")
  2651. } else {
  2652. ctx.Build(pctx, android.BuildParams{
  2653. Rule: android.Cp,
  2654. Input: inputJar,
  2655. Output: dexOutputFile,
  2656. })
  2657. }
  2658. j.dexJarFile = dexOutputFile
  2659. j.dexpreopt(ctx, dexOutputFile)
  2660. if apexInfo.IsForPlatform() {
  2661. ctx.InstallFile(android.PathForModuleInstall(ctx, "framework"),
  2662. j.Stem()+".jar", dexOutputFile)
  2663. }
  2664. }
  2665. func (j *DexImport) DexJarBuildPath() android.Path {
  2666. return j.dexJarFile
  2667. }
  2668. var _ android.ApexModule = (*DexImport)(nil)
  2669. // Implements android.ApexModule
  2670. func (j *DexImport) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
  2671. sdkVersion android.ApiLevel) error {
  2672. // we don't check prebuilt modules for sdk_version
  2673. return nil
  2674. }
  2675. // dex_import imports a `.jar` file containing classes.dex files.
  2676. //
  2677. // A dex_import module cannot be used as a dependency of a java_* or android_* module, it can only be installed
  2678. // to the device.
  2679. func DexImportFactory() android.Module {
  2680. module := &DexImport{}
  2681. module.AddProperties(&module.properties)
  2682. android.InitPrebuiltModule(module, &module.properties.Jars)
  2683. android.InitApexModule(module)
  2684. InitJavaModule(module, android.DeviceSupported)
  2685. return module
  2686. }
  2687. //
  2688. // Defaults
  2689. //
  2690. type Defaults struct {
  2691. android.ModuleBase
  2692. android.DefaultsModuleBase
  2693. android.ApexModuleBase
  2694. }
  2695. // java_defaults provides a set of properties that can be inherited by other java or android modules.
  2696. //
  2697. // A module can use the properties from a java_defaults module using `defaults: ["defaults_module_name"]`. Each
  2698. // property in the defaults module that exists in the depending module will be prepended to the depending module's
  2699. // value for that property.
  2700. //
  2701. // Example:
  2702. //
  2703. // java_defaults {
  2704. // name: "example_defaults",
  2705. // srcs: ["common/**/*.java"],
  2706. // javacflags: ["-Xlint:all"],
  2707. // aaptflags: ["--auto-add-overlay"],
  2708. // }
  2709. //
  2710. // java_library {
  2711. // name: "example",
  2712. // defaults: ["example_defaults"],
  2713. // srcs: ["example/**/*.java"],
  2714. // }
  2715. //
  2716. // is functionally identical to:
  2717. //
  2718. // java_library {
  2719. // name: "example",
  2720. // srcs: [
  2721. // "common/**/*.java",
  2722. // "example/**/*.java",
  2723. // ],
  2724. // javacflags: ["-Xlint:all"],
  2725. // }
  2726. func defaultsFactory() android.Module {
  2727. return DefaultsFactory()
  2728. }
  2729. func DefaultsFactory() android.Module {
  2730. module := &Defaults{}
  2731. module.AddProperties(
  2732. &CompilerProperties{},
  2733. &CompilerDeviceProperties{},
  2734. &DexProperties{},
  2735. &DexpreoptProperties{},
  2736. &android.ProtoProperties{},
  2737. &aaptProperties{},
  2738. &androidLibraryProperties{},
  2739. &appProperties{},
  2740. &appTestProperties{},
  2741. &overridableAppProperties{},
  2742. &testProperties{},
  2743. &ImportProperties{},
  2744. &AARImportProperties{},
  2745. &sdkLibraryProperties{},
  2746. &commonToSdkLibraryAndImportProperties{},
  2747. &DexImportProperties{},
  2748. &android.ApexProperties{},
  2749. &RuntimeResourceOverlayProperties{},
  2750. &LintProperties{},
  2751. &appTestHelperAppProperties{},
  2752. )
  2753. android.InitDefaultsModule(module)
  2754. return module
  2755. }
  2756. func kytheExtractJavaFactory() android.Singleton {
  2757. return &kytheExtractJavaSingleton{}
  2758. }
  2759. type kytheExtractJavaSingleton struct {
  2760. }
  2761. func (ks *kytheExtractJavaSingleton) GenerateBuildActions(ctx android.SingletonContext) {
  2762. var xrefTargets android.Paths
  2763. ctx.VisitAllModules(func(module android.Module) {
  2764. if javaModule, ok := module.(xref); ok {
  2765. xrefTargets = append(xrefTargets, javaModule.XrefJavaFiles()...)
  2766. }
  2767. })
  2768. // TODO(asmundak): perhaps emit a rule to output a warning if there were no xrefTargets
  2769. if len(xrefTargets) > 0 {
  2770. ctx.Phony("xref_java", xrefTargets...)
  2771. }
  2772. }
  2773. var Bool = proptools.Bool
  2774. var BoolDefault = proptools.BoolDefault
  2775. var String = proptools.String
  2776. var inList = android.InList
  2777. // TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
  2778. // this interface.
  2779. type ProvidesUsesLib interface {
  2780. ProvidesUsesLib() *string
  2781. }
  2782. func (j *Module) ProvidesUsesLib() *string {
  2783. return j.usesLibraryProperties.Provides_uses_lib
  2784. }
  2785. // Add class loader context (CLC) of a given dependency to the current CLC.
  2786. func addCLCFromDep(ctx android.ModuleContext, depModule android.Module,
  2787. clcMap dexpreopt.ClassLoaderContextMap) {
  2788. dep, ok := depModule.(UsesLibraryDependency)
  2789. if !ok {
  2790. return
  2791. }
  2792. // Find out if the dependency is either an SDK library or an ordinary library that is disguised
  2793. // as an SDK library by the means of `provides_uses_lib` property. If yes, the library is itself
  2794. // a <uses-library> and should be added as a node in the CLC tree, and its CLC should be added
  2795. // as subtree of that node. Otherwise the library is not a <uses_library> and should not be
  2796. // added to CLC, but the transitive <uses-library> dependencies from its CLC should be added to
  2797. // the current CLC.
  2798. var implicitSdkLib *string
  2799. comp, isComp := depModule.(SdkLibraryComponentDependency)
  2800. if isComp {
  2801. implicitSdkLib = comp.OptionalImplicitSdkLibrary()
  2802. // OptionalImplicitSdkLibrary() may be nil so need to fall through to ProvidesUsesLib().
  2803. }
  2804. if implicitSdkLib == nil {
  2805. if ulib, ok := depModule.(ProvidesUsesLib); ok {
  2806. implicitSdkLib = ulib.ProvidesUsesLib()
  2807. }
  2808. }
  2809. depTag := ctx.OtherModuleDependencyTag(depModule)
  2810. if depTag == libTag || depTag == usesLibTag {
  2811. // Ok, propagate <uses-library> through non-static library dependencies.
  2812. } else if depTag == staticLibTag {
  2813. // Propagate <uses-library> through static library dependencies, unless it is a component
  2814. // library (such as stubs). Component libraries have a dependency on their SDK library,
  2815. // which should not be pulled just because of a static component library.
  2816. if implicitSdkLib != nil {
  2817. return
  2818. }
  2819. } else {
  2820. // Don't propagate <uses-library> for other dependency tags.
  2821. return
  2822. }
  2823. if implicitSdkLib != nil {
  2824. clcMap.AddContext(ctx, dexpreopt.AnySdkVersion, *implicitSdkLib,
  2825. dep.DexJarBuildPath(), dep.DexJarInstallPath(), dep.ClassLoaderContexts())
  2826. } else {
  2827. depName := ctx.OtherModuleName(depModule)
  2828. clcMap.AddContextMap(dep.ClassLoaderContexts(), depName)
  2829. }
  2830. }