sdk_library.go 121 KB

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