1// Copyright (C) 2019 The Android Open Source Project
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	"sort"
20	"strings"
21
22	"github.com/google/blueprint"
23	"github.com/google/blueprint/proptools"
24)
25
26// minApiLevelForSdkSnapshot provides access to the min_sdk_version for MinApiLevelForSdkSnapshot
27type minApiLevelForSdkSnapshot interface {
28	MinSdkVersion(ctx EarlyModuleContext) ApiLevel
29}
30
31// MinApiLevelForSdkSnapshot returns the ApiLevel of the min_sdk_version of the supplied module.
32//
33// If the module does not provide a min_sdk_version then it defaults to 1.
34func MinApiLevelForSdkSnapshot(ctx EarlyModuleContext, module Module) ApiLevel {
35	minApiLevel := NoneApiLevel
36	if m, ok := module.(minApiLevelForSdkSnapshot); ok {
37		minApiLevel = m.MinSdkVersion(ctx)
38	}
39	if minApiLevel == NoneApiLevel {
40		// The default min API level is 1.
41		minApiLevel = uncheckedFinalApiLevel(1)
42	}
43	return minApiLevel
44}
45
46// SnapshotBuilder provides support for generating the build rules which will build the snapshot.
47type SnapshotBuilder interface {
48	// CopyToSnapshot generates a rule that will copy the src to the dest (which is a snapshot
49	// relative path) and add the dest to the zip.
50	CopyToSnapshot(src Path, dest string)
51
52	// EmptyFile returns the path to an empty file.
53	//
54	// This can be used by sdk member types that need to create an empty file in the snapshot, simply
55	// pass the value returned from this to the CopyToSnapshot() method.
56	EmptyFile() Path
57
58	// UnzipToSnapshot generates a rule that will unzip the supplied zip into the snapshot relative
59	// directory destDir.
60	UnzipToSnapshot(zipPath Path, destDir string)
61
62	// AddPrebuiltModule adds a new prebuilt module to the snapshot.
63	//
64	// It is intended to be called from SdkMemberType.AddPrebuiltModule which can add module type
65	// specific properties that are not variant specific. The following properties will be
66	// automatically populated before returning.
67	//
68	// * name
69	// * sdk_member_name
70	// * prefer
71	//
72	// Properties that are variant specific will be handled by SdkMemberProperties structure.
73	//
74	// Each module created by this method can be output to the generated Android.bp file in two
75	// different forms, depending on the setting of the SOONG_SDK_SNAPSHOT_VERSION build property.
76	// The two forms are:
77	// 1. A versioned Soong module that is referenced from a corresponding similarly versioned
78	//    snapshot module.
79	// 2. An unversioned Soong module that.
80	//
81	// See sdk/update.go for more information.
82	AddPrebuiltModule(member SdkMember, moduleType string) BpModule
83
84	// SdkMemberReferencePropertyTag returns a property tag to use when adding a property to a
85	// BpModule that contains references to other sdk members.
86	//
87	// Using this will ensure that the reference is correctly output for both versioned and
88	// unversioned prebuilts in the snapshot.
89	//
90	// "required: true" means that the property must only contain references to other members of the
91	// sdk. Passing a reference to a module that is not a member of the sdk will result in a build
92	// error.
93	//
94	// "required: false" means that the property can contain references to modules that are either
95	// members or not members of the sdk. If a reference is to a module that is a non member then the
96	// reference is left unchanged, i.e. it is not transformed as references to members are.
97	//
98	// The handling of the member names is dependent on whether it is an internal or exported member.
99	// An exported member is one whose name is specified in one of the member type specific
100	// properties. An internal member is one that is added due to being a part of an exported (or
101	// other internal) member and is not itself an exported member.
102	//
103	// Member names are handled as follows:
104	// * When creating the unversioned form of the module the name is left unchecked unless the member
105	//   is internal in which case it is transformed into an sdk specific name, i.e. by prefixing with
106	//   the sdk name.
107	//
108	// * When creating the versioned form of the module the name is transformed into a versioned sdk
109	//   specific name, i.e. by prefixing with the sdk name and suffixing with the version.
110	//
111	// e.g.
112	// bpPropertySet.AddPropertyWithTag("libs", []string{"member1", "member2"}, builder.SdkMemberReferencePropertyTag(true))
113	SdkMemberReferencePropertyTag(required bool) BpPropertyTag
114}
115
116// BpPropertyTag is a marker interface that can be associated with properties in a BpPropertySet to
117// provide additional information which can be used to customize their behavior.
118type BpPropertyTag interface{}
119
120// BpPropertySet is a set of properties for use in a .bp file.
121type BpPropertySet interface {
122	// AddProperty adds a property.
123	//
124	// The value can be one of the following types:
125	// * string
126	// * array of the above
127	// * bool
128	// For these types it is an error if multiple properties with the same name
129	// are added.
130	//
131	// * pointer to a struct
132	// * BpPropertySet
133	//
134	// A pointer to a Blueprint-style property struct is first converted into a
135	// BpPropertySet by traversing the fields and adding their values as
136	// properties in a BpPropertySet. A field with a struct value is itself
137	// converted into a BpPropertySet before adding.
138	//
139	// Adding a BpPropertySet is done as follows:
140	// * If no property with the name exists then the BpPropertySet is added
141	//   directly to this property. Care must be taken to ensure that it does not
142	//   introduce a cycle.
143	// * If a property exists with the name and the current value is a
144	//   BpPropertySet then every property of the new BpPropertySet is added to
145	//   the existing BpPropertySet.
146	// * Otherwise, if a property exists with the name then it is an error.
147	AddProperty(name string, value interface{})
148
149	// AddPropertyWithTag adds a property with an associated property tag.
150	AddPropertyWithTag(name string, value interface{}, tag BpPropertyTag)
151
152	// AddPropertySet adds a property set with the specified name and returns it so that additional
153	// properties can be added to it.
154	AddPropertySet(name string) BpPropertySet
155
156	// AddCommentForProperty adds a comment for the named property (or property set).
157	AddCommentForProperty(name, text string)
158}
159
160// BpModule represents a module definition in a .bp file.
161type BpModule interface {
162	BpPropertySet
163
164	// ModuleType returns the module type of the module
165	ModuleType() string
166
167	// Name returns the name of the module or "" if no name has been specified.
168	Name() string
169}
170
171// BpPrintable is a marker interface that must be implemented by any struct that is added as a
172// property value.
173type BpPrintable interface {
174	bpPrintable()
175}
176
177// BpPrintableBase must be embedded within any struct that is added as a
178// property value.
179type BpPrintableBase struct {
180}
181
182func (b BpPrintableBase) bpPrintable() {
183}
184
185var _ BpPrintable = BpPrintableBase{}
186
187// sdkRegisterable defines the interface that must be implemented by objects that can be registered
188// in an sdkRegistry.
189type sdkRegisterable interface {
190	// SdkPropertyName returns the name of the corresponding property on an sdk module.
191	SdkPropertyName() string
192}
193
194// sdkRegistry provides support for registering and retrieving objects that define properties for
195// use by sdk and module_exports module types.
196type sdkRegistry struct {
197	// The list of registered objects sorted by property name.
198	list []sdkRegisterable
199}
200
201// copyAndAppend creates a new sdkRegistry that includes all the traits registered in
202// this registry plus the supplied trait.
203func (r *sdkRegistry) copyAndAppend(registerable sdkRegisterable) *sdkRegistry {
204	oldList := r.list
205
206	// Make sure that list does not already contain the property. Uses a simple linear search instead
207	// of a binary search even though the list is sorted. That is because the number of items in the
208	// list is small and so not worth the overhead of a binary search.
209	found := false
210	newPropertyName := registerable.SdkPropertyName()
211	for _, r := range oldList {
212		if r.SdkPropertyName() == newPropertyName {
213			found = true
214			break
215		}
216	}
217	if found {
218		names := []string{}
219		for _, r := range oldList {
220			names = append(names, r.SdkPropertyName())
221		}
222		panic(fmt.Errorf("duplicate properties found, %q already exists in %q", newPropertyName, names))
223	}
224
225	// Copy the slice just in case this is being read while being modified, e.g. when testing.
226	list := make([]sdkRegisterable, 0, len(oldList)+1)
227	list = append(list, oldList...)
228	list = append(list, registerable)
229
230	// Sort the registered objects by their property name to ensure that registry order has no effect
231	// on behavior.
232	sort.Slice(list, func(i1, i2 int) bool {
233		t1 := list[i1]
234		t2 := list[i2]
235
236		return t1.SdkPropertyName() < t2.SdkPropertyName()
237	})
238
239	// Create a new registry so the pointer uniquely identifies the set of registered types.
240	return &sdkRegistry{
241		list: list,
242	}
243}
244
245// registeredObjects returns the list of registered instances.
246func (r *sdkRegistry) registeredObjects() []sdkRegisterable {
247	return r.list
248}
249
250// uniqueOnceKey returns a key that uniquely identifies this instance and can be used with
251// OncePer.Once
252func (r *sdkRegistry) uniqueOnceKey() OnceKey {
253	// Use the pointer to the registry as the unique key. The pointer is used because it is guaranteed
254	// to uniquely identify the contained list. The list itself cannot be used as slices are not
255	// comparable. Using the pointer does mean that two separate registries with identical lists would
256	// have different keys and so cause whatever information is cached to be created multiple times.
257	// However, that is not an issue in practice as it should not occur outside tests. Constructing a
258	// string representation of the list to use instead would avoid that but is an unnecessary
259	// complication that provides no significant benefit.
260	return NewCustomOnceKey(r)
261}
262
263// SdkMemberTrait represents a trait that members of an sdk module can contribute to the sdk
264// snapshot.
265//
266// A trait is simply a characteristic of sdk member that is not required by default which may be
267// required for some members but not others. Traits can cause additional information to be output
268// to the sdk snapshot or replace the default information exported for a member with something else.
269// e.g.
270//   - By default cc libraries only export the default image variants to the SDK. However, for some
271//     members it may be necessary to export specific image variants, e.g. vendor, or recovery.
272//   - By default cc libraries export all the configured architecture variants except for the native
273//     bridge architecture variants. However, for some members it may be necessary to export the
274//     native bridge architecture variants as well.
275//   - By default cc libraries export the platform variant (i.e. sdk:). However, for some members it
276//     may be necessary to export the sdk variant (i.e. sdk:sdk).
277//
278// A sdk can request a module to provide no traits, one trait or a collection of traits. The exact
279// behavior of a trait is determined by how SdkMemberType implementations handle the traits. A trait
280// could be specific to one SdkMemberType or many. Some trait combinations could be incompatible.
281//
282// The sdk module type will create a special traits structure that contains a property for each
283// trait registered with RegisterSdkMemberTrait(). The property names are those returned from
284// SdkPropertyName(). Each property contains a list of modules that are required to have that trait.
285// e.g. something like this:
286//
287//	sdk {
288//	  name: "sdk",
289//	  ...
290//	  traits: {
291//	    recovery_image: ["module1", "module4", "module5"],
292//	    native_bridge: ["module1", "module2"],
293//	    native_sdk: ["module1", "module3"],
294//	    ...
295//	  },
296//	  ...
297//	}
298type SdkMemberTrait interface {
299	// SdkPropertyName returns the name of the traits property on an sdk module.
300	SdkPropertyName() string
301}
302
303var _ sdkRegisterable = (SdkMemberTrait)(nil)
304
305// SdkMemberTraitBase is the base struct that must be embedded within any type that implements
306// SdkMemberTrait.
307type SdkMemberTraitBase struct {
308	// PropertyName is the name of the property
309	PropertyName string
310}
311
312func (b *SdkMemberTraitBase) SdkPropertyName() string {
313	return b.PropertyName
314}
315
316// SdkMemberTraitSet is a set of SdkMemberTrait instances.
317type SdkMemberTraitSet interface {
318	// Empty returns true if this set is empty.
319	Empty() bool
320
321	// Contains returns true if this set contains the specified trait.
322	Contains(trait SdkMemberTrait) bool
323
324	// Subtract returns a new set containing all elements of this set except for those in the
325	// other set.
326	Subtract(other SdkMemberTraitSet) SdkMemberTraitSet
327
328	// String returns a string representation of the set and its contents.
329	String() string
330}
331
332func NewSdkMemberTraitSet(traits []SdkMemberTrait) SdkMemberTraitSet {
333	if len(traits) == 0 {
334		return EmptySdkMemberTraitSet()
335	}
336
337	m := sdkMemberTraitSet{}
338	for _, trait := range traits {
339		m[trait] = true
340	}
341	return m
342}
343
344func EmptySdkMemberTraitSet() SdkMemberTraitSet {
345	return (sdkMemberTraitSet)(nil)
346}
347
348type sdkMemberTraitSet map[SdkMemberTrait]bool
349
350var _ SdkMemberTraitSet = (sdkMemberTraitSet{})
351
352func (s sdkMemberTraitSet) Empty() bool {
353	return len(s) == 0
354}
355
356func (s sdkMemberTraitSet) Contains(trait SdkMemberTrait) bool {
357	return s[trait]
358}
359
360func (s sdkMemberTraitSet) Subtract(other SdkMemberTraitSet) SdkMemberTraitSet {
361	if other.Empty() {
362		return s
363	}
364
365	var remainder []SdkMemberTrait
366	for trait, _ := range s {
367		if !other.Contains(trait) {
368			remainder = append(remainder, trait)
369		}
370	}
371
372	return NewSdkMemberTraitSet(remainder)
373}
374
375func (s sdkMemberTraitSet) String() string {
376	list := []string{}
377	for trait, _ := range s {
378		list = append(list, trait.SdkPropertyName())
379	}
380	sort.Strings(list)
381	return fmt.Sprintf("[%s]", strings.Join(list, ","))
382}
383
384var registeredSdkMemberTraits = &sdkRegistry{}
385
386// RegisteredSdkMemberTraits returns a OnceKey and a sorted list of registered traits.
387//
388// The key uniquely identifies the array of traits and can be used with OncePer.Once() to cache
389// information derived from the array of traits.
390func RegisteredSdkMemberTraits() (OnceKey, []SdkMemberTrait) {
391	registerables := registeredSdkMemberTraits.registeredObjects()
392	traits := make([]SdkMemberTrait, len(registerables))
393	for i, registerable := range registerables {
394		traits[i] = registerable.(SdkMemberTrait)
395	}
396	return registeredSdkMemberTraits.uniqueOnceKey(), traits
397}
398
399// RegisterSdkMemberTrait registers an SdkMemberTrait object to allow them to be used in the
400// module_exports, module_exports_snapshot, sdk and sdk_snapshot module types.
401func RegisterSdkMemberTrait(trait SdkMemberTrait) {
402	registeredSdkMemberTraits = registeredSdkMemberTraits.copyAndAppend(trait)
403}
404
405// SdkMember is an individual member of the SDK.
406//
407// It includes all of the variants that the SDK depends upon.
408type SdkMember interface {
409	// Name returns the name of the member.
410	Name() string
411
412	// Variants returns all the variants of this module depended upon by the SDK.
413	Variants() []Module
414}
415
416// SdkMemberDependencyTag is the interface that a tag must implement in order to allow the
417// dependent module to be automatically added to the sdk.
418type SdkMemberDependencyTag interface {
419	blueprint.DependencyTag
420
421	// SdkMemberType returns the SdkMemberType that will be used to automatically add the child module
422	// to the sdk.
423	//
424	// Returning nil will prevent the module being added to the sdk.
425	SdkMemberType(child Module) SdkMemberType
426
427	// ExportMember determines whether a module added to the sdk through this tag will be exported
428	// from the sdk or not.
429	//
430	// An exported member is added to the sdk using its own name, e.g. if "foo" was exported from sdk
431	// "bar" then its prebuilt would be simply called "foo". A member can be added to the sdk via
432	// multiple tags and if any of those tags returns true from this method then the membe will be
433	// exported. Every module added directly to the sdk via one of the member type specific
434	// properties, e.g. java_libs, will automatically be exported.
435	//
436	// If a member is not exported then it is treated as an internal implementation detail of the
437	// sdk and so will be added with an sdk specific name. e.g. if "foo" was an internal member of sdk
438	// "bar" then its prebuilt would be called "bar_foo". Additionally its visibility will be set to
439	// "//visibility:private" so it will not be accessible from outside its Android.bp file.
440	ExportMember() bool
441}
442
443var _ SdkMemberDependencyTag = (*sdkMemberDependencyTag)(nil)
444var _ ReplaceSourceWithPrebuilt = (*sdkMemberDependencyTag)(nil)
445
446type sdkMemberDependencyTag struct {
447	blueprint.BaseDependencyTag
448	memberType SdkMemberType
449	export     bool
450}
451
452func (t *sdkMemberDependencyTag) SdkMemberType(_ Module) SdkMemberType {
453	return t.memberType
454}
455
456func (t *sdkMemberDependencyTag) ExportMember() bool {
457	return t.export
458}
459
460// ReplaceSourceWithPrebuilt prevents dependencies from the sdk/module_exports onto their members
461// from being replaced with a preferred prebuilt.
462func (t *sdkMemberDependencyTag) ReplaceSourceWithPrebuilt() bool {
463	return false
464}
465
466// DependencyTagForSdkMemberType creates an SdkMemberDependencyTag that will cause any
467// dependencies added by the tag to be added to the sdk as the specified SdkMemberType and exported
468// (or not) as specified by the export parameter.
469func DependencyTagForSdkMemberType(memberType SdkMemberType, export bool) SdkMemberDependencyTag {
470	return &sdkMemberDependencyTag{memberType: memberType, export: export}
471}
472
473// SdkMemberType is the interface that must be implemented for every type that can be a member of an
474// sdk.
475//
476// The basic implementation should look something like this, where ModuleType is
477// the name of the module type being supported.
478//
479//	type moduleTypeSdkMemberType struct {
480//	    android.SdkMemberTypeBase
481//	}
482//
483//	func init() {
484//	    android.RegisterSdkMemberType(&moduleTypeSdkMemberType{
485//	        SdkMemberTypeBase: android.SdkMemberTypeBase{
486//	            PropertyName: "module_types",
487//	        },
488//	    }
489//	}
490//
491//	...methods...
492type SdkMemberType interface {
493	// SdkPropertyName returns the name of the member type property on an sdk module.
494	SdkPropertyName() string
495
496	// RequiresBpProperty returns true if this member type requires its property to be usable within
497	// an Android.bp file.
498	RequiresBpProperty() bool
499
500	// SupportedBuildReleases returns the string representation of a set of target build releases that
501	// support this member type.
502	SupportedBuildReleases() string
503
504	// UsableWithSdkAndSdkSnapshot returns true if the member type supports the sdk/sdk_snapshot,
505	// false otherwise.
506	UsableWithSdkAndSdkSnapshot() bool
507
508	// IsHostOsDependent returns true if prebuilt host artifacts may be specific to the host OS. Only
509	// applicable to modules where HostSupported() is true. If this is true, snapshots will list each
510	// host OS variant explicitly and disable all other host OS'es.
511	IsHostOsDependent() bool
512
513	// SupportedLinkages returns the names of the linkage variants supported by this module.
514	SupportedLinkages() []string
515
516	// ArePrebuiltsRequired returns true if prebuilts are required in the sdk snapshot, false
517	// otherwise.
518	ArePrebuiltsRequired() bool
519
520	// AddDependencies adds dependencies from the SDK module to all the module variants the member
521	// type contributes to the SDK. `names` is the list of module names given in the member type
522	// property (as returned by SdkPropertyName()) in the SDK module. The exact set of variants
523	// required is determined by the SDK and its properties. The dependencies must be added with the
524	// supplied tag.
525	//
526	// The BottomUpMutatorContext provided is for the SDK module.
527	AddDependencies(ctx SdkDependencyContext, dependencyTag blueprint.DependencyTag, names []string)
528
529	// IsInstance returns true if the supplied module is an instance of this member type.
530	//
531	// This is used to check the type of each variant before added to the SdkMember. Returning false
532	// will cause an error to be logged explaining that the module is not allowed in whichever sdk
533	// property it was added.
534	IsInstance(module Module) bool
535
536	// UsesSourceModuleTypeInSnapshot returns true when the AddPrebuiltModule() method returns a
537	// source module type.
538	UsesSourceModuleTypeInSnapshot() bool
539
540	// AddPrebuiltModule is called to add a prebuilt module that the sdk will populate.
541	//
542	// The sdk module code generates the snapshot as follows:
543	//
544	// * A properties struct of type SdkMemberProperties is created for each variant and
545	//   populated with information from the variant by calling PopulateFromVariant(Module)
546	//   on the struct.
547	//
548	// * An additional properties struct is created into which the common properties will be
549	//   added.
550	//
551	// * The variant property structs are analysed to find exported (capitalized) fields which
552	//   have common values. Those fields are cleared and the common value added to the common
553	//   properties.
554	//
555	//   A field annotated with a tag of `sdk:"ignore"` will be treated as if it
556	//   was not capitalized, i.e. ignored and not optimized for common values.
557	//
558	//   A field annotated with a tag of `sdk:"keep"` will not be cleared even if the value is common
559	//   across multiple structs. Common values will still be copied into the common property struct.
560	//   So, if the same value is placed in all structs populated from variants that value would be
561	//   copied into all common property structs and so be available in every instance.
562	//
563	//   A field annotated with a tag of `android:"arch_variant"` will be allowed to have
564	//   values that differ by arch, fields not tagged as such must have common values across
565	//   all variants.
566	//
567	// * Additional field tags can be specified on a field that will ignore certain values
568	//   for the purpose of common value optimization. A value that is ignored must have the
569	//   default value for the property type. This is to ensure that significant value are not
570	//   ignored by accident. The purpose of this is to allow the snapshot generation to reflect
571	//   the behavior of the runtime. e.g. if a property is ignored on the host then a property
572	//   that is common for android can be treated as if it was common for android and host as
573	//   the setting for host is ignored anyway.
574	//   * `sdk:"ignored-on-host" - this indicates the property is ignored on the host variant.
575	//
576	// * The sdk module type populates the BpModule structure, creating the arch specific
577	//   structure and calls AddToPropertySet(...) on the properties struct to add the member
578	//   specific properties in the correct place in the structure.
579	//
580	AddPrebuiltModule(ctx SdkMemberContext, member SdkMember) BpModule
581
582	// CreateVariantPropertiesStruct creates a structure into which variant specific properties can be
583	// added.
584	CreateVariantPropertiesStruct() SdkMemberProperties
585
586	// SupportedTraits returns the set of traits supported by this member type.
587	SupportedTraits() SdkMemberTraitSet
588
589	// Overrides returns whether type overrides other SdkMemberType
590	Overrides(SdkMemberType) bool
591}
592
593var _ sdkRegisterable = (SdkMemberType)(nil)
594
595// SdkDependencyContext provides access to information needed by the SdkMemberType.AddDependencies()
596// implementations.
597type SdkDependencyContext interface {
598	BottomUpMutatorContext
599
600	// RequiredTraits returns the set of SdkMemberTrait instances that the sdk requires the named
601	// member to provide.
602	RequiredTraits(name string) SdkMemberTraitSet
603
604	// RequiresTrait returns true if the sdk requires the member with the supplied name to provide the
605	// supplied trait.
606	RequiresTrait(name string, trait SdkMemberTrait) bool
607}
608
609// SdkMemberTypeBase is the base type for SdkMemberType implementations and must be embedded in any
610// struct that implements SdkMemberType.
611type SdkMemberTypeBase struct {
612	PropertyName string
613
614	// Property names that this SdkMemberTypeBase can override, this is useful when a module type is a
615	// superset of another module type.
616	OverridesPropertyNames map[string]bool
617
618	// The names of linkage variants supported by this module.
619	SupportedLinkageNames []string
620
621	// When set to true BpPropertyNotRequired indicates that the member type does not require the
622	// property to be specifiable in an Android.bp file.
623	BpPropertyNotRequired bool
624
625	// The name of the first targeted build release.
626	//
627	// If not specified then it is assumed to be available on all targeted build releases.
628	SupportedBuildReleaseSpecification string
629
630	// Set to true if this must be usable with the sdk/sdk_snapshot module types. Otherwise, it will
631	// only be usable with module_exports/module_exports_snapshots module types.
632	SupportsSdk bool
633
634	// Set to true if prebuilt host artifacts of this member may be specific to the host OS. Only
635	// applicable to modules where HostSupported() is true.
636	HostOsDependent bool
637
638	// When set to true UseSourceModuleTypeInSnapshot indicates that the member type creates a source
639	// module type in its SdkMemberType.AddPrebuiltModule() method. That prevents the sdk snapshot
640	// code from automatically adding a prefer: true flag.
641	UseSourceModuleTypeInSnapshot bool
642
643	// Set to proptools.BoolPtr(false) if this member does not generate prebuilts but is only provided
644	// to allow the sdk to gather members from this member's dependencies. If not specified then
645	// defaults to true.
646	PrebuiltsRequired *bool
647
648	// The list of supported traits.
649	Traits []SdkMemberTrait
650}
651
652func (b *SdkMemberTypeBase) SdkPropertyName() string {
653	return b.PropertyName
654}
655
656func (b *SdkMemberTypeBase) RequiresBpProperty() bool {
657	return !b.BpPropertyNotRequired
658}
659
660func (b *SdkMemberTypeBase) SupportedBuildReleases() string {
661	return b.SupportedBuildReleaseSpecification
662}
663
664func (b *SdkMemberTypeBase) UsableWithSdkAndSdkSnapshot() bool {
665	return b.SupportsSdk
666}
667
668func (b *SdkMemberTypeBase) IsHostOsDependent() bool {
669	return b.HostOsDependent
670}
671
672func (b *SdkMemberTypeBase) ArePrebuiltsRequired() bool {
673	return proptools.BoolDefault(b.PrebuiltsRequired, true)
674}
675
676func (b *SdkMemberTypeBase) UsesSourceModuleTypeInSnapshot() bool {
677	return b.UseSourceModuleTypeInSnapshot
678}
679
680func (b *SdkMemberTypeBase) SupportedTraits() SdkMemberTraitSet {
681	return NewSdkMemberTraitSet(b.Traits)
682}
683
684func (b *SdkMemberTypeBase) Overrides(other SdkMemberType) bool {
685	return b.OverridesPropertyNames[other.SdkPropertyName()]
686}
687
688func (b *SdkMemberTypeBase) SupportedLinkages() []string {
689	return b.SupportedLinkageNames
690}
691
692// registeredModuleExportsMemberTypes is the set of registered SdkMemberTypes for module_exports
693// modules.
694var registeredModuleExportsMemberTypes = &sdkRegistry{}
695
696// registeredSdkMemberTypes is the set of registered registeredSdkMemberTypes for sdk modules.
697var registeredSdkMemberTypes = &sdkRegistry{}
698
699// RegisteredSdkMemberTypes returns a OnceKey and a sorted list of registered types.
700//
701// If moduleExports is true then the slice of types includes all registered types that can be used
702// with the module_exports and module_exports_snapshot module types. Otherwise, the slice of types
703// only includes those registered types that can be used with the sdk and sdk_snapshot module
704// types.
705//
706// The key uniquely identifies the array of types and can be used with OncePer.Once() to cache
707// information derived from the array of types.
708func RegisteredSdkMemberTypes(moduleExports bool) (OnceKey, []SdkMemberType) {
709	var registry *sdkRegistry
710	if moduleExports {
711		registry = registeredModuleExportsMemberTypes
712	} else {
713		registry = registeredSdkMemberTypes
714	}
715
716	registerables := registry.registeredObjects()
717	types := make([]SdkMemberType, len(registerables))
718	for i, registerable := range registerables {
719		types[i] = registerable.(SdkMemberType)
720	}
721	return registry.uniqueOnceKey(), types
722}
723
724// RegisterSdkMemberType registers an SdkMemberType object to allow them to be used in the
725// module_exports, module_exports_snapshot and (depending on the value returned from
726// SdkMemberType.UsableWithSdkAndSdkSnapshot) the sdk and sdk_snapshot module types.
727func RegisterSdkMemberType(memberType SdkMemberType) {
728	// All member types are usable with module_exports.
729	registeredModuleExportsMemberTypes = registeredModuleExportsMemberTypes.copyAndAppend(memberType)
730
731	// Only those that explicitly indicate it are usable with sdk.
732	if memberType.UsableWithSdkAndSdkSnapshot() {
733		registeredSdkMemberTypes = registeredSdkMemberTypes.copyAndAppend(memberType)
734	}
735}
736
737// SdkMemberPropertiesBase is the base structure for all implementations of SdkMemberProperties and
738// must be embedded in any struct that implements SdkMemberProperties.
739//
740// Contains common properties that apply across many different member types.
741type SdkMemberPropertiesBase struct {
742	// The number of unique os types supported by the member variants.
743	//
744	// If a member has a variant with more than one os type then it will need to differentiate
745	// the locations of any of their prebuilt files in the snapshot by os type to prevent them
746	// from colliding. See OsPrefix().
747	//
748	// Ignore this property during optimization. This is needed because this property is the same for
749	// all variants of a member and so would be optimized away if it was not ignored.
750	Os_count int `sdk:"ignore"`
751
752	// The os type for which these properties refer.
753	//
754	// Provided to allow a member to differentiate between os types in the locations of their
755	// prebuilt files when it supports more than one os type.
756	//
757	// Ignore this property during optimization. This is needed because this property is the same for
758	// all variants of a member and so would be optimized away if it was not ignored.
759	Os OsType `sdk:"ignore"`
760
761	// The setting to use for the compile_multilib property.
762	Compile_multilib string `android:"arch_variant"`
763}
764
765// OsPrefix returns the os prefix to use for any file paths in the sdk.
766//
767// Is an empty string if the member only provides variants for a single os type, otherwise
768// is the OsType.Name.
769func (b *SdkMemberPropertiesBase) OsPrefix() string {
770	if b.Os_count == 1 {
771		return ""
772	} else {
773		return b.Os.Name
774	}
775}
776
777func (b *SdkMemberPropertiesBase) Base() *SdkMemberPropertiesBase {
778	return b
779}
780
781// SdkMemberProperties is the interface to be implemented on top of a structure that contains
782// variant specific information.
783//
784// Struct fields that are capitalized are examined for common values to extract. Fields that are not
785// capitalized are assumed to be arch specific.
786type SdkMemberProperties interface {
787	// Base returns the base structure.
788	Base() *SdkMemberPropertiesBase
789
790	// PopulateFromVariant populates this structure with information from a module variant.
791	//
792	// It will typically be called once for each variant of a member module that the SDK depends upon.
793	PopulateFromVariant(ctx SdkMemberContext, variant Module)
794
795	// AddToPropertySet adds the information from this structure to the property set.
796	//
797	// This will be called for each instance of this structure on which the PopulateFromVariant method
798	// was called and also on a number of different instances of this structure into which properties
799	// common to one or more variants have been copied. Therefore, implementations of this must handle
800	// the case when this structure is only partially populated.
801	AddToPropertySet(ctx SdkMemberContext, propertySet BpPropertySet)
802}
803
804// SdkMemberContext provides access to information common to a specific member.
805type SdkMemberContext interface {
806
807	// SdkModuleContext returns the module context of the sdk common os variant which is creating the
808	// snapshot.
809	//
810	// This is common to all members of the sdk and is not specific to the member being processed.
811	// If information about the member being processed needs to be obtained from this ModuleContext it
812	// must be obtained using one of the OtherModule... methods not the Module... methods.
813	SdkModuleContext() ModuleContext
814
815	// SnapshotBuilder the builder of the snapshot.
816	SnapshotBuilder() SnapshotBuilder
817
818	// MemberType returns the type of the member currently being processed.
819	MemberType() SdkMemberType
820
821	// Name returns the name of the member currently being processed.
822	//
823	// Provided for use by sdk members to create a member specific location within the snapshot
824	// into which to copy the prebuilt files.
825	Name() string
826
827	// RequiresTrait returns true if this member is expected to provide the specified trait.
828	RequiresTrait(trait SdkMemberTrait) bool
829
830	// IsTargetBuildBeforeTiramisu return true if the target build release for which this snapshot is
831	// being generated is before Tiramisu, i.e. S.
832	IsTargetBuildBeforeTiramisu() bool
833
834	// ModuleErrorf reports an error at the line number of the module type in the module definition.
835	ModuleErrorf(fmt string, args ...interface{})
836}
837
838// ExportedComponentsInfo contains information about the components that this module exports to an
839// sdk snapshot.
840//
841// A component of a module is a child module that the module creates and which forms an integral
842// part of the functionality that the creating module provides. A component module is essentially
843// owned by its creator and is tightly coupled to the creator and other components.
844//
845// e.g. the child modules created by prebuilt_apis are not components because they are not tightly
846// coupled to the prebuilt_apis module. Once they are created the prebuilt_apis ignores them. The
847// child impl and stub library created by java_sdk_library (and corresponding import) are components
848// because the creating module depends upon them in order to provide some of its own functionality.
849//
850// A component is exported if it is part of an sdk snapshot. e.g. The xml and impl child modules are
851// components but they are not exported as they are not part of an sdk snapshot.
852//
853// This information is used by the sdk snapshot generation code to ensure that it does not create
854// an sdk snapshot that contains a declaration of the component module and the module that creates
855// it as that would result in duplicate modules when attempting to use the snapshot. e.g. a snapshot
856// that included the java_sdk_library_import "foo" and also a java_import "foo.stubs" would fail
857// as there would be two modules called "foo.stubs".
858type ExportedComponentsInfo struct {
859	// The names of the exported components.
860	Components []string
861}
862
863var ExportedComponentsInfoProvider = blueprint.NewProvider[ExportedComponentsInfo]()
864
865// AdditionalSdkInfo contains additional properties to add to the generated SDK info file.
866type AdditionalSdkInfo struct {
867	Properties map[string]interface{}
868}
869
870var AdditionalSdkInfoProvider = blueprint.NewProvider[AdditionalSdkInfo]()
871
872var apiFingerprintPathKey = NewOnceKey("apiFingerprintPathKey")
873
874func ApiFingerprintPath(ctx PathContext) OutputPath {
875	return ctx.Config().Once(apiFingerprintPathKey, func() interface{} {
876		return PathForOutput(ctx, "api_fingerprint.txt")
877	}).(OutputPath)
878}
879