api_levels.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. // Copyright 2017 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 android
  15. import (
  16. "android/soong/starlark_import"
  17. "encoding/json"
  18. "fmt"
  19. "strconv"
  20. )
  21. func init() {
  22. RegisterParallelSingletonType("api_levels", ApiLevelsSingleton)
  23. }
  24. const previewAPILevelBase = 9000
  25. // An API level, which may be a finalized (numbered) API, a preview (codenamed)
  26. // API, or the future API level (10000). Can be parsed from a string with
  27. // ApiLevelFromUser or ApiLevelOrPanic.
  28. //
  29. // The different *types* of API levels are handled separately. Currently only
  30. // Java has these, and they're managed with the SdkKind enum of the SdkSpec. A
  31. // future cleanup should be to migrate SdkSpec to using ApiLevel instead of its
  32. // SdkVersion int, and to move SdkSpec into this package.
  33. type ApiLevel struct {
  34. // The string representation of the API level.
  35. value string
  36. // A number associated with the API level. The exact value depends on
  37. // whether this API level is a preview or final API.
  38. //
  39. // For final API levels, this is the assigned version number.
  40. //
  41. // For preview API levels, this value has no meaning except to index known
  42. // previews to determine ordering.
  43. number int
  44. // Identifies this API level as either a preview or final API level.
  45. isPreview bool
  46. }
  47. func (this ApiLevel) FinalInt() int {
  48. if this.IsInvalid() {
  49. panic(fmt.Errorf("%v is not a recognized api_level\n", this))
  50. }
  51. if this.IsPreview() {
  52. panic("Requested a final int from a non-final ApiLevel")
  53. } else {
  54. return this.number
  55. }
  56. }
  57. func (this ApiLevel) FinalOrFutureInt() int {
  58. if this.IsInvalid() {
  59. panic(fmt.Errorf("%v is not a recognized api_level\n", this))
  60. }
  61. if this.IsPreview() {
  62. return FutureApiLevelInt
  63. } else {
  64. return this.number
  65. }
  66. }
  67. // FinalOrPreviewInt distinguishes preview versions from "current" (future).
  68. // This is for "native" stubs and should be in sync with ndkstubgen/getApiLevelsMap().
  69. // - "current" -> future (10000)
  70. // - preview codenames -> preview base (9000) + index
  71. // - otherwise -> cast to int
  72. func (this ApiLevel) FinalOrPreviewInt() int {
  73. if this.IsInvalid() {
  74. panic(fmt.Errorf("%v is not a recognized api_level\n", this))
  75. }
  76. if this.IsCurrent() {
  77. return this.number
  78. }
  79. if this.IsPreview() {
  80. return previewAPILevelBase + this.number
  81. }
  82. return this.number
  83. }
  84. // Returns the canonical name for this API level. For a finalized API level
  85. // this will be the API number as a string. For a preview API level this
  86. // will be the codename, or "current".
  87. func (this ApiLevel) String() string {
  88. return this.value
  89. }
  90. // Returns true if this is a non-final API level.
  91. func (this ApiLevel) IsPreview() bool {
  92. return this.isPreview
  93. }
  94. // Returns true if the raw api level string is invalid
  95. func (this ApiLevel) IsInvalid() bool {
  96. return this.EqualTo(InvalidApiLevel)
  97. }
  98. // Returns true if this is the unfinalized "current" API level. This means
  99. // different things across Java and native. Java APIs do not use explicit
  100. // codenames, so all non-final codenames are grouped into "current". For native
  101. // explicit codenames are typically used, and current is the union of all
  102. // non-final APIs, including those that may not yet be in any codename.
  103. //
  104. // Note that in a build where the platform is final, "current" will not be a
  105. // preview API level but will instead be canonicalized to the final API level.
  106. func (this ApiLevel) IsCurrent() bool {
  107. return this.value == "current"
  108. }
  109. func (this ApiLevel) IsNone() bool {
  110. return this.number == -1
  111. }
  112. // Returns true if an app is compiling against private apis.
  113. // e.g. if sdk_version = "" in Android.bp, then the ApiLevel of that "sdk" is at PrivateApiLevel.
  114. func (this ApiLevel) IsPrivate() bool {
  115. return this.number == PrivateApiLevel.number
  116. }
  117. // EffectiveVersion converts an ApiLevel into the concrete ApiLevel that the module should use. For
  118. // modules targeting an unreleased SDK (meaning it does not yet have a number) it returns
  119. // FutureApiLevel(10000).
  120. func (l ApiLevel) EffectiveVersion(ctx EarlyModuleContext) (ApiLevel, error) {
  121. if l.EqualTo(InvalidApiLevel) {
  122. return l, fmt.Errorf("invalid version in sdk_version %q", l.value)
  123. }
  124. if !l.IsPreview() {
  125. return l, nil
  126. }
  127. ret := ctx.Config().DefaultAppTargetSdk(ctx)
  128. if ret.IsPreview() {
  129. return FutureApiLevel, nil
  130. }
  131. return ret, nil
  132. }
  133. // EffectiveVersionString converts an SdkSpec into the concrete version string that the module
  134. // should use. For modules targeting an unreleased SDK (meaning it does not yet have a number)
  135. // it returns the codename (P, Q, R, etc.)
  136. func (l ApiLevel) EffectiveVersionString(ctx EarlyModuleContext) (string, error) {
  137. if l.EqualTo(InvalidApiLevel) {
  138. return l.value, fmt.Errorf("invalid version in sdk_version %q", l.value)
  139. }
  140. if !l.IsPreview() {
  141. return l.String(), nil
  142. }
  143. // Determine the default sdk
  144. ret := ctx.Config().DefaultAppTargetSdk(ctx)
  145. if !ret.IsPreview() {
  146. // If the default sdk has been finalized, return that
  147. return ret.String(), nil
  148. }
  149. // There can be more than one active in-development sdks
  150. // If an app is targeting an active sdk, but not the default one, return the requested active sdk.
  151. // e.g.
  152. // SETUP
  153. // In-development: UpsideDownCake, VanillaIceCream
  154. // Default: VanillaIceCream
  155. // Android.bp
  156. // min_sdk_version: `UpsideDownCake`
  157. // RETURN
  158. // UpsideDownCake and not VanillaIceCream
  159. for _, preview := range ctx.Config().PreviewApiLevels() {
  160. if l.String() == preview.String() {
  161. return preview.String(), nil
  162. }
  163. }
  164. // Otherwise return the default one
  165. return ret.String(), nil
  166. }
  167. // Specified returns true if the module is targeting a recognzized api_level.
  168. // It returns false if either
  169. // 1. min_sdk_version is not an int or a recognized codename
  170. // 2. both min_sdk_version and sdk_version are empty. In this case, MinSdkVersion() defaults to SdkSpecPrivate.ApiLevel
  171. func (this ApiLevel) Specified() bool {
  172. return !this.IsInvalid() && !this.IsPrivate()
  173. }
  174. // Returns -1 if the current API level is less than the argument, 0 if they
  175. // are equal, and 1 if it is greater than the argument.
  176. func (this ApiLevel) CompareTo(other ApiLevel) int {
  177. if this.IsPreview() && !other.IsPreview() {
  178. return 1
  179. } else if !this.IsPreview() && other.IsPreview() {
  180. return -1
  181. }
  182. if this.number < other.number {
  183. return -1
  184. } else if this.number == other.number {
  185. return 0
  186. } else {
  187. return 1
  188. }
  189. }
  190. func (this ApiLevel) EqualTo(other ApiLevel) bool {
  191. return this.CompareTo(other) == 0
  192. }
  193. func (this ApiLevel) GreaterThan(other ApiLevel) bool {
  194. return this.CompareTo(other) > 0
  195. }
  196. func (this ApiLevel) GreaterThanOrEqualTo(other ApiLevel) bool {
  197. return this.CompareTo(other) >= 0
  198. }
  199. func (this ApiLevel) LessThan(other ApiLevel) bool {
  200. return this.CompareTo(other) < 0
  201. }
  202. func (this ApiLevel) LessThanOrEqualTo(other ApiLevel) bool {
  203. return this.CompareTo(other) <= 0
  204. }
  205. func uncheckedFinalApiLevel(num int) ApiLevel {
  206. return ApiLevel{
  207. value: strconv.Itoa(num),
  208. number: num,
  209. isPreview: false,
  210. }
  211. }
  212. var NoneApiLevel = ApiLevel{
  213. value: "(no version)",
  214. // Not 0 because we don't want this to compare equal with the first preview.
  215. number: -1,
  216. isPreview: true,
  217. }
  218. // Sentinel ApiLevel to validate that an apiLevel is either an int or a recognized codename.
  219. var InvalidApiLevel = NewInvalidApiLevel("invalid")
  220. // Returns an apiLevel object at the same level as InvalidApiLevel.
  221. // The object contains the raw string provied in bp file, and can be used for error handling.
  222. func NewInvalidApiLevel(raw string) ApiLevel {
  223. return ApiLevel{
  224. value: raw,
  225. number: -2, // One less than NoneApiLevel
  226. isPreview: true,
  227. }
  228. }
  229. // The first version that introduced 64-bit ABIs.
  230. var FirstLp64Version = uncheckedFinalApiLevel(21)
  231. // Android has had various kinds of packed relocations over the years
  232. // (http://b/187907243).
  233. //
  234. // API level 30 is where the now-standard SHT_RELR is available.
  235. var FirstShtRelrVersion = uncheckedFinalApiLevel(30)
  236. // API level 28 introduced SHT_RELR when it was still Android-only, and used an
  237. // Android-specific relocation.
  238. var FirstAndroidRelrVersion = uncheckedFinalApiLevel(28)
  239. // API level 23 was when we first had the Chrome relocation packer, which is
  240. // obsolete and has been removed, but lld can now generate compatible packed
  241. // relocations itself.
  242. var FirstPackedRelocationsVersion = uncheckedFinalApiLevel(23)
  243. // The first API level that does not require NDK code to link
  244. // libandroid_support.
  245. var FirstNonLibAndroidSupportVersion = uncheckedFinalApiLevel(21)
  246. // LastWithoutModuleLibCoreSystemModules is the last API level where prebuilts/sdk does not contain
  247. // a core-for-system-modules.jar for the module-lib API scope.
  248. var LastWithoutModuleLibCoreSystemModules = uncheckedFinalApiLevel(31)
  249. // ReplaceFinalizedCodenames returns the API level number associated with that API level
  250. // if the `raw` input is the codename of an API level has been finalized.
  251. // If the input is *not* a finalized codename, the input is returned unmodified.
  252. func ReplaceFinalizedCodenames(config Config, raw string) (string, error) {
  253. finalCodenamesMap, err := getFinalCodenamesMap(config)
  254. if err != nil {
  255. return raw, err
  256. }
  257. num, ok := finalCodenamesMap[raw]
  258. if !ok {
  259. return raw, nil
  260. }
  261. return strconv.Itoa(num), nil
  262. }
  263. // ApiLevelFrom converts the given string `raw` to an ApiLevel.
  264. // If `raw` is invalid (empty string, unrecognized codename etc.) it returns an invalid ApiLevel
  265. func ApiLevelFrom(ctx PathContext, raw string) ApiLevel {
  266. ret, err := ApiLevelFromUser(ctx, raw)
  267. if err != nil {
  268. return NewInvalidApiLevel(raw)
  269. }
  270. return ret
  271. }
  272. // ApiLevelFromUser converts the given string `raw` to an ApiLevel, possibly returning an error.
  273. //
  274. // `raw` must be non-empty. Passing an empty string results in a panic.
  275. //
  276. // "current" will return CurrentApiLevel, which is the ApiLevel associated with
  277. // an arbitrary future release (often referred to as API level 10000).
  278. //
  279. // Finalized codenames will be interpreted as their final API levels, not the
  280. // preview of the associated releases. R is now API 30, not the R preview.
  281. //
  282. // Future codenames return a preview API level that has no associated integer.
  283. //
  284. // Inputs that are not "current", known previews, or convertible to an integer
  285. // will return an error.
  286. func ApiLevelFromUser(ctx PathContext, raw string) (ApiLevel, error) {
  287. return ApiLevelFromUserWithConfig(ctx.Config(), raw)
  288. }
  289. // ApiLevelFromUserWithConfig implements ApiLevelFromUser, see comments for
  290. // ApiLevelFromUser for more details.
  291. func ApiLevelFromUserWithConfig(config Config, raw string) (ApiLevel, error) {
  292. // This logic is replicated in starlark, if changing logic here update starlark code too
  293. // https://cs.android.com/android/platform/superproject/+/master:build/bazel/rules/common/api.bzl;l=42;drc=231c7e8c8038fd478a79eb68aa5b9f5c64e0e061
  294. if raw == "" {
  295. panic("API level string must be non-empty")
  296. }
  297. if raw == "current" {
  298. return FutureApiLevel, nil
  299. }
  300. for _, preview := range config.PreviewApiLevels() {
  301. if raw == preview.String() {
  302. return preview, nil
  303. }
  304. }
  305. apiLevelsReleasedVersions, err := getApiLevelsMapReleasedVersions()
  306. if err != nil {
  307. return NoneApiLevel, err
  308. }
  309. canonical, ok := apiLevelsReleasedVersions[raw]
  310. if !ok {
  311. asInt, err := strconv.Atoi(raw)
  312. if err != nil {
  313. return NoneApiLevel, fmt.Errorf("%q could not be parsed as an integer and is not a recognized codename", raw)
  314. }
  315. return uncheckedFinalApiLevel(asInt), nil
  316. }
  317. return uncheckedFinalApiLevel(canonical), nil
  318. }
  319. // ApiLevelForTest returns an ApiLevel constructed from the supplied raw string.
  320. //
  321. // This only supports "current" and numeric levels, code names are not supported.
  322. func ApiLevelForTest(raw string) ApiLevel {
  323. if raw == "" {
  324. panic("API level string must be non-empty")
  325. }
  326. if raw == "current" {
  327. return FutureApiLevel
  328. }
  329. asInt, err := strconv.Atoi(raw)
  330. if err != nil {
  331. panic(fmt.Errorf("%q could not be parsed as an integer and is not a recognized codename", raw))
  332. }
  333. apiLevel := uncheckedFinalApiLevel(asInt)
  334. return apiLevel
  335. }
  336. // Converts an API level string `raw` into an ApiLevel in the same method as
  337. // `ApiLevelFromUser`, but the input is assumed to have no errors and any errors
  338. // will panic instead of returning an error.
  339. func ApiLevelOrPanic(ctx PathContext, raw string) ApiLevel {
  340. value, err := ApiLevelFromUser(ctx, raw)
  341. if err != nil {
  342. panic(err.Error())
  343. }
  344. return value
  345. }
  346. func ApiLevelsSingleton() Singleton {
  347. return &apiLevelsSingleton{}
  348. }
  349. type apiLevelsSingleton struct{}
  350. func createApiLevelsJson(ctx SingletonContext, file WritablePath,
  351. apiLevelsMap map[string]int) {
  352. jsonStr, err := json.Marshal(apiLevelsMap)
  353. if err != nil {
  354. ctx.Errorf(err.Error())
  355. }
  356. WriteFileRule(ctx, file, string(jsonStr))
  357. }
  358. func GetApiLevelsJson(ctx PathContext) WritablePath {
  359. return PathForOutput(ctx, "api_levels.json")
  360. }
  361. func getApiLevelsMapReleasedVersions() (map[string]int, error) {
  362. return starlark_import.GetStarlarkValue[map[string]int]("api_levels_released_versions")
  363. }
  364. var finalCodenamesMapKey = NewOnceKey("FinalCodenamesMap")
  365. func getFinalCodenamesMap(config Config) (map[string]int, error) {
  366. type resultStruct struct {
  367. result map[string]int
  368. err error
  369. }
  370. // This logic is replicated in starlark, if changing logic here update starlark code too
  371. // https://cs.android.com/android/platform/superproject/+/master:build/bazel/rules/common/api.bzl;l=30;drc=231c7e8c8038fd478a79eb68aa5b9f5c64e0e061
  372. result := config.Once(finalCodenamesMapKey, func() interface{} {
  373. apiLevelsMap, err := getApiLevelsMapReleasedVersions()
  374. // TODO: Differentiate "current" and "future".
  375. // The code base calls it FutureApiLevel, but the spelling is "current",
  376. // and these are really two different things. When defining APIs it
  377. // means the API has not yet been added to a specific release. When
  378. // choosing an API level to build for it means that the future API level
  379. // should be used, except in the case where the build is finalized in
  380. // which case the platform version should be used. This is *weird*,
  381. // because in the circumstance where API foo was added in R and bar was
  382. // added in S, both of these are usable when building for "current" when
  383. // neither R nor S are final, but the S APIs stop being available in a
  384. // final R build.
  385. if err == nil && Bool(config.productVariables.Platform_sdk_final) {
  386. apiLevelsMap["current"] = config.PlatformSdkVersion().FinalOrFutureInt()
  387. }
  388. return resultStruct{apiLevelsMap, err}
  389. }).(resultStruct)
  390. return result.result, result.err
  391. }
  392. var apiLevelsMapKey = NewOnceKey("ApiLevelsMap")
  393. // ApiLevelsMap has entries for preview API levels
  394. func GetApiLevelsMap(config Config) (map[string]int, error) {
  395. type resultStruct struct {
  396. result map[string]int
  397. err error
  398. }
  399. // This logic is replicated in starlark, if changing logic here update starlark code too
  400. // https://cs.android.com/android/platform/superproject/+/master:build/bazel/rules/common/api.bzl;l=23;drc=231c7e8c8038fd478a79eb68aa5b9f5c64e0e061
  401. result := config.Once(apiLevelsMapKey, func() interface{} {
  402. apiLevelsMap, err := getApiLevelsMapReleasedVersions()
  403. if err == nil {
  404. for i, codename := range config.PlatformVersionAllPreviewCodenames() {
  405. apiLevelsMap[codename] = previewAPILevelBase + i
  406. }
  407. }
  408. return resultStruct{apiLevelsMap, err}
  409. }).(resultStruct)
  410. return result.result, result.err
  411. }
  412. func (a *apiLevelsSingleton) GenerateBuildActions(ctx SingletonContext) {
  413. apiLevelsMap, err := GetApiLevelsMap(ctx.Config())
  414. if err != nil {
  415. ctx.Errorf("%s\n", err)
  416. return
  417. }
  418. apiLevelsJson := GetApiLevelsJson(ctx)
  419. createApiLevelsJson(ctx, apiLevelsJson, apiLevelsMap)
  420. }