blob: e48a69ea2b0d323256533514ba8c21a81dfe946e [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
Dan Albert1a246272020-07-06 14:49:35 -0700188// Returns -1 if the current API level is less than the argument, 0 if they
189// are equal, and 1 if it is greater than the argument.
190func (this ApiLevel) CompareTo(other ApiLevel) int {
191 if this.IsPreview() && !other.IsPreview() {
192 return 1
193 } else if !this.IsPreview() && other.IsPreview() {
194 return -1
195 }
196
197 if this.number < other.number {
198 return -1
199 } else if this.number == other.number {
200 return 0
201 } else {
202 return 1
203 }
204}
205
206func (this ApiLevel) EqualTo(other ApiLevel) bool {
207 return this.CompareTo(other) == 0
208}
209
210func (this ApiLevel) GreaterThan(other ApiLevel) bool {
211 return this.CompareTo(other) > 0
212}
213
214func (this ApiLevel) GreaterThanOrEqualTo(other ApiLevel) bool {
215 return this.CompareTo(other) >= 0
216}
217
218func (this ApiLevel) LessThan(other ApiLevel) bool {
219 return this.CompareTo(other) < 0
220}
221
222func (this ApiLevel) LessThanOrEqualTo(other ApiLevel) bool {
223 return this.CompareTo(other) <= 0
224}
225
226func uncheckedFinalApiLevel(num int) ApiLevel {
227 return ApiLevel{
228 value: strconv.Itoa(num),
229 number: num,
230 isPreview: false,
231 }
232}
233
Dan Albert1a246272020-07-06 14:49:35 -0700234var NoneApiLevel = ApiLevel{
235 value: "(no version)",
236 // Not 0 because we don't want this to compare equal with the first preview.
237 number: -1,
238 isPreview: true,
239}
240
Spandan Das15da5882023-03-02 23:36:39 +0000241// Sentinel ApiLevel to validate that an apiLevel is either an int or a recognized codename.
242var InvalidApiLevel = NewInvalidApiLevel("invalid")
243
244// Returns an apiLevel object at the same level as InvalidApiLevel.
245// The object contains the raw string provied in bp file, and can be used for error handling.
246func NewInvalidApiLevel(raw string) ApiLevel {
247 return ApiLevel{
248 value: raw,
249 number: -2, // One less than NoneApiLevel
250 isPreview: true,
251 }
252}
253
Dan Albert1a246272020-07-06 14:49:35 -0700254// The first version that introduced 64-bit ABIs.
255var FirstLp64Version = uncheckedFinalApiLevel(21)
256
Elliott Hughes0e9cdb02021-05-14 13:07:32 -0700257// Android has had various kinds of packed relocations over the years
258// (http://b/187907243).
259//
260// API level 30 is where the now-standard SHT_RELR is available.
261var FirstShtRelrVersion = uncheckedFinalApiLevel(30)
262
263// API level 28 introduced SHT_RELR when it was still Android-only, and used an
264// Android-specific relocation.
265var FirstAndroidRelrVersion = uncheckedFinalApiLevel(28)
266
267// API level 23 was when we first had the Chrome relocation packer, which is
268// obsolete and has been removed, but lld can now generate compatible packed
269// relocations itself.
270var FirstPackedRelocationsVersion = uncheckedFinalApiLevel(23)
271
Dan Albert1a246272020-07-06 14:49:35 -0700272// The first API level that does not require NDK code to link
273// libandroid_support.
274var FirstNonLibAndroidSupportVersion = uncheckedFinalApiLevel(21)
275
Paul Duffin004547f2021-10-29 13:50:24 +0100276// LastWithoutModuleLibCoreSystemModules is the last API level where prebuilts/sdk does not contain
277// a core-for-system-modules.jar for the module-lib API scope.
278var LastWithoutModuleLibCoreSystemModules = uncheckedFinalApiLevel(31)
279
Vinh Tranf1924742022-06-24 16:40:11 -0400280// ReplaceFinalizedCodenames returns the API level number associated with that API level
281// if the `raw` input is the codename of an API level has been finalized.
282// If the input is *not* a finalized codename, the input is returned unmodified.
satayev0ee2f912021-12-01 17:39:48 +0000283func ReplaceFinalizedCodenames(config Config, raw string) string {
284 num, ok := getFinalCodenamesMap(config)[raw]
Dan Albert1a246272020-07-06 14:49:35 -0700285 if !ok {
286 return raw
287 }
288
289 return strconv.Itoa(num)
290}
291
satayev0ee2f912021-12-01 17:39:48 +0000292// ApiLevelFromUser converts the given string `raw` to an ApiLevel, possibly returning an error.
Dan Albert1a246272020-07-06 14:49:35 -0700293//
294// `raw` must be non-empty. Passing an empty string results in a panic.
295//
296// "current" will return CurrentApiLevel, which is the ApiLevel associated with
297// an arbitrary future release (often referred to as API level 10000).
298//
299// Finalized codenames will be interpreted as their final API levels, not the
300// preview of the associated releases. R is now API 30, not the R preview.
301//
302// Future codenames return a preview API level that has no associated integer.
303//
304// Inputs that are not "current", known previews, or convertible to an integer
305// will return an error.
Colin Cross9f720ce2020-10-02 10:26:04 -0700306func ApiLevelFromUser(ctx PathContext, raw string) (ApiLevel, error) {
satayev0ee2f912021-12-01 17:39:48 +0000307 return ApiLevelFromUserWithConfig(ctx.Config(), raw)
308}
309
310// ApiLevelFromUserWithConfig implements ApiLevelFromUser, see comments for
311// ApiLevelFromUser for more details.
312func ApiLevelFromUserWithConfig(config Config, raw string) (ApiLevel, error) {
Alixfb7f7b92023-03-02 19:35:02 +0000313 // This logic is replicated in starlark, if changing logic here update starlark code too
314 // 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 -0700315 if raw == "" {
316 panic("API level string must be non-empty")
317 }
318
319 if raw == "current" {
Dan Albert0b176c82020-07-23 16:43:25 -0700320 return FutureApiLevel, nil
Dan Albert1a246272020-07-06 14:49:35 -0700321 }
322
satayev0ee2f912021-12-01 17:39:48 +0000323 for _, preview := range config.PreviewApiLevels() {
Dan Albert1a246272020-07-06 14:49:35 -0700324 if raw == preview.String() {
325 return preview, nil
326 }
327 }
328
satayev0ee2f912021-12-01 17:39:48 +0000329 canonical := ReplaceFinalizedCodenames(config, raw)
Dan Albert1a246272020-07-06 14:49:35 -0700330 asInt, err := strconv.Atoi(canonical)
331 if err != nil {
332 return NoneApiLevel, fmt.Errorf("%q could not be parsed as an integer and is not a recognized codename", canonical)
333 }
334
335 apiLevel := uncheckedFinalApiLevel(asInt)
336 return apiLevel, nil
337}
338
Paul Duffin004547f2021-10-29 13:50:24 +0100339// ApiLevelForTest returns an ApiLevel constructed from the supplied raw string.
340//
341// This only supports "current" and numeric levels, code names are not supported.
342func ApiLevelForTest(raw string) ApiLevel {
343 if raw == "" {
344 panic("API level string must be non-empty")
345 }
346
347 if raw == "current" {
348 return FutureApiLevel
349 }
350
351 asInt, err := strconv.Atoi(raw)
352 if err != nil {
353 panic(fmt.Errorf("%q could not be parsed as an integer and is not a recognized codename", raw))
354 }
355
356 apiLevel := uncheckedFinalApiLevel(asInt)
357 return apiLevel
358}
359
Dan Albert1a246272020-07-06 14:49:35 -0700360// Converts an API level string `raw` into an ApiLevel in the same method as
361// `ApiLevelFromUser`, but the input is assumed to have no errors and any errors
362// will panic instead of returning an error.
Colin Cross9f720ce2020-10-02 10:26:04 -0700363func ApiLevelOrPanic(ctx PathContext, raw string) ApiLevel {
Dan Albert1a246272020-07-06 14:49:35 -0700364 value, err := ApiLevelFromUser(ctx, raw)
365 if err != nil {
366 panic(err.Error())
367 }
368 return value
369}
370
Colin Cross0875c522017-11-28 17:34:01 -0800371func ApiLevelsSingleton() Singleton {
Dan Albert30c9d6e2017-03-28 14:54:55 -0700372 return &apiLevelsSingleton{}
373}
374
375type apiLevelsSingleton struct{}
376
Colin Cross0875c522017-11-28 17:34:01 -0800377func createApiLevelsJson(ctx SingletonContext, file WritablePath,
Dan Albert30c9d6e2017-03-28 14:54:55 -0700378 apiLevelsMap map[string]int) {
379
380 jsonStr, err := json.Marshal(apiLevelsMap)
381 if err != nil {
382 ctx.Errorf(err.Error())
383 }
384
Colin Crosscf371cc2020-11-13 11:48:42 -0800385 WriteFileRule(ctx, file, string(jsonStr))
Dan Albert30c9d6e2017-03-28 14:54:55 -0700386}
387
Colin Cross0875c522017-11-28 17:34:01 -0800388func GetApiLevelsJson(ctx PathContext) WritablePath {
Dan Albert30c9d6e2017-03-28 14:54:55 -0700389 return PathForOutput(ctx, "api_levels.json")
390}
391
Alix Espino4fd7e742023-02-24 14:46:43 +0000392func getApiLevelsMapReleasedVersions() map[string]int {
393 return map[string]int{
394 "G": 9,
395 "I": 14,
396 "J": 16,
397 "J-MR1": 17,
398 "J-MR2": 18,
399 "K": 19,
400 "L": 21,
401 "L-MR1": 22,
402 "M": 23,
403 "N": 24,
404 "N-MR1": 25,
405 "O": 26,
406 "O-MR1": 27,
407 "P": 28,
408 "Q": 29,
409 "R": 30,
410 "S": 31,
411 "S-V2": 32,
412 "Tiramisu": 33,
413 }
414}
415
Dan Albert1a246272020-07-06 14:49:35 -0700416var finalCodenamesMapKey = NewOnceKey("FinalCodenamesMap")
417
418func getFinalCodenamesMap(config Config) map[string]int {
Alixfb7f7b92023-03-02 19:35:02 +0000419 // This logic is replicated in starlark, if changing logic here update starlark code too
420 // 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 -0700421 return config.Once(finalCodenamesMapKey, func() interface{} {
Alix Espino4fd7e742023-02-24 14:46:43 +0000422 apiLevelsMap := getApiLevelsMapReleasedVersions()
Dan Albert1a246272020-07-06 14:49:35 -0700423
Dan Albertc8060532020-07-22 22:32:17 -0700424 // TODO: Differentiate "current" and "future".
425 // The code base calls it FutureApiLevel, but the spelling is "current",
426 // and these are really two different things. When defining APIs it
427 // means the API has not yet been added to a specific release. When
428 // choosing an API level to build for it means that the future API level
429 // should be used, except in the case where the build is finalized in
430 // which case the platform version should be used. This is *weird*,
431 // because in the circumstance where API foo was added in R and bar was
432 // added in S, both of these are usable when building for "current" when
433 // neither R nor S are final, but the S APIs stop being available in a
434 // final R build.
Dan Albert1a246272020-07-06 14:49:35 -0700435 if Bool(config.productVariables.Platform_sdk_final) {
Dan Albert4f378d72020-07-23 17:32:15 -0700436 apiLevelsMap["current"] = config.PlatformSdkVersion().FinalOrFutureInt()
Dan Albert1a246272020-07-06 14:49:35 -0700437 }
438
439 return apiLevelsMap
440 }).(map[string]int)
441}
442
Colin Cross571cccf2019-02-04 11:22:08 -0800443var apiLevelsMapKey = NewOnceKey("ApiLevelsMap")
444
Alix Espino4fd7e742023-02-24 14:46:43 +0000445// ApiLevelsMap has entries for preview API levels
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000446func GetApiLevelsMap(config Config) map[string]int {
Alixfb7f7b92023-03-02 19:35:02 +0000447 // This logic is replicated in starlark, if changing logic here update starlark code too
448 // 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 -0800449 return config.Once(apiLevelsMapKey, func() interface{} {
Alix Espino4fd7e742023-02-24 14:46:43 +0000450 apiLevelsMap := getApiLevelsMapReleasedVersions()
Jooyung Han424175d2020-04-08 09:22:26 +0900451 for i, codename := range config.PlatformVersionActiveCodenames() {
Jooyung Han11b0fbd2021-02-05 02:28:22 +0900452 apiLevelsMap[codename] = previewAPILevelBase + i
Dan Albert6bc5b832018-05-03 15:42:34 -0700453 }
Dan Albert30c9d6e2017-03-28 14:54:55 -0700454
Dan Albert6bc5b832018-05-03 15:42:34 -0700455 return apiLevelsMap
456 }).(map[string]int)
457}
458
Dan Albert6bc5b832018-05-03 15:42:34 -0700459func (a *apiLevelsSingleton) GenerateBuildActions(ctx SingletonContext) {
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000460 apiLevelsMap := GetApiLevelsMap(ctx.Config())
Dan Albert30c9d6e2017-03-28 14:54:55 -0700461 apiLevelsJson := GetApiLevelsJson(ctx)
Colin Cross0875c522017-11-28 17:34:01 -0800462 createApiLevelsJson(ctx, apiLevelsJson, apiLevelsMap)
Dan Albert30c9d6e2017-03-28 14:54:55 -0700463}
Yu Liufc603162022-03-01 15:44:08 -0800464
Yu Liufc603162022-03-01 15:44:08 -0800465func StarlarkApiLevelConfigs(config Config) string {
Sam Delmerico7f889562022-03-25 14:55:40 +0000466 return fmt.Sprintf(bazel.GeneratedBazelFileWarning+`
Alix Espino4fd7e742023-02-24 14:46:43 +0000467_api_levels_released_versions = %s
Yu Liufc603162022-03-01 15:44:08 -0800468
Alix Espino4fd7e742023-02-24 14:46:43 +0000469api_levels_released_versions = _api_levels_released_versions
470`, starlark_fmt.PrintStringIntDict(getApiLevelsMapReleasedVersions(), 0),
Yu Liufc603162022-03-01 15:44:08 -0800471 )
Sam Delmerico7f889562022-03-25 14:55:40 +0000472}