1// Copyright 2016 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 "fmt" 19 "reflect" 20 "strings" 21 22 "github.com/google/blueprint" 23 "github.com/google/blueprint/proptools" 24) 25 26// This file implements common functionality for handling modules that may exist as prebuilts, 27// source, or both. 28 29func RegisterPrebuiltMutators(ctx RegistrationContext) { 30 ctx.PreArchMutators(RegisterPrebuiltsPreArchMutators) 31 ctx.PostDepsMutators(RegisterPrebuiltsPostDepsMutators) 32} 33 34// Marks a dependency tag as possibly preventing a reference to a source from being 35// replaced with the prebuilt. 36type ReplaceSourceWithPrebuilt interface { 37 blueprint.DependencyTag 38 39 // Return true if the dependency defined by this tag should be replaced with the 40 // prebuilt. 41 ReplaceSourceWithPrebuilt() bool 42} 43 44type prebuiltDependencyTag struct { 45 blueprint.BaseDependencyTag 46} 47 48var PrebuiltDepTag prebuiltDependencyTag 49 50// Mark this tag so dependencies that use it are excluded from visibility enforcement. 51func (t prebuiltDependencyTag) ExcludeFromVisibilityEnforcement() {} 52 53// Mark this tag so dependencies that use it are excluded from APEX contents. 54func (t prebuiltDependencyTag) ExcludeFromApexContents() {} 55 56var _ ExcludeFromVisibilityEnforcementTag = PrebuiltDepTag 57var _ ExcludeFromApexContentsTag = PrebuiltDepTag 58 59// UserSuppliedPrebuiltProperties contains the prebuilt properties that can be specified in an 60// Android.bp file. 61type UserSuppliedPrebuiltProperties struct { 62 // When prefer is set to true the prebuilt will be used instead of any source module with 63 // a matching name. 64 Prefer *bool `android:"arch_variant"` 65 66 // When specified this names a Soong config variable that controls the prefer property. 67 // 68 // If the value of the named Soong config variable is true then prefer is set to false and vice 69 // versa. If the Soong config variable is not set then it defaults to false, so prefer defaults 70 // to true. 71 // 72 // If specified then the prefer property is ignored in favor of the value of the Soong config 73 // variable. 74 // 75 // DEPRECATED: This property is being deprecated b/308188211. 76 // Use RELEASE_APEX_CONTRIBUTIONS build flags to select prebuilts of mainline modules. 77 Use_source_config_var *ConfigVarProperties 78} 79 80// CopyUserSuppliedPropertiesFromPrebuilt copies the user supplied prebuilt properties from the 81// prebuilt properties. 82func (u *UserSuppliedPrebuiltProperties) CopyUserSuppliedPropertiesFromPrebuilt(p *Prebuilt) { 83 *u = p.properties.UserSuppliedPrebuiltProperties 84} 85 86type PrebuiltProperties struct { 87 UserSuppliedPrebuiltProperties 88 89 SourceExists bool `blueprint:"mutated"` 90 UsePrebuilt bool `blueprint:"mutated"` 91 92 // Set if the module has been renamed to remove the "prebuilt_" prefix. 93 PrebuiltRenamedToSource bool `blueprint:"mutated"` 94} 95 96// Properties that can be used to select a Soong config variable. 97type ConfigVarProperties struct { 98 // Allow instances of this struct to be used as a property value in a BpPropertySet. 99 BpPrintableBase 100 101 // The name of the configuration namespace. 102 // 103 // As passed to add_soong_config_namespace in Make. 104 Config_namespace *string 105 106 // The name of the configuration variable. 107 // 108 // As passed to add_soong_config_var_value in Make. 109 Var_name *string 110} 111 112type Prebuilt struct { 113 properties PrebuiltProperties 114 115 // nil if the prebuilt has no srcs property at all. See InitPrebuiltModuleWithoutSrcs. 116 srcsSupplier PrebuiltSrcsSupplier 117 118 // "-" if the prebuilt has no srcs property at all. See InitPrebuiltModuleWithoutSrcs. 119 srcsPropertyName string 120} 121 122// RemoveOptionalPrebuiltPrefix returns the result of removing the "prebuilt_" prefix from the 123// supplied name if it has one, or returns the name unmodified if it does not. 124func RemoveOptionalPrebuiltPrefix(name string) string { 125 return strings.TrimPrefix(name, "prebuilt_") 126} 127 128// RemoveOptionalPrebuiltPrefixFromBazelLabel removes the "prebuilt_" prefix from the *target name* of a Bazel label. 129// This differs from RemoveOptionalPrebuiltPrefix in that it does not remove it from the start of the string, but 130// instead removes it from the target name itself. 131func RemoveOptionalPrebuiltPrefixFromBazelLabel(label string) string { 132 splitLabel := strings.Split(label, ":") 133 bazelModuleNameNoPrebuilt := RemoveOptionalPrebuiltPrefix(splitLabel[1]) 134 return strings.Join([]string{ 135 splitLabel[0], 136 bazelModuleNameNoPrebuilt, 137 }, ":") 138} 139 140func (p *Prebuilt) Name(name string) string { 141 return PrebuiltNameFromSource(name) 142} 143 144// PrebuiltNameFromSource returns the result of prepending the "prebuilt_" prefix to the supplied 145// name. 146func PrebuiltNameFromSource(name string) string { 147 return "prebuilt_" + name 148} 149 150func (p *Prebuilt) ForcePrefer() { 151 p.properties.Prefer = proptools.BoolPtr(true) 152} 153 154func (p *Prebuilt) Prefer() bool { 155 return proptools.Bool(p.properties.Prefer) 156} 157 158// SingleSourcePathFromSupplier invokes the supplied supplier for the current module in the 159// supplied context to retrieve a list of file paths, ensures that the returned list of file paths 160// contains a single value and then assumes that is a module relative file path and converts it to 161// a Path accordingly. 162// 163// Any issues, such as nil supplier or not exactly one file path will be reported as errors on the 164// supplied context and this will return nil. 165func SingleSourcePathFromSupplier(ctx ModuleContext, srcsSupplier PrebuiltSrcsSupplier, srcsPropertyName string) Path { 166 if srcsSupplier != nil { 167 srcs := srcsSupplier(ctx, ctx.Module()) 168 169 if len(srcs) == 0 { 170 ctx.PropertyErrorf(srcsPropertyName, "missing prebuilt source file") 171 return nil 172 } 173 174 if len(srcs) > 1 { 175 ctx.PropertyErrorf(srcsPropertyName, "multiple prebuilt source files") 176 return nil 177 } 178 179 // Return the singleton source after expanding any filegroup in the 180 // sources. 181 src := srcs[0] 182 return PathForModuleSrc(ctx, src) 183 } else { 184 ctx.ModuleErrorf("prebuilt source was not set") 185 return nil 186 } 187} 188 189// The below source-related functions and the srcs, src fields are based on an assumption that 190// prebuilt modules have a static source property at the moment. Currently there is only one 191// exception, android_app_import, which chooses a source file depending on the product's DPI 192// preference configs. We'll want to add native support for dynamic source cases if we end up having 193// more modules like this. 194func (p *Prebuilt) SingleSourcePath(ctx ModuleContext) Path { 195 return SingleSourcePathFromSupplier(ctx, p.srcsSupplier, p.srcsPropertyName) 196} 197 198func (p *Prebuilt) UsePrebuilt() bool { 199 return p.properties.UsePrebuilt 200} 201 202// Called to provide the srcs value for the prebuilt module. 203// 204// This can be called with a context for any module not just the prebuilt one itself. It can also be 205// called concurrently. 206// 207// Return the src value or nil if it is not available. 208type PrebuiltSrcsSupplier func(ctx BaseModuleContext, prebuilt Module) []string 209 210func initPrebuiltModuleCommon(module PrebuiltInterface) *Prebuilt { 211 p := module.Prebuilt() 212 module.AddProperties(&p.properties) 213 return p 214} 215 216// Initialize the module as a prebuilt module that has no dedicated property that lists its 217// sources. SingleSourcePathFromSupplier should not be called for this module. 218// 219// This is the case e.g. for header modules, which provides the headers in source form 220// regardless whether they are prebuilt or not. 221func InitPrebuiltModuleWithoutSrcs(module PrebuiltInterface) { 222 p := initPrebuiltModuleCommon(module) 223 p.srcsPropertyName = "-" 224} 225 226// Initialize the module as a prebuilt module that uses the provided supplier to access the 227// prebuilt sources of the module. 228// 229// The supplier will be called multiple times and must return the same values each time it 230// is called. If it returns an empty array (or nil) then the prebuilt module will not be used 231// as a replacement for a source module with the same name even if prefer = true. 232// 233// If the Prebuilt.SingleSourcePath() is called on the module then this must return an array 234// containing exactly one source file. 235// 236// The provided property name is used to provide helpful error messages in the event that 237// a problem arises, e.g. calling SingleSourcePath() when more than one source is provided. 238func InitPrebuiltModuleWithSrcSupplier(module PrebuiltInterface, srcsSupplier PrebuiltSrcsSupplier, srcsPropertyName string) { 239 if srcsSupplier == nil { 240 panic(fmt.Errorf("srcsSupplier must not be nil")) 241 } 242 if srcsPropertyName == "" { 243 panic(fmt.Errorf("srcsPropertyName must not be empty")) 244 } 245 246 p := initPrebuiltModuleCommon(module) 247 p.srcsSupplier = srcsSupplier 248 p.srcsPropertyName = srcsPropertyName 249} 250 251func InitPrebuiltModule(module PrebuiltInterface, srcs *[]string) { 252 if srcs == nil { 253 panic(fmt.Errorf("srcs must not be nil")) 254 } 255 256 srcsSupplier := func(ctx BaseModuleContext, _ Module) []string { 257 return *srcs 258 } 259 260 InitPrebuiltModuleWithSrcSupplier(module, srcsSupplier, "srcs") 261} 262 263func InitSingleSourcePrebuiltModule(module PrebuiltInterface, srcProps interface{}, srcField string) { 264 srcPropsValue := reflect.ValueOf(srcProps).Elem() 265 srcStructField, _ := srcPropsValue.Type().FieldByName(srcField) 266 if !srcPropsValue.IsValid() || srcStructField.Name == "" { 267 panic(fmt.Errorf("invalid single source prebuilt %+v", module)) 268 } 269 270 if srcPropsValue.Kind() != reflect.Struct && srcPropsValue.Kind() != reflect.Interface { 271 panic(fmt.Errorf("invalid single source prebuilt %+v", srcProps)) 272 } 273 274 srcFieldIndex := srcStructField.Index 275 srcPropertyName := proptools.PropertyNameForField(srcField) 276 277 srcsSupplier := func(ctx BaseModuleContext, _ Module) []string { 278 if !module.Enabled(ctx) { 279 return nil 280 } 281 value := srcPropsValue.FieldByIndex(srcFieldIndex) 282 if value.Kind() == reflect.Ptr { 283 if value.IsNil() { 284 return nil 285 } 286 value = value.Elem() 287 } 288 if value.Kind() != reflect.String { 289 panic(fmt.Errorf("prebuilt src field %q in %T in module %s should be a string or a pointer to one but was %v", srcField, srcProps, module, value)) 290 } 291 src := value.String() 292 if src == "" { 293 return nil 294 } 295 return []string{src} 296 } 297 298 InitPrebuiltModuleWithSrcSupplier(module, srcsSupplier, srcPropertyName) 299} 300 301type PrebuiltInterface interface { 302 Module 303 Prebuilt() *Prebuilt 304} 305 306// IsModulePreferred returns true if the given module is preferred. 307// 308// A source module is preferred if there is no corresponding prebuilt module or the prebuilt module 309// does not have "prefer: true". 310// 311// A prebuilt module is preferred if there is no corresponding source module or the prebuilt module 312// has "prefer: true". 313func IsModulePreferred(module Module) bool { 314 if module.IsReplacedByPrebuilt() { 315 // A source module that has been replaced by a prebuilt counterpart. 316 return false 317 } 318 if p := GetEmbeddedPrebuilt(module); p != nil { 319 return p.UsePrebuilt() 320 } 321 return true 322} 323 324// IsModulePrebuilt returns true if the module implements PrebuiltInterface and 325// has been initialized as a prebuilt and so returns a non-nil value from the 326// PrebuiltInterface.Prebuilt() method. 327func IsModulePrebuilt(module Module) bool { 328 return GetEmbeddedPrebuilt(module) != nil 329} 330 331// GetEmbeddedPrebuilt returns a pointer to the embedded Prebuilt structure or 332// nil if the module does not implement PrebuiltInterface or has not been 333// initialized as a prebuilt module. 334func GetEmbeddedPrebuilt(module Module) *Prebuilt { 335 if p, ok := module.(PrebuiltInterface); ok { 336 return p.Prebuilt() 337 } 338 339 return nil 340} 341 342// PrebuiltGetPreferred returns the module that is preferred for the given 343// module. That is either the module itself or the prebuilt counterpart that has 344// taken its place. The given module must be a direct dependency of the current 345// context module, and it must be the source module if both source and prebuilt 346// exist. 347// 348// This function is for use on dependencies after PrebuiltPostDepsMutator has 349// run - any dependency that is registered before that will already reference 350// the right module. This function is only safe to call after all mutators that 351// may call CreateVariations, e.g. in GenerateAndroidBuildActions. 352func PrebuiltGetPreferred(ctx BaseModuleContext, module Module) Module { 353 if !module.IsReplacedByPrebuilt() { 354 return module 355 } 356 if IsModulePrebuilt(module) { 357 // If we're given a prebuilt then assume there's no source module around. 358 return module 359 } 360 361 sourceModDepFound := false 362 var prebuiltMod Module 363 364 ctx.WalkDeps(func(child, parent Module) bool { 365 if prebuiltMod != nil { 366 return false 367 } 368 if parent == ctx.Module() { 369 // First level: Only recurse if the module is found as a direct dependency. 370 sourceModDepFound = child == module 371 return sourceModDepFound 372 } 373 // Second level: Follow PrebuiltDepTag to the prebuilt. 374 if t := ctx.OtherModuleDependencyTag(child); t == PrebuiltDepTag { 375 prebuiltMod = child 376 } 377 return false 378 }) 379 380 if prebuiltMod == nil { 381 if !sourceModDepFound { 382 panic(fmt.Errorf("Failed to find source module as a direct dependency: %s", module)) 383 } else { 384 panic(fmt.Errorf("Failed to find prebuilt for source module: %s", module)) 385 } 386 } 387 return prebuiltMod 388} 389 390func RegisterPrebuiltsPreArchMutators(ctx RegisterMutatorsContext) { 391 ctx.BottomUp("prebuilt_rename", PrebuiltRenameMutator).Parallel() 392} 393 394func RegisterPrebuiltsPostDepsMutators(ctx RegisterMutatorsContext) { 395 ctx.BottomUp("prebuilt_source", PrebuiltSourceDepsMutator).Parallel() 396 ctx.BottomUp("prebuilt_select", PrebuiltSelectModuleMutator).Parallel() 397 ctx.BottomUp("prebuilt_postdeps", PrebuiltPostDepsMutator).Parallel() 398} 399 400// Returns the name of the source module corresponding to a prebuilt module 401// For source modules, it returns its own name 402type baseModuleName interface { 403 BaseModuleName() string 404} 405 406// PrebuiltRenameMutator ensures that there always is a module with an 407// undecorated name. 408func PrebuiltRenameMutator(ctx BottomUpMutatorContext) { 409 m := ctx.Module() 410 if p := GetEmbeddedPrebuilt(m); p != nil { 411 bmn, _ := m.(baseModuleName) 412 name := bmn.BaseModuleName() 413 if !ctx.OtherModuleExists(name) { 414 ctx.Rename(name) 415 p.properties.PrebuiltRenamedToSource = true 416 } 417 } 418} 419 420// PrebuiltSourceDepsMutator adds dependencies to the prebuilt module from the 421// corresponding source module, if one exists for the same variant. 422// Add a dependency from the prebuilt to `all_apex_contributions` 423// The metadata will be used for source vs prebuilts selection 424func PrebuiltSourceDepsMutator(ctx BottomUpMutatorContext) { 425 m := ctx.Module() 426 if p := GetEmbeddedPrebuilt(m); p != nil { 427 // Add a dependency from the prebuilt to the `all_apex_contributions` 428 // metadata module 429 // TODO: When all branches contain this singleton module, make this strict 430 // TODO: Add this dependency only for mainline prebuilts and not every prebuilt module 431 if ctx.OtherModuleExists("all_apex_contributions") { 432 ctx.AddDependency(m, AcDepTag, "all_apex_contributions") 433 } 434 if m.Enabled(ctx) && !p.properties.PrebuiltRenamedToSource { 435 // If this module is a prebuilt, is enabled and has not been renamed to source then add a 436 // dependency onto the source if it is present. 437 bmn, _ := m.(baseModuleName) 438 name := bmn.BaseModuleName() 439 if ctx.OtherModuleReverseDependencyVariantExists(name) { 440 ctx.AddReverseDependency(ctx.Module(), PrebuiltDepTag, name) 441 p.properties.SourceExists = true 442 } 443 } 444 } 445} 446 447// checkInvariantsForSourceAndPrebuilt checks if invariants are kept when replacing 448// source with prebuilt. Note that the current module for the context is the source module. 449func checkInvariantsForSourceAndPrebuilt(ctx BaseModuleContext, s, p Module) { 450 if _, ok := s.(OverrideModule); ok { 451 // skip the check when the source module is `override_X` because it's only a placeholder 452 // for the actual source module. The check will be invoked for the actual module. 453 return 454 } 455 if sourcePartition, prebuiltPartition := s.PartitionTag(ctx.DeviceConfig()), p.PartitionTag(ctx.DeviceConfig()); sourcePartition != prebuiltPartition { 456 ctx.OtherModuleErrorf(p, "partition is different: %s(%s) != %s(%s)", 457 sourcePartition, ctx.ModuleName(), prebuiltPartition, ctx.OtherModuleName(p)) 458 } 459} 460 461// PrebuiltSelectModuleMutator marks prebuilts that are used, either overriding source modules or 462// because the source module doesn't exist. It also disables installing overridden source modules. 463// 464// If the visited module is the metadata module `all_apex_contributions`, it sets a 465// provider containing metadata about whether source or prebuilt of mainline modules should be used. 466// This logic was added here to prevent the overhead of creating a new mutator. 467func PrebuiltSelectModuleMutator(ctx BottomUpMutatorContext) { 468 m := ctx.Module() 469 if p := GetEmbeddedPrebuilt(m); p != nil { 470 if p.srcsSupplier == nil && p.srcsPropertyName == "" { 471 panic(fmt.Errorf("prebuilt module did not have InitPrebuiltModule called on it")) 472 } 473 if !p.properties.SourceExists { 474 p.properties.UsePrebuilt = p.usePrebuilt(ctx, nil, m) 475 } 476 // Propagate the provider received from `all_apex_contributions` 477 // to the source module 478 ctx.VisitDirectDepsWithTag(AcDepTag, func(am Module) { 479 psi, _ := OtherModuleProvider(ctx, am, PrebuiltSelectionInfoProvider) 480 SetProvider(ctx, PrebuiltSelectionInfoProvider, psi) 481 }) 482 483 } else if s, ok := ctx.Module().(Module); ok { 484 // Use `all_apex_contributions` for source vs prebuilt selection. 485 psi := PrebuiltSelectionInfoMap{} 486 ctx.VisitDirectDepsWithTag(PrebuiltDepTag, func(am Module) { 487 // The value of psi gets overwritten with the provider from the last visited prebuilt. 488 // But all prebuilts have the same value of the provider, so this should be idempontent. 489 psi, _ = OtherModuleProvider(ctx, am, PrebuiltSelectionInfoProvider) 490 }) 491 ctx.VisitDirectDepsWithTag(PrebuiltDepTag, func(prebuiltModule Module) { 492 p := GetEmbeddedPrebuilt(prebuiltModule) 493 if p.usePrebuilt(ctx, s, prebuiltModule) { 494 checkInvariantsForSourceAndPrebuilt(ctx, s, prebuiltModule) 495 496 p.properties.UsePrebuilt = true 497 s.ReplacedByPrebuilt() 498 } 499 }) 500 501 // If any module in this mainline module family has been flagged using apex_contributions, disable every other module in that family 502 // Add source 503 allModules := []Module{s} 504 // Add each prebuilt 505 ctx.VisitDirectDepsWithTag(PrebuiltDepTag, func(prebuiltModule Module) { 506 allModules = append(allModules, prebuiltModule) 507 }) 508 hideUnflaggedModules(ctx, psi, allModules) 509 510 } 511 512 // If this is `all_apex_contributions`, set a provider containing 513 // metadata about source vs prebuilts selection 514 if am, ok := m.(*allApexContributions); ok { 515 am.SetPrebuiltSelectionInfoProvider(ctx) 516 } 517} 518 519// If any module in this mainline module family has been flagged using apex_contributions, disable every other module in that family 520func hideUnflaggedModules(ctx BottomUpMutatorContext, psi PrebuiltSelectionInfoMap, allModulesInFamily []Module) { 521 var selectedModuleInFamily Module 522 // query all_apex_contributions to see if any module in this family has been selected 523 for _, moduleInFamily := range allModulesInFamily { 524 // validate that are no duplicates 525 if isSelected(psi, moduleInFamily) { 526 if selectedModuleInFamily == nil { 527 // Store this so we can validate that there are no duplicates 528 selectedModuleInFamily = moduleInFamily 529 } else { 530 // There are duplicate modules from the same mainline module family 531 ctx.ModuleErrorf("Found duplicate variations of the same module in apex_contributions: %s and %s. Please remove one of these.\n", selectedModuleInFamily.Name(), moduleInFamily.Name()) 532 } 533 } 534 } 535 536 // If a module has been selected, hide all other modules 537 if selectedModuleInFamily != nil { 538 for _, moduleInFamily := range allModulesInFamily { 539 if moduleInFamily.Name() != selectedModuleInFamily.Name() { 540 moduleInFamily.HideFromMake() 541 // If this is a prebuilt module, unset properties.UsePrebuilt 542 // properties.UsePrebuilt might evaluate to true via soong config var fallback mechanism 543 // Set it to false explicitly so that the following mutator does not replace rdeps to this unselected prebuilt 544 if p := GetEmbeddedPrebuilt(moduleInFamily); p != nil { 545 p.properties.UsePrebuilt = false 546 } 547 } 548 } 549 } 550 // Do a validation pass to make sure that multiple prebuilts of a specific module are not selected. 551 // This might happen if the prebuilts share the same soong config var namespace. 552 // This should be an error, unless one of the prebuilts has been explicitly declared in apex_contributions 553 var selectedPrebuilt Module 554 for _, moduleInFamily := range allModulesInFamily { 555 // Skip if this module is in a different namespace 556 if !moduleInFamily.ExportedToMake() { 557 continue 558 } 559 // Skip for the top-level java_sdk_library_(_import). This has some special cases that need to be addressed first. 560 // This does not run into non-determinism because PrebuiltPostDepsMutator also has the special case 561 if sdkLibrary, ok := moduleInFamily.(interface{ SdkLibraryName() *string }); ok && sdkLibrary.SdkLibraryName() != nil { 562 continue 563 } 564 if p := GetEmbeddedPrebuilt(moduleInFamily); p != nil && p.properties.UsePrebuilt { 565 if selectedPrebuilt == nil { 566 selectedPrebuilt = moduleInFamily 567 } else { 568 ctx.ModuleErrorf("Multiple prebuilt modules %v and %v have been marked as preferred for this source module. "+ 569 "Please add the appropriate prebuilt module to apex_contributions for this release config.", selectedPrebuilt.Name(), moduleInFamily.Name()) 570 } 571 } 572 } 573} 574 575// PrebuiltPostDepsMutator replaces dependencies on the source module with dependencies on the 576// prebuilt when both modules exist and the prebuilt should be used. When the prebuilt should not 577// be used, disable installing it. 578func PrebuiltPostDepsMutator(ctx BottomUpMutatorContext) { 579 m := ctx.Module() 580 if p := GetEmbeddedPrebuilt(m); p != nil { 581 bmn, _ := m.(baseModuleName) 582 name := bmn.BaseModuleName() 583 psi := PrebuiltSelectionInfoMap{} 584 ctx.VisitDirectDepsWithTag(AcDepTag, func(am Module) { 585 psi, _ = OtherModuleProvider(ctx, am, PrebuiltSelectionInfoProvider) 586 }) 587 588 if p.properties.UsePrebuilt { 589 if p.properties.SourceExists { 590 ctx.ReplaceDependenciesIf(name, func(from blueprint.Module, tag blueprint.DependencyTag, to blueprint.Module) bool { 591 if sdkLibrary, ok := m.(interface{ SdkLibraryName() *string }); ok && sdkLibrary.SdkLibraryName() != nil { 592 // Do not replace deps to the top-level prebuilt java_sdk_library hook. 593 // This hook has been special-cased in #isSelected to be _always_ active, even in next builds 594 // for dexpreopt and hiddenapi processing. 595 // If we do not special-case this here, rdeps referring to a java_sdk_library in next builds via libs 596 // will get prebuilt stubs 597 // TODO (b/308187268): Remove this after the apexes have been added to apex_contributions 598 if psi.IsSelected(name) { 599 return false 600 } 601 } 602 603 if t, ok := tag.(ReplaceSourceWithPrebuilt); ok { 604 return t.ReplaceSourceWithPrebuilt() 605 } 606 return true 607 }) 608 } 609 } else { 610 m.HideFromMake() 611 } 612 } 613} 614 615// A wrapper around PrebuiltSelectionInfoMap.IsSelected with special handling for java_sdk_library 616// java_sdk_library is a macro that creates 617// 1. top-level impl library 618// 2. stub libraries (suffixed with .stubs...) 619// 620// java_sdk_library_import is a macro that creates 621// 1. top-level "impl" library 622// 2. stub libraries (suffixed with .stubs...) 623// 624// the impl of java_sdk_library_import is a "hook" for hiddenapi and dexpreopt processing. It does not have an impl jar, but acts as a shim 625// to provide the jar deapxed from the prebuilt apex 626// 627// isSelected uses `all_apex_contributions` to supersede source vs prebuilts selection of the stub libraries. It does not supersede the 628// selection of the top-level "impl" library so that this hook can work 629// 630// TODO (b/308174306) - Fix this when we need to support multiple prebuilts in main 631func isSelected(psi PrebuiltSelectionInfoMap, m Module) bool { 632 if sdkLibrary, ok := m.(interface{ SdkLibraryName() *string }); ok && sdkLibrary.SdkLibraryName() != nil { 633 sln := proptools.String(sdkLibrary.SdkLibraryName()) 634 635 // This is the top-level library 636 // Do not supersede the existing prebuilts vs source selection mechanisms 637 // TODO (b/308187268): Remove this after the apexes have been added to apex_contributions 638 if bmn, ok := m.(baseModuleName); ok && sln == bmn.BaseModuleName() { 639 return false 640 } 641 642 // Stub library created by java_sdk_library_import 643 // java_sdk_library creates several child modules (java_import + prebuilt_stubs_sources) dynamically. 644 // This code block ensures that these child modules are selected if the top-level java_sdk_library_import is listed 645 // in the selected apex_contributions. 646 if javaImport, ok := m.(createdByJavaSdkLibraryName); ok && javaImport.CreatedByJavaSdkLibraryName() != nil { 647 return psi.IsSelected(PrebuiltNameFromSource(proptools.String(javaImport.CreatedByJavaSdkLibraryName()))) 648 } 649 650 // Stub library created by java_sdk_library 651 return psi.IsSelected(sln) 652 } 653 return psi.IsSelected(m.Name()) 654} 655 656// implemented by child modules of java_sdk_library_import 657type createdByJavaSdkLibraryName interface { 658 CreatedByJavaSdkLibraryName() *string 659} 660 661// Returns true if the prebuilt variant is disabled 662// e.g. for a cc_prebuilt_library_shared, this will return 663// - true for the static variant of the module 664// - false for the shared variant of the module 665// 666// Even though this is a cc_prebuilt_library_shared, we create both the variants today 667// https://source.corp.google.com/h/googleplex-android/platform/build/soong/+/e08e32b45a18a77bc3c3e751f730539b1b374f1b:cc/library.go;l=2113-2116;drc=2c4a9779cd1921d0397a12b3d3521f4c9b30d747;bpv=1;bpt=0 668func (p *Prebuilt) variantIsDisabled(ctx BaseMutatorContext, prebuilt Module) bool { 669 return p.srcsSupplier != nil && len(p.srcsSupplier(ctx, prebuilt)) == 0 670} 671 672type apexVariationName interface { 673 ApexVariationName() string 674} 675 676// usePrebuilt returns true if a prebuilt should be used instead of the source module. The prebuilt 677// will be used if it is marked "prefer" or if the source module is disabled. 678func (p *Prebuilt) usePrebuilt(ctx BaseMutatorContext, source Module, prebuilt Module) bool { 679 isMainlinePrebuilt := func(prebuilt Module) bool { 680 apex, ok := prebuilt.(apexVariationName) 681 if !ok { 682 return false 683 } 684 // Prebuilts of aosp apexes in prebuilts/runtime 685 // Used in minimal art branches 686 if prebuilt.base().BaseModuleName() == apex.ApexVariationName() { 687 return false 688 } 689 return InList(apex.ApexVariationName(), ctx.Config().AllMainlineApexNames()) 690 } 691 692 // Use `all_apex_contributions` for source vs prebuilt selection. 693 psi := PrebuiltSelectionInfoMap{} 694 var psiDepTag blueprint.DependencyTag 695 if p := GetEmbeddedPrebuilt(ctx.Module()); p != nil { 696 // This is a prebuilt module, visit all_apex_contributions to get the info 697 psiDepTag = AcDepTag 698 } else { 699 // This is a source module, visit any of its prebuilts to get the info 700 psiDepTag = PrebuiltDepTag 701 } 702 ctx.VisitDirectDepsWithTag(psiDepTag, func(am Module) { 703 psi, _ = OtherModuleProvider(ctx, am, PrebuiltSelectionInfoProvider) 704 }) 705 706 // If the source module is explicitly listed in the metadata module, use that 707 if source != nil && isSelected(psi, source) { 708 return false 709 } 710 // If the prebuilt module is explicitly listed in the metadata module, use that 711 if isSelected(psi, prebuilt) && !p.variantIsDisabled(ctx, prebuilt) { 712 return true 713 } 714 715 // If this is a mainline prebuilt, but has not been flagged, hide it. 716 if isMainlinePrebuilt(prebuilt) { 717 return false 718 } 719 720 // If the baseModuleName could not be found in the metadata module, 721 // fall back to the existing source vs prebuilt selection. 722 // TODO: Drop the fallback mechanisms 723 724 if p.variantIsDisabled(ctx, prebuilt) { 725 return false 726 } 727 728 // Skip prebuilt modules under unexported namespaces so that we won't 729 // end up shadowing non-prebuilt module when prebuilt module under same 730 // name happens to have a `Prefer` property set to true. 731 if ctx.Config().KatiEnabled() && !prebuilt.ExportedToMake() { 732 return false 733 } 734 735 // If source is not available or is disabled then always use the prebuilt. 736 if source == nil || !source.Enabled(ctx) { 737 return true 738 } 739 740 // TODO: use p.Properties.Name and ctx.ModuleDir to override preference 741 return Bool(p.properties.Prefer) 742} 743 744func (p *Prebuilt) SourceExists() bool { 745 return p.properties.SourceExists 746} 747