blob: 0c0b2b4339e57d4ab175c9a86040712dd402b904 [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
satayev0ee2f912021-12-01 17:39:48 +0000347 canonical := ReplaceFinalizedCodenames(config, raw)
Dan Albert1a246272020-07-06 14:49:35 -0700348 asInt, err := strconv.Atoi(canonical)
349 if err != nil {
350 return NoneApiLevel, fmt.Errorf("%q could not be parsed as an integer and is not a recognized codename", canonical)
351 }
352
353 apiLevel := uncheckedFinalApiLevel(asInt)
354 return apiLevel, nil
355}
356
Paul Duffin004547f2021-10-29 13:50:24 +0100357// ApiLevelForTest returns an ApiLevel constructed from the supplied raw string.
358//
359// This only supports "current" and numeric levels, code names are not supported.
360func ApiLevelForTest(raw string) ApiLevel {
361 if raw == "" {
362 panic("API level string must be non-empty")
363 }
364
365 if raw == "current" {
366 return FutureApiLevel
367 }
368
369 asInt, err := strconv.Atoi(raw)
370 if err != nil {
371 panic(fmt.Errorf("%q could not be parsed as an integer and is not a recognized codename", raw))
372 }
373
374 apiLevel := uncheckedFinalApiLevel(asInt)
375 return apiLevel
376}
377
Dan Albert1a246272020-07-06 14:49:35 -0700378// Converts an API level string `raw` into an ApiLevel in the same method as
379// `ApiLevelFromUser`, but the input is assumed to have no errors and any errors
380// will panic instead of returning an error.
Colin Cross9f720ce2020-10-02 10:26:04 -0700381func ApiLevelOrPanic(ctx PathContext, raw string) ApiLevel {
Dan Albert1a246272020-07-06 14:49:35 -0700382 value, err := ApiLevelFromUser(ctx, raw)
383 if err != nil {
384 panic(err.Error())
385 }
386 return value
387}
388
Colin Cross0875c522017-11-28 17:34:01 -0800389func ApiLevelsSingleton() Singleton {
Dan Albert30c9d6e2017-03-28 14:54:55 -0700390 return &apiLevelsSingleton{}
391}
392
393type apiLevelsSingleton struct{}
394
Colin Cross0875c522017-11-28 17:34:01 -0800395func createApiLevelsJson(ctx SingletonContext, file WritablePath,
Dan Albert30c9d6e2017-03-28 14:54:55 -0700396 apiLevelsMap map[string]int) {
397
398 jsonStr, err := json.Marshal(apiLevelsMap)
399 if err != nil {
400 ctx.Errorf(err.Error())
401 }
402
Colin Crosscf371cc2020-11-13 11:48:42 -0800403 WriteFileRule(ctx, file, string(jsonStr))
Dan Albert30c9d6e2017-03-28 14:54:55 -0700404}
405
Colin Cross0875c522017-11-28 17:34:01 -0800406func GetApiLevelsJson(ctx PathContext) WritablePath {
Dan Albert30c9d6e2017-03-28 14:54:55 -0700407 return PathForOutput(ctx, "api_levels.json")
408}
409
Alix Espino4fd7e742023-02-24 14:46:43 +0000410func getApiLevelsMapReleasedVersions() map[string]int {
411 return map[string]int{
412 "G": 9,
413 "I": 14,
414 "J": 16,
415 "J-MR1": 17,
416 "J-MR2": 18,
417 "K": 19,
418 "L": 21,
419 "L-MR1": 22,
420 "M": 23,
421 "N": 24,
422 "N-MR1": 25,
423 "O": 26,
424 "O-MR1": 27,
425 "P": 28,
426 "Q": 29,
427 "R": 30,
428 "S": 31,
429 "S-V2": 32,
430 "Tiramisu": 33,
431 }
432}
433
Dan Albert1a246272020-07-06 14:49:35 -0700434var finalCodenamesMapKey = NewOnceKey("FinalCodenamesMap")
435
436func getFinalCodenamesMap(config Config) map[string]int {
Alixfb7f7b92023-03-02 19:35:02 +0000437 // This logic is replicated in starlark, if changing logic here update starlark code too
438 // 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 -0700439 return config.Once(finalCodenamesMapKey, func() interface{} {
Alix Espino4fd7e742023-02-24 14:46:43 +0000440 apiLevelsMap := getApiLevelsMapReleasedVersions()
Dan Albert1a246272020-07-06 14:49:35 -0700441
Dan Albertc8060532020-07-22 22:32:17 -0700442 // TODO: Differentiate "current" and "future".
443 // The code base calls it FutureApiLevel, but the spelling is "current",
444 // and these are really two different things. When defining APIs it
445 // means the API has not yet been added to a specific release. When
446 // choosing an API level to build for it means that the future API level
447 // should be used, except in the case where the build is finalized in
448 // which case the platform version should be used. This is *weird*,
449 // because in the circumstance where API foo was added in R and bar was
450 // added in S, both of these are usable when building for "current" when
451 // neither R nor S are final, but the S APIs stop being available in a
452 // final R build.
Dan Albert1a246272020-07-06 14:49:35 -0700453 if Bool(config.productVariables.Platform_sdk_final) {
Dan Albert4f378d72020-07-23 17:32:15 -0700454 apiLevelsMap["current"] = config.PlatformSdkVersion().FinalOrFutureInt()
Dan Albert1a246272020-07-06 14:49:35 -0700455 }
456
457 return apiLevelsMap
458 }).(map[string]int)
459}
460
Colin Cross571cccf2019-02-04 11:22:08 -0800461var apiLevelsMapKey = NewOnceKey("ApiLevelsMap")
462
Alix Espino4fd7e742023-02-24 14:46:43 +0000463// ApiLevelsMap has entries for preview API levels
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000464func GetApiLevelsMap(config Config) map[string]int {
Alixfb7f7b92023-03-02 19:35:02 +0000465 // This logic is replicated in starlark, if changing logic here update starlark code too
466 // 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 -0800467 return config.Once(apiLevelsMapKey, func() interface{} {
Alix Espino4fd7e742023-02-24 14:46:43 +0000468 apiLevelsMap := getApiLevelsMapReleasedVersions()
Jooyung Han424175d2020-04-08 09:22:26 +0900469 for i, codename := range config.PlatformVersionActiveCodenames() {
Jooyung Han11b0fbd2021-02-05 02:28:22 +0900470 apiLevelsMap[codename] = previewAPILevelBase + i
Dan Albert6bc5b832018-05-03 15:42:34 -0700471 }
Dan Albert30c9d6e2017-03-28 14:54:55 -0700472
Dan Albert6bc5b832018-05-03 15:42:34 -0700473 return apiLevelsMap
474 }).(map[string]int)
475}
476
Dan Albert6bc5b832018-05-03 15:42:34 -0700477func (a *apiLevelsSingleton) GenerateBuildActions(ctx SingletonContext) {
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000478 apiLevelsMap := GetApiLevelsMap(ctx.Config())
Dan Albert30c9d6e2017-03-28 14:54:55 -0700479 apiLevelsJson := GetApiLevelsJson(ctx)
Colin Cross0875c522017-11-28 17:34:01 -0800480 createApiLevelsJson(ctx, apiLevelsJson, apiLevelsMap)
Dan Albert30c9d6e2017-03-28 14:54:55 -0700481}
Yu Liufc603162022-03-01 15:44:08 -0800482
Yu Liufc603162022-03-01 15:44:08 -0800483func StarlarkApiLevelConfigs(config Config) string {
Sam Delmerico7f889562022-03-25 14:55:40 +0000484 return fmt.Sprintf(bazel.GeneratedBazelFileWarning+`
Alix Espino4fd7e742023-02-24 14:46:43 +0000485_api_levels_released_versions = %s
Yu Liufc603162022-03-01 15:44:08 -0800486
Alix Espino4fd7e742023-02-24 14:46:43 +0000487api_levels_released_versions = _api_levels_released_versions
488`, starlark_fmt.PrintStringIntDict(getApiLevelsMapReleasedVersions(), 0),
Yu Liufc603162022-03-01 15:44:08 -0800489 )
Sam Delmerico7f889562022-03-25 14:55:40 +0000490}