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 15package android 16 17import ( 18 "encoding/json" 19 "fmt" 20 "strconv" 21 22 "android/soong/bazel" 23 "android/soong/starlark_fmt" 24) 25 26func init() { 27 RegisterSingletonType("api_levels", ApiLevelsSingleton) 28} 29 30const previewAPILevelBase = 9000 31 32// 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 37// 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. 40type 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 57func (this ApiLevel) FinalInt() int { 58 if this.IsInvalid() { 59 panic(fmt.Errorf("%v is not a recognized api_level\n", this)) 60 } 61 if this.IsPreview() { 62 panic("Requested a final int from a non-final ApiLevel") 63 } else { 64 return this.number 65 } 66} 67 68func (this ApiLevel) FinalOrFutureInt() int { 69 if this.IsInvalid() { 70 panic(fmt.Errorf("%v is not a recognized api_level\n", this)) 71 } 72 if this.IsPreview() { 73 return FutureApiLevelInt 74 } else { 75 return this.number 76 } 77} 78 79// 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 { 85 if this.IsInvalid() { 86 panic(fmt.Errorf("%v is not a recognized api_level\n", this)) 87 } 88 if this.IsCurrent() { 89 return this.number 90 } 91 if this.IsPreview() { 92 return previewAPILevelBase + this.number 93 } 94 return this.number 95} 96 97// 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 109// Returns true if the raw api level string is invalid 110func (this ApiLevel) IsInvalid() bool { 111 return this.EqualTo(InvalidApiLevel) 112} 113 114// 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 126func (this ApiLevel) IsNone() bool { 127 return this.number == -1 128} 129 130// 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 136// 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 188// 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 196// 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 242var 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 249// 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 262// The first version that introduced 64-bit ABIs. 263var FirstLp64Version = uncheckedFinalApiLevel(21) 264 265// 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 280// The first API level that does not require NDK code to link 281// libandroid_support. 282var FirstNonLibAndroidSupportVersion = uncheckedFinalApiLevel(21) 283 284// 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 288// 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. 291func ReplaceFinalizedCodenames(config Config, raw string) string { 292 num, ok := getFinalCodenamesMap(config)[raw] 293 if !ok { 294 return raw 295 } 296 297 return strconv.Itoa(num) 298} 299 300// 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 310// ApiLevelFromUser converts the given string `raw` to an ApiLevel, possibly returning an error. 311// 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. 324func ApiLevelFromUser(ctx PathContext, raw string) (ApiLevel, error) { 325 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) { 331 // 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 333 if raw == "" { 334 panic("API level string must be non-empty") 335 } 336 337 if raw == "current" { 338 return FutureApiLevel, nil 339 } 340 341 for _, preview := range config.PreviewApiLevels() { 342 if raw == preview.String() { 343 return preview, nil 344 } 345 } 346 347 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 354 } 355 356 return uncheckedFinalApiLevel(canonical), nil 357 358} 359 360// 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 381// 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. 384func ApiLevelOrPanic(ctx PathContext, raw string) ApiLevel { 385 value, err := ApiLevelFromUser(ctx, raw) 386 if err != nil { 387 panic(err.Error()) 388 } 389 return value 390} 391 392func ApiLevelsSingleton() Singleton { 393 return &apiLevelsSingleton{} 394} 395 396type apiLevelsSingleton struct{} 397 398func createApiLevelsJson(ctx SingletonContext, file WritablePath, 399 apiLevelsMap map[string]int) { 400 401 jsonStr, err := json.Marshal(apiLevelsMap) 402 if err != nil { 403 ctx.Errorf(err.Error()) 404 } 405 406 WriteFileRule(ctx, file, string(jsonStr)) 407} 408 409func GetApiLevelsJson(ctx PathContext) WritablePath { 410 return PathForOutput(ctx, "api_levels.json") 411} 412 413func 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 "UpsideDownCake": 34, 435 } 436} 437 438var finalCodenamesMapKey = NewOnceKey("FinalCodenamesMap") 439 440func getFinalCodenamesMap(config Config) map[string]int { 441 // This logic is replicated in starlark, if changing logic here update starlark code too 442 // https://cs.android.com/android/platform/superproject/+/master:build/bazel/rules/common/api.bzl;l=30;drc=231c7e8c8038fd478a79eb68aa5b9f5c64e0e061 443 return config.Once(finalCodenamesMapKey, func() interface{} { 444 apiLevelsMap := getApiLevelsMapReleasedVersions() 445 446 // TODO: Differentiate "current" and "future". 447 // The code base calls it FutureApiLevel, but the spelling is "current", 448 // and these are really two different things. When defining APIs it 449 // means the API has not yet been added to a specific release. When 450 // choosing an API level to build for it means that the future API level 451 // should be used, except in the case where the build is finalized in 452 // which case the platform version should be used. This is *weird*, 453 // because in the circumstance where API foo was added in R and bar was 454 // added in S, both of these are usable when building for "current" when 455 // neither R nor S are final, but the S APIs stop being available in a 456 // final R build. 457 if Bool(config.productVariables.Platform_sdk_final) { 458 apiLevelsMap["current"] = config.PlatformSdkVersion().FinalOrFutureInt() 459 } 460 461 return apiLevelsMap 462 }).(map[string]int) 463} 464 465var apiLevelsMapKey = NewOnceKey("ApiLevelsMap") 466 467// ApiLevelsMap has entries for preview API levels 468func GetApiLevelsMap(config Config) map[string]int { 469 // This logic is replicated in starlark, if changing logic here update starlark code too 470 // https://cs.android.com/android/platform/superproject/+/master:build/bazel/rules/common/api.bzl;l=23;drc=231c7e8c8038fd478a79eb68aa5b9f5c64e0e061 471 return config.Once(apiLevelsMapKey, func() interface{} { 472 apiLevelsMap := getApiLevelsMapReleasedVersions() 473 for i, codename := range config.PlatformVersionAllPreviewCodenames() { 474 apiLevelsMap[codename] = previewAPILevelBase + i 475 } 476 477 return apiLevelsMap 478 }).(map[string]int) 479} 480 481func (a *apiLevelsSingleton) GenerateBuildActions(ctx SingletonContext) { 482 apiLevelsMap := GetApiLevelsMap(ctx.Config()) 483 apiLevelsJson := GetApiLevelsJson(ctx) 484 createApiLevelsJson(ctx, apiLevelsJson, apiLevelsMap) 485} 486 487func StarlarkApiLevelConfigs(config Config) string { 488 return fmt.Sprintf(bazel.GeneratedBazelFileWarning+` 489_api_levels_released_versions = %s 490 491api_levels_released_versions = _api_levels_released_versions 492`, starlark_fmt.PrintStringIntDict(getApiLevelsMapReleasedVersions(), 0), 493 ) 494} 495