blob: 7214ccbb6898e2b1dd0112626f87251e6896c6d9 [file] [log] [blame]
Dan Albert30c9d6e2017-03-28 14:54:55 -07001// 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
15package android
16
17import (
18 "encoding/json"
Jooyung Han29e91d22020-04-02 01:41:41 +090019 "fmt"
Dan Albert6bc5b832018-05-03 15:42:34 -070020 "strconv"
Yu Liufc603162022-03-01 15:44:08 -080021
Sam Delmerico7f889562022-03-25 14:55:40 +000022 "android/soong/bazel"
Yu Liufc603162022-03-01 15:44:08 -080023 "android/soong/starlark_fmt"
Dan Albert30c9d6e2017-03-28 14:54:55 -070024)
25
26func init() {
27 RegisterSingletonType("api_levels", ApiLevelsSingleton)
28}
29
Jooyung Han11b0fbd2021-02-05 02:28:22 +090030const previewAPILevelBase = 9000
31
Dan Albert1a246272020-07-06 14:49:35 -070032// An API level, which may be a finalized (numbered) API, a preview (codenamed)
33// API, or the future API level (10000). Can be parsed from a string with
34// ApiLevelFromUser or ApiLevelOrPanic.
35//
36// The different *types* of API levels are handled separately. Currently only
Jiyong Parkf1691d22021-03-29 20:11:58 +090037// Java has these, and they're managed with the SdkKind enum of the SdkSpec. A
38// future cleanup should be to migrate SdkSpec to using ApiLevel instead of its
39// SdkVersion int, and to move SdkSpec into this package.
Dan Albert1a246272020-07-06 14:49:35 -070040type ApiLevel struct {
41 // The string representation of the API level.
42 value string
43
44 // A number associated with the API level. The exact value depends on
45 // whether this API level is a preview or final API.
46 //
47 // For final API levels, this is the assigned version number.
48 //
49 // For preview API levels, this value has no meaning except to index known
50 // previews to determine ordering.
51 number int
52
53 // Identifies this API level as either a preview or final API level.
54 isPreview bool
55}
56
Cole Fauste5bf3fb2022-07-01 19:39:14 +000057func (this ApiLevel) FinalInt() int {
Spandan Das15da5882023-03-02 23:36:39 +000058 if this.IsInvalid() {
59 panic(fmt.Errorf("%v is not a recognized api_level\n", this))
60 }
Cole Fauste5bf3fb2022-07-01 19:39:14 +000061 if this.IsPreview() {
62 panic("Requested a final int from a non-final ApiLevel")
63 } else {
64 return this.number
65 }
66}
67
Dan Albertc8060532020-07-22 22:32:17 -070068func (this ApiLevel) FinalOrFutureInt() int {
Spandan Das15da5882023-03-02 23:36:39 +000069 if this.IsInvalid() {
70 panic(fmt.Errorf("%v is not a recognized api_level\n", this))
71 }
Dan Albertc8060532020-07-22 22:32:17 -070072 if this.IsPreview() {
Dan Albert0b176c82020-07-23 16:43:25 -070073 return FutureApiLevelInt
Dan Albertc8060532020-07-22 22:32:17 -070074 } else {
75 return this.number
76 }
77}
78
Jooyung Han11b0fbd2021-02-05 02:28:22 +090079// FinalOrPreviewInt distinguishes preview versions from "current" (future).
80// This is for "native" stubs and should be in sync with ndkstubgen/getApiLevelsMap().
81// - "current" -> future (10000)
82// - preview codenames -> preview base (9000) + index
83// - otherwise -> cast to int
84func (this ApiLevel) FinalOrPreviewInt() int {
Spandan Das15da5882023-03-02 23:36:39 +000085 if this.IsInvalid() {
86 panic(fmt.Errorf("%v is not a recognized api_level\n", this))
87 }
Jooyung Han11b0fbd2021-02-05 02:28:22 +090088 if this.IsCurrent() {
89 return this.number
90 }
91 if this.IsPreview() {
92 return previewAPILevelBase + this.number
93 }
94 return this.number
95}
96
Dan Albert1a246272020-07-06 14:49:35 -070097// Returns the canonical name for this API level. For a finalized API level
98// this will be the API number as a string. For a preview API level this
99// will be the codename, or "current".
100func (this ApiLevel) String() string {
101 return this.value
102}
103
104// Returns true if this is a non-final API level.
105func (this ApiLevel) IsPreview() bool {
106 return this.isPreview
107}
108
Spandan Das15da5882023-03-02 23:36:39 +0000109// Returns true if the raw api level string is invalid
110func (this ApiLevel) IsInvalid() bool {
111 return this.EqualTo(InvalidApiLevel)
112}
113
Dan Albert1a246272020-07-06 14:49:35 -0700114// Returns true if this is the unfinalized "current" API level. This means
115// different things across Java and native. Java APIs do not use explicit
116// codenames, so all non-final codenames are grouped into "current". For native
117// explicit codenames are typically used, and current is the union of all
118// non-final APIs, including those that may not yet be in any codename.
119//
120// Note that in a build where the platform is final, "current" will not be a
121// preview API level but will instead be canonicalized to the final API level.
122func (this ApiLevel) IsCurrent() bool {
123 return this.value == "current"
124}
125
Jooyung Haned124c32021-01-26 11:43:46 +0900126func (this ApiLevel) IsNone() bool {
127 return this.number == -1
128}
129
Spandan Das15da5882023-03-02 23:36:39 +0000130// Returns true if an app is compiling against private apis.
131// e.g. if sdk_version = "" in Android.bp, then the ApiLevel of that "sdk" is at PrivateApiLevel.
132func (this ApiLevel) IsPrivate() bool {
133 return this.number == PrivateApiLevel.number
134}
135
Spandan Dasdd7057c2023-01-05 01:03:47 +0000136// EffectiveVersion converts an ApiLevel into the concrete ApiLevel that the module should use. For
137// modules targeting an unreleased SDK (meaning it does not yet have a number) it returns
138// FutureApiLevel(10000).
139func (l ApiLevel) EffectiveVersion(ctx EarlyModuleContext) (ApiLevel, error) {
140 if l.EqualTo(InvalidApiLevel) {
141 return l, fmt.Errorf("invalid version in sdk_version %q", l.value)
142 }
143 if !l.IsPreview() {
144 return l, nil
145 }
146 ret := ctx.Config().DefaultAppTargetSdk(ctx)
147 if ret.IsPreview() {
148 return FutureApiLevel, nil
149 }
150 return ret, nil
151}
152
153// EffectiveVersionString converts an SdkSpec into the concrete version string that the module
154// should use. For modules targeting an unreleased SDK (meaning it does not yet have a number)
155// it returns the codename (P, Q, R, etc.)
156func (l ApiLevel) EffectiveVersionString(ctx EarlyModuleContext) (string, error) {
157 if l.EqualTo(InvalidApiLevel) {
158 return l.value, fmt.Errorf("invalid version in sdk_version %q", l.value)
159 }
160 if !l.IsPreview() {
161 return l.String(), nil
162 }
163 // Determine the default sdk
164 ret := ctx.Config().DefaultAppTargetSdk(ctx)
165 if !ret.IsPreview() {
166 // If the default sdk has been finalized, return that
167 return ret.String(), nil
168 }
169 // There can be more than one active in-development sdks
170 // If an app is targeting an active sdk, but not the default one, return the requested active sdk.
171 // e.g.
172 // SETUP
173 // In-development: UpsideDownCake, VanillaIceCream
174 // Default: VanillaIceCream
175 // Android.bp
176 // min_sdk_version: `UpsideDownCake`
177 // RETURN
178 // UpsideDownCake and not VanillaIceCream
179 for _, preview := range ctx.Config().PreviewApiLevels() {
180 if l.String() == preview.String() {
181 return preview.String(), nil
182 }
183 }
184 // Otherwise return the default one
185 return ret.String(), nil
186}
187
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000188// Specified returns true if the module is targeting a recognzized api_level.
189// It returns false if either
190// 1. min_sdk_version is not an int or a recognized codename
191// 2. both min_sdk_version and sdk_version are empty. In this case, MinSdkVersion() defaults to SdkSpecPrivate.ApiLevel
192func (this ApiLevel) Specified() bool {
193 return !this.IsInvalid() && !this.IsPrivate()
194}
195
Dan Albert1a246272020-07-06 14:49:35 -0700196// Returns -1 if the current API level is less than the argument, 0 if they
197// are equal, and 1 if it is greater than the argument.
198func (this ApiLevel) CompareTo(other ApiLevel) int {
199 if this.IsPreview() && !other.IsPreview() {
200 return 1
201 } else if !this.IsPreview() && other.IsPreview() {
202 return -1
203 }
204
205 if this.number < other.number {
206 return -1
207 } else if this.number == other.number {
208 return 0
209 } else {
210 return 1
211 }
212}
213
214func (this ApiLevel) EqualTo(other ApiLevel) bool {
215 return this.CompareTo(other) == 0
216}
217
218func (this ApiLevel) GreaterThan(other ApiLevel) bool {
219 return this.CompareTo(other) > 0
220}
221
222func (this ApiLevel) GreaterThanOrEqualTo(other ApiLevel) bool {
223 return this.CompareTo(other) >= 0
224}
225
226func (this ApiLevel) LessThan(other ApiLevel) bool {
227 return this.CompareTo(other) < 0
228}
229
230func (this ApiLevel) LessThanOrEqualTo(other ApiLevel) bool {
231 return this.CompareTo(other) <= 0
232}
233
234func uncheckedFinalApiLevel(num int) ApiLevel {
235 return ApiLevel{
236 value: strconv.Itoa(num),
237 number: num,
238 isPreview: false,
239 }
240}
241
Dan Albert1a246272020-07-06 14:49:35 -0700242var NoneApiLevel = ApiLevel{
243 value: "(no version)",
244 // Not 0 because we don't want this to compare equal with the first preview.
245 number: -1,
246 isPreview: true,
247}
248
Spandan Das15da5882023-03-02 23:36:39 +0000249// Sentinel ApiLevel to validate that an apiLevel is either an int or a recognized codename.
250var InvalidApiLevel = NewInvalidApiLevel("invalid")
251
252// Returns an apiLevel object at the same level as InvalidApiLevel.
253// The object contains the raw string provied in bp file, and can be used for error handling.
254func NewInvalidApiLevel(raw string) ApiLevel {
255 return ApiLevel{
256 value: raw,
257 number: -2, // One less than NoneApiLevel
258 isPreview: true,
259 }
260}
261
Dan Albert1a246272020-07-06 14:49:35 -0700262// The first version that introduced 64-bit ABIs.
263var FirstLp64Version = uncheckedFinalApiLevel(21)
264
Elliott Hughes0e9cdb02021-05-14 13:07:32 -0700265// Android has had various kinds of packed relocations over the years
266// (http://b/187907243).
267//
268// API level 30 is where the now-standard SHT_RELR is available.
269var FirstShtRelrVersion = uncheckedFinalApiLevel(30)
270
271// API level 28 introduced SHT_RELR when it was still Android-only, and used an
272// Android-specific relocation.
273var FirstAndroidRelrVersion = uncheckedFinalApiLevel(28)
274
275// API level 23 was when we first had the Chrome relocation packer, which is
276// obsolete and has been removed, but lld can now generate compatible packed
277// relocations itself.
278var FirstPackedRelocationsVersion = uncheckedFinalApiLevel(23)
279
Dan Albert1a246272020-07-06 14:49:35 -0700280// The first API level that does not require NDK code to link
281// libandroid_support.
282var FirstNonLibAndroidSupportVersion = uncheckedFinalApiLevel(21)
283
Paul Duffin004547f2021-10-29 13:50:24 +0100284// LastWithoutModuleLibCoreSystemModules is the last API level where prebuilts/sdk does not contain
285// a core-for-system-modules.jar for the module-lib API scope.
286var LastWithoutModuleLibCoreSystemModules = uncheckedFinalApiLevel(31)
287
Vinh Tranf1924742022-06-24 16:40:11 -0400288// ReplaceFinalizedCodenames returns the API level number associated with that API level
289// if the `raw` input is the codename of an API level has been finalized.
290// If the input is *not* a finalized codename, the input is returned unmodified.
satayev0ee2f912021-12-01 17:39:48 +0000291func ReplaceFinalizedCodenames(config Config, raw string) string {
292 num, ok := getFinalCodenamesMap(config)[raw]
Dan Albert1a246272020-07-06 14:49:35 -0700293 if !ok {
294 return raw
295 }
296
297 return strconv.Itoa(num)
298}
299
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000300// ApiLevelFrom converts the given string `raw` to an ApiLevel.
301// If `raw` is invalid (empty string, unrecognized codename etc.) it returns an invalid ApiLevel
302func ApiLevelFrom(ctx PathContext, raw string) ApiLevel {
303 ret, err := ApiLevelFromUser(ctx, raw)
304 if err != nil {
305 return NewInvalidApiLevel(raw)
306 }
307 return ret
308}
309
satayev0ee2f912021-12-01 17:39:48 +0000310// ApiLevelFromUser converts the given string `raw` to an ApiLevel, possibly returning an error.
Dan Albert1a246272020-07-06 14:49:35 -0700311//
312// `raw` must be non-empty. Passing an empty string results in a panic.
313//
314// "current" will return CurrentApiLevel, which is the ApiLevel associated with
315// an arbitrary future release (often referred to as API level 10000).
316//
317// Finalized codenames will be interpreted as their final API levels, not the
318// preview of the associated releases. R is now API 30, not the R preview.
319//
320// Future codenames return a preview API level that has no associated integer.
321//
322// Inputs that are not "current", known previews, or convertible to an integer
323// will return an error.
Colin Cross9f720ce2020-10-02 10:26:04 -0700324func ApiLevelFromUser(ctx PathContext, raw string) (ApiLevel, error) {
satayev0ee2f912021-12-01 17:39:48 +0000325 return ApiLevelFromUserWithConfig(ctx.Config(), raw)
326}
327
328// ApiLevelFromUserWithConfig implements ApiLevelFromUser, see comments for
329// ApiLevelFromUser for more details.
330func ApiLevelFromUserWithConfig(config Config, raw string) (ApiLevel, error) {
Alixfb7f7b92023-03-02 19:35:02 +0000331 // This logic is replicated in starlark, if changing logic here update starlark code too
332 // https://cs.android.com/android/platform/superproject/+/master:build/bazel/rules/common/api.bzl;l=42;drc=231c7e8c8038fd478a79eb68aa5b9f5c64e0e061
Dan Albert1a246272020-07-06 14:49:35 -0700333 if raw == "" {
334 panic("API level string must be non-empty")
335 }
336
337 if raw == "current" {
Dan Albert0b176c82020-07-23 16:43:25 -0700338 return FutureApiLevel, nil
Dan Albert1a246272020-07-06 14:49:35 -0700339 }
340
satayev0ee2f912021-12-01 17:39:48 +0000341 for _, preview := range config.PreviewApiLevels() {
Dan Albert1a246272020-07-06 14:49:35 -0700342 if raw == preview.String() {
343 return preview, nil
344 }
345 }
346
Alixfb502512023-03-06 21:04:30 +0000347 canonical, ok := getApiLevelsMapReleasedVersions()[raw]
348 if !ok {
349 asInt, err := strconv.Atoi(raw)
350 if err != nil {
351 return NoneApiLevel, fmt.Errorf("%q could not be parsed as an integer and is not a recognized codename", raw)
352 }
353 return uncheckedFinalApiLevel(asInt), nil
Dan Albert1a246272020-07-06 14:49:35 -0700354 }
355
Alixfb502512023-03-06 21:04:30 +0000356 return uncheckedFinalApiLevel(canonical), nil
357
Dan Albert1a246272020-07-06 14:49:35 -0700358}
359
Paul Duffin004547f2021-10-29 13:50:24 +0100360// ApiLevelForTest returns an ApiLevel constructed from the supplied raw string.
361//
362// This only supports "current" and numeric levels, code names are not supported.
363func ApiLevelForTest(raw string) ApiLevel {
364 if raw == "" {
365 panic("API level string must be non-empty")
366 }
367
368 if raw == "current" {
369 return FutureApiLevel
370 }
371
372 asInt, err := strconv.Atoi(raw)
373 if err != nil {
374 panic(fmt.Errorf("%q could not be parsed as an integer and is not a recognized codename", raw))
375 }
376
377 apiLevel := uncheckedFinalApiLevel(asInt)
378 return apiLevel
379}
380
Dan Albert1a246272020-07-06 14:49:35 -0700381// Converts an API level string `raw` into an ApiLevel in the same method as
382// `ApiLevelFromUser`, but the input is assumed to have no errors and any errors
383// will panic instead of returning an error.
Colin Cross9f720ce2020-10-02 10:26:04 -0700384func ApiLevelOrPanic(ctx PathContext, raw string) ApiLevel {
Dan Albert1a246272020-07-06 14:49:35 -0700385 value, err := ApiLevelFromUser(ctx, raw)
386 if err != nil {
387 panic(err.Error())
388 }
389 return value
390}
391
Colin Cross0875c522017-11-28 17:34:01 -0800392func ApiLevelsSingleton() Singleton {
Dan Albert30c9d6e2017-03-28 14:54:55 -0700393 return &apiLevelsSingleton{}
394}
395
396type apiLevelsSingleton struct{}
397
Colin Cross0875c522017-11-28 17:34:01 -0800398func createApiLevelsJson(ctx SingletonContext, file WritablePath,
Dan Albert30c9d6e2017-03-28 14:54:55 -0700399 apiLevelsMap map[string]int) {
400
401 jsonStr, err := json.Marshal(apiLevelsMap)
402 if err != nil {
403 ctx.Errorf(err.Error())
404 }
405
Colin Crosscf371cc2020-11-13 11:48:42 -0800406 WriteFileRule(ctx, file, string(jsonStr))
Dan Albert30c9d6e2017-03-28 14:54:55 -0700407}
408
Colin Cross0875c522017-11-28 17:34:01 -0800409func GetApiLevelsJson(ctx PathContext) WritablePath {
Dan Albert30c9d6e2017-03-28 14:54:55 -0700410 return PathForOutput(ctx, "api_levels.json")
411}
412
Alix Espino4fd7e742023-02-24 14:46:43 +0000413func getApiLevelsMapReleasedVersions() map[string]int {
414 return map[string]int{
415 "G": 9,
416 "I": 14,
417 "J": 16,
418 "J-MR1": 17,
419 "J-MR2": 18,
420 "K": 19,
421 "L": 21,
422 "L-MR1": 22,
423 "M": 23,
424 "N": 24,
425 "N-MR1": 25,
426 "O": 26,
427 "O-MR1": 27,
428 "P": 28,
429 "Q": 29,
430 "R": 30,
431 "S": 31,
432 "S-V2": 32,
433 "Tiramisu": 33,
434 }
435}
436
Dan Albert1a246272020-07-06 14:49:35 -0700437var finalCodenamesMapKey = NewOnceKey("FinalCodenamesMap")
438
439func getFinalCodenamesMap(config Config) map[string]int {
Alixfb7f7b92023-03-02 19:35:02 +0000440 // This logic is replicated in starlark, if changing logic here update starlark code too
441 // https://cs.android.com/android/platform/superproject/+/master:build/bazel/rules/common/api.bzl;l=30;drc=231c7e8c8038fd478a79eb68aa5b9f5c64e0e061
Dan Albert1a246272020-07-06 14:49:35 -0700442 return config.Once(finalCodenamesMapKey, func() interface{} {
Alix Espino4fd7e742023-02-24 14:46:43 +0000443 apiLevelsMap := getApiLevelsMapReleasedVersions()
Dan Albert1a246272020-07-06 14:49:35 -0700444
Dan Albertc8060532020-07-22 22:32:17 -0700445 // TODO: Differentiate "current" and "future".
446 // The code base calls it FutureApiLevel, but the spelling is "current",
447 // and these are really two different things. When defining APIs it
448 // means the API has not yet been added to a specific release. When
449 // choosing an API level to build for it means that the future API level
450 // should be used, except in the case where the build is finalized in
451 // which case the platform version should be used. This is *weird*,
452 // because in the circumstance where API foo was added in R and bar was
453 // added in S, both of these are usable when building for "current" when
454 // neither R nor S are final, but the S APIs stop being available in a
455 // final R build.
Dan Albert1a246272020-07-06 14:49:35 -0700456 if Bool(config.productVariables.Platform_sdk_final) {
Dan Albert4f378d72020-07-23 17:32:15 -0700457 apiLevelsMap["current"] = config.PlatformSdkVersion().FinalOrFutureInt()
Dan Albert1a246272020-07-06 14:49:35 -0700458 }
459
460 return apiLevelsMap
461 }).(map[string]int)
462}
463
Colin Cross571cccf2019-02-04 11:22:08 -0800464var apiLevelsMapKey = NewOnceKey("ApiLevelsMap")
465
Alix Espino4fd7e742023-02-24 14:46:43 +0000466// ApiLevelsMap has entries for preview API levels
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000467func GetApiLevelsMap(config Config) map[string]int {
Alixfb7f7b92023-03-02 19:35:02 +0000468 // This logic is replicated in starlark, if changing logic here update starlark code too
469 // https://cs.android.com/android/platform/superproject/+/master:build/bazel/rules/common/api.bzl;l=23;drc=231c7e8c8038fd478a79eb68aa5b9f5c64e0e061
Colin Cross571cccf2019-02-04 11:22:08 -0800470 return config.Once(apiLevelsMapKey, func() interface{} {
Alix Espino4fd7e742023-02-24 14:46:43 +0000471 apiLevelsMap := getApiLevelsMapReleasedVersions()
Dan Albert8c7a9942023-03-27 20:34:01 +0000472 for i, codename := range config.PlatformVersionAllPreviewCodenames() {
Jooyung Han11b0fbd2021-02-05 02:28:22 +0900473 apiLevelsMap[codename] = previewAPILevelBase + i
Dan Albert6bc5b832018-05-03 15:42:34 -0700474 }
Dan Albert30c9d6e2017-03-28 14:54:55 -0700475
Dan Albert6bc5b832018-05-03 15:42:34 -0700476 return apiLevelsMap
477 }).(map[string]int)
478}
479
Dan Albert6bc5b832018-05-03 15:42:34 -0700480func (a *apiLevelsSingleton) GenerateBuildActions(ctx SingletonContext) {
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000481 apiLevelsMap := GetApiLevelsMap(ctx.Config())
Dan Albert30c9d6e2017-03-28 14:54:55 -0700482 apiLevelsJson := GetApiLevelsJson(ctx)
Colin Cross0875c522017-11-28 17:34:01 -0800483 createApiLevelsJson(ctx, apiLevelsJson, apiLevelsMap)
Dan Albert30c9d6e2017-03-28 14:54:55 -0700484}
Yu Liufc603162022-03-01 15:44:08 -0800485
Yu Liufc603162022-03-01 15:44:08 -0800486func StarlarkApiLevelConfigs(config Config) string {
Sam Delmerico7f889562022-03-25 14:55:40 +0000487 return fmt.Sprintf(bazel.GeneratedBazelFileWarning+`
Alix Espino4fd7e742023-02-24 14:46:43 +0000488_api_levels_released_versions = %s
Yu Liufc603162022-03-01 15:44:08 -0800489
Alix Espino4fd7e742023-02-24 14:46:43 +0000490api_levels_released_versions = _api_levels_released_versions
491`, starlark_fmt.PrintStringIntDict(getApiLevelsMapReleasedVersions(), 0),
Yu Liufc603162022-03-01 15:44:08 -0800492 )
Sam Delmerico7f889562022-03-25 14:55:40 +0000493}