sdk_library.go 106 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930
  1. // Copyright 2018 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. import (
  16. "fmt"
  17. "path"
  18. "path/filepath"
  19. "reflect"
  20. "regexp"
  21. "sort"
  22. "strconv"
  23. "strings"
  24. "sync"
  25. "github.com/google/blueprint"
  26. "github.com/google/blueprint/proptools"
  27. "android/soong/android"
  28. "android/soong/dexpreopt"
  29. )
  30. const (
  31. sdkXmlFileSuffix = ".xml"
  32. )
  33. // A tag to associated a dependency with a specific api scope.
  34. type scopeDependencyTag struct {
  35. blueprint.BaseDependencyTag
  36. name string
  37. apiScope *apiScope
  38. // Function for extracting appropriate path information from the dependency.
  39. depInfoExtractor func(paths *scopePaths, ctx android.ModuleContext, dep android.Module) error
  40. }
  41. // Extract tag specific information from the dependency.
  42. func (tag scopeDependencyTag) extractDepInfo(ctx android.ModuleContext, dep android.Module, paths *scopePaths) {
  43. err := tag.depInfoExtractor(paths, ctx, dep)
  44. if err != nil {
  45. ctx.ModuleErrorf("has an invalid {scopeDependencyTag: %s} dependency on module %s: %s", tag.name, ctx.OtherModuleName(dep), err.Error())
  46. }
  47. }
  48. var _ android.ReplaceSourceWithPrebuilt = (*scopeDependencyTag)(nil)
  49. func (tag scopeDependencyTag) ReplaceSourceWithPrebuilt() bool {
  50. return false
  51. }
  52. // Provides information about an api scope, e.g. public, system, test.
  53. type apiScope struct {
  54. // The name of the api scope, e.g. public, system, test
  55. name string
  56. // The api scope that this scope extends.
  57. extends *apiScope
  58. // The legacy enabled status for a specific scope can be dependent on other
  59. // properties that have been specified on the library so it is provided by
  60. // a function that can determine the status by examining those properties.
  61. legacyEnabledStatus func(module *SdkLibrary) bool
  62. // The default enabled status for non-legacy behavior, which is triggered by
  63. // explicitly enabling at least one api scope.
  64. defaultEnabledStatus bool
  65. // Gets a pointer to the scope specific properties.
  66. scopeSpecificProperties func(module *SdkLibrary) *ApiScopeProperties
  67. // The name of the field in the dynamically created structure.
  68. fieldName string
  69. // The name of the property in the java_sdk_library_import
  70. propertyName string
  71. // The tag to use to depend on the stubs library module.
  72. stubsTag scopeDependencyTag
  73. // The tag to use to depend on the stubs source module (if separate from the API module).
  74. stubsSourceTag scopeDependencyTag
  75. // The tag to use to depend on the API file generating module (if separate from the stubs source module).
  76. apiFileTag scopeDependencyTag
  77. // The tag to use to depend on the stubs source and API module.
  78. stubsSourceAndApiTag scopeDependencyTag
  79. // The scope specific prefix to add to the api file base of "current.txt" or "removed.txt".
  80. apiFilePrefix string
  81. // The scope specific prefix to add to the sdk library module name to construct a scope specific
  82. // module name.
  83. moduleSuffix string
  84. // SDK version that the stubs library is built against. Note that this is always
  85. // *current. Older stubs library built with a numbered SDK version is created from
  86. // the prebuilt jar.
  87. sdkVersion string
  88. // The annotation that identifies this API level, empty for the public API scope.
  89. annotation string
  90. // Extra arguments to pass to droidstubs for this scope.
  91. //
  92. // This is not used directly but is used to construct the droidstubsArgs.
  93. extraArgs []string
  94. // The args that must be passed to droidstubs to generate the API and stubs source
  95. // for this scope, constructed dynamically by initApiScope().
  96. //
  97. // The API only includes the additional members that this scope adds over the scope
  98. // that it extends.
  99. //
  100. // The stubs source must include the definitions of everything that is in this
  101. // api scope and all the scopes that this one extends.
  102. droidstubsArgs []string
  103. // Whether the api scope can be treated as unstable, and should skip compat checks.
  104. unstable bool
  105. }
  106. // Initialize a scope, creating and adding appropriate dependency tags
  107. func initApiScope(scope *apiScope) *apiScope {
  108. name := scope.name
  109. scopeByName[name] = scope
  110. allScopeNames = append(allScopeNames, name)
  111. scope.propertyName = strings.ReplaceAll(name, "-", "_")
  112. scope.fieldName = proptools.FieldNameForProperty(scope.propertyName)
  113. scope.stubsTag = scopeDependencyTag{
  114. name: name + "-stubs",
  115. apiScope: scope,
  116. depInfoExtractor: (*scopePaths).extractStubsLibraryInfoFromDependency,
  117. }
  118. scope.stubsSourceTag = scopeDependencyTag{
  119. name: name + "-stubs-source",
  120. apiScope: scope,
  121. depInfoExtractor: (*scopePaths).extractStubsSourceInfoFromDep,
  122. }
  123. scope.apiFileTag = scopeDependencyTag{
  124. name: name + "-api",
  125. apiScope: scope,
  126. depInfoExtractor: (*scopePaths).extractApiInfoFromDep,
  127. }
  128. scope.stubsSourceAndApiTag = scopeDependencyTag{
  129. name: name + "-stubs-source-and-api",
  130. apiScope: scope,
  131. depInfoExtractor: (*scopePaths).extractStubsSourceAndApiInfoFromApiStubsProvider,
  132. }
  133. // To get the args needed to generate the stubs source append all the args from
  134. // this scope and all the scopes it extends as each set of args adds additional
  135. // members to the stubs.
  136. var scopeSpecificArgs []string
  137. if scope.annotation != "" {
  138. scopeSpecificArgs = []string{"--show-annotation", scope.annotation}
  139. }
  140. for s := scope; s != nil; s = s.extends {
  141. scopeSpecificArgs = append(scopeSpecificArgs, s.extraArgs...)
  142. // Ensure that the generated stubs includes all the API elements from the API scope
  143. // that this scope extends.
  144. if s != scope && s.annotation != "" {
  145. scopeSpecificArgs = append(scopeSpecificArgs, "--show-for-stub-purposes-annotation", s.annotation)
  146. }
  147. }
  148. // Escape any special characters in the arguments. This is needed because droidstubs
  149. // passes these directly to the shell command.
  150. scope.droidstubsArgs = proptools.ShellEscapeList(scopeSpecificArgs)
  151. return scope
  152. }
  153. func (scope *apiScope) stubsLibraryModuleNameSuffix() string {
  154. return ".stubs" + scope.moduleSuffix
  155. }
  156. func (scope *apiScope) stubsLibraryModuleName(baseName string) string {
  157. return baseName + scope.stubsLibraryModuleNameSuffix()
  158. }
  159. func (scope *apiScope) stubsSourceModuleName(baseName string) string {
  160. return baseName + ".stubs.source" + scope.moduleSuffix
  161. }
  162. func (scope *apiScope) apiModuleName(baseName string) string {
  163. return baseName + ".api" + scope.moduleSuffix
  164. }
  165. func (scope *apiScope) String() string {
  166. return scope.name
  167. }
  168. type apiScopes []*apiScope
  169. func (scopes apiScopes) Strings(accessor func(*apiScope) string) []string {
  170. var list []string
  171. for _, scope := range scopes {
  172. list = append(list, accessor(scope))
  173. }
  174. return list
  175. }
  176. var (
  177. scopeByName = make(map[string]*apiScope)
  178. allScopeNames []string
  179. apiScopePublic = initApiScope(&apiScope{
  180. name: "public",
  181. // Public scope is enabled by default for both legacy and non-legacy modes.
  182. legacyEnabledStatus: func(module *SdkLibrary) bool {
  183. return true
  184. },
  185. defaultEnabledStatus: true,
  186. scopeSpecificProperties: func(module *SdkLibrary) *ApiScopeProperties {
  187. return &module.sdkLibraryProperties.Public
  188. },
  189. sdkVersion: "current",
  190. })
  191. apiScopeSystem = initApiScope(&apiScope{
  192. name: "system",
  193. extends: apiScopePublic,
  194. legacyEnabledStatus: (*SdkLibrary).generateTestAndSystemScopesByDefault,
  195. scopeSpecificProperties: func(module *SdkLibrary) *ApiScopeProperties {
  196. return &module.sdkLibraryProperties.System
  197. },
  198. apiFilePrefix: "system-",
  199. moduleSuffix: ".system",
  200. sdkVersion: "system_current",
  201. annotation: "android.annotation.SystemApi(client=android.annotation.SystemApi.Client.PRIVILEGED_APPS)",
  202. })
  203. apiScopeTest = initApiScope(&apiScope{
  204. name: "test",
  205. extends: apiScopeSystem,
  206. legacyEnabledStatus: (*SdkLibrary).generateTestAndSystemScopesByDefault,
  207. scopeSpecificProperties: func(module *SdkLibrary) *ApiScopeProperties {
  208. return &module.sdkLibraryProperties.Test
  209. },
  210. apiFilePrefix: "test-",
  211. moduleSuffix: ".test",
  212. sdkVersion: "test_current",
  213. annotation: "android.annotation.TestApi",
  214. unstable: true,
  215. })
  216. apiScopeModuleLib = initApiScope(&apiScope{
  217. name: "module-lib",
  218. extends: apiScopeSystem,
  219. // The module-lib scope is disabled by default in legacy mode.
  220. //
  221. // Enabling this would break existing usages.
  222. legacyEnabledStatus: func(module *SdkLibrary) bool {
  223. return false
  224. },
  225. scopeSpecificProperties: func(module *SdkLibrary) *ApiScopeProperties {
  226. return &module.sdkLibraryProperties.Module_lib
  227. },
  228. apiFilePrefix: "module-lib-",
  229. moduleSuffix: ".module_lib",
  230. sdkVersion: "module_current",
  231. annotation: "android.annotation.SystemApi(client=android.annotation.SystemApi.Client.MODULE_LIBRARIES)",
  232. })
  233. apiScopeSystemServer = initApiScope(&apiScope{
  234. name: "system-server",
  235. extends: apiScopePublic,
  236. // The system-server scope is disabled by default in legacy mode.
  237. //
  238. // Enabling this would break existing usages.
  239. legacyEnabledStatus: func(module *SdkLibrary) bool {
  240. return false
  241. },
  242. scopeSpecificProperties: func(module *SdkLibrary) *ApiScopeProperties {
  243. return &module.sdkLibraryProperties.System_server
  244. },
  245. apiFilePrefix: "system-server-",
  246. moduleSuffix: ".system_server",
  247. sdkVersion: "system_server_current",
  248. annotation: "android.annotation.SystemApi(client=android.annotation.SystemApi.Client.SYSTEM_SERVER)",
  249. extraArgs: []string{
  250. "--hide-annotation", "android.annotation.Hide",
  251. // com.android.* classes are okay in this interface"
  252. "--hide", "InternalClasses",
  253. },
  254. })
  255. allApiScopes = apiScopes{
  256. apiScopePublic,
  257. apiScopeSystem,
  258. apiScopeTest,
  259. apiScopeModuleLib,
  260. apiScopeSystemServer,
  261. }
  262. )
  263. var (
  264. javaSdkLibrariesLock sync.Mutex
  265. )
  266. // TODO: these are big features that are currently missing
  267. // 1) disallowing linking to the runtime shared lib
  268. // 2) HTML generation
  269. func init() {
  270. RegisterSdkLibraryBuildComponents(android.InitRegistrationContext)
  271. android.RegisterMakeVarsProvider(pctx, func(ctx android.MakeVarsContext) {
  272. javaSdkLibraries := javaSdkLibraries(ctx.Config())
  273. sort.Strings(*javaSdkLibraries)
  274. ctx.Strict("JAVA_SDK_LIBRARIES", strings.Join(*javaSdkLibraries, " "))
  275. })
  276. // Register sdk member types.
  277. android.RegisterSdkMemberType(javaSdkLibrarySdkMemberType)
  278. }
  279. func RegisterSdkLibraryBuildComponents(ctx android.RegistrationContext) {
  280. ctx.RegisterModuleType("java_sdk_library", SdkLibraryFactory)
  281. ctx.RegisterModuleType("java_sdk_library_import", sdkLibraryImportFactory)
  282. }
  283. // Properties associated with each api scope.
  284. type ApiScopeProperties struct {
  285. // Indicates whether the api surface is generated.
  286. //
  287. // If this is set for any scope then all scopes must explicitly specify if they
  288. // are enabled. This is to prevent new usages from depending on legacy behavior.
  289. //
  290. // Otherwise, if this is not set for any scope then the default behavior is
  291. // scope specific so please refer to the scope specific property documentation.
  292. Enabled *bool
  293. // The sdk_version to use for building the stubs.
  294. //
  295. // If not specified then it will use an sdk_version determined as follows:
  296. //
  297. // 1) If the sdk_version specified on the java_sdk_library is none then this
  298. // will be none. This is used for java_sdk_library instances that are used
  299. // to create stubs that contribute to the core_current sdk version.
  300. // 2) Otherwise, it is assumed that this library extends but does not
  301. // contribute directly to a specific sdk_version and so this uses the
  302. // sdk_version appropriate for the api scope. e.g. public will use
  303. // sdk_version: current, system will use sdk_version: system_current, etc.
  304. //
  305. // This does not affect the sdk_version used for either generating the stubs source
  306. // or the API file. They both have to use the same sdk_version as is used for
  307. // compiling the implementation library.
  308. Sdk_version *string
  309. }
  310. type sdkLibraryProperties struct {
  311. // List of source files that are needed to compile the API, but are not part of runtime library.
  312. Api_srcs []string `android:"arch_variant"`
  313. // Visibility for impl library module. If not specified then defaults to the
  314. // visibility property.
  315. Impl_library_visibility []string
  316. // Visibility for stubs library modules. If not specified then defaults to the
  317. // visibility property.
  318. Stubs_library_visibility []string
  319. // Visibility for stubs source modules. If not specified then defaults to the
  320. // visibility property.
  321. Stubs_source_visibility []string
  322. // List of Java libraries that will be in the classpath when building the implementation lib
  323. Impl_only_libs []string `android:"arch_variant"`
  324. // List of Java libraries that will be in the classpath when building stubs
  325. Stub_only_libs []string `android:"arch_variant"`
  326. // List of Java libraries that will included in stub libraries
  327. Stub_only_static_libs []string `android:"arch_variant"`
  328. // list of package names that will be documented and publicized as API.
  329. // This allows the API to be restricted to a subset of the source files provided.
  330. // If this is unspecified then all the source files will be treated as being part
  331. // of the API.
  332. Api_packages []string
  333. // list of package names that must be hidden from the API
  334. Hidden_api_packages []string
  335. // the relative path to the directory containing the api specification files.
  336. // Defaults to "api".
  337. Api_dir *string
  338. // Determines whether a runtime implementation library is built; defaults to false.
  339. //
  340. // If true then it also prevents the module from being used as a shared module, i.e.
  341. // it is as is shared_library: false, was set.
  342. Api_only *bool
  343. // local files that are used within user customized droiddoc options.
  344. Droiddoc_option_files []string
  345. // additional droiddoc options.
  346. // Available variables for substitution:
  347. //
  348. // $(location <label>): the path to the droiddoc_option_files with name <label>
  349. Droiddoc_options []string
  350. // is set to true, Metalava will allow framework SDK to contain annotations.
  351. Annotations_enabled *bool
  352. // a list of top-level directories containing files to merge qualifier annotations
  353. // (i.e. those intended to be included in the stubs written) from.
  354. Merge_annotations_dirs []string
  355. // a list of top-level directories containing Java stub files to merge show/hide annotations from.
  356. Merge_inclusion_annotations_dirs []string
  357. // If set to true then don't create dist rules.
  358. No_dist *bool
  359. // The stem for the artifacts that are copied to the dist, if not specified
  360. // then defaults to the base module name.
  361. //
  362. // For each scope the following artifacts are copied to the apistubs/<scope>
  363. // directory in the dist.
  364. // * stubs impl jar -> <dist-stem>.jar
  365. // * API specification file -> api/<dist-stem>.txt
  366. // * Removed API specification file -> api/<dist-stem>-removed.txt
  367. //
  368. // Also used to construct the name of the filegroup (created by prebuilt_apis)
  369. // that references the latest released API and remove API specification files.
  370. // * API specification filegroup -> <dist-stem>.api.<scope>.latest
  371. // * Removed API specification filegroup -> <dist-stem>-removed.api.<scope>.latest
  372. // * API incompatibilities baseline filegroup -> <dist-stem>-incompatibilities.api.<scope>.latest
  373. Dist_stem *string
  374. // The subdirectory for the artifacts that are copied to the dist directory. If not specified
  375. // then defaults to "unknown". Should be set to "android" for anything that should be published
  376. // in the public Android SDK.
  377. Dist_group *string
  378. // A compatibility mode that allows historical API-tracking files to not exist.
  379. // Do not use.
  380. Unsafe_ignore_missing_latest_api bool
  381. // indicates whether system and test apis should be generated.
  382. Generate_system_and_test_apis bool `blueprint:"mutated"`
  383. // The properties specific to the public api scope
  384. //
  385. // Unless explicitly specified by using public.enabled the public api scope is
  386. // enabled by default in both legacy and non-legacy mode.
  387. Public ApiScopeProperties
  388. // The properties specific to the system api scope
  389. //
  390. // In legacy mode the system api scope is enabled by default when sdk_version
  391. // is set to something other than "none".
  392. //
  393. // In non-legacy mode the system api scope is disabled by default.
  394. System ApiScopeProperties
  395. // The properties specific to the test api scope
  396. //
  397. // In legacy mode the test api scope is enabled by default when sdk_version
  398. // is set to something other than "none".
  399. //
  400. // In non-legacy mode the test api scope is disabled by default.
  401. Test ApiScopeProperties
  402. // The properties specific to the module-lib api scope
  403. //
  404. // Unless explicitly specified by using test.enabled the module-lib api scope is
  405. // disabled by default.
  406. Module_lib ApiScopeProperties
  407. // The properties specific to the system-server api scope
  408. //
  409. // Unless explicitly specified by using test.enabled the module-lib api scope is
  410. // disabled by default.
  411. System_server ApiScopeProperties
  412. // Determines if the stubs are preferred over the implementation library
  413. // for linking, even when the client doesn't specify sdk_version. When this
  414. // is set to true, such clients are provided with the widest API surface that
  415. // this lib provides. Note however that this option doesn't affect the clients
  416. // that are in the same APEX as this library. In that case, the clients are
  417. // always linked with the implementation library. Default is false.
  418. Default_to_stubs *bool
  419. // Properties related to api linting.
  420. Api_lint struct {
  421. // Enable api linting.
  422. Enabled *bool
  423. }
  424. // TODO: determines whether to create HTML doc or not
  425. //Html_doc *bool
  426. }
  427. // Paths to outputs from java_sdk_library and java_sdk_library_import.
  428. //
  429. // Fields that are android.Paths are always set (during GenerateAndroidBuildActions).
  430. // OptionalPaths are always set by java_sdk_library but may not be set by
  431. // java_sdk_library_import as not all instances provide that information.
  432. type scopePaths struct {
  433. // The path (represented as Paths for convenience when returning) to the stubs header jar.
  434. //
  435. // That is the jar that is created by turbine.
  436. stubsHeaderPath android.Paths
  437. // The path (represented as Paths for convenience when returning) to the stubs implementation jar.
  438. //
  439. // This is not the implementation jar, it still only contains stubs.
  440. stubsImplPath android.Paths
  441. // The dex jar for the stubs.
  442. //
  443. // This is not the implementation jar, it still only contains stubs.
  444. stubsDexJarPath OptionalDexJarPath
  445. // The API specification file, e.g. system_current.txt.
  446. currentApiFilePath android.OptionalPath
  447. // The specification of API elements removed since the last release.
  448. removedApiFilePath android.OptionalPath
  449. // The stubs source jar.
  450. stubsSrcJar android.OptionalPath
  451. // Extracted annotations.
  452. annotationsZip android.OptionalPath
  453. }
  454. func (paths *scopePaths) extractStubsLibraryInfoFromDependency(ctx android.ModuleContext, dep android.Module) error {
  455. if ctx.OtherModuleHasProvider(dep, JavaInfoProvider) {
  456. lib := ctx.OtherModuleProvider(dep, JavaInfoProvider).(JavaInfo)
  457. paths.stubsHeaderPath = lib.HeaderJars
  458. paths.stubsImplPath = lib.ImplementationJars
  459. libDep := dep.(UsesLibraryDependency)
  460. paths.stubsDexJarPath = libDep.DexJarBuildPath()
  461. return nil
  462. } else {
  463. return fmt.Errorf("expected module that has JavaInfoProvider, e.g. java_library")
  464. }
  465. }
  466. func (paths *scopePaths) treatDepAsApiStubsProvider(dep android.Module, action func(provider ApiStubsProvider)) error {
  467. if apiStubsProvider, ok := dep.(ApiStubsProvider); ok {
  468. action(apiStubsProvider)
  469. return nil
  470. } else {
  471. return fmt.Errorf("expected module that implements ApiStubsProvider, e.g. droidstubs")
  472. }
  473. }
  474. func (paths *scopePaths) treatDepAsApiStubsSrcProvider(dep android.Module, action func(provider ApiStubsSrcProvider)) error {
  475. if apiStubsProvider, ok := dep.(ApiStubsSrcProvider); ok {
  476. action(apiStubsProvider)
  477. return nil
  478. } else {
  479. return fmt.Errorf("expected module that implements ApiStubsSrcProvider, e.g. droidstubs")
  480. }
  481. }
  482. func (paths *scopePaths) extractApiInfoFromApiStubsProvider(provider ApiStubsProvider) {
  483. paths.annotationsZip = android.OptionalPathForPath(provider.AnnotationsZip())
  484. paths.currentApiFilePath = android.OptionalPathForPath(provider.ApiFilePath())
  485. paths.removedApiFilePath = android.OptionalPathForPath(provider.RemovedApiFilePath())
  486. }
  487. func (paths *scopePaths) extractApiInfoFromDep(ctx android.ModuleContext, dep android.Module) error {
  488. return paths.treatDepAsApiStubsProvider(dep, func(provider ApiStubsProvider) {
  489. paths.extractApiInfoFromApiStubsProvider(provider)
  490. })
  491. }
  492. func (paths *scopePaths) extractStubsSourceInfoFromApiStubsProviders(provider ApiStubsSrcProvider) {
  493. paths.stubsSrcJar = android.OptionalPathForPath(provider.StubsSrcJar())
  494. }
  495. func (paths *scopePaths) extractStubsSourceInfoFromDep(ctx android.ModuleContext, dep android.Module) error {
  496. return paths.treatDepAsApiStubsSrcProvider(dep, func(provider ApiStubsSrcProvider) {
  497. paths.extractStubsSourceInfoFromApiStubsProviders(provider)
  498. })
  499. }
  500. func (paths *scopePaths) extractStubsSourceAndApiInfoFromApiStubsProvider(ctx android.ModuleContext, dep android.Module) error {
  501. return paths.treatDepAsApiStubsProvider(dep, func(provider ApiStubsProvider) {
  502. paths.extractApiInfoFromApiStubsProvider(provider)
  503. paths.extractStubsSourceInfoFromApiStubsProviders(provider)
  504. })
  505. }
  506. type commonToSdkLibraryAndImportProperties struct {
  507. // The naming scheme to use for the components that this module creates.
  508. //
  509. // If not specified then it defaults to "default".
  510. //
  511. // This is a temporary mechanism to simplify conversion from separate modules for each
  512. // component that follow a different naming pattern to the default one.
  513. //
  514. // TODO(b/155480189) - Remove once naming inconsistencies have been resolved.
  515. Naming_scheme *string
  516. // Specifies whether this module can be used as an Android shared library; defaults
  517. // to true.
  518. //
  519. // An Android shared library is one that can be referenced in a <uses-library> element
  520. // in an AndroidManifest.xml.
  521. Shared_library *bool
  522. // Files containing information about supported java doc tags.
  523. Doctag_files []string `android:"path"`
  524. // Signals that this shared library is part of the bootclasspath starting
  525. // on the version indicated in this attribute.
  526. //
  527. // This will make platforms at this level and above to ignore
  528. // <uses-library> tags with this library name because the library is already
  529. // available
  530. On_bootclasspath_since *string
  531. // Signals that this shared library was part of the bootclasspath before
  532. // (but not including) the version indicated in this attribute.
  533. //
  534. // The system will automatically add a <uses-library> tag with this library to
  535. // apps that target any SDK less than the version indicated in this attribute.
  536. On_bootclasspath_before *string
  537. // Indicates that PackageManager should ignore this shared library if the
  538. // platform is below the version indicated in this attribute.
  539. //
  540. // This means that the device won't recognise this library as installed.
  541. Min_device_sdk *string
  542. // Indicates that PackageManager should ignore this shared library if the
  543. // platform is above the version indicated in this attribute.
  544. //
  545. // This means that the device won't recognise this library as installed.
  546. Max_device_sdk *string
  547. }
  548. // commonSdkLibraryAndImportModule defines the interface that must be provided by a module that
  549. // embeds the commonToSdkLibraryAndImport struct.
  550. type commonSdkLibraryAndImportModule interface {
  551. android.SdkAware
  552. BaseModuleName() string
  553. }
  554. // Common code between sdk library and sdk library import
  555. type commonToSdkLibraryAndImport struct {
  556. module commonSdkLibraryAndImportModule
  557. scopePaths map[*apiScope]*scopePaths
  558. namingScheme sdkLibraryComponentNamingScheme
  559. commonSdkLibraryProperties commonToSdkLibraryAndImportProperties
  560. // Paths to commonSdkLibraryProperties.Doctag_files
  561. doctagPaths android.Paths
  562. // Functionality related to this being used as a component of a java_sdk_library.
  563. EmbeddableSdkLibraryComponent
  564. }
  565. func (c *commonToSdkLibraryAndImport) initCommon(module commonSdkLibraryAndImportModule) {
  566. c.module = module
  567. module.AddProperties(&c.commonSdkLibraryProperties)
  568. // Initialize this as an sdk library component.
  569. c.initSdkLibraryComponent(module)
  570. }
  571. func (c *commonToSdkLibraryAndImport) initCommonAfterDefaultsApplied(ctx android.DefaultableHookContext) bool {
  572. schemeProperty := proptools.StringDefault(c.commonSdkLibraryProperties.Naming_scheme, "default")
  573. switch schemeProperty {
  574. case "default":
  575. c.namingScheme = &defaultNamingScheme{}
  576. default:
  577. ctx.PropertyErrorf("naming_scheme", "expected 'default' but was %q", schemeProperty)
  578. return false
  579. }
  580. namePtr := proptools.StringPtr(c.module.BaseModuleName())
  581. c.sdkLibraryComponentProperties.SdkLibraryName = namePtr
  582. // Only track this sdk library if this can be used as a shared library.
  583. if c.sharedLibrary() {
  584. // Use the name specified in the module definition as the owner.
  585. c.sdkLibraryComponentProperties.SdkLibraryToImplicitlyTrack = namePtr
  586. }
  587. return true
  588. }
  589. // uniqueApexVariations provides common implementation of the ApexModule.UniqueApexVariations
  590. // method.
  591. func (c *commonToSdkLibraryAndImport) uniqueApexVariations() bool {
  592. // A java_sdk_library that is a shared library produces an XML file that makes the shared library
  593. // usable from an AndroidManifest.xml's <uses-library> entry. That XML file contains the name of
  594. // the APEX and so it needs a unique variation per APEX.
  595. return c.sharedLibrary()
  596. }
  597. func (c *commonToSdkLibraryAndImport) generateCommonBuildActions(ctx android.ModuleContext) {
  598. c.doctagPaths = android.PathsForModuleSrc(ctx, c.commonSdkLibraryProperties.Doctag_files)
  599. }
  600. // Module name of the runtime implementation library
  601. func (c *commonToSdkLibraryAndImport) implLibraryModuleName() string {
  602. return c.module.BaseModuleName() + ".impl"
  603. }
  604. // Module name of the XML file for the lib
  605. func (c *commonToSdkLibraryAndImport) xmlPermissionsModuleName() string {
  606. return c.module.BaseModuleName() + sdkXmlFileSuffix
  607. }
  608. // Name of the java_library module that compiles the stubs source.
  609. func (c *commonToSdkLibraryAndImport) stubsLibraryModuleName(apiScope *apiScope) string {
  610. baseName := c.module.BaseModuleName()
  611. return c.module.SdkMemberComponentName(baseName, func(name string) string {
  612. return c.namingScheme.stubsLibraryModuleName(apiScope, name)
  613. })
  614. }
  615. // Name of the droidstubs module that generates the stubs source and may also
  616. // generate/check the API.
  617. func (c *commonToSdkLibraryAndImport) stubsSourceModuleName(apiScope *apiScope) string {
  618. baseName := c.module.BaseModuleName()
  619. return c.module.SdkMemberComponentName(baseName, func(name string) string {
  620. return c.namingScheme.stubsSourceModuleName(apiScope, name)
  621. })
  622. }
  623. // The component names for different outputs of the java_sdk_library.
  624. //
  625. // They are similar to the names used for the child modules it creates
  626. const (
  627. stubsSourceComponentName = "stubs.source"
  628. apiTxtComponentName = "api.txt"
  629. removedApiTxtComponentName = "removed-api.txt"
  630. annotationsComponentName = "annotations.zip"
  631. )
  632. // A regular expression to match tags that reference a specific stubs component.
  633. //
  634. // It will only match if given a valid scope and a valid component. It is verfy strict
  635. // to ensure it does not accidentally match a similar looking tag that should be processed
  636. // by the embedded Library.
  637. var tagSplitter = func() *regexp.Regexp {
  638. // Given a list of literal string items returns a regular expression that will
  639. // match any one of the items.
  640. choice := func(items ...string) string {
  641. return `\Q` + strings.Join(items, `\E|\Q`) + `\E`
  642. }
  643. // Regular expression to match one of the scopes.
  644. scopesRegexp := choice(allScopeNames...)
  645. // Regular expression to match one of the components.
  646. componentsRegexp := choice(stubsSourceComponentName, apiTxtComponentName, removedApiTxtComponentName, annotationsComponentName)
  647. // Regular expression to match any combination of one scope and one component.
  648. return regexp.MustCompile(fmt.Sprintf(`^\.(%s)\.(%s)$`, scopesRegexp, componentsRegexp))
  649. }()
  650. // For OutputFileProducer interface
  651. //
  652. // .<scope>.<component name>, for all ComponentNames (for example: .public.removed-api.txt)
  653. func (c *commonToSdkLibraryAndImport) commonOutputFiles(tag string) (android.Paths, error) {
  654. if groups := tagSplitter.FindStringSubmatch(tag); groups != nil {
  655. scopeName := groups[1]
  656. component := groups[2]
  657. if scope, ok := scopeByName[scopeName]; ok {
  658. paths := c.findScopePaths(scope)
  659. if paths == nil {
  660. return nil, fmt.Errorf("%q does not provide api scope %s", c.module.BaseModuleName(), scopeName)
  661. }
  662. switch component {
  663. case stubsSourceComponentName:
  664. if paths.stubsSrcJar.Valid() {
  665. return android.Paths{paths.stubsSrcJar.Path()}, nil
  666. }
  667. case apiTxtComponentName:
  668. if paths.currentApiFilePath.Valid() {
  669. return android.Paths{paths.currentApiFilePath.Path()}, nil
  670. }
  671. case removedApiTxtComponentName:
  672. if paths.removedApiFilePath.Valid() {
  673. return android.Paths{paths.removedApiFilePath.Path()}, nil
  674. }
  675. case annotationsComponentName:
  676. if paths.annotationsZip.Valid() {
  677. return android.Paths{paths.annotationsZip.Path()}, nil
  678. }
  679. }
  680. return nil, fmt.Errorf("%s not available for api scope %s", component, scopeName)
  681. } else {
  682. return nil, fmt.Errorf("unknown scope %s in %s", scope, tag)
  683. }
  684. } else {
  685. switch tag {
  686. case ".doctags":
  687. if c.doctagPaths != nil {
  688. return c.doctagPaths, nil
  689. } else {
  690. return nil, fmt.Errorf("no doctag_files specified on %s", c.module.BaseModuleName())
  691. }
  692. }
  693. return nil, nil
  694. }
  695. }
  696. func (c *commonToSdkLibraryAndImport) getScopePathsCreateIfNeeded(scope *apiScope) *scopePaths {
  697. if c.scopePaths == nil {
  698. c.scopePaths = make(map[*apiScope]*scopePaths)
  699. }
  700. paths := c.scopePaths[scope]
  701. if paths == nil {
  702. paths = &scopePaths{}
  703. c.scopePaths[scope] = paths
  704. }
  705. return paths
  706. }
  707. func (c *commonToSdkLibraryAndImport) findScopePaths(scope *apiScope) *scopePaths {
  708. if c.scopePaths == nil {
  709. return nil
  710. }
  711. return c.scopePaths[scope]
  712. }
  713. // If this does not support the requested api scope then find the closest available
  714. // scope it does support. Returns nil if no such scope is available.
  715. func (c *commonToSdkLibraryAndImport) findClosestScopePath(scope *apiScope) *scopePaths {
  716. for s := scope; s != nil; s = s.extends {
  717. if paths := c.findScopePaths(s); paths != nil {
  718. return paths
  719. }
  720. }
  721. // This should never happen outside tests as public should be the base scope for every
  722. // scope and is enabled by default.
  723. return nil
  724. }
  725. func (c *commonToSdkLibraryAndImport) selectHeaderJarsForSdkVersion(ctx android.BaseModuleContext, sdkVersion android.SdkSpec) android.Paths {
  726. // If a specific numeric version has been requested then use prebuilt versions of the sdk.
  727. if !sdkVersion.ApiLevel.IsPreview() {
  728. return PrebuiltJars(ctx, c.module.BaseModuleName(), sdkVersion)
  729. }
  730. paths := c.selectScopePaths(ctx, sdkVersion.Kind)
  731. if paths == nil {
  732. return nil
  733. }
  734. return paths.stubsHeaderPath
  735. }
  736. // selectScopePaths returns the *scopePaths appropriate for the specific kind.
  737. //
  738. // If the module does not support the specific kind then it will return the *scopePaths for the
  739. // closest kind which is a subset of the requested kind. e.g. if requesting android.SdkModule then
  740. // it will return *scopePaths for android.SdkSystem if available or android.SdkPublic of not.
  741. func (c *commonToSdkLibraryAndImport) selectScopePaths(ctx android.BaseModuleContext, kind android.SdkKind) *scopePaths {
  742. apiScope := sdkKindToApiScope(kind)
  743. paths := c.findClosestScopePath(apiScope)
  744. if paths == nil {
  745. var scopes []string
  746. for _, s := range allApiScopes {
  747. if c.findScopePaths(s) != nil {
  748. scopes = append(scopes, s.name)
  749. }
  750. }
  751. ctx.ModuleErrorf("requires api scope %s from %s but it only has %q available", apiScope.name, c.module.BaseModuleName(), scopes)
  752. return nil
  753. }
  754. return paths
  755. }
  756. // sdkKindToApiScope maps from android.SdkKind to apiScope.
  757. func sdkKindToApiScope(kind android.SdkKind) *apiScope {
  758. var apiScope *apiScope
  759. switch kind {
  760. case android.SdkSystem:
  761. apiScope = apiScopeSystem
  762. case android.SdkModule:
  763. apiScope = apiScopeModuleLib
  764. case android.SdkTest:
  765. apiScope = apiScopeTest
  766. case android.SdkSystemServer:
  767. apiScope = apiScopeSystemServer
  768. default:
  769. apiScope = apiScopePublic
  770. }
  771. return apiScope
  772. }
  773. // to satisfy SdkLibraryDependency interface
  774. func (c *commonToSdkLibraryAndImport) SdkApiStubDexJar(ctx android.BaseModuleContext, kind android.SdkKind) OptionalDexJarPath {
  775. paths := c.selectScopePaths(ctx, kind)
  776. if paths == nil {
  777. return makeUnsetDexJarPath()
  778. }
  779. return paths.stubsDexJarPath
  780. }
  781. // to satisfy SdkLibraryDependency interface
  782. func (c *commonToSdkLibraryAndImport) SdkRemovedTxtFile(ctx android.BaseModuleContext, kind android.SdkKind) android.OptionalPath {
  783. apiScope := sdkKindToApiScope(kind)
  784. paths := c.findScopePaths(apiScope)
  785. if paths == nil {
  786. return android.OptionalPath{}
  787. }
  788. return paths.removedApiFilePath
  789. }
  790. func (c *commonToSdkLibraryAndImport) sdkComponentPropertiesForChildLibrary() interface{} {
  791. componentProps := &struct {
  792. SdkLibraryName *string
  793. SdkLibraryToImplicitlyTrack *string
  794. }{}
  795. namePtr := proptools.StringPtr(c.module.BaseModuleName())
  796. componentProps.SdkLibraryName = namePtr
  797. if c.sharedLibrary() {
  798. // Mark the stubs library as being components of this java_sdk_library so that
  799. // any app that includes code which depends (directly or indirectly) on the stubs
  800. // library will have the appropriate <uses-library> invocation inserted into its
  801. // manifest if necessary.
  802. componentProps.SdkLibraryToImplicitlyTrack = namePtr
  803. }
  804. return componentProps
  805. }
  806. func (c *commonToSdkLibraryAndImport) sharedLibrary() bool {
  807. return proptools.BoolDefault(c.commonSdkLibraryProperties.Shared_library, true)
  808. }
  809. // Check if the stub libraries should be compiled for dex
  810. func (c *commonToSdkLibraryAndImport) stubLibrariesCompiledForDex() bool {
  811. // Always compile the dex file files for the stub libraries if they will be used on the
  812. // bootclasspath.
  813. return !c.sharedLibrary()
  814. }
  815. // Properties related to the use of a module as an component of a java_sdk_library.
  816. type SdkLibraryComponentProperties struct {
  817. // The name of the java_sdk_library/_import module.
  818. SdkLibraryName *string `blueprint:"mutated"`
  819. // The name of the java_sdk_library/_import to add to a <uses-library> entry
  820. // in the AndroidManifest.xml of any Android app that includes code that references
  821. // this module. If not set then no java_sdk_library/_import is tracked.
  822. SdkLibraryToImplicitlyTrack *string `blueprint:"mutated"`
  823. }
  824. // Structure to be embedded in a module struct that needs to support the
  825. // SdkLibraryComponentDependency interface.
  826. type EmbeddableSdkLibraryComponent struct {
  827. sdkLibraryComponentProperties SdkLibraryComponentProperties
  828. }
  829. func (e *EmbeddableSdkLibraryComponent) initSdkLibraryComponent(module android.Module) {
  830. module.AddProperties(&e.sdkLibraryComponentProperties)
  831. }
  832. // to satisfy SdkLibraryComponentDependency
  833. func (e *EmbeddableSdkLibraryComponent) SdkLibraryName() *string {
  834. return e.sdkLibraryComponentProperties.SdkLibraryName
  835. }
  836. // to satisfy SdkLibraryComponentDependency
  837. func (e *EmbeddableSdkLibraryComponent) OptionalSdkLibraryImplementation() *string {
  838. // For shared libraries, this is the same as the SDK library name. If a Java library or app
  839. // depends on a component library (e.g. a stub library) it still needs to know the name of the
  840. // run-time library and the corresponding module that provides the implementation. This name is
  841. // passed to manifest_fixer (to be added to AndroidManifest.xml) and added to CLC (to be used
  842. // in dexpreopt).
  843. //
  844. // For non-shared SDK (component or not) libraries this returns `nil`, as they are not
  845. // <uses-library> and should not be added to the manifest or to CLC.
  846. return e.sdkLibraryComponentProperties.SdkLibraryToImplicitlyTrack
  847. }
  848. // Implemented by modules that are (or possibly could be) a component of a java_sdk_library
  849. // (including the java_sdk_library) itself.
  850. type SdkLibraryComponentDependency interface {
  851. UsesLibraryDependency
  852. // SdkLibraryName returns the name of the java_sdk_library/_import module.
  853. SdkLibraryName() *string
  854. // The name of the implementation library for the optional SDK library or nil, if there isn't one.
  855. OptionalSdkLibraryImplementation() *string
  856. }
  857. // Make sure that all the module types that are components of java_sdk_library/_import
  858. // and which can be referenced (directly or indirectly) from an android app implement
  859. // the SdkLibraryComponentDependency interface.
  860. var _ SdkLibraryComponentDependency = (*Library)(nil)
  861. var _ SdkLibraryComponentDependency = (*Import)(nil)
  862. var _ SdkLibraryComponentDependency = (*SdkLibrary)(nil)
  863. var _ SdkLibraryComponentDependency = (*SdkLibraryImport)(nil)
  864. // Provides access to sdk_version related files, e.g. header and implementation jars.
  865. type SdkLibraryDependency interface {
  866. SdkLibraryComponentDependency
  867. // Get the header jars appropriate for the supplied sdk_version.
  868. //
  869. // These are turbine generated jars so they only change if the externals of the
  870. // class changes but it does not contain and implementation or JavaDoc.
  871. SdkHeaderJars(ctx android.BaseModuleContext, sdkVersion android.SdkSpec) android.Paths
  872. // Get the implementation jars appropriate for the supplied sdk version.
  873. //
  874. // These are either the implementation jar for the whole sdk library or the implementation
  875. // jars for the stubs. The latter should only be needed when generating JavaDoc as otherwise
  876. // they are identical to the corresponding header jars.
  877. SdkImplementationJars(ctx android.BaseModuleContext, sdkVersion android.SdkSpec) android.Paths
  878. // SdkApiStubDexJar returns the dex jar for the stubs. It is needed by the hiddenapi processing
  879. // tool which processes dex files.
  880. SdkApiStubDexJar(ctx android.BaseModuleContext, kind android.SdkKind) OptionalDexJarPath
  881. // SdkRemovedTxtFile returns the optional path to the removed.txt file for the specified sdk kind.
  882. SdkRemovedTxtFile(ctx android.BaseModuleContext, kind android.SdkKind) android.OptionalPath
  883. // sharedLibrary returns true if this can be used as a shared library.
  884. sharedLibrary() bool
  885. }
  886. type SdkLibrary struct {
  887. Library
  888. sdkLibraryProperties sdkLibraryProperties
  889. // Map from api scope to the scope specific property structure.
  890. scopeToProperties map[*apiScope]*ApiScopeProperties
  891. commonToSdkLibraryAndImport
  892. }
  893. var _ SdkLibraryDependency = (*SdkLibrary)(nil)
  894. func (module *SdkLibrary) generateTestAndSystemScopesByDefault() bool {
  895. return module.sdkLibraryProperties.Generate_system_and_test_apis
  896. }
  897. func (module *SdkLibrary) getGeneratedApiScopes(ctx android.EarlyModuleContext) apiScopes {
  898. // Check to see if any scopes have been explicitly enabled. If any have then all
  899. // must be.
  900. anyScopesExplicitlyEnabled := false
  901. for _, scope := range allApiScopes {
  902. scopeProperties := module.scopeToProperties[scope]
  903. if scopeProperties.Enabled != nil {
  904. anyScopesExplicitlyEnabled = true
  905. break
  906. }
  907. }
  908. var generatedScopes apiScopes
  909. enabledScopes := make(map[*apiScope]struct{})
  910. for _, scope := range allApiScopes {
  911. scopeProperties := module.scopeToProperties[scope]
  912. // If any scopes are explicitly enabled then ignore the legacy enabled status.
  913. // This is to ensure that any new usages of this module type do not rely on legacy
  914. // behaviour.
  915. defaultEnabledStatus := false
  916. if anyScopesExplicitlyEnabled {
  917. defaultEnabledStatus = scope.defaultEnabledStatus
  918. } else {
  919. defaultEnabledStatus = scope.legacyEnabledStatus(module)
  920. }
  921. enabled := proptools.BoolDefault(scopeProperties.Enabled, defaultEnabledStatus)
  922. if enabled {
  923. enabledScopes[scope] = struct{}{}
  924. generatedScopes = append(generatedScopes, scope)
  925. }
  926. }
  927. // Now check to make sure that any scope that is extended by an enabled scope is also
  928. // enabled.
  929. for _, scope := range allApiScopes {
  930. if _, ok := enabledScopes[scope]; ok {
  931. extends := scope.extends
  932. if extends != nil {
  933. if _, ok := enabledScopes[extends]; !ok {
  934. ctx.ModuleErrorf("enabled api scope %q depends on disabled scope %q", scope, extends)
  935. }
  936. }
  937. }
  938. }
  939. return generatedScopes
  940. }
  941. var _ android.ModuleWithMinSdkVersionCheck = (*SdkLibrary)(nil)
  942. func (module *SdkLibrary) CheckMinSdkVersion(ctx android.ModuleContext) {
  943. android.CheckMinSdkVersion(ctx, module.MinSdkVersion(ctx).ApiLevel, func(c android.ModuleContext, do android.PayloadDepsCallback) {
  944. ctx.WalkDeps(func(child android.Module, parent android.Module) bool {
  945. isExternal := !module.depIsInSameApex(ctx, child)
  946. if am, ok := child.(android.ApexModule); ok {
  947. if !do(ctx, parent, am, isExternal) {
  948. return false
  949. }
  950. }
  951. return !isExternal
  952. })
  953. })
  954. }
  955. type sdkLibraryComponentTag struct {
  956. blueprint.BaseDependencyTag
  957. name string
  958. }
  959. // Mark this tag so dependencies that use it are excluded from visibility enforcement.
  960. func (t sdkLibraryComponentTag) ExcludeFromVisibilityEnforcement() {}
  961. var xmlPermissionsFileTag = sdkLibraryComponentTag{name: "xml-permissions-file"}
  962. func IsXmlPermissionsFileDepTag(depTag blueprint.DependencyTag) bool {
  963. if dt, ok := depTag.(sdkLibraryComponentTag); ok {
  964. return dt == xmlPermissionsFileTag
  965. }
  966. return false
  967. }
  968. var implLibraryTag = sdkLibraryComponentTag{name: "impl-library"}
  969. // Add the dependencies on the child modules in the component deps mutator.
  970. func (module *SdkLibrary) ComponentDepsMutator(ctx android.BottomUpMutatorContext) {
  971. for _, apiScope := range module.getGeneratedApiScopes(ctx) {
  972. // Add dependencies to the stubs library
  973. ctx.AddVariationDependencies(nil, apiScope.stubsTag, module.stubsLibraryModuleName(apiScope))
  974. // Add a dependency on the stubs source in order to access both stubs source and api information.
  975. ctx.AddVariationDependencies(nil, apiScope.stubsSourceAndApiTag, module.stubsSourceModuleName(apiScope))
  976. }
  977. if module.requiresRuntimeImplementationLibrary() {
  978. // Add dependency to the rule for generating the implementation library.
  979. ctx.AddDependency(module, implLibraryTag, module.implLibraryModuleName())
  980. if module.sharedLibrary() {
  981. // Add dependency to the rule for generating the xml permissions file
  982. ctx.AddDependency(module, xmlPermissionsFileTag, module.xmlPermissionsModuleName())
  983. }
  984. }
  985. }
  986. // Add other dependencies as normal.
  987. func (module *SdkLibrary) DepsMutator(ctx android.BottomUpMutatorContext) {
  988. var missingApiModules []string
  989. for _, apiScope := range module.getGeneratedApiScopes(ctx) {
  990. if apiScope.unstable {
  991. continue
  992. }
  993. if m := android.SrcIsModule(module.latestApiFilegroupName(apiScope)); !ctx.OtherModuleExists(m) {
  994. missingApiModules = append(missingApiModules, m)
  995. }
  996. if m := android.SrcIsModule(module.latestRemovedApiFilegroupName(apiScope)); !ctx.OtherModuleExists(m) {
  997. missingApiModules = append(missingApiModules, m)
  998. }
  999. if m := android.SrcIsModule(module.latestIncompatibilitiesFilegroupName(apiScope)); !ctx.OtherModuleExists(m) {
  1000. missingApiModules = append(missingApiModules, m)
  1001. }
  1002. }
  1003. if len(missingApiModules) != 0 && !module.sdkLibraryProperties.Unsafe_ignore_missing_latest_api {
  1004. m := module.Name() + " is missing tracking files for previously released library versions.\n"
  1005. m += "You need to do one of the following:\n"
  1006. m += "- Add `unsafe_ignore_missing_latest_api: true` to your blueprint (to disable compat tracking)\n"
  1007. m += "- Add a set of prebuilt txt files representing the last released version of this library for compat checking.\n"
  1008. m += " (the current set of API files can be used as a seed for this compatibility tracking\n"
  1009. m += "\n"
  1010. m += "The following filegroup modules are missing:\n "
  1011. m += strings.Join(missingApiModules, "\n ") + "\n"
  1012. m += "Please see the documentation of the prebuilt_apis module type (and a usage example in prebuilts/sdk) for a convenient way to generate these."
  1013. ctx.ModuleErrorf(m)
  1014. }
  1015. if module.requiresRuntimeImplementationLibrary() {
  1016. // Only add the deps for the library if it is actually going to be built.
  1017. module.Library.deps(ctx)
  1018. }
  1019. }
  1020. func (module *SdkLibrary) OutputFiles(tag string) (android.Paths, error) {
  1021. paths, err := module.commonOutputFiles(tag)
  1022. if paths != nil || err != nil {
  1023. return paths, err
  1024. }
  1025. if module.requiresRuntimeImplementationLibrary() {
  1026. return module.Library.OutputFiles(tag)
  1027. }
  1028. if tag == "" {
  1029. return nil, nil
  1030. }
  1031. return nil, fmt.Errorf("unsupported module reference tag %q", tag)
  1032. }
  1033. func (module *SdkLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  1034. if proptools.String(module.deviceProperties.Min_sdk_version) != "" {
  1035. module.CheckMinSdkVersion(ctx)
  1036. }
  1037. module.generateCommonBuildActions(ctx)
  1038. // Only build an implementation library if required.
  1039. if module.requiresRuntimeImplementationLibrary() {
  1040. module.Library.GenerateAndroidBuildActions(ctx)
  1041. }
  1042. // Collate the components exported by this module. All scope specific modules are exported but
  1043. // the impl and xml component modules are not.
  1044. exportedComponents := map[string]struct{}{}
  1045. // Record the paths to the header jars of the library (stubs and impl).
  1046. // When this java_sdk_library is depended upon from others via "libs" property,
  1047. // the recorded paths will be returned depending on the link type of the caller.
  1048. ctx.VisitDirectDeps(func(to android.Module) {
  1049. tag := ctx.OtherModuleDependencyTag(to)
  1050. // Extract information from any of the scope specific dependencies.
  1051. if scopeTag, ok := tag.(scopeDependencyTag); ok {
  1052. apiScope := scopeTag.apiScope
  1053. scopePaths := module.getScopePathsCreateIfNeeded(apiScope)
  1054. // Extract information from the dependency. The exact information extracted
  1055. // is determined by the nature of the dependency which is determined by the tag.
  1056. scopeTag.extractDepInfo(ctx, to, scopePaths)
  1057. exportedComponents[ctx.OtherModuleName(to)] = struct{}{}
  1058. }
  1059. })
  1060. // Make the set of components exported by this module available for use elsewhere.
  1061. exportedComponentInfo := android.ExportedComponentsInfo{Components: android.SortedStringKeys(exportedComponents)}
  1062. ctx.SetProvider(android.ExportedComponentsInfoProvider, exportedComponentInfo)
  1063. }
  1064. func (module *SdkLibrary) AndroidMkEntries() []android.AndroidMkEntries {
  1065. if !module.requiresRuntimeImplementationLibrary() {
  1066. return nil
  1067. }
  1068. entriesList := module.Library.AndroidMkEntries()
  1069. if module.sharedLibrary() {
  1070. entries := &entriesList[0]
  1071. entries.Required = append(entries.Required, module.xmlPermissionsModuleName())
  1072. }
  1073. return entriesList
  1074. }
  1075. // The dist path of the stub artifacts
  1076. func (module *SdkLibrary) apiDistPath(apiScope *apiScope) string {
  1077. return path.Join("apistubs", module.distGroup(), apiScope.name)
  1078. }
  1079. // Get the sdk version for use when compiling the stubs library.
  1080. func (module *SdkLibrary) sdkVersionForStubsLibrary(mctx android.EarlyModuleContext, apiScope *apiScope) string {
  1081. scopeProperties := module.scopeToProperties[apiScope]
  1082. if scopeProperties.Sdk_version != nil {
  1083. return proptools.String(scopeProperties.Sdk_version)
  1084. }
  1085. sdkDep := decodeSdkDep(mctx, android.SdkContext(&module.Library))
  1086. if sdkDep.hasStandardLibs() {
  1087. // If building against a standard sdk then use the sdk version appropriate for the scope.
  1088. return apiScope.sdkVersion
  1089. } else {
  1090. // Otherwise, use no system module.
  1091. return "none"
  1092. }
  1093. }
  1094. func (module *SdkLibrary) distStem() string {
  1095. return proptools.StringDefault(module.sdkLibraryProperties.Dist_stem, module.BaseModuleName())
  1096. }
  1097. // distGroup returns the subdirectory of the dist path of the stub artifacts.
  1098. func (module *SdkLibrary) distGroup() string {
  1099. return proptools.StringDefault(module.sdkLibraryProperties.Dist_group, "unknown")
  1100. }
  1101. func (module *SdkLibrary) latestApiFilegroupName(apiScope *apiScope) string {
  1102. return ":" + module.distStem() + ".api." + apiScope.name + ".latest"
  1103. }
  1104. func (module *SdkLibrary) latestRemovedApiFilegroupName(apiScope *apiScope) string {
  1105. return ":" + module.distStem() + "-removed.api." + apiScope.name + ".latest"
  1106. }
  1107. func (module *SdkLibrary) latestIncompatibilitiesFilegroupName(apiScope *apiScope) string {
  1108. return ":" + module.distStem() + "-incompatibilities.api." + apiScope.name + ".latest"
  1109. }
  1110. func childModuleVisibility(childVisibility []string) []string {
  1111. if childVisibility == nil {
  1112. // No child visibility set. The child will use the visibility of the sdk_library.
  1113. return nil
  1114. }
  1115. // Prepend an override to ignore the sdk_library's visibility, and rely on the child visibility.
  1116. var visibility []string
  1117. visibility = append(visibility, "//visibility:override")
  1118. visibility = append(visibility, childVisibility...)
  1119. return visibility
  1120. }
  1121. // Creates the implementation java library
  1122. func (module *SdkLibrary) createImplLibrary(mctx android.DefaultableHookContext) {
  1123. visibility := childModuleVisibility(module.sdkLibraryProperties.Impl_library_visibility)
  1124. props := struct {
  1125. Name *string
  1126. Visibility []string
  1127. Instrument bool
  1128. Libs []string
  1129. }{
  1130. Name: proptools.StringPtr(module.implLibraryModuleName()),
  1131. Visibility: visibility,
  1132. // Set the instrument property to ensure it is instrumented when instrumentation is required.
  1133. Instrument: true,
  1134. // Set the impl_only libs. Note that the module's "Libs" get appended as well, via the
  1135. // addition of &module.properties below.
  1136. Libs: module.sdkLibraryProperties.Impl_only_libs,
  1137. }
  1138. properties := []interface{}{
  1139. &module.properties,
  1140. &module.protoProperties,
  1141. &module.deviceProperties,
  1142. &module.dexProperties,
  1143. &module.dexpreoptProperties,
  1144. &module.linter.properties,
  1145. &props,
  1146. module.sdkComponentPropertiesForChildLibrary(),
  1147. }
  1148. mctx.CreateModule(LibraryFactory, properties...)
  1149. }
  1150. // Creates a static java library that has API stubs
  1151. func (module *SdkLibrary) createStubsLibrary(mctx android.DefaultableHookContext, apiScope *apiScope) {
  1152. props := struct {
  1153. Name *string
  1154. Visibility []string
  1155. Srcs []string
  1156. Installable *bool
  1157. Sdk_version *string
  1158. System_modules *string
  1159. Patch_module *string
  1160. Libs []string
  1161. Static_libs []string
  1162. Compile_dex *bool
  1163. Java_version *string
  1164. Openjdk9 struct {
  1165. Srcs []string
  1166. Javacflags []string
  1167. }
  1168. Dist struct {
  1169. Targets []string
  1170. Dest *string
  1171. Dir *string
  1172. Tag *string
  1173. }
  1174. }{}
  1175. props.Name = proptools.StringPtr(module.stubsLibraryModuleName(apiScope))
  1176. props.Visibility = childModuleVisibility(module.sdkLibraryProperties.Stubs_library_visibility)
  1177. // sources are generated from the droiddoc
  1178. props.Srcs = []string{":" + module.stubsSourceModuleName(apiScope)}
  1179. sdkVersion := module.sdkVersionForStubsLibrary(mctx, apiScope)
  1180. props.Sdk_version = proptools.StringPtr(sdkVersion)
  1181. props.System_modules = module.deviceProperties.System_modules
  1182. props.Patch_module = module.properties.Patch_module
  1183. props.Installable = proptools.BoolPtr(false)
  1184. props.Libs = module.sdkLibraryProperties.Stub_only_libs
  1185. props.Static_libs = module.sdkLibraryProperties.Stub_only_static_libs
  1186. // The stub-annotations library contains special versions of the annotations
  1187. // with CLASS retention policy, so that they're kept.
  1188. if proptools.Bool(module.sdkLibraryProperties.Annotations_enabled) {
  1189. props.Libs = append(props.Libs, "stub-annotations")
  1190. }
  1191. props.Openjdk9.Srcs = module.properties.Openjdk9.Srcs
  1192. props.Openjdk9.Javacflags = module.properties.Openjdk9.Javacflags
  1193. // We compile the stubs for 1.8 in line with the main android.jar stubs, and potential
  1194. // interop with older developer tools that don't support 1.9.
  1195. props.Java_version = proptools.StringPtr("1.8")
  1196. // The imports need to be compiled to dex if the java_sdk_library requests it.
  1197. compileDex := module.dexProperties.Compile_dex
  1198. if module.stubLibrariesCompiledForDex() {
  1199. compileDex = proptools.BoolPtr(true)
  1200. }
  1201. props.Compile_dex = compileDex
  1202. // Dist the class jar artifact for sdk builds.
  1203. if !Bool(module.sdkLibraryProperties.No_dist) {
  1204. props.Dist.Targets = []string{"sdk", "win_sdk"}
  1205. props.Dist.Dest = proptools.StringPtr(fmt.Sprintf("%v.jar", module.distStem()))
  1206. props.Dist.Dir = proptools.StringPtr(module.apiDistPath(apiScope))
  1207. props.Dist.Tag = proptools.StringPtr(".jar")
  1208. }
  1209. mctx.CreateModule(LibraryFactory, &props, module.sdkComponentPropertiesForChildLibrary())
  1210. }
  1211. // Creates a droidstubs module that creates stubs source files from the given full source
  1212. // files and also updates and checks the API specification files.
  1213. func (module *SdkLibrary) createStubsSourcesAndApi(mctx android.DefaultableHookContext, apiScope *apiScope, name string, scopeSpecificDroidstubsArgs []string) {
  1214. props := struct {
  1215. Name *string
  1216. Visibility []string
  1217. Srcs []string
  1218. Installable *bool
  1219. Sdk_version *string
  1220. System_modules *string
  1221. Libs []string
  1222. Output_javadoc_comments *bool
  1223. Arg_files []string
  1224. Args *string
  1225. Java_version *string
  1226. Annotations_enabled *bool
  1227. Merge_annotations_dirs []string
  1228. Merge_inclusion_annotations_dirs []string
  1229. Generate_stubs *bool
  1230. Previous_api *string
  1231. Check_api struct {
  1232. Current ApiToCheck
  1233. Last_released ApiToCheck
  1234. Api_lint struct {
  1235. Enabled *bool
  1236. New_since *string
  1237. Baseline_file *string
  1238. }
  1239. }
  1240. Aidl struct {
  1241. Include_dirs []string
  1242. Local_include_dirs []string
  1243. }
  1244. Dists []android.Dist
  1245. }{}
  1246. // The stubs source processing uses the same compile time classpath when extracting the
  1247. // API from the implementation library as it does when compiling it. i.e. the same
  1248. // * sdk version
  1249. // * system_modules
  1250. // * libs (static_libs/libs)
  1251. props.Name = proptools.StringPtr(name)
  1252. props.Visibility = childModuleVisibility(module.sdkLibraryProperties.Stubs_source_visibility)
  1253. props.Srcs = append(props.Srcs, module.properties.Srcs...)
  1254. props.Srcs = append(props.Srcs, module.sdkLibraryProperties.Api_srcs...)
  1255. props.Sdk_version = module.deviceProperties.Sdk_version
  1256. props.System_modules = module.deviceProperties.System_modules
  1257. props.Installable = proptools.BoolPtr(false)
  1258. // A droiddoc module has only one Libs property and doesn't distinguish between
  1259. // shared libs and static libs. So we need to add both of these libs to Libs property.
  1260. props.Libs = module.properties.Libs
  1261. props.Libs = append(props.Libs, module.properties.Static_libs...)
  1262. props.Aidl.Include_dirs = module.deviceProperties.Aidl.Include_dirs
  1263. props.Aidl.Local_include_dirs = module.deviceProperties.Aidl.Local_include_dirs
  1264. props.Java_version = module.properties.Java_version
  1265. props.Annotations_enabled = module.sdkLibraryProperties.Annotations_enabled
  1266. props.Merge_annotations_dirs = module.sdkLibraryProperties.Merge_annotations_dirs
  1267. props.Merge_inclusion_annotations_dirs = module.sdkLibraryProperties.Merge_inclusion_annotations_dirs
  1268. droidstubsArgs := []string{}
  1269. if len(module.sdkLibraryProperties.Api_packages) != 0 {
  1270. droidstubsArgs = append(droidstubsArgs, "--stub-packages "+strings.Join(module.sdkLibraryProperties.Api_packages, ":"))
  1271. }
  1272. if len(module.sdkLibraryProperties.Hidden_api_packages) != 0 {
  1273. droidstubsArgs = append(droidstubsArgs,
  1274. android.JoinWithPrefix(module.sdkLibraryProperties.Hidden_api_packages, " --hide-package "))
  1275. }
  1276. droidstubsArgs = append(droidstubsArgs, module.sdkLibraryProperties.Droiddoc_options...)
  1277. disabledWarnings := []string{
  1278. "MissingPermission",
  1279. "BroadcastBehavior",
  1280. "HiddenSuperclass",
  1281. "DeprecationMismatch",
  1282. "UnavailableSymbol",
  1283. "SdkConstant",
  1284. "HiddenTypeParameter",
  1285. "Todo",
  1286. "Typo",
  1287. }
  1288. droidstubsArgs = append(droidstubsArgs, android.JoinWithPrefix(disabledWarnings, "--hide "))
  1289. // Output Javadoc comments for public scope.
  1290. if apiScope == apiScopePublic {
  1291. props.Output_javadoc_comments = proptools.BoolPtr(true)
  1292. }
  1293. // Add in scope specific arguments.
  1294. droidstubsArgs = append(droidstubsArgs, scopeSpecificDroidstubsArgs...)
  1295. props.Arg_files = module.sdkLibraryProperties.Droiddoc_option_files
  1296. props.Args = proptools.StringPtr(strings.Join(droidstubsArgs, " "))
  1297. // List of APIs identified from the provided source files are created. They are later
  1298. // compared against to the not-yet-released (a.k.a current) list of APIs and to the
  1299. // last-released (a.k.a numbered) list of API.
  1300. currentApiFileName := apiScope.apiFilePrefix + "current.txt"
  1301. removedApiFileName := apiScope.apiFilePrefix + "removed.txt"
  1302. apiDir := module.getApiDir()
  1303. currentApiFileName = path.Join(apiDir, currentApiFileName)
  1304. removedApiFileName = path.Join(apiDir, removedApiFileName)
  1305. // check against the not-yet-release API
  1306. props.Check_api.Current.Api_file = proptools.StringPtr(currentApiFileName)
  1307. props.Check_api.Current.Removed_api_file = proptools.StringPtr(removedApiFileName)
  1308. if !(apiScope.unstable || module.sdkLibraryProperties.Unsafe_ignore_missing_latest_api) {
  1309. // check against the latest released API
  1310. latestApiFilegroupName := proptools.StringPtr(module.latestApiFilegroupName(apiScope))
  1311. props.Previous_api = latestApiFilegroupName
  1312. props.Check_api.Last_released.Api_file = latestApiFilegroupName
  1313. props.Check_api.Last_released.Removed_api_file = proptools.StringPtr(
  1314. module.latestRemovedApiFilegroupName(apiScope))
  1315. props.Check_api.Last_released.Baseline_file = proptools.StringPtr(
  1316. module.latestIncompatibilitiesFilegroupName(apiScope))
  1317. if proptools.Bool(module.sdkLibraryProperties.Api_lint.Enabled) {
  1318. // Enable api lint.
  1319. props.Check_api.Api_lint.Enabled = proptools.BoolPtr(true)
  1320. props.Check_api.Api_lint.New_since = latestApiFilegroupName
  1321. // If it exists then pass a lint-baseline.txt through to droidstubs.
  1322. baselinePath := path.Join(apiDir, apiScope.apiFilePrefix+"lint-baseline.txt")
  1323. baselinePathRelativeToRoot := path.Join(mctx.ModuleDir(), baselinePath)
  1324. paths, err := mctx.GlobWithDeps(baselinePathRelativeToRoot, nil)
  1325. if err != nil {
  1326. mctx.ModuleErrorf("error checking for presence of %s: %s", baselinePathRelativeToRoot, err)
  1327. }
  1328. if len(paths) == 1 {
  1329. props.Check_api.Api_lint.Baseline_file = proptools.StringPtr(baselinePath)
  1330. } else if len(paths) != 0 {
  1331. mctx.ModuleErrorf("error checking for presence of %s: expected one path, found: %v", baselinePathRelativeToRoot, paths)
  1332. }
  1333. }
  1334. }
  1335. if !Bool(module.sdkLibraryProperties.No_dist) {
  1336. // Dist the api txt and removed api txt artifacts for sdk builds.
  1337. distDir := proptools.StringPtr(path.Join(module.apiDistPath(apiScope), "api"))
  1338. for _, p := range []struct {
  1339. tag string
  1340. pattern string
  1341. }{
  1342. {tag: ".api.txt", pattern: "%s.txt"},
  1343. {tag: ".removed-api.txt", pattern: "%s-removed.txt"},
  1344. } {
  1345. props.Dists = append(props.Dists, android.Dist{
  1346. Targets: []string{"sdk", "win_sdk"},
  1347. Dir: distDir,
  1348. Dest: proptools.StringPtr(fmt.Sprintf(p.pattern, module.distStem())),
  1349. Tag: proptools.StringPtr(p.tag),
  1350. })
  1351. }
  1352. }
  1353. mctx.CreateModule(DroidstubsFactory, &props)
  1354. }
  1355. // Implements android.ApexModule
  1356. func (module *SdkLibrary) DepIsInSameApex(mctx android.BaseModuleContext, dep android.Module) bool {
  1357. depTag := mctx.OtherModuleDependencyTag(dep)
  1358. if depTag == xmlPermissionsFileTag {
  1359. return true
  1360. }
  1361. return module.Library.DepIsInSameApex(mctx, dep)
  1362. }
  1363. // Implements android.ApexModule
  1364. func (module *SdkLibrary) UniqueApexVariations() bool {
  1365. return module.uniqueApexVariations()
  1366. }
  1367. // Creates the xml file that publicizes the runtime library
  1368. func (module *SdkLibrary) createXmlFile(mctx android.DefaultableHookContext) {
  1369. moduleMinApiLevel := module.Library.MinSdkVersion(mctx).ApiLevel
  1370. var moduleMinApiLevelStr = moduleMinApiLevel.String()
  1371. if moduleMinApiLevel == android.NoneApiLevel {
  1372. moduleMinApiLevelStr = "current"
  1373. }
  1374. props := struct {
  1375. Name *string
  1376. Lib_name *string
  1377. Apex_available []string
  1378. On_bootclasspath_since *string
  1379. On_bootclasspath_before *string
  1380. Min_device_sdk *string
  1381. Max_device_sdk *string
  1382. Sdk_library_min_api_level *string
  1383. }{
  1384. Name: proptools.StringPtr(module.xmlPermissionsModuleName()),
  1385. Lib_name: proptools.StringPtr(module.BaseModuleName()),
  1386. Apex_available: module.ApexProperties.Apex_available,
  1387. On_bootclasspath_since: module.commonSdkLibraryProperties.On_bootclasspath_since,
  1388. On_bootclasspath_before: module.commonSdkLibraryProperties.On_bootclasspath_before,
  1389. Min_device_sdk: module.commonSdkLibraryProperties.Min_device_sdk,
  1390. Max_device_sdk: module.commonSdkLibraryProperties.Max_device_sdk,
  1391. Sdk_library_min_api_level: &moduleMinApiLevelStr,
  1392. }
  1393. mctx.CreateModule(sdkLibraryXmlFactory, &props)
  1394. }
  1395. func PrebuiltJars(ctx android.BaseModuleContext, baseName string, s android.SdkSpec) android.Paths {
  1396. var ver android.ApiLevel
  1397. var kind android.SdkKind
  1398. if s.UsePrebuilt(ctx) {
  1399. ver = s.ApiLevel
  1400. kind = s.Kind
  1401. } else {
  1402. // We don't have prebuilt SDK for the specific sdkVersion.
  1403. // Instead of breaking the build, fallback to use "system_current"
  1404. ver = android.FutureApiLevel
  1405. kind = android.SdkSystem
  1406. }
  1407. dir := filepath.Join("prebuilts", "sdk", ver.String(), kind.String())
  1408. jar := filepath.Join(dir, baseName+".jar")
  1409. jarPath := android.ExistentPathForSource(ctx, jar)
  1410. if !jarPath.Valid() {
  1411. if ctx.Config().AllowMissingDependencies() {
  1412. return android.Paths{android.PathForSource(ctx, jar)}
  1413. } else {
  1414. ctx.PropertyErrorf("sdk_library", "invalid sdk version %q, %q does not exist", s.Raw, jar)
  1415. }
  1416. return nil
  1417. }
  1418. return android.Paths{jarPath.Path()}
  1419. }
  1420. // Check to see if the other module is within the same set of named APEXes as this module.
  1421. //
  1422. // If either this or the other module are on the platform then this will return
  1423. // false.
  1424. func withinSameApexesAs(ctx android.BaseModuleContext, other android.Module) bool {
  1425. apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
  1426. otherApexInfo := ctx.OtherModuleProvider(other, android.ApexInfoProvider).(android.ApexInfo)
  1427. return len(otherApexInfo.InApexVariants) > 0 && reflect.DeepEqual(apexInfo.InApexVariants, otherApexInfo.InApexVariants)
  1428. }
  1429. func (module *SdkLibrary) sdkJars(ctx android.BaseModuleContext, sdkVersion android.SdkSpec, headerJars bool) android.Paths {
  1430. // If the client doesn't set sdk_version, but if this library prefers stubs over
  1431. // the impl library, let's provide the widest API surface possible. To do so,
  1432. // force override sdk_version to module_current so that the closest possible API
  1433. // surface could be found in selectHeaderJarsForSdkVersion
  1434. if module.defaultsToStubs() && !sdkVersion.Specified() {
  1435. sdkVersion = android.SdkSpecFrom(ctx, "module_current")
  1436. }
  1437. // Only provide access to the implementation library if it is actually built.
  1438. if module.requiresRuntimeImplementationLibrary() {
  1439. // Check any special cases for java_sdk_library.
  1440. //
  1441. // Only allow access to the implementation library in the following condition:
  1442. // * No sdk_version specified on the referencing module.
  1443. // * The referencing module is in the same apex as this.
  1444. if sdkVersion.Kind == android.SdkPrivate || withinSameApexesAs(ctx, module) {
  1445. if headerJars {
  1446. return module.HeaderJars()
  1447. } else {
  1448. return module.ImplementationJars()
  1449. }
  1450. }
  1451. }
  1452. return module.selectHeaderJarsForSdkVersion(ctx, sdkVersion)
  1453. }
  1454. // to satisfy SdkLibraryDependency interface
  1455. func (module *SdkLibrary) SdkHeaderJars(ctx android.BaseModuleContext, sdkVersion android.SdkSpec) android.Paths {
  1456. return module.sdkJars(ctx, sdkVersion, true /*headerJars*/)
  1457. }
  1458. // to satisfy SdkLibraryDependency interface
  1459. func (module *SdkLibrary) SdkImplementationJars(ctx android.BaseModuleContext, sdkVersion android.SdkSpec) android.Paths {
  1460. return module.sdkJars(ctx, sdkVersion, false /*headerJars*/)
  1461. }
  1462. var javaSdkLibrariesKey = android.NewOnceKey("javaSdkLibraries")
  1463. func javaSdkLibraries(config android.Config) *[]string {
  1464. return config.Once(javaSdkLibrariesKey, func() interface{} {
  1465. return &[]string{}
  1466. }).(*[]string)
  1467. }
  1468. func (module *SdkLibrary) getApiDir() string {
  1469. return proptools.StringDefault(module.sdkLibraryProperties.Api_dir, "api")
  1470. }
  1471. // For a java_sdk_library module, create internal modules for stubs, docs,
  1472. // runtime libs and xml file. If requested, the stubs and docs are created twice
  1473. // once for public API level and once for system API level
  1474. func (module *SdkLibrary) CreateInternalModules(mctx android.DefaultableHookContext) {
  1475. // If the module has been disabled then don't create any child modules.
  1476. if !module.Enabled() {
  1477. return
  1478. }
  1479. if len(module.properties.Srcs) == 0 {
  1480. mctx.PropertyErrorf("srcs", "java_sdk_library must specify srcs")
  1481. return
  1482. }
  1483. // If this builds against standard libraries (i.e. is not part of the core libraries)
  1484. // then assume it provides both system and test apis.
  1485. sdkDep := decodeSdkDep(mctx, android.SdkContext(&module.Library))
  1486. hasSystemAndTestApis := sdkDep.hasStandardLibs()
  1487. module.sdkLibraryProperties.Generate_system_and_test_apis = hasSystemAndTestApis
  1488. missingCurrentApi := false
  1489. generatedScopes := module.getGeneratedApiScopes(mctx)
  1490. apiDir := module.getApiDir()
  1491. for _, scope := range generatedScopes {
  1492. for _, api := range []string{"current.txt", "removed.txt"} {
  1493. path := path.Join(mctx.ModuleDir(), apiDir, scope.apiFilePrefix+api)
  1494. p := android.ExistentPathForSource(mctx, path)
  1495. if !p.Valid() {
  1496. if mctx.Config().AllowMissingDependencies() {
  1497. mctx.AddMissingDependencies([]string{path})
  1498. } else {
  1499. mctx.ModuleErrorf("Current api file %#v doesn't exist", path)
  1500. missingCurrentApi = true
  1501. }
  1502. }
  1503. }
  1504. }
  1505. if missingCurrentApi {
  1506. script := "build/soong/scripts/gen-java-current-api-files.sh"
  1507. p := android.ExistentPathForSource(mctx, script)
  1508. if !p.Valid() {
  1509. panic(fmt.Sprintf("script file %s doesn't exist", script))
  1510. }
  1511. mctx.ModuleErrorf("One or more current api files are missing. "+
  1512. "You can update them by:\n"+
  1513. "%s %q %s && m update-api",
  1514. script, filepath.Join(mctx.ModuleDir(), apiDir),
  1515. strings.Join(generatedScopes.Strings(func(s *apiScope) string { return s.apiFilePrefix }), " "))
  1516. return
  1517. }
  1518. for _, scope := range generatedScopes {
  1519. // Use the stubs source name for legacy reasons.
  1520. module.createStubsSourcesAndApi(mctx, scope, module.stubsSourceModuleName(scope), scope.droidstubsArgs)
  1521. module.createStubsLibrary(mctx, scope)
  1522. }
  1523. if module.requiresRuntimeImplementationLibrary() {
  1524. // Create child module to create an implementation library.
  1525. //
  1526. // This temporarily creates a second implementation library that can be explicitly
  1527. // referenced.
  1528. //
  1529. // TODO(b/156618935) - update comment once only one implementation library is created.
  1530. module.createImplLibrary(mctx)
  1531. // Only create an XML permissions file that declares the library as being usable
  1532. // as a shared library if required.
  1533. if module.sharedLibrary() {
  1534. module.createXmlFile(mctx)
  1535. }
  1536. // record java_sdk_library modules so that they are exported to make
  1537. javaSdkLibraries := javaSdkLibraries(mctx.Config())
  1538. javaSdkLibrariesLock.Lock()
  1539. defer javaSdkLibrariesLock.Unlock()
  1540. *javaSdkLibraries = append(*javaSdkLibraries, module.BaseModuleName())
  1541. }
  1542. // Add the impl_only_libs *after* we're done using the Libs prop in submodules.
  1543. module.properties.Libs = append(module.properties.Libs, module.sdkLibraryProperties.Impl_only_libs...)
  1544. }
  1545. func (module *SdkLibrary) InitSdkLibraryProperties() {
  1546. module.addHostAndDeviceProperties()
  1547. module.AddProperties(&module.sdkLibraryProperties)
  1548. module.initSdkLibraryComponent(module)
  1549. module.properties.Installable = proptools.BoolPtr(true)
  1550. module.deviceProperties.IsSDKLibrary = true
  1551. }
  1552. func (module *SdkLibrary) requiresRuntimeImplementationLibrary() bool {
  1553. return !proptools.Bool(module.sdkLibraryProperties.Api_only)
  1554. }
  1555. func (module *SdkLibrary) defaultsToStubs() bool {
  1556. return proptools.Bool(module.sdkLibraryProperties.Default_to_stubs)
  1557. }
  1558. // Defines how to name the individual component modules the sdk library creates.
  1559. type sdkLibraryComponentNamingScheme interface {
  1560. stubsLibraryModuleName(scope *apiScope, baseName string) string
  1561. stubsSourceModuleName(scope *apiScope, baseName string) string
  1562. }
  1563. type defaultNamingScheme struct {
  1564. }
  1565. func (s *defaultNamingScheme) stubsLibraryModuleName(scope *apiScope, baseName string) string {
  1566. return scope.stubsLibraryModuleName(baseName)
  1567. }
  1568. func (s *defaultNamingScheme) stubsSourceModuleName(scope *apiScope, baseName string) string {
  1569. return scope.stubsSourceModuleName(baseName)
  1570. }
  1571. var _ sdkLibraryComponentNamingScheme = (*defaultNamingScheme)(nil)
  1572. func moduleStubLinkType(name string) (stub bool, ret sdkLinkType) {
  1573. // This suffix-based approach is fragile and could potentially mis-trigger.
  1574. // TODO(b/155164730): Clean this up when modules no longer reference sdk_lib stubs directly.
  1575. if strings.HasSuffix(name, apiScopePublic.stubsLibraryModuleNameSuffix()) {
  1576. if name == "hwbinder.stubs" || name == "libcore_private.stubs" {
  1577. // Due to a previous bug, these modules were not considered stubs, so we retain that.
  1578. return false, javaPlatform
  1579. }
  1580. return true, javaSdk
  1581. }
  1582. if strings.HasSuffix(name, apiScopeSystem.stubsLibraryModuleNameSuffix()) {
  1583. return true, javaSystem
  1584. }
  1585. if strings.HasSuffix(name, apiScopeModuleLib.stubsLibraryModuleNameSuffix()) {
  1586. return true, javaModule
  1587. }
  1588. if strings.HasSuffix(name, apiScopeTest.stubsLibraryModuleNameSuffix()) {
  1589. return true, javaSystem
  1590. }
  1591. return false, javaPlatform
  1592. }
  1593. // java_sdk_library is a special Java library that provides optional platform APIs to apps.
  1594. // In practice, it can be viewed as a combination of several modules: 1) stubs library that clients
  1595. // are linked against to, 2) droiddoc module that internally generates API stubs source files,
  1596. // 3) the real runtime shared library that implements the APIs, and 4) XML file for adding
  1597. // the runtime lib to the classpath at runtime if requested via <uses-library>.
  1598. func SdkLibraryFactory() android.Module {
  1599. module := &SdkLibrary{}
  1600. // Initialize information common between source and prebuilt.
  1601. module.initCommon(module)
  1602. module.InitSdkLibraryProperties()
  1603. android.InitApexModule(module)
  1604. android.InitSdkAwareModule(module)
  1605. InitJavaModule(module, android.HostAndDeviceSupported)
  1606. // Initialize the map from scope to scope specific properties.
  1607. scopeToProperties := make(map[*apiScope]*ApiScopeProperties)
  1608. for _, scope := range allApiScopes {
  1609. scopeToProperties[scope] = scope.scopeSpecificProperties(module)
  1610. }
  1611. module.scopeToProperties = scopeToProperties
  1612. // Add the properties containing visibility rules so that they are checked.
  1613. android.AddVisibilityProperty(module, "impl_library_visibility", &module.sdkLibraryProperties.Impl_library_visibility)
  1614. android.AddVisibilityProperty(module, "stubs_library_visibility", &module.sdkLibraryProperties.Stubs_library_visibility)
  1615. android.AddVisibilityProperty(module, "stubs_source_visibility", &module.sdkLibraryProperties.Stubs_source_visibility)
  1616. module.SetDefaultableHook(func(ctx android.DefaultableHookContext) {
  1617. // If no implementation is required then it cannot be used as a shared library
  1618. // either.
  1619. if !module.requiresRuntimeImplementationLibrary() {
  1620. // If shared_library has been explicitly set to true then it is incompatible
  1621. // with api_only: true.
  1622. if proptools.Bool(module.commonSdkLibraryProperties.Shared_library) {
  1623. ctx.PropertyErrorf("api_only/shared_library", "inconsistent settings, shared_library and api_only cannot both be true")
  1624. }
  1625. // Set shared_library: false.
  1626. module.commonSdkLibraryProperties.Shared_library = proptools.BoolPtr(false)
  1627. }
  1628. if module.initCommonAfterDefaultsApplied(ctx) {
  1629. module.CreateInternalModules(ctx)
  1630. }
  1631. })
  1632. return module
  1633. }
  1634. //
  1635. // SDK library prebuilts
  1636. //
  1637. // Properties associated with each api scope.
  1638. type sdkLibraryScopeProperties struct {
  1639. Jars []string `android:"path"`
  1640. Sdk_version *string
  1641. // List of shared java libs that this module has dependencies to
  1642. Libs []string
  1643. // The stubs source.
  1644. Stub_srcs []string `android:"path"`
  1645. // The current.txt
  1646. Current_api *string `android:"path"`
  1647. // The removed.txt
  1648. Removed_api *string `android:"path"`
  1649. // Annotation zip
  1650. Annotations *string `android:"path"`
  1651. }
  1652. type sdkLibraryImportProperties struct {
  1653. // List of shared java libs, common to all scopes, that this module has
  1654. // dependencies to
  1655. Libs []string
  1656. // If set to true, compile dex files for the stubs. Defaults to false.
  1657. Compile_dex *bool
  1658. // If not empty, classes are restricted to the specified packages and their sub-packages.
  1659. Permitted_packages []string
  1660. }
  1661. type SdkLibraryImport struct {
  1662. android.ModuleBase
  1663. android.DefaultableModuleBase
  1664. prebuilt android.Prebuilt
  1665. android.ApexModuleBase
  1666. android.SdkBase
  1667. hiddenAPI
  1668. dexpreopter
  1669. properties sdkLibraryImportProperties
  1670. // Map from api scope to the scope specific property structure.
  1671. scopeProperties map[*apiScope]*sdkLibraryScopeProperties
  1672. commonToSdkLibraryAndImport
  1673. // The reference to the implementation library created by the source module.
  1674. // Is nil if the source module does not exist.
  1675. implLibraryModule *Library
  1676. // The reference to the xml permissions module created by the source module.
  1677. // Is nil if the source module does not exist.
  1678. xmlPermissionsFileModule *sdkLibraryXml
  1679. // Build path to the dex implementation jar obtained from the prebuilt_apex, if any.
  1680. dexJarFile OptionalDexJarPath
  1681. // Expected install file path of the source module(sdk_library)
  1682. // or dex implementation jar obtained from the prebuilt_apex, if any.
  1683. installFile android.Path
  1684. }
  1685. var _ SdkLibraryDependency = (*SdkLibraryImport)(nil)
  1686. // The type of a structure that contains a field of type sdkLibraryScopeProperties
  1687. // for each apiscope in allApiScopes, e.g. something like:
  1688. // struct {
  1689. // Public sdkLibraryScopeProperties
  1690. // System sdkLibraryScopeProperties
  1691. // ...
  1692. // }
  1693. var allScopeStructType = createAllScopePropertiesStructType()
  1694. // Dynamically create a structure type for each apiscope in allApiScopes.
  1695. func createAllScopePropertiesStructType() reflect.Type {
  1696. var fields []reflect.StructField
  1697. for _, apiScope := range allApiScopes {
  1698. field := reflect.StructField{
  1699. Name: apiScope.fieldName,
  1700. Type: reflect.TypeOf(sdkLibraryScopeProperties{}),
  1701. }
  1702. fields = append(fields, field)
  1703. }
  1704. return reflect.StructOf(fields)
  1705. }
  1706. // Create an instance of the scope specific structure type and return a map
  1707. // from apiscope to a pointer to each scope specific field.
  1708. func createPropertiesInstance() (interface{}, map[*apiScope]*sdkLibraryScopeProperties) {
  1709. allScopePropertiesPtr := reflect.New(allScopeStructType)
  1710. allScopePropertiesStruct := allScopePropertiesPtr.Elem()
  1711. scopeProperties := make(map[*apiScope]*sdkLibraryScopeProperties)
  1712. for _, apiScope := range allApiScopes {
  1713. field := allScopePropertiesStruct.FieldByName(apiScope.fieldName)
  1714. scopeProperties[apiScope] = field.Addr().Interface().(*sdkLibraryScopeProperties)
  1715. }
  1716. return allScopePropertiesPtr.Interface(), scopeProperties
  1717. }
  1718. // java_sdk_library_import imports a prebuilt java_sdk_library.
  1719. func sdkLibraryImportFactory() android.Module {
  1720. module := &SdkLibraryImport{}
  1721. allScopeProperties, scopeToProperties := createPropertiesInstance()
  1722. module.scopeProperties = scopeToProperties
  1723. module.AddProperties(&module.properties, allScopeProperties)
  1724. // Initialize information common between source and prebuilt.
  1725. module.initCommon(module)
  1726. android.InitPrebuiltModule(module, &[]string{""})
  1727. android.InitApexModule(module)
  1728. android.InitSdkAwareModule(module)
  1729. InitJavaModule(module, android.HostAndDeviceSupported)
  1730. module.SetDefaultableHook(func(mctx android.DefaultableHookContext) {
  1731. if module.initCommonAfterDefaultsApplied(mctx) {
  1732. module.createInternalModules(mctx)
  1733. }
  1734. })
  1735. return module
  1736. }
  1737. var _ PermittedPackagesForUpdatableBootJars = (*SdkLibraryImport)(nil)
  1738. func (module *SdkLibraryImport) PermittedPackagesForUpdatableBootJars() []string {
  1739. return module.properties.Permitted_packages
  1740. }
  1741. func (module *SdkLibraryImport) Prebuilt() *android.Prebuilt {
  1742. return &module.prebuilt
  1743. }
  1744. func (module *SdkLibraryImport) Name() string {
  1745. return module.prebuilt.Name(module.ModuleBase.Name())
  1746. }
  1747. func (module *SdkLibraryImport) createInternalModules(mctx android.DefaultableHookContext) {
  1748. // If the build is configured to use prebuilts then force this to be preferred.
  1749. if mctx.Config().AlwaysUsePrebuiltSdks() {
  1750. module.prebuilt.ForcePrefer()
  1751. }
  1752. for apiScope, scopeProperties := range module.scopeProperties {
  1753. if len(scopeProperties.Jars) == 0 {
  1754. continue
  1755. }
  1756. module.createJavaImportForStubs(mctx, apiScope, scopeProperties)
  1757. if len(scopeProperties.Stub_srcs) > 0 {
  1758. module.createPrebuiltStubsSources(mctx, apiScope, scopeProperties)
  1759. }
  1760. }
  1761. javaSdkLibraries := javaSdkLibraries(mctx.Config())
  1762. javaSdkLibrariesLock.Lock()
  1763. defer javaSdkLibrariesLock.Unlock()
  1764. *javaSdkLibraries = append(*javaSdkLibraries, module.BaseModuleName())
  1765. }
  1766. func (module *SdkLibraryImport) createJavaImportForStubs(mctx android.DefaultableHookContext, apiScope *apiScope, scopeProperties *sdkLibraryScopeProperties) {
  1767. // Creates a java import for the jar with ".stubs" suffix
  1768. props := struct {
  1769. Name *string
  1770. Sdk_version *string
  1771. Libs []string
  1772. Jars []string
  1773. Prefer *bool
  1774. Compile_dex *bool
  1775. }{}
  1776. props.Name = proptools.StringPtr(module.stubsLibraryModuleName(apiScope))
  1777. props.Sdk_version = scopeProperties.Sdk_version
  1778. // Prepend any of the libs from the legacy public properties to the libs for each of the
  1779. // scopes to avoid having to duplicate them in each scope.
  1780. props.Libs = append(module.properties.Libs, scopeProperties.Libs...)
  1781. props.Jars = scopeProperties.Jars
  1782. // The imports are preferred if the java_sdk_library_import is preferred.
  1783. props.Prefer = proptools.BoolPtr(module.prebuilt.Prefer())
  1784. // The imports need to be compiled to dex if the java_sdk_library_import requests it.
  1785. compileDex := module.properties.Compile_dex
  1786. if module.stubLibrariesCompiledForDex() {
  1787. compileDex = proptools.BoolPtr(true)
  1788. }
  1789. props.Compile_dex = compileDex
  1790. mctx.CreateModule(ImportFactory, &props, module.sdkComponentPropertiesForChildLibrary())
  1791. }
  1792. func (module *SdkLibraryImport) createPrebuiltStubsSources(mctx android.DefaultableHookContext, apiScope *apiScope, scopeProperties *sdkLibraryScopeProperties) {
  1793. props := struct {
  1794. Name *string
  1795. Srcs []string
  1796. Prefer *bool
  1797. }{}
  1798. props.Name = proptools.StringPtr(module.stubsSourceModuleName(apiScope))
  1799. props.Srcs = scopeProperties.Stub_srcs
  1800. mctx.CreateModule(PrebuiltStubsSourcesFactory, &props)
  1801. // The stubs source is preferred if the java_sdk_library_import is preferred.
  1802. props.Prefer = proptools.BoolPtr(module.prebuilt.Prefer())
  1803. }
  1804. // Add the dependencies on the child module in the component deps mutator so that it
  1805. // creates references to the prebuilt and not the source modules.
  1806. func (module *SdkLibraryImport) ComponentDepsMutator(ctx android.BottomUpMutatorContext) {
  1807. for apiScope, scopeProperties := range module.scopeProperties {
  1808. if len(scopeProperties.Jars) == 0 {
  1809. continue
  1810. }
  1811. // Add dependencies to the prebuilt stubs library
  1812. ctx.AddVariationDependencies(nil, apiScope.stubsTag, android.PrebuiltNameFromSource(module.stubsLibraryModuleName(apiScope)))
  1813. if len(scopeProperties.Stub_srcs) > 0 {
  1814. // Add dependencies to the prebuilt stubs source library
  1815. ctx.AddVariationDependencies(nil, apiScope.stubsSourceTag, android.PrebuiltNameFromSource(module.stubsSourceModuleName(apiScope)))
  1816. }
  1817. }
  1818. }
  1819. // Add other dependencies as normal.
  1820. func (module *SdkLibraryImport) DepsMutator(ctx android.BottomUpMutatorContext) {
  1821. implName := module.implLibraryModuleName()
  1822. if ctx.OtherModuleExists(implName) {
  1823. ctx.AddVariationDependencies(nil, implLibraryTag, implName)
  1824. xmlPermissionsModuleName := module.xmlPermissionsModuleName()
  1825. if module.sharedLibrary() && ctx.OtherModuleExists(xmlPermissionsModuleName) {
  1826. // Add dependency to the rule for generating the xml permissions file
  1827. ctx.AddDependency(module, xmlPermissionsFileTag, xmlPermissionsModuleName)
  1828. }
  1829. }
  1830. }
  1831. func (module *SdkLibraryImport) AndroidMkEntries() []android.AndroidMkEntries {
  1832. // For an SDK library imported from a prebuilt APEX, we don't need a Make module for itself, as we
  1833. // don't need to install it. However, we need to add its dexpreopt outputs as sub-modules, if it
  1834. // is preopted.
  1835. dexpreoptEntries := module.dexpreopter.AndroidMkEntriesForApex()
  1836. return append(dexpreoptEntries, android.AndroidMkEntries{Disabled: true})
  1837. }
  1838. var _ android.ApexModule = (*SdkLibraryImport)(nil)
  1839. // Implements android.ApexModule
  1840. func (module *SdkLibraryImport) DepIsInSameApex(mctx android.BaseModuleContext, dep android.Module) bool {
  1841. depTag := mctx.OtherModuleDependencyTag(dep)
  1842. if depTag == xmlPermissionsFileTag {
  1843. return true
  1844. }
  1845. // None of the other dependencies of the java_sdk_library_import are in the same apex
  1846. // as the one that references this module.
  1847. return false
  1848. }
  1849. // Implements android.ApexModule
  1850. func (module *SdkLibraryImport) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
  1851. sdkVersion android.ApiLevel) error {
  1852. // we don't check prebuilt modules for sdk_version
  1853. return nil
  1854. }
  1855. // Implements android.ApexModule
  1856. func (module *SdkLibraryImport) UniqueApexVariations() bool {
  1857. return module.uniqueApexVariations()
  1858. }
  1859. func (module *SdkLibraryImport) OutputFiles(tag string) (android.Paths, error) {
  1860. return module.commonOutputFiles(tag)
  1861. }
  1862. func (module *SdkLibraryImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  1863. module.generateCommonBuildActions(ctx)
  1864. // Assume that source module(sdk_library) is installed in /<sdk_library partition>/framework
  1865. module.installFile = android.PathForModuleInstall(ctx, "framework", module.Stem()+".jar")
  1866. // Record the paths to the prebuilt stubs library and stubs source.
  1867. ctx.VisitDirectDeps(func(to android.Module) {
  1868. tag := ctx.OtherModuleDependencyTag(to)
  1869. // Extract information from any of the scope specific dependencies.
  1870. if scopeTag, ok := tag.(scopeDependencyTag); ok {
  1871. apiScope := scopeTag.apiScope
  1872. scopePaths := module.getScopePathsCreateIfNeeded(apiScope)
  1873. // Extract information from the dependency. The exact information extracted
  1874. // is determined by the nature of the dependency which is determined by the tag.
  1875. scopeTag.extractDepInfo(ctx, to, scopePaths)
  1876. } else if tag == implLibraryTag {
  1877. if implLibrary, ok := to.(*Library); ok {
  1878. module.implLibraryModule = implLibrary
  1879. } else {
  1880. ctx.ModuleErrorf("implementation library must be of type *java.Library but was %T", to)
  1881. }
  1882. } else if tag == xmlPermissionsFileTag {
  1883. if xmlPermissionsFileModule, ok := to.(*sdkLibraryXml); ok {
  1884. module.xmlPermissionsFileModule = xmlPermissionsFileModule
  1885. } else {
  1886. ctx.ModuleErrorf("xml permissions file module must be of type *sdkLibraryXml but was %T", to)
  1887. }
  1888. }
  1889. })
  1890. // Populate the scope paths with information from the properties.
  1891. for apiScope, scopeProperties := range module.scopeProperties {
  1892. if len(scopeProperties.Jars) == 0 {
  1893. continue
  1894. }
  1895. paths := module.getScopePathsCreateIfNeeded(apiScope)
  1896. paths.annotationsZip = android.OptionalPathForModuleSrc(ctx, scopeProperties.Annotations)
  1897. paths.currentApiFilePath = android.OptionalPathForModuleSrc(ctx, scopeProperties.Current_api)
  1898. paths.removedApiFilePath = android.OptionalPathForModuleSrc(ctx, scopeProperties.Removed_api)
  1899. }
  1900. if ctx.Device() {
  1901. // If this is a variant created for a prebuilt_apex then use the dex implementation jar
  1902. // obtained from the associated deapexer module.
  1903. ai := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
  1904. if ai.ForPrebuiltApex {
  1905. // Get the path of the dex implementation jar from the `deapexer` module.
  1906. di := android.FindDeapexerProviderForModule(ctx)
  1907. if di == nil {
  1908. return // An error has been reported by FindDeapexerProviderForModule.
  1909. }
  1910. if dexOutputPath := di.PrebuiltExportPath(apexRootRelativePathToJavaLib(module.BaseModuleName())); dexOutputPath != nil {
  1911. dexJarFile := makeDexJarPathFromPath(dexOutputPath)
  1912. module.dexJarFile = dexJarFile
  1913. installPath := android.PathForModuleInPartitionInstall(
  1914. ctx, "apex", ai.ApexVariationName, apexRootRelativePathToJavaLib(module.BaseModuleName()))
  1915. module.installFile = installPath
  1916. module.initHiddenAPI(ctx, dexJarFile, module.findScopePaths(apiScopePublic).stubsImplPath[0], nil)
  1917. // Dexpreopting.
  1918. module.dexpreopter.installPath = module.dexpreopter.getInstallPath(ctx, installPath)
  1919. module.dexpreopter.isSDKLibrary = true
  1920. module.dexpreopter.uncompressedDex = shouldUncompressDex(ctx, &module.dexpreopter)
  1921. module.dexpreopt(ctx, dexOutputPath)
  1922. } else {
  1923. // This should never happen as a variant for a prebuilt_apex is only created if the
  1924. // prebuilt_apex has been configured to export the java library dex file.
  1925. ctx.ModuleErrorf("internal error: no dex implementation jar available from prebuilt APEX %s", di.ApexModuleName())
  1926. }
  1927. }
  1928. }
  1929. }
  1930. func (module *SdkLibraryImport) sdkJars(ctx android.BaseModuleContext, sdkVersion android.SdkSpec, headerJars bool) android.Paths {
  1931. // For consistency with SdkLibrary make the implementation jar available to libraries that
  1932. // are within the same APEX.
  1933. implLibraryModule := module.implLibraryModule
  1934. if implLibraryModule != nil && withinSameApexesAs(ctx, module) {
  1935. if headerJars {
  1936. return implLibraryModule.HeaderJars()
  1937. } else {
  1938. return implLibraryModule.ImplementationJars()
  1939. }
  1940. }
  1941. return module.selectHeaderJarsForSdkVersion(ctx, sdkVersion)
  1942. }
  1943. // to satisfy SdkLibraryDependency interface
  1944. func (module *SdkLibraryImport) SdkHeaderJars(ctx android.BaseModuleContext, sdkVersion android.SdkSpec) android.Paths {
  1945. // This module is just a wrapper for the prebuilt stubs.
  1946. return module.sdkJars(ctx, sdkVersion, true)
  1947. }
  1948. // to satisfy SdkLibraryDependency interface
  1949. func (module *SdkLibraryImport) SdkImplementationJars(ctx android.BaseModuleContext, sdkVersion android.SdkSpec) android.Paths {
  1950. // This module is just a wrapper for the stubs.
  1951. return module.sdkJars(ctx, sdkVersion, false)
  1952. }
  1953. // to satisfy UsesLibraryDependency interface
  1954. func (module *SdkLibraryImport) DexJarBuildPath() OptionalDexJarPath {
  1955. // The dex implementation jar extracted from the .apex file should be used in preference to the
  1956. // source.
  1957. if module.dexJarFile.IsSet() {
  1958. return module.dexJarFile
  1959. }
  1960. if module.implLibraryModule == nil {
  1961. return makeUnsetDexJarPath()
  1962. } else {
  1963. return module.implLibraryModule.DexJarBuildPath()
  1964. }
  1965. }
  1966. // to satisfy UsesLibraryDependency interface
  1967. func (module *SdkLibraryImport) DexJarInstallPath() android.Path {
  1968. return module.installFile
  1969. }
  1970. // to satisfy UsesLibraryDependency interface
  1971. func (module *SdkLibraryImport) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
  1972. return nil
  1973. }
  1974. // to satisfy apex.javaDependency interface
  1975. func (module *SdkLibraryImport) JacocoReportClassesFile() android.Path {
  1976. if module.implLibraryModule == nil {
  1977. return nil
  1978. } else {
  1979. return module.implLibraryModule.JacocoReportClassesFile()
  1980. }
  1981. }
  1982. // to satisfy apex.javaDependency interface
  1983. func (module *SdkLibraryImport) LintDepSets() LintDepSets {
  1984. if module.implLibraryModule == nil {
  1985. return LintDepSets{}
  1986. } else {
  1987. return module.implLibraryModule.LintDepSets()
  1988. }
  1989. }
  1990. func (module *SdkLibraryImport) getStrictUpdatabilityLinting() bool {
  1991. if module.implLibraryModule == nil {
  1992. return false
  1993. } else {
  1994. return module.implLibraryModule.getStrictUpdatabilityLinting()
  1995. }
  1996. }
  1997. func (module *SdkLibraryImport) setStrictUpdatabilityLinting(strictLinting bool) {
  1998. if module.implLibraryModule != nil {
  1999. module.implLibraryModule.setStrictUpdatabilityLinting(strictLinting)
  2000. }
  2001. }
  2002. // to satisfy apex.javaDependency interface
  2003. func (module *SdkLibraryImport) Stem() string {
  2004. return module.BaseModuleName()
  2005. }
  2006. var _ ApexDependency = (*SdkLibraryImport)(nil)
  2007. // to satisfy java.ApexDependency interface
  2008. func (module *SdkLibraryImport) HeaderJars() android.Paths {
  2009. if module.implLibraryModule == nil {
  2010. return nil
  2011. } else {
  2012. return module.implLibraryModule.HeaderJars()
  2013. }
  2014. }
  2015. // to satisfy java.ApexDependency interface
  2016. func (module *SdkLibraryImport) ImplementationAndResourcesJars() android.Paths {
  2017. if module.implLibraryModule == nil {
  2018. return nil
  2019. } else {
  2020. return module.implLibraryModule.ImplementationAndResourcesJars()
  2021. }
  2022. }
  2023. // to satisfy java.DexpreopterInterface interface
  2024. func (module *SdkLibraryImport) IsInstallable() bool {
  2025. return true
  2026. }
  2027. var _ android.RequiredFilesFromPrebuiltApex = (*SdkLibraryImport)(nil)
  2028. func (module *SdkLibraryImport) RequiredFilesFromPrebuiltApex(ctx android.BaseModuleContext) []string {
  2029. name := module.BaseModuleName()
  2030. return requiredFilesFromPrebuiltApexForImport(name)
  2031. }
  2032. //
  2033. // java_sdk_library_xml
  2034. //
  2035. type sdkLibraryXml struct {
  2036. android.ModuleBase
  2037. android.DefaultableModuleBase
  2038. android.ApexModuleBase
  2039. properties sdkLibraryXmlProperties
  2040. outputFilePath android.OutputPath
  2041. installDirPath android.InstallPath
  2042. hideApexVariantFromMake bool
  2043. }
  2044. type sdkLibraryXmlProperties struct {
  2045. // canonical name of the lib
  2046. Lib_name *string
  2047. // Signals that this shared library is part of the bootclasspath starting
  2048. // on the version indicated in this attribute.
  2049. //
  2050. // This will make platforms at this level and above to ignore
  2051. // <uses-library> tags with this library name because the library is already
  2052. // available
  2053. On_bootclasspath_since *string
  2054. // Signals that this shared library was part of the bootclasspath before
  2055. // (but not including) the version indicated in this attribute.
  2056. //
  2057. // The system will automatically add a <uses-library> tag with this library to
  2058. // apps that target any SDK less than the version indicated in this attribute.
  2059. On_bootclasspath_before *string
  2060. // Indicates that PackageManager should ignore this shared library if the
  2061. // platform is below the version indicated in this attribute.
  2062. //
  2063. // This means that the device won't recognise this library as installed.
  2064. Min_device_sdk *string
  2065. // Indicates that PackageManager should ignore this shared library if the
  2066. // platform is above the version indicated in this attribute.
  2067. //
  2068. // This means that the device won't recognise this library as installed.
  2069. Max_device_sdk *string
  2070. // The SdkLibrary's min api level as a string
  2071. //
  2072. // This value comes from the ApiLevel of the MinSdkVersion property.
  2073. Sdk_library_min_api_level *string
  2074. }
  2075. // java_sdk_library_xml builds the permission xml file for a java_sdk_library.
  2076. // Not to be used directly by users. java_sdk_library internally uses this.
  2077. func sdkLibraryXmlFactory() android.Module {
  2078. module := &sdkLibraryXml{}
  2079. module.AddProperties(&module.properties)
  2080. android.InitApexModule(module)
  2081. android.InitAndroidArchModule(module, android.DeviceSupported, android.MultilibCommon)
  2082. return module
  2083. }
  2084. func (module *sdkLibraryXml) UniqueApexVariations() bool {
  2085. // sdkLibraryXml needs a unique variation per APEX because the generated XML file contains the path to the
  2086. // mounted APEX, which contains the name of the APEX.
  2087. return true
  2088. }
  2089. // from android.PrebuiltEtcModule
  2090. func (module *sdkLibraryXml) BaseDir() string {
  2091. return "etc"
  2092. }
  2093. // from android.PrebuiltEtcModule
  2094. func (module *sdkLibraryXml) SubDir() string {
  2095. return "permissions"
  2096. }
  2097. // from android.PrebuiltEtcModule
  2098. func (module *sdkLibraryXml) OutputFile() android.OutputPath {
  2099. return module.outputFilePath
  2100. }
  2101. // from android.ApexModule
  2102. func (module *sdkLibraryXml) AvailableFor(what string) bool {
  2103. return true
  2104. }
  2105. func (module *sdkLibraryXml) DepsMutator(ctx android.BottomUpMutatorContext) {
  2106. // do nothing
  2107. }
  2108. var _ android.ApexModule = (*sdkLibraryXml)(nil)
  2109. // Implements android.ApexModule
  2110. func (module *sdkLibraryXml) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
  2111. sdkVersion android.ApiLevel) error {
  2112. // sdkLibraryXml doesn't need to be checked separately because java_sdk_library is checked
  2113. return nil
  2114. }
  2115. // File path to the runtime implementation library
  2116. func (module *sdkLibraryXml) implPath(ctx android.ModuleContext) string {
  2117. implName := proptools.String(module.properties.Lib_name)
  2118. if apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo); !apexInfo.IsForPlatform() {
  2119. // TODO(b/146468504): ApexVariationName() is only a soong module name, not apex name.
  2120. // In most cases, this works fine. But when apex_name is set or override_apex is used
  2121. // this can be wrong.
  2122. return fmt.Sprintf("/apex/%s/javalib/%s.jar", apexInfo.ApexVariationName, implName)
  2123. }
  2124. partition := "system"
  2125. if module.SocSpecific() {
  2126. partition = "vendor"
  2127. } else if module.DeviceSpecific() {
  2128. partition = "odm"
  2129. } else if module.ProductSpecific() {
  2130. partition = "product"
  2131. } else if module.SystemExtSpecific() {
  2132. partition = "system_ext"
  2133. }
  2134. return "/" + partition + "/framework/" + implName + ".jar"
  2135. }
  2136. func formattedOptionalSdkLevelAttribute(ctx android.ModuleContext, attrName string, value *string) string {
  2137. if value == nil {
  2138. return ""
  2139. }
  2140. apiLevel, err := android.ApiLevelFromUser(ctx, *value)
  2141. if err != nil {
  2142. // attributes in bp files have underscores but in the xml have dashes.
  2143. ctx.PropertyErrorf(strings.ReplaceAll(attrName, "-", "_"), err.Error())
  2144. return ""
  2145. }
  2146. intStr := strconv.Itoa(apiLevel.FinalOrPreviewInt())
  2147. return formattedOptionalAttribute(attrName, &intStr)
  2148. }
  2149. // formats an attribute for the xml permissions file if the value is not null
  2150. // returns empty string otherwise
  2151. func formattedOptionalAttribute(attrName string, value *string) string {
  2152. if value == nil {
  2153. return ""
  2154. }
  2155. return fmt.Sprintf(` %s=\"%s\"\n`, attrName, *value)
  2156. }
  2157. func (module *sdkLibraryXml) permissionsContents(ctx android.ModuleContext) string {
  2158. libName := proptools.String(module.properties.Lib_name)
  2159. libNameAttr := formattedOptionalAttribute("name", &libName)
  2160. filePath := module.implPath(ctx)
  2161. filePathAttr := formattedOptionalAttribute("file", &filePath)
  2162. implicitFromAttr := formattedOptionalSdkLevelAttribute(ctx, "on-bootclasspath-since", module.properties.On_bootclasspath_since)
  2163. implicitUntilAttr := formattedOptionalSdkLevelAttribute(ctx, "on-bootclasspath-before", module.properties.On_bootclasspath_before)
  2164. minSdkAttr := formattedOptionalSdkLevelAttribute(ctx, "min-device-sdk", module.properties.Min_device_sdk)
  2165. maxSdkAttr := formattedOptionalSdkLevelAttribute(ctx, "max-device-sdk", module.properties.Max_device_sdk)
  2166. // <library> is understood in all android versions whereas <updatable-library> is only understood from API T (and ignored before that).
  2167. // similarly, min_device_sdk is only understood from T. So if a library is using that, we need to use the updatable-library to make sure this library is not loaded before T
  2168. var libraryTag string
  2169. if module.properties.Min_device_sdk != nil {
  2170. libraryTag = ` <updatable-library\n`
  2171. } else {
  2172. libraryTag = ` <library\n`
  2173. }
  2174. return strings.Join([]string{
  2175. `<?xml version=\"1.0\" encoding=\"utf-8\"?>\n`,
  2176. `<!-- Copyright (C) 2018 The Android Open Source Project\n`,
  2177. `\n`,
  2178. ` Licensed under the Apache License, Version 2.0 (the \"License\");\n`,
  2179. ` you may not use this file except in compliance with the License.\n`,
  2180. ` You may obtain a copy of the License at\n`,
  2181. `\n`,
  2182. ` http://www.apache.org/licenses/LICENSE-2.0\n`,
  2183. `\n`,
  2184. ` Unless required by applicable law or agreed to in writing, software\n`,
  2185. ` distributed under the License is distributed on an \"AS IS\" BASIS,\n`,
  2186. ` WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n`,
  2187. ` See the License for the specific language governing permissions and\n`,
  2188. ` limitations under the License.\n`,
  2189. `-->\n`,
  2190. `<permissions>\n`,
  2191. libraryTag,
  2192. libNameAttr,
  2193. filePathAttr,
  2194. implicitFromAttr,
  2195. implicitUntilAttr,
  2196. minSdkAttr,
  2197. maxSdkAttr,
  2198. ` />\n`,
  2199. `</permissions>\n`}, "")
  2200. }
  2201. func (module *sdkLibraryXml) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  2202. module.hideApexVariantFromMake = !ctx.Provider(android.ApexInfoProvider).(android.ApexInfo).IsForPlatform()
  2203. libName := proptools.String(module.properties.Lib_name)
  2204. module.selfValidate(ctx)
  2205. xmlContent := module.permissionsContents(ctx)
  2206. module.outputFilePath = android.PathForModuleOut(ctx, libName+".xml").OutputPath
  2207. rule := android.NewRuleBuilder(pctx, ctx)
  2208. rule.Command().
  2209. Text("/bin/bash -c \"echo -e '" + xmlContent + "'\" > ").
  2210. Output(module.outputFilePath)
  2211. rule.Build("java_sdk_xml", "Permission XML")
  2212. module.installDirPath = android.PathForModuleInstall(ctx, "etc", module.SubDir())
  2213. }
  2214. func (module *sdkLibraryXml) AndroidMkEntries() []android.AndroidMkEntries {
  2215. if module.hideApexVariantFromMake {
  2216. return []android.AndroidMkEntries{{
  2217. Disabled: true,
  2218. }}
  2219. }
  2220. return []android.AndroidMkEntries{{
  2221. Class: "ETC",
  2222. OutputFile: android.OptionalPathForPath(module.outputFilePath),
  2223. ExtraEntries: []android.AndroidMkExtraEntriesFunc{
  2224. func(ctx android.AndroidMkExtraEntriesContext, entries *android.AndroidMkEntries) {
  2225. entries.SetString("LOCAL_MODULE_TAGS", "optional")
  2226. entries.SetString("LOCAL_MODULE_PATH", module.installDirPath.String())
  2227. entries.SetString("LOCAL_INSTALLED_MODULE_STEM", module.outputFilePath.Base())
  2228. },
  2229. },
  2230. }}
  2231. }
  2232. func (module *sdkLibraryXml) selfValidate(ctx android.ModuleContext) {
  2233. module.validateAtLeastTAttributes(ctx)
  2234. module.validateMinAndMaxDeviceSdk(ctx)
  2235. module.validateMinMaxDeviceSdkAndModuleMinSdk(ctx)
  2236. module.validateOnBootclasspathBeforeRequirements(ctx)
  2237. }
  2238. func (module *sdkLibraryXml) validateAtLeastTAttributes(ctx android.ModuleContext) {
  2239. t := android.ApiLevelOrPanic(ctx, "Tiramisu")
  2240. module.attrAtLeastT(ctx, t, module.properties.Min_device_sdk, "min_device_sdk")
  2241. module.attrAtLeastT(ctx, t, module.properties.Max_device_sdk, "max_device_sdk")
  2242. module.attrAtLeastT(ctx, t, module.properties.On_bootclasspath_before, "on_bootclasspath_before")
  2243. module.attrAtLeastT(ctx, t, module.properties.On_bootclasspath_since, "on_bootclasspath_since")
  2244. }
  2245. func (module *sdkLibraryXml) attrAtLeastT(ctx android.ModuleContext, t android.ApiLevel, attr *string, attrName string) {
  2246. if attr != nil {
  2247. if level, err := android.ApiLevelFromUser(ctx, *attr); err == nil {
  2248. // we will inform the user of invalid inputs when we try to write the
  2249. // permissions xml file so we don't need to do it here
  2250. if t.GreaterThan(level) {
  2251. ctx.PropertyErrorf(attrName, "Attribute value needs to be at least T")
  2252. }
  2253. }
  2254. }
  2255. }
  2256. func (module *sdkLibraryXml) validateMinAndMaxDeviceSdk(ctx android.ModuleContext) {
  2257. if module.properties.Min_device_sdk != nil && module.properties.Max_device_sdk != nil {
  2258. min, minErr := android.ApiLevelFromUser(ctx, *module.properties.Min_device_sdk)
  2259. max, maxErr := android.ApiLevelFromUser(ctx, *module.properties.Max_device_sdk)
  2260. if minErr == nil && maxErr == nil {
  2261. // we will inform the user of invalid inputs when we try to write the
  2262. // permissions xml file so we don't need to do it here
  2263. if min.GreaterThan(max) {
  2264. ctx.ModuleErrorf("min_device_sdk can't be greater than max_device_sdk")
  2265. }
  2266. }
  2267. }
  2268. }
  2269. func (module *sdkLibraryXml) validateMinMaxDeviceSdkAndModuleMinSdk(ctx android.ModuleContext) {
  2270. moduleMinApi := android.ApiLevelOrPanic(ctx, *module.properties.Sdk_library_min_api_level)
  2271. if module.properties.Min_device_sdk != nil {
  2272. api, err := android.ApiLevelFromUser(ctx, *module.properties.Min_device_sdk)
  2273. if err == nil {
  2274. if moduleMinApi.GreaterThan(api) {
  2275. ctx.PropertyErrorf("min_device_sdk", "Can't be less than module's min sdk (%s)", moduleMinApi)
  2276. }
  2277. }
  2278. }
  2279. if module.properties.Max_device_sdk != nil {
  2280. api, err := android.ApiLevelFromUser(ctx, *module.properties.Max_device_sdk)
  2281. if err == nil {
  2282. if moduleMinApi.GreaterThan(api) {
  2283. ctx.PropertyErrorf("max_device_sdk", "Can't be less than module's min sdk (%s)", moduleMinApi)
  2284. }
  2285. }
  2286. }
  2287. }
  2288. func (module *sdkLibraryXml) validateOnBootclasspathBeforeRequirements(ctx android.ModuleContext) {
  2289. moduleMinApi := android.ApiLevelOrPanic(ctx, *module.properties.Sdk_library_min_api_level)
  2290. if module.properties.On_bootclasspath_before != nil {
  2291. t := android.ApiLevelOrPanic(ctx, "Tiramisu")
  2292. // if we use the attribute, then we need to do this validation
  2293. if moduleMinApi.LessThan(t) {
  2294. // if minAPi is < T, then we need to have min_device_sdk (which only accepts T+)
  2295. if module.properties.Min_device_sdk == nil {
  2296. ctx.PropertyErrorf("on_bootclasspath_before", "Using this property requires that the module's min_sdk_version or the shared library's min_device_sdk is at least T")
  2297. }
  2298. }
  2299. }
  2300. }
  2301. type sdkLibrarySdkMemberType struct {
  2302. android.SdkMemberTypeBase
  2303. }
  2304. func (s *sdkLibrarySdkMemberType) AddDependencies(ctx android.SdkDependencyContext, dependencyTag blueprint.DependencyTag, names []string) {
  2305. ctx.AddVariationDependencies(nil, dependencyTag, names...)
  2306. }
  2307. func (s *sdkLibrarySdkMemberType) IsInstance(module android.Module) bool {
  2308. _, ok := module.(*SdkLibrary)
  2309. return ok
  2310. }
  2311. func (s *sdkLibrarySdkMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
  2312. return ctx.SnapshotBuilder().AddPrebuiltModule(member, "java_sdk_library_import")
  2313. }
  2314. func (s *sdkLibrarySdkMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
  2315. return &sdkLibrarySdkMemberProperties{}
  2316. }
  2317. var javaSdkLibrarySdkMemberType = &sdkLibrarySdkMemberType{
  2318. android.SdkMemberTypeBase{
  2319. PropertyName: "java_sdk_libs",
  2320. SupportsSdk: true,
  2321. },
  2322. }
  2323. type sdkLibrarySdkMemberProperties struct {
  2324. android.SdkMemberPropertiesBase
  2325. // Scope to per scope properties.
  2326. Scopes map[*apiScope]scopeProperties
  2327. // The Java stubs source files.
  2328. Stub_srcs []string
  2329. // The naming scheme.
  2330. Naming_scheme *string
  2331. // True if the java_sdk_library_import is for a shared library, false
  2332. // otherwise.
  2333. Shared_library *bool
  2334. // True if the stub imports should produce dex jars.
  2335. Compile_dex *bool
  2336. // The paths to the doctag files to add to the prebuilt.
  2337. Doctag_paths android.Paths
  2338. Permitted_packages []string
  2339. // Signals that this shared library is part of the bootclasspath starting
  2340. // on the version indicated in this attribute.
  2341. //
  2342. // This will make platforms at this level and above to ignore
  2343. // <uses-library> tags with this library name because the library is already
  2344. // available
  2345. On_bootclasspath_since *string
  2346. // Signals that this shared library was part of the bootclasspath before
  2347. // (but not including) the version indicated in this attribute.
  2348. //
  2349. // The system will automatically add a <uses-library> tag with this library to
  2350. // apps that target any SDK less than the version indicated in this attribute.
  2351. On_bootclasspath_before *string
  2352. // Indicates that PackageManager should ignore this shared library if the
  2353. // platform is below the version indicated in this attribute.
  2354. //
  2355. // This means that the device won't recognise this library as installed.
  2356. Min_device_sdk *string
  2357. // Indicates that PackageManager should ignore this shared library if the
  2358. // platform is above the version indicated in this attribute.
  2359. //
  2360. // This means that the device won't recognise this library as installed.
  2361. Max_device_sdk *string
  2362. }
  2363. type scopeProperties struct {
  2364. Jars android.Paths
  2365. StubsSrcJar android.Path
  2366. CurrentApiFile android.Path
  2367. RemovedApiFile android.Path
  2368. AnnotationsZip android.Path
  2369. SdkVersion string
  2370. }
  2371. func (s *sdkLibrarySdkMemberProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
  2372. sdk := variant.(*SdkLibrary)
  2373. s.Scopes = make(map[*apiScope]scopeProperties)
  2374. for _, apiScope := range allApiScopes {
  2375. paths := sdk.findScopePaths(apiScope)
  2376. if paths == nil {
  2377. continue
  2378. }
  2379. jars := paths.stubsImplPath
  2380. if len(jars) > 0 {
  2381. properties := scopeProperties{}
  2382. properties.Jars = jars
  2383. properties.SdkVersion = sdk.sdkVersionForStubsLibrary(ctx.SdkModuleContext(), apiScope)
  2384. properties.StubsSrcJar = paths.stubsSrcJar.Path()
  2385. if paths.currentApiFilePath.Valid() {
  2386. properties.CurrentApiFile = paths.currentApiFilePath.Path()
  2387. }
  2388. if paths.removedApiFilePath.Valid() {
  2389. properties.RemovedApiFile = paths.removedApiFilePath.Path()
  2390. }
  2391. // The annotations zip is only available for modules that set annotations_enabled: true.
  2392. if paths.annotationsZip.Valid() {
  2393. properties.AnnotationsZip = paths.annotationsZip.Path()
  2394. }
  2395. s.Scopes[apiScope] = properties
  2396. }
  2397. }
  2398. s.Naming_scheme = sdk.commonSdkLibraryProperties.Naming_scheme
  2399. s.Shared_library = proptools.BoolPtr(sdk.sharedLibrary())
  2400. s.Compile_dex = sdk.dexProperties.Compile_dex
  2401. s.Doctag_paths = sdk.doctagPaths
  2402. s.Permitted_packages = sdk.PermittedPackagesForUpdatableBootJars()
  2403. s.On_bootclasspath_since = sdk.commonSdkLibraryProperties.On_bootclasspath_since
  2404. s.On_bootclasspath_before = sdk.commonSdkLibraryProperties.On_bootclasspath_before
  2405. s.Min_device_sdk = sdk.commonSdkLibraryProperties.Min_device_sdk
  2406. s.Max_device_sdk = sdk.commonSdkLibraryProperties.Max_device_sdk
  2407. }
  2408. func (s *sdkLibrarySdkMemberProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
  2409. if s.Naming_scheme != nil {
  2410. propertySet.AddProperty("naming_scheme", proptools.String(s.Naming_scheme))
  2411. }
  2412. if s.Shared_library != nil {
  2413. propertySet.AddProperty("shared_library", *s.Shared_library)
  2414. }
  2415. if s.Compile_dex != nil {
  2416. propertySet.AddProperty("compile_dex", *s.Compile_dex)
  2417. }
  2418. if len(s.Permitted_packages) > 0 {
  2419. propertySet.AddProperty("permitted_packages", s.Permitted_packages)
  2420. }
  2421. for _, apiScope := range allApiScopes {
  2422. if properties, ok := s.Scopes[apiScope]; ok {
  2423. scopeSet := propertySet.AddPropertySet(apiScope.propertyName)
  2424. scopeDir := filepath.Join("sdk_library", s.OsPrefix(), apiScope.name)
  2425. var jars []string
  2426. for _, p := range properties.Jars {
  2427. dest := filepath.Join(scopeDir, ctx.Name()+"-stubs.jar")
  2428. ctx.SnapshotBuilder().CopyToSnapshot(p, dest)
  2429. jars = append(jars, dest)
  2430. }
  2431. scopeSet.AddProperty("jars", jars)
  2432. if ctx.SdkModuleContext().Config().IsEnvTrue("SOONG_SDK_SNAPSHOT_USE_SRCJAR") {
  2433. // Copy the stubs source jar into the snapshot zip as is.
  2434. srcJarSnapshotPath := filepath.Join(scopeDir, ctx.Name()+".srcjar")
  2435. ctx.SnapshotBuilder().CopyToSnapshot(properties.StubsSrcJar, srcJarSnapshotPath)
  2436. scopeSet.AddProperty("stub_srcs", []string{srcJarSnapshotPath})
  2437. } else {
  2438. // Merge the stubs source jar into the snapshot zip so that when it is unpacked
  2439. // the source files are also unpacked.
  2440. snapshotRelativeDir := filepath.Join(scopeDir, ctx.Name()+"_stub_sources")
  2441. ctx.SnapshotBuilder().UnzipToSnapshot(properties.StubsSrcJar, snapshotRelativeDir)
  2442. scopeSet.AddProperty("stub_srcs", []string{snapshotRelativeDir})
  2443. }
  2444. if properties.CurrentApiFile != nil {
  2445. currentApiSnapshotPath := filepath.Join(scopeDir, ctx.Name()+".txt")
  2446. ctx.SnapshotBuilder().CopyToSnapshot(properties.CurrentApiFile, currentApiSnapshotPath)
  2447. scopeSet.AddProperty("current_api", currentApiSnapshotPath)
  2448. }
  2449. if properties.RemovedApiFile != nil {
  2450. removedApiSnapshotPath := filepath.Join(scopeDir, ctx.Name()+"-removed.txt")
  2451. ctx.SnapshotBuilder().CopyToSnapshot(properties.RemovedApiFile, removedApiSnapshotPath)
  2452. scopeSet.AddProperty("removed_api", removedApiSnapshotPath)
  2453. }
  2454. if properties.AnnotationsZip != nil {
  2455. annotationsSnapshotPath := filepath.Join(scopeDir, ctx.Name()+"_annotations.zip")
  2456. ctx.SnapshotBuilder().CopyToSnapshot(properties.AnnotationsZip, annotationsSnapshotPath)
  2457. scopeSet.AddProperty("annotations", annotationsSnapshotPath)
  2458. }
  2459. if properties.SdkVersion != "" {
  2460. scopeSet.AddProperty("sdk_version", properties.SdkVersion)
  2461. }
  2462. }
  2463. }
  2464. if len(s.Doctag_paths) > 0 {
  2465. dests := []string{}
  2466. for _, p := range s.Doctag_paths {
  2467. dest := filepath.Join("doctags", p.Rel())
  2468. ctx.SnapshotBuilder().CopyToSnapshot(p, dest)
  2469. dests = append(dests, dest)
  2470. }
  2471. propertySet.AddProperty("doctag_files", dests)
  2472. }
  2473. }