sdk_library.go 121 KB

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