sdk_library.go 119 KB

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