• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright (C) 2017 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.f
14
15package hidl
16
17import (
18	"fmt"
19	"strings"
20
21	"github.com/google/blueprint"
22	"github.com/google/blueprint/proptools"
23
24	"android/soong/android"
25	"android/soong/cc"
26	"android/soong/genrule"
27	"android/soong/java"
28)
29
30var (
31	hidlInterfaceSuffix       = "_interface"
32	hidlMetadataSingletonName = "hidl_metadata_json"
33
34	pctx = android.NewPackageContext("android/hidl")
35
36	hidl             = pctx.HostBinToolVariable("hidl", "hidl-gen")
37	hidlLint         = pctx.HostBinToolVariable("lint", "hidl-lint")
38	soong_zip        = pctx.HostBinToolVariable("soong_zip", "soong_zip")
39	intermediatesDir = pctx.IntermediatesPathVariable("intermediatesDir", "")
40
41	hidlRule = pctx.StaticRule("hidlRule", blueprint.RuleParams{
42		Depfile:     "${out}.d",
43		Deps:        blueprint.DepsGCC,
44		Command:     "rm -rf ${genDir} && ${hidl} -R -p . -d ${out}.d -o ${genDir} -L ${language} ${options} ${fqName}",
45		CommandDeps: []string{"${hidl}"},
46		Description: "HIDL ${language}: ${in} => ${out}",
47	}, "fqName", "genDir", "language", "options")
48
49	hidlSrcJarRule = pctx.StaticRule("hidlSrcJarRule", blueprint.RuleParams{
50		Depfile: "${out}.d",
51		Deps:    blueprint.DepsGCC,
52		Command: "rm -rf ${genDir} && " +
53			"${hidl} -R -p . -d ${out}.d -o ${genDir}/srcs -L ${language} ${options} ${fqName} && " +
54			"${soong_zip} -o ${genDir}/srcs.srcjar -C ${genDir}/srcs -D ${genDir}/srcs",
55		CommandDeps: []string{"${hidl}", "${soong_zip}"},
56		Description: "HIDL ${language}: ${in} => srcs.srcjar",
57	}, "fqName", "genDir", "language", "options")
58
59	lintRule = pctx.StaticRule("lintRule", blueprint.RuleParams{
60		Command:     "rm -f ${output} && touch ${output} && ${lint} -j -e -R -p . ${options} ${fqName} > ${output}",
61		CommandDeps: []string{"${lint}"},
62		Description: "hidl-lint ${fqName}: ${out}",
63	}, "output", "options", "fqName")
64
65	zipLintRule = pctx.StaticRule("zipLintRule", blueprint.RuleParams{
66		Rspfile:        "$out.rsp",
67		RspfileContent: "$files",
68		Command:        "rm -f ${output} && ${soong_zip} -o ${output} -C ${intermediatesDir} -l ${out}.rsp",
69		CommandDeps:    []string{"${soong_zip}"},
70		Description:    "Zipping hidl-lints into ${output}",
71	}, "output", "files")
72
73	inheritanceHierarchyRule = pctx.StaticRule("inheritanceHierarchyRule", blueprint.RuleParams{
74		Command:     "rm -f ${out} && ${hidl} -L inheritance-hierarchy ${options} ${fqInterface} > ${out}",
75		CommandDeps: []string{"${hidl}"},
76		Description: "HIDL inheritance hierarchy: ${fqInterface} => ${out}",
77	}, "options", "fqInterface")
78
79	joinJsonObjectsToArrayRule = pctx.StaticRule("joinJsonObjectsToArrayRule", blueprint.RuleParams{
80		Rspfile:        "$out.rsp",
81		RspfileContent: "$files",
82		Command: "rm -rf ${out} && " +
83			// Start the output array with an opening bracket.
84			"echo '[' >> ${out} && " +
85			// Add prebuilt declarations
86			"echo \"${extras}\" >> ${out} && " +
87			// Append each input file and a comma to the output.
88			"for file in $$(cat ${out}.rsp); do " +
89			"cat $$file >> ${out}; echo ',' >> ${out}; " +
90			"done && " +
91			// Remove the last comma, replacing it with the closing bracket.
92			"sed -i '$$d' ${out} && echo ']' >> ${out}",
93		Description: "Joining JSON objects into array ${out}",
94	}, "extras", "files")
95)
96
97func init() {
98	android.RegisterModuleType("prebuilt_hidl_interfaces", prebuiltHidlInterfaceFactory)
99	android.RegisterModuleType("hidl_interface", HidlInterfaceFactory)
100	android.RegisterParallelSingletonType("all_hidl_lints", allHidlLintsFactory)
101	android.RegisterModuleType("hidl_interfaces_metadata", hidlInterfacesMetadataSingletonFactory)
102	pctx.Import("android/soong/android")
103}
104
105func hidlInterfacesMetadataSingletonFactory() android.Module {
106	i := &hidlInterfacesMetadataSingleton{}
107	android.InitAndroidModule(i)
108	return i
109}
110
111type hidlInterfacesMetadataSingleton struct {
112	android.ModuleBase
113}
114
115func (m *hidlInterfacesMetadataSingleton) GenerateAndroidBuildActions(ctx android.ModuleContext) {
116	if m.Name() != hidlMetadataSingletonName {
117		ctx.PropertyErrorf("name", "must be %s", hidlMetadataSingletonName)
118		return
119	}
120
121	var inheritanceHierarchyOutputs android.Paths
122	additionalInterfaces := []string{}
123	ctx.VisitDirectDeps(func(m android.Module) {
124		if !m.ExportedToMake() {
125			return
126		}
127		if t, ok := m.(*hidlGenRule); ok {
128			if t.properties.Language == "inheritance-hierarchy" {
129				inheritanceHierarchyOutputs = append(inheritanceHierarchyOutputs, t.genOutputs.Paths()...)
130			}
131		} else if t, ok := m.(*prebuiltHidlInterface); ok {
132			additionalInterfaces = append(additionalInterfaces, t.properties.Interfaces...)
133		}
134	})
135
136	inheritanceHierarchyPath := android.PathForIntermediates(ctx, "hidl_inheritance_hierarchy.json")
137
138	ctx.Build(pctx, android.BuildParams{
139		Rule:   joinJsonObjectsToArrayRule,
140		Inputs: inheritanceHierarchyOutputs,
141		Output: inheritanceHierarchyPath,
142		Args: map[string]string{
143			"extras": strings.Join(wrap("{\\\"interface\\\":\\\"", additionalInterfaces, "\\\"},"), " "),
144			"files":  strings.Join(inheritanceHierarchyOutputs.Strings(), " "),
145		},
146	})
147
148	ctx.SetOutputFiles(android.Paths{inheritanceHierarchyPath}, "")
149}
150
151func allHidlLintsFactory() android.Singleton {
152	return &allHidlLintsSingleton{}
153}
154
155type allHidlLintsSingleton struct {
156	outPath android.OutputPath
157}
158
159func (m *allHidlLintsSingleton) GenerateBuildActions(ctx android.SingletonContext) {
160	var hidlLintOutputs android.Paths
161	ctx.VisitAllModuleProxies(func(m android.ModuleProxy) {
162		if t, ok := android.OtherModuleProvider(ctx, m, HidlGenRuleInfoProvider); ok {
163			if t.Language == "lint" {
164				if len(t.GenOutputs) == 1 {
165					hidlLintOutputs = append(hidlLintOutputs, t.GenOutputs[0])
166				} else {
167					panic("-hidl-lint target was not configured correctly")
168				}
169			}
170		}
171	})
172
173	outPath := android.PathForIntermediates(ctx, "hidl-lint.zip")
174	m.outPath = outPath
175
176	ctx.Build(pctx, android.BuildParams{
177		Rule:   zipLintRule,
178		Inputs: hidlLintOutputs,
179		Output: outPath,
180		Args: map[string]string{
181			"output": outPath.String(),
182			"files":  strings.Join(hidlLintOutputs.Strings(), " "),
183		},
184	})
185
186	ctx.DistForGoal("dist_files", outPath)
187}
188
189func (m *allHidlLintsSingleton) MakeVars(ctx android.MakeVarsContext) {
190	ctx.Strict("ALL_HIDL_LINTS_ZIP", m.outPath.String())
191}
192
193type hidlGenProperties struct {
194	Language       string
195	FqName         string
196	Root           string
197	Interfaces     []string
198	Inputs         []string
199	Outputs        []string
200	Apex_available []string
201}
202
203type hidlGenRule struct {
204	android.ModuleBase
205
206	properties hidlGenProperties
207
208	genOutputDir android.Path
209	genInputs    android.Paths
210	genOutputs   android.WritablePaths
211}
212
213type HidlGenRuleInfo struct {
214	Language   string
215	GenOutputs android.WritablePaths
216}
217
218var HidlGenRuleInfoProvider = blueprint.NewProvider[HidlGenRuleInfo]()
219
220var _ android.SourceFileProducer = (*hidlGenRule)(nil)
221var _ genrule.SourceFileGenerator = (*hidlGenRule)(nil)
222
223func (g *hidlGenRule) GenerateAndroidBuildActions(ctx android.ModuleContext) {
224	g.genOutputDir = android.PathForModuleGen(ctx)
225
226	for _, input := range g.properties.Inputs {
227		g.genInputs = append(g.genInputs, android.PathForModuleSrc(ctx, input))
228	}
229
230	var interfaces []string
231	for _, src := range g.properties.Inputs {
232		if strings.HasSuffix(src, ".hal") && strings.HasPrefix(src, "I") {
233			interfaces = append(interfaces, strings.TrimSuffix(src, ".hal"))
234		}
235	}
236
237	switch g.properties.Language {
238	case "lint":
239		g.genOutputs = append(g.genOutputs, android.PathForModuleGen(ctx, "lint.json"))
240	case "inheritance-hierarchy":
241		for _, intf := range interfaces {
242			g.genOutputs = append(g.genOutputs, android.PathForModuleGen(ctx, intf+"_inheritance_hierarchy.json"))
243		}
244	default:
245		for _, output := range g.properties.Outputs {
246			g.genOutputs = append(g.genOutputs, android.PathForModuleGen(ctx, output))
247		}
248	}
249
250	var extraOptions []string // including roots
251	var currentPath android.OptionalPath
252	ctx.VisitDirectDeps(func(dep android.Module) {
253		switch t := dep.(type) {
254		case *hidlInterface:
255			extraOptions = append(extraOptions, t.properties.Full_root_option)
256		case *hidlPackageRoot:
257			if currentPath.Valid() {
258				panic(fmt.Sprintf("Expecting only one path, but found %v %v", currentPath, t.getCurrentPath()))
259			}
260
261			currentPath = t.getCurrentPath()
262
263			if t.requireFrozen() {
264				extraOptions = append(extraOptions, "-F")
265			}
266		}
267	})
268
269	extraOptions = android.FirstUniqueStrings(extraOptions)
270
271	inputs := g.genInputs
272	if currentPath.Valid() {
273		inputs = append(inputs, currentPath.Path())
274	}
275
276	rule := hidlRule
277	if g.properties.Language == "java" {
278		rule = hidlSrcJarRule
279	}
280
281	android.SetProvider(ctx, HidlGenRuleInfoProvider, HidlGenRuleInfo{
282		Language:   g.properties.Language,
283		GenOutputs: g.genOutputs,
284	})
285
286	if g.properties.Language == "lint" {
287		ctx.Build(pctx, android.BuildParams{
288			Rule:   lintRule,
289			Inputs: inputs,
290			Output: g.genOutputs[0],
291			Args: map[string]string{
292				"output":  g.genOutputs[0].String(),
293				"fqName":  g.properties.FqName,
294				"options": strings.Join(extraOptions, " "),
295			},
296		})
297
298		return
299	}
300
301	if g.properties.Language == "inheritance-hierarchy" {
302		for i, intf := range interfaces {
303			ctx.Build(pctx, android.BuildParams{
304				Rule:   inheritanceHierarchyRule,
305				Inputs: inputs,
306				Output: g.genOutputs[i],
307				Args: map[string]string{
308					"fqInterface": g.properties.FqName + "::" + intf,
309					"options":     strings.Join(extraOptions, " "),
310				},
311			})
312		}
313
314		return
315	}
316
317	ctx.ModuleBuild(pctx, android.ModuleBuildParams{
318		Rule:            rule,
319		Inputs:          inputs,
320		Output:          g.genOutputs[0],
321		ImplicitOutputs: g.genOutputs[1:],
322		Args: map[string]string{
323			"genDir":   g.genOutputDir.String(),
324			"fqName":   g.properties.FqName,
325			"language": g.properties.Language,
326			"options":  strings.Join(extraOptions, " "),
327		},
328	})
329}
330
331func (g *hidlGenRule) GeneratedSourceFiles() android.Paths {
332	return g.genOutputs.Paths()
333}
334
335func (g *hidlGenRule) Srcs() android.Paths {
336	return g.genOutputs.Paths()
337}
338
339func (g *hidlGenRule) GeneratedDeps() android.Paths {
340	return g.genOutputs.Paths()
341}
342
343func (g *hidlGenRule) GeneratedHeaderDirs() android.Paths {
344	return android.Paths{g.genOutputDir}
345}
346
347func (g *hidlGenRule) DepsMutator(ctx android.BottomUpMutatorContext) {
348	ctx.AddDependency(ctx.Module(), nil, g.properties.FqName+hidlInterfaceSuffix)
349	ctx.AddDependency(ctx.Module(), nil, wrap("", g.properties.Interfaces, hidlInterfaceSuffix)...)
350	ctx.AddDependency(ctx.Module(), nil, g.properties.Root)
351
352	ctx.AddReverseDependency(ctx.Module(), nil, hidlMetadataSingletonName)
353}
354
355func hidlGenFactory() android.Module {
356	g := &hidlGenRule{}
357	g.AddProperties(&g.properties)
358	android.InitAndroidModule(g)
359	return g
360}
361
362type prebuiltHidlInterfaceProperties struct {
363	// List of interfaces to consider valid, e.g. "vendor.foo.bar@1.0::IFoo" for typo checking
364	// between init.rc, VINTF, and elsewhere. Note that inheritance properties will not be
365	// checked for these (but would be checked in a branch where the actual hidl_interface
366	// exists).
367	Interfaces []string
368}
369
370type prebuiltHidlInterface struct {
371	android.ModuleBase
372
373	properties prebuiltHidlInterfaceProperties
374}
375
376func (p *prebuiltHidlInterface) GenerateAndroidBuildActions(ctx android.ModuleContext) {}
377
378func (p *prebuiltHidlInterface) DepsMutator(ctx android.BottomUpMutatorContext) {
379	ctx.AddReverseDependency(ctx.Module(), nil, hidlMetadataSingletonName)
380}
381
382func prebuiltHidlInterfaceFactory() android.Module {
383	i := &prebuiltHidlInterface{}
384	i.AddProperties(&i.properties)
385	android.InitAndroidModule(i)
386	return i
387}
388
389type hidlInterfaceProperties struct {
390	// List of .hal files which compose this interface.
391	Srcs []string
392
393	// List of hal interface packages that this library depends on.
394	Interfaces []string
395
396	// Package root for this package, must be a prefix of name
397	Root string
398
399	// Unused/deprecated: List of non-TypeDef types declared in types.hal.
400	Types []string
401
402	// Whether to generate the Java library stubs.
403	// Default: true
404	Gen_java *bool
405
406	// Whether to generate a Java library containing constants
407	// expressed by @export annotations in the hal files.
408	Gen_java_constants bool
409
410	// Whether to generate VTS-related testing libraries.
411	Gen_vts *bool
412
413	// example: -randroid.hardware:hardware/interfaces
414	Full_root_option string `blueprint:"mutated"`
415
416	// List of APEX modules this interface can be used in.
417	//
418	// WARNING: HIDL is not fully supported in APEX since VINTF currently doesn't
419	// read files from APEXes (b/130058564).
420	//
421	// "//apex_available:anyapex" is a pseudo APEX name that matches to any APEX.
422	// "//apex_available:platform" refers to non-APEX partitions like "system.img"
423	//
424	// Note, this only applies to C++ libs, Java libs, and Java constant libs. It
425	// does  not apply to VTS targets targets/fuzzers since these components
426	// should not be shipped on device.
427	Apex_available []string
428
429	// Installs the vendor variant of the module to the /odm partition instead of
430	// the /vendor partition.
431	Odm_available *bool
432}
433
434type hidlInterface struct {
435	android.ModuleBase
436
437	properties hidlInterfaceProperties
438}
439
440func processSources(mctx android.LoadHookContext, srcs []string) ([]string, []string, bool) {
441	var interfaces []string
442	var types []string // hidl-gen only supports types.hal, but don't assume that here
443
444	hasError := false
445
446	for _, v := range srcs {
447		if !strings.HasSuffix(v, ".hal") {
448			mctx.PropertyErrorf("srcs", "Source must be a .hal file: "+v)
449			hasError = true
450			continue
451		}
452
453		name := strings.TrimSuffix(v, ".hal")
454
455		if strings.HasPrefix(name, "I") {
456			baseName := strings.TrimPrefix(name, "I")
457			interfaces = append(interfaces, baseName)
458		} else {
459			types = append(types, name)
460		}
461	}
462
463	return interfaces, types, !hasError
464}
465
466func processDependencies(mctx android.LoadHookContext, interfaces []string) ([]string, []string, bool) {
467	var dependencies []string
468	var javaDependencies []string
469
470	hasError := false
471
472	for _, v := range interfaces {
473		name, err := parseFqName(v)
474		if err != nil {
475			mctx.PropertyErrorf("interfaces", err.Error())
476			hasError = true
477			continue
478		}
479		dependencies = append(dependencies, name.string())
480		javaDependencies = append(javaDependencies, name.javaName())
481	}
482
483	return dependencies, javaDependencies, !hasError
484}
485
486func removeCoreDependencies(mctx android.LoadHookContext, dependencies []string) []string {
487	var ret []string
488
489	for _, i := range dependencies {
490		if !isCorePackage(i) {
491			ret = append(ret, i)
492		}
493	}
494
495	return ret
496}
497
498func hidlInterfaceMutator(mctx android.LoadHookContext, i *hidlInterface) {
499	if !canInterfaceExist(i.ModuleBase.Name()) {
500		mctx.PropertyErrorf("name", "No more HIDL interfaces can be added to Android. Please use AIDL.")
501		return
502	}
503
504	name, err := parseFqName(i.ModuleBase.Name())
505	if err != nil {
506		mctx.PropertyErrorf("name", err.Error())
507	}
508
509	if !name.inPackage(i.properties.Root) {
510		mctx.PropertyErrorf("root", i.properties.Root+" must be a prefix of  "+name.string()+".")
511	}
512	if lookupPackageRoot(i.properties.Root) == nil {
513		mctx.PropertyErrorf("interfaces", `Cannot find package root specification for package `+
514			`root '%s' needed for module '%s'. Either this is a mispelling of the package `+
515			`root, or a new hidl_package_root module needs to be added. For example, you can `+
516			`fix this error by adding the following to <some path>/Android.bp:
517
518hidl_package_root {
519name: "%s",
520// if you want to require <some path>/current.txt for interface versioning
521use_current: true,
522}
523
524This corresponds to the "-r%s:<some path>" option that would be passed into hidl-gen.`,
525			i.properties.Root, name, i.properties.Root, i.properties.Root)
526	}
527
528	interfaces, types, _ := processSources(mctx, i.properties.Srcs)
529
530	if len(interfaces) == 0 && len(types) == 0 {
531		mctx.PropertyErrorf("srcs", "No sources provided.")
532	}
533
534	dependencies, javaDependencies, _ := processDependencies(mctx, i.properties.Interfaces)
535	cppDependencies := removeCoreDependencies(mctx, dependencies)
536
537	if mctx.Failed() {
538		return
539	}
540
541	shouldGenerateLibrary := !isCorePackage(name.string())
542	// explicitly true if not specified to give early warning to devs
543	shouldGenerateJava := proptools.BoolDefault(i.properties.Gen_java, true)
544	shouldGenerateJavaConstants := i.properties.Gen_java_constants
545
546	var productAvailable *bool
547	if !mctx.ProductSpecific() {
548		productAvailable = proptools.BoolPtr(true)
549	}
550
551	var vendorAvailable *bool
552	if !proptools.Bool(i.properties.Odm_available) {
553		vendorAvailable = proptools.BoolPtr(true)
554	}
555
556	// TODO(b/69002743): remove filegroups
557	mctx.CreateModule(android.FileGroupFactory, &fileGroupProperties{
558		Name: proptools.StringPtr(name.fileGroupName()),
559		Srcs: i.properties.Srcs,
560	})
561
562	mctx.CreateModule(hidlGenFactory, &nameProperties{
563		Name: proptools.StringPtr(name.sourcesName()),
564	}, &hidlGenProperties{
565		Language:   "c++-sources",
566		FqName:     name.string(),
567		Root:       i.properties.Root,
568		Interfaces: i.properties.Interfaces,
569		Inputs:     i.properties.Srcs,
570		Outputs:    concat(wrap(name.dir(), interfaces, "All.cpp"), wrap(name.dir(), types, ".cpp")),
571	})
572
573	mctx.CreateModule(hidlGenFactory, &nameProperties{
574		Name: proptools.StringPtr(name.headersName()),
575	}, &hidlGenProperties{
576		Language:   "c++-headers",
577		FqName:     name.string(),
578		Root:       i.properties.Root,
579		Interfaces: i.properties.Interfaces,
580		Inputs:     i.properties.Srcs,
581		Outputs: concat(wrap(name.dir()+"I", interfaces, ".h"),
582			wrap(name.dir()+"Bs", interfaces, ".h"),
583			wrap(name.dir()+"BnHw", interfaces, ".h"),
584			wrap(name.dir()+"BpHw", interfaces, ".h"),
585			wrap(name.dir()+"IHw", interfaces, ".h"),
586			wrap(name.dir(), types, ".h"),
587			wrap(name.dir()+"hw", types, ".h")),
588	})
589
590	if shouldGenerateLibrary {
591		mctx.CreateModule(cc.LibraryFactory, &ccProperties{
592			Name:               proptools.StringPtr(name.string()),
593			Host_supported:     proptools.BoolPtr(true),
594			Recovery_available: proptools.BoolPtr(true),
595			Vendor_available:   vendorAvailable,
596			Odm_available:      i.properties.Odm_available,
597			Product_available:  productAvailable,
598			Double_loadable:    proptools.BoolPtr(isDoubleLoadable(name.string())),
599			Defaults:           []string{"hidl-module-defaults"},
600			Generated_sources:  []string{name.sourcesName()},
601			Generated_headers:  []string{name.headersName()},
602			Shared_libs: concat(cppDependencies, []string{
603				"libhidlbase",
604				"liblog",
605				"libutils",
606				"libcutils",
607			}),
608			Export_shared_lib_headers: concat(cppDependencies, []string{
609				"libhidlbase",
610				"libutils",
611			}),
612			Export_generated_headers: []string{name.headersName()},
613			Apex_available:           i.properties.Apex_available,
614			Min_sdk_version:          getMinSdkVersion(name.string()),
615		})
616	}
617
618	if shouldGenerateJava {
619		mctx.CreateModule(hidlGenFactory, &nameProperties{
620			Name: proptools.StringPtr(name.javaSourcesName()),
621		}, &hidlGenProperties{
622			Language:   "java",
623			FqName:     name.string(),
624			Root:       i.properties.Root,
625			Interfaces: i.properties.Interfaces,
626			Inputs:     i.properties.Srcs,
627			Outputs:    []string{"srcs.srcjar"},
628		})
629
630		commonJavaProperties := javaProperties{
631			Defaults:    []string{"hidl-java-module-defaults"},
632			Installable: proptools.BoolPtr(true),
633			Srcs:        []string{":" + name.javaSourcesName()},
634
635			// This should ideally be system_current, but android.hidl.base-V1.0-java is used
636			// to build framework, which is used to build system_current.  Use core_current
637			// plus hwbinder.stubs, which together form a subset of system_current that does
638			// not depend on framework.
639			Sdk_version:     proptools.StringPtr("core_current"),
640			Libs:            []string{"hwbinder.stubs"},
641			Apex_available:  i.properties.Apex_available,
642			Min_sdk_version: getMinSdkVersion(name.string()),
643			Is_stubs_module: proptools.BoolPtr(true),
644		}
645
646		mctx.CreateModule(java.LibraryFactory, &javaProperties{
647			Name:        proptools.StringPtr(name.javaName()),
648			Static_libs: javaDependencies,
649		}, &commonJavaProperties)
650		mctx.CreateModule(java.LibraryFactory, &javaProperties{
651			Name: proptools.StringPtr(name.javaSharedName()),
652			Libs: javaDependencies,
653		}, &commonJavaProperties)
654	}
655
656	if shouldGenerateJavaConstants {
657		mctx.CreateModule(hidlGenFactory, &nameProperties{
658			Name: proptools.StringPtr(name.javaConstantsSourcesName()),
659		}, &hidlGenProperties{
660			Language:   "java-constants",
661			FqName:     name.string(),
662			Root:       i.properties.Root,
663			Interfaces: i.properties.Interfaces,
664			Inputs:     i.properties.Srcs,
665			Outputs:    []string{name.sanitizedDir() + "Constants.java"},
666		})
667		mctx.CreateModule(java.LibraryFactory, &javaProperties{
668			Name:            proptools.StringPtr(name.javaConstantsName()),
669			Defaults:        []string{"hidl-java-module-defaults"},
670			Sdk_version:     proptools.StringPtr("core_current"),
671			Srcs:            []string{":" + name.javaConstantsSourcesName()},
672			Apex_available:  i.properties.Apex_available,
673			Min_sdk_version: getMinSdkVersion(name.string()),
674			Is_stubs_module: proptools.BoolPtr(true),
675		})
676	}
677
678	mctx.CreateModule(hidlGenFactory, &nameProperties{
679		Name: proptools.StringPtr(name.lintName()),
680	}, &hidlGenProperties{
681		Language:   "lint",
682		FqName:     name.string(),
683		Root:       i.properties.Root,
684		Interfaces: i.properties.Interfaces,
685		Inputs:     i.properties.Srcs,
686	})
687
688	mctx.CreateModule(hidlGenFactory, &nameProperties{
689		Name: proptools.StringPtr(name.inheritanceHierarchyName()),
690	}, &hidlGenProperties{
691		Language:   "inheritance-hierarchy",
692		FqName:     name.string(),
693		Root:       i.properties.Root,
694		Interfaces: i.properties.Interfaces,
695		Inputs:     i.properties.Srcs,
696	})
697}
698
699func (h *hidlInterface) Name() string {
700	return h.ModuleBase.Name() + hidlInterfaceSuffix
701}
702func (h *hidlInterface) GenerateAndroidBuildActions(ctx android.ModuleContext) {
703	visited := false
704	ctx.VisitDirectDeps(func(dep android.Module) {
705		if r, ok := dep.(*hidlPackageRoot); ok {
706			if visited {
707				panic("internal error, multiple dependencies found but only one added")
708			}
709			visited = true
710			h.properties.Full_root_option = r.getFullPackageRoot()
711		}
712	})
713	if !visited {
714		panic("internal error, no dependencies found but dependency added")
715	}
716
717}
718func (h *hidlInterface) DepsMutator(ctx android.BottomUpMutatorContext) {
719	ctx.AddDependency(ctx.Module(), nil, h.properties.Root)
720}
721
722func HidlInterfaceFactory() android.Module {
723	i := &hidlInterface{}
724	i.AddProperties(&i.properties)
725	android.InitAndroidModule(i)
726	android.AddLoadHook(i, func(ctx android.LoadHookContext) { hidlInterfaceMutator(ctx, i) })
727
728	return i
729}
730
731var minSdkVersion = map[string]string{
732	"android.hardware.audio.common@5.0":            "30",
733	"android.hardware.audio.common@6.0":            "31",
734	"android.hardware.automotive.audiocontrol@1.0": "31",
735	"android.hardware.automotive.audiocontrol@2.0": "31",
736	"android.hardware.automotive.vehicle@2.0":      "31",
737	"android.hardware.bluetooth.a2dp@1.0":          "30",
738	"android.hardware.bluetooth.audio@2.0":         "30",
739	"android.hardware.bluetooth.audio@2.1":         "30",
740	"android.hardware.bluetooth.audio@2.2":         "30",
741	"android.hardware.bluetooth@1.0":               "30",
742	"android.hardware.bluetooth@1.1":               "30",
743	"android.hardware.health@1.0":                  "31",
744	"android.hardware.health@2.0":                  "31",
745	"android.hardware.neuralnetworks@1.0":          "30",
746	"android.hardware.neuralnetworks@1.1":          "30",
747	"android.hardware.neuralnetworks@1.2":          "30",
748	"android.hardware.neuralnetworks@1.3":          "30",
749	"android.hardware.wifi@1.0":                    "30",
750	"android.hardware.wifi@1.1":                    "30",
751	"android.hardware.wifi@1.2":                    "30",
752	"android.hardware.wifi@1.3":                    "30",
753	"android.hardware.wifi@1.4":                    "30",
754	"android.hardware.wifi@1.5":                    "30",
755	"android.hardware.wifi@1.6":                    "30",
756	"android.hardware.wifi.hostapd@1.0":            "30",
757	"android.hardware.wifi.hostapd@1.1":            "30",
758	"android.hardware.wifi.hostapd@1.2":            "30",
759	"android.hardware.wifi.hostapd@1.3":            "30",
760	"android.hardware.wifi.supplicant@1.0":         "30",
761	"android.hardware.wifi.supplicant@1.1":         "30",
762	"android.hardware.wifi.supplicant@1.2":         "30",
763	"android.hardware.wifi.supplicant@1.3":         "30",
764	"android.hardware.wifi.supplicant@1.4":         "30",
765	"android.hidl.manager@1.0":                     "30",
766	"android.hidl.manager@1.1":                     "30",
767	"android.hidl.manager@1.2":                     "30",
768}
769
770func getMinSdkVersion(name string) *string {
771	if ver, ok := minSdkVersion[name]; ok {
772		return proptools.StringPtr(ver)
773	}
774	// legacy, as used
775	if name == "android.hardware.tetheroffload.config@1.0" ||
776		name == "android.hardware.tetheroffload.control@1.0" ||
777		name == "android.hardware.tetheroffload.control@1.1" ||
778		name == "android.hardware.radio@1.0" ||
779		name == "android.hidl.base@1.0" {
780
781		return nil
782	}
783	return proptools.StringPtr("29")
784}
785
786var doubleLoadablePackageNames = []string{
787	"android.frameworks.bufferhub@1.0",
788	"android.hardware.cas@1.0",
789	"android.hardware.cas.native@1.0",
790	"android.hardware.configstore@",
791	"android.hardware.drm@",
792	"android.hardware.graphics.allocator@",
793	"android.hardware.graphics.bufferqueue@",
794	"android.hardware.graphics.common@",
795	"android.hardware.graphics.mapper@",
796	"android.hardware.media@",
797	"android.hardware.media.bufferpool@",
798	"android.hardware.media.c2@",
799	"android.hardware.media.omx@",
800	"android.hardware.memtrack@1.0",
801	"android.hardware.neuralnetworks@",
802	"android.hidl.allocator@",
803	"android.hidl.memory@",
804	"android.hidl.memory.token@",
805	"android.hidl.safe_union@",
806	"android.hidl.token@",
807	"android.hardware.renderscript@",
808	"android.system.suspend@1.0",
809}
810
811func isDoubleLoadable(name string) bool {
812	for _, pkgname := range doubleLoadablePackageNames {
813		if strings.HasPrefix(name, pkgname) {
814			return true
815		}
816	}
817	return false
818}
819
820// packages in libhidlbase
821var coreDependencyPackageNames = []string{
822	"android.hidl.base@",
823	"android.hidl.manager@",
824}
825
826func isCorePackage(name string) bool {
827	for _, pkgname := range coreDependencyPackageNames {
828		if strings.HasPrefix(name, pkgname) {
829			return true
830		}
831	}
832	return false
833}
834
835var fuzzerPackageNameBlacklist = []string{
836	"android.hardware.keymaster@", // to avoid deleteAllKeys()
837	// Same-process HALs are always opened in the same process as their client.
838	// So stability guarantees don't apply to them, e.g. it's OK to crash on
839	// NULL input from client. Disable corresponding fuzzers as they create too
840	// much noise.
841	"android.hardware.graphics.mapper@",
842	"android.hardware.renderscript@",
843	"android.hidl.memory@",
844}
845
846func isFuzzerEnabled(name string) bool {
847	// TODO(151338797): re-enable fuzzers
848	return false
849}
850
851func canInterfaceExist(name string) bool {
852	if strings.HasPrefix(name, "android.") {
853		return allAospHidlInterfaces[name]
854	}
855
856	return true
857}
858
859var allAospHidlInterfaces = map[string]bool{
860	"android.frameworks.automotive.display@1.0":    true,
861	"android.frameworks.bufferhub@1.0":             true,
862	"android.frameworks.cameraservice.common@2.0":  true,
863	"android.frameworks.cameraservice.device@2.0":  true,
864	"android.frameworks.cameraservice.device@2.1":  true,
865	"android.frameworks.cameraservice.service@2.0": true,
866	"android.frameworks.cameraservice.service@2.1": true,
867	"android.frameworks.cameraservice.service@2.2": true,
868	"android.frameworks.displayservice@1.0":        true,
869	"android.frameworks.schedulerservice@1.0":      true,
870	"android.frameworks.sensorservice@1.0":         true,
871	"android.frameworks.stats@1.0":                 true,
872	"android.frameworks.vr.composer@1.0":           true,
873	"android.frameworks.vr.composer@2.0":           true,
874	"android.hardware.atrace@1.0":                  true,
875	"android.hardware.audio@2.0":                   true,
876	"android.hardware.audio@4.0":                   true,
877	"android.hardware.audio@5.0":                   true,
878	"android.hardware.audio@6.0":                   true,
879	"android.hardware.audio@7.0":                   true,
880	"android.hardware.audio@7.1":                   true,
881	"android.hardware.audio.common@2.0":            true,
882	"android.hardware.audio.common@4.0":            true,
883	"android.hardware.audio.common@5.0":            true,
884	"android.hardware.audio.common@6.0":            true,
885	"android.hardware.audio.common@7.0":            true,
886	"android.hardware.audio.effect@2.0":            true,
887	"android.hardware.audio.effect@4.0":            true,
888	"android.hardware.audio.effect@5.0":            true,
889	"android.hardware.audio.effect@6.0":            true,
890	"android.hardware.audio.effect@7.0":            true,
891	"android.hardware.authsecret@1.0":              true,
892	"android.hardware.automotive.audiocontrol@1.0": true,
893	"android.hardware.automotive.audiocontrol@2.0": true,
894	"android.hardware.automotive.can@1.0":          true,
895	"android.hardware.automotive.evs@1.0":          true,
896	"android.hardware.automotive.evs@1.1":          true,
897	"android.hardware.automotive.sv@1.0":           true,
898	"android.hardware.automotive.vehicle@2.0":      true,
899	"android.hardware.biometrics.face@1.0":         true,
900	"android.hardware.biometrics.fingerprint@2.1":  true,
901	"android.hardware.biometrics.fingerprint@2.2":  true,
902	"android.hardware.biometrics.fingerprint@2.3":  true,
903	"android.hardware.bluetooth@1.0":               true,
904	"android.hardware.bluetooth@1.1":               true,
905	"android.hardware.bluetooth.a2dp@1.0":          true,
906	"android.hardware.bluetooth.audio@2.0":         true,
907	"android.hardware.bluetooth.audio@2.1":         true,
908	"android.hardware.bluetooth.audio@2.2":         true,
909	"android.hardware.boot@1.0":                    true,
910	"android.hardware.boot@1.1":                    true,
911	"android.hardware.boot@1.2":                    true,
912	"android.hardware.broadcastradio@1.0":          true,
913	"android.hardware.broadcastradio@1.1":          true,
914	"android.hardware.broadcastradio@2.0":          true,
915	"android.hardware.camera.common@1.0":           true,
916	"android.hardware.camera.device@1.0":           true,
917	"android.hardware.camera.device@3.2":           true,
918	"android.hardware.camera.device@3.3":           true,
919	"android.hardware.camera.device@3.4":           true,
920	"android.hardware.camera.device@3.5":           true,
921	"android.hardware.camera.device@3.6":           true,
922	"android.hardware.camera.device@3.7":           true,
923	"android.hardware.camera.device@3.8":           true,
924	"android.hardware.camera.metadata@3.2":         true,
925	"android.hardware.camera.metadata@3.3":         true,
926	"android.hardware.camera.metadata@3.4":         true,
927	"android.hardware.camera.metadata@3.5":         true,
928	"android.hardware.camera.metadata@3.6":         true,
929	// TODO: Remove metadata@3.8 after AIDL migration b/196432585
930	"android.hardware.camera.metadata@3.7":              true,
931	"android.hardware.camera.metadata@3.8":              true,
932	"android.hardware.camera.provider@2.4":              true,
933	"android.hardware.camera.provider@2.5":              true,
934	"android.hardware.camera.provider@2.6":              true,
935	"android.hardware.camera.provider@2.7":              true,
936	"android.hardware.cas@1.0":                          true,
937	"android.hardware.cas@1.1":                          true,
938	"android.hardware.cas@1.2":                          true,
939	"android.hardware.cas.native@1.0":                   true,
940	"android.hardware.configstore@1.0":                  true,
941	"android.hardware.configstore@1.1":                  true,
942	"android.hardware.confirmationui@1.0":               true,
943	"android.hardware.contexthub@1.0":                   true,
944	"android.hardware.contexthub@1.1":                   true,
945	"android.hardware.contexthub@1.2":                   true,
946	"android.hardware.drm@1.0":                          true,
947	"android.hardware.drm@1.1":                          true,
948	"android.hardware.drm@1.2":                          true,
949	"android.hardware.drm@1.3":                          true,
950	"android.hardware.drm@1.4":                          true,
951	"android.hardware.dumpstate@1.0":                    true,
952	"android.hardware.dumpstate@1.1":                    true,
953	"android.hardware.fastboot@1.0":                     true,
954	"android.hardware.fastboot@1.1":                     true,
955	"android.hardware.gatekeeper@1.0":                   true,
956	"android.hardware.gnss@1.0":                         true,
957	"android.hardware.gnss@1.1":                         true,
958	"android.hardware.gnss@2.0":                         true,
959	"android.hardware.gnss@2.1":                         true,
960	"android.hardware.gnss.measurement_corrections@1.0": true,
961	"android.hardware.gnss.measurement_corrections@1.1": true,
962	"android.hardware.gnss.visibility_control@1.0":      true,
963	"android.hardware.graphics.allocator@2.0":           true,
964	"android.hardware.graphics.allocator@3.0":           true,
965	"android.hardware.graphics.allocator@4.0":           true,
966	"android.hardware.graphics.bufferqueue@1.0":         true,
967	"android.hardware.graphics.bufferqueue@2.0":         true,
968	"android.hardware.graphics.common@1.0":              true,
969	"android.hardware.graphics.common@1.1":              true,
970	"android.hardware.graphics.common@1.2":              true,
971	"android.hardware.graphics.composer@2.1":            true,
972	"android.hardware.graphics.composer@2.2":            true,
973	"android.hardware.graphics.composer@2.3":            true,
974	"android.hardware.graphics.composer@2.4":            true,
975	"android.hardware.graphics.mapper@2.0":              true,
976	"android.hardware.graphics.mapper@2.1":              true,
977	"android.hardware.graphics.mapper@3.0":              true,
978	"android.hardware.graphics.mapper@4.0":              true,
979	"android.hardware.health@1.0":                       true,
980	"android.hardware.health@2.0":                       true,
981	"android.hardware.health@2.1":                       true,
982	"android.hardware.health.storage@1.0":               true,
983	"android.hardware.input.classifier@1.0":             true,
984	"android.hardware.input.common@1.0":                 true,
985	"android.hardware.ir@1.0":                           true,
986	"android.hardware.keymaster@3.0":                    true,
987	"android.hardware.keymaster@4.0":                    true,
988	"android.hardware.keymaster@4.1":                    true,
989	"android.hardware.light@2.0":                        true,
990	"android.hardware.media@1.0":                        true,
991	"android.hardware.media.bufferpool@1.0":             true,
992	"android.hardware.media.bufferpool@2.0":             true,
993	"android.hardware.media.c2@1.0":                     true,
994	"android.hardware.media.c2@1.1":                     true,
995	"android.hardware.media.c2@1.2":                     true,
996	"android.hardware.media.omx@1.0":                    true,
997	"android.hardware.memtrack@1.0":                     true,
998	"android.hardware.neuralnetworks@1.0":               true,
999	"android.hardware.neuralnetworks@1.1":               true,
1000	"android.hardware.neuralnetworks@1.2":               true,
1001	"android.hardware.neuralnetworks@1.3":               true,
1002	"android.hardware.nfc@1.0":                          true,
1003	"android.hardware.nfc@1.1":                          true,
1004	"android.hardware.nfc@1.2":                          true,
1005	"android.hardware.oemlock@1.0":                      true,
1006	"android.hardware.power@1.0":                        true,
1007	"android.hardware.power@1.1":                        true,
1008	"android.hardware.power@1.2":                        true,
1009	"android.hardware.power@1.3":                        true,
1010	"android.hardware.power.stats@1.0":                  true,
1011	"android.hardware.radio@1.0":                        true,
1012	"android.hardware.radio@1.1":                        true,
1013	"android.hardware.radio@1.2":                        true,
1014	"android.hardware.radio@1.3":                        true,
1015	"android.hardware.radio@1.4":                        true,
1016	"android.hardware.radio@1.5":                        true,
1017	"android.hardware.radio@1.6":                        true,
1018	"android.hardware.radio.config@1.0":                 true,
1019	"android.hardware.radio.config@1.1":                 true,
1020	"android.hardware.radio.config@1.2":                 true,
1021	"android.hardware.radio.config@1.3":                 true,
1022	"android.hardware.radio.deprecated@1.0":             true,
1023	"android.hardware.renderscript@1.0":                 true,
1024	"android.hardware.secure_element@1.0":               true,
1025	"android.hardware.secure_element@1.1":               true,
1026	"android.hardware.secure_element@1.2":               true,
1027	"android.hardware.sensors@1.0":                      true,
1028	"android.hardware.sensors@2.0":                      true,
1029	"android.hardware.sensors@2.1":                      true,
1030	"android.hardware.soundtrigger@2.0":                 true,
1031	"android.hardware.soundtrigger@2.1":                 true,
1032	"android.hardware.soundtrigger@2.2":                 true,
1033	"android.hardware.soundtrigger@2.3":                 true,
1034	"android.hardware.soundtrigger@2.4":                 true,
1035	"android.hardware.tests.bar@1.0":                    true,
1036	"android.hardware.tests.baz@1.0":                    true,
1037	"android.hardware.tests.expression@1.0":             true,
1038	"android.hardware.tests.extension.light@2.0":        true,
1039	"android.hardware.tests.foo@1.0":                    true,
1040	"android.hardware.tests.hash@1.0":                   true,
1041	"android.hardware.tests.inheritance@1.0":            true,
1042	"android.hardware.tests.lazy@1.0":                   true,
1043	"android.hardware.tests.lazy@1.1":                   true,
1044	"android.hardware.tests.lazy_cb@1.0":                true,
1045	"android.hardware.tests.libhwbinder@1.0":            true,
1046	"android.hardware.tests.memory@1.0":                 true,
1047	"android.hardware.tests.memory@2.0":                 true,
1048	"android.hardware.tests.msgq@1.0":                   true,
1049	"android.hardware.tests.multithread@1.0":            true,
1050	"android.hardware.tests.safeunion@1.0":              true,
1051	"android.hardware.tests.safeunion.cpp@1.0":          true,
1052	"android.hardware.tests.trie@1.0":                   true,
1053	"android.hardware.tetheroffload.config@1.0":         true,
1054	"android.hardware.tetheroffload.control@1.0":        true,
1055	"android.hardware.tetheroffload.control@1.1":        true,
1056	"android.hardware.thermal@1.0":                      true,
1057	"android.hardware.thermal@1.1":                      true,
1058	"android.hardware.thermal@2.0":                      true,
1059	"android.hardware.tv.cec@1.0":                       true,
1060	"android.hardware.tv.cec@1.1":                       true,
1061	"android.hardware.tv.input@1.0":                     true,
1062	"android.hardware.tv.tuner@1.0":                     true,
1063	"android.hardware.tv.tuner@1.1":                     true,
1064	"android.hardware.usb@1.0":                          true,
1065	"android.hardware.usb@1.1":                          true,
1066	"android.hardware.usb@1.2":                          true,
1067	"android.hardware.usb@1.3":                          true,
1068	"android.hardware.usb.gadget@1.0":                   true,
1069	"android.hardware.usb.gadget@1.1":                   true,
1070	"android.hardware.usb.gadget@1.2":                   true,
1071	"android.hardware.vibrator@1.0":                     true,
1072	"android.hardware.vibrator@1.1":                     true,
1073	"android.hardware.vibrator@1.2":                     true,
1074	"android.hardware.vibrator@1.3":                     true,
1075	"android.hardware.vr@1.0":                           true,
1076	"android.hardware.weaver@1.0":                       true,
1077	"android.hardware.wifi@1.0":                         true,
1078	"android.hardware.wifi@1.1":                         true,
1079	"android.hardware.wifi@1.2":                         true,
1080	"android.hardware.wifi@1.3":                         true,
1081	"android.hardware.wifi@1.4":                         true,
1082	"android.hardware.wifi@1.5":                         true,
1083	"android.hardware.wifi@1.6":                         true,
1084	"android.hardware.wifi.hostapd@1.0":                 true,
1085	"android.hardware.wifi.hostapd@1.1":                 true,
1086	"android.hardware.wifi.hostapd@1.2":                 true,
1087	"android.hardware.wifi.hostapd@1.3":                 true,
1088	"android.hardware.wifi.offload@1.0":                 true,
1089	"android.hardware.wifi.supplicant@1.0":              true,
1090	"android.hardware.wifi.supplicant@1.1":              true,
1091	"android.hardware.wifi.supplicant@1.2":              true,
1092	"android.hardware.wifi.supplicant@1.3":              true,
1093	"android.hardware.wifi.supplicant@1.4":              true,
1094	"android.hidl.allocator@1.0":                        true,
1095	"android.hidl.base@1.0":                             true,
1096	"android.hidl.manager@1.0":                          true,
1097	"android.hidl.manager@1.1":                          true,
1098	"android.hidl.manager@1.2":                          true,
1099	"android.hidl.memory@1.0":                           true,
1100	"android.hidl.memory.block@1.0":                     true,
1101	"android.hidl.memory.token@1.0":                     true,
1102	"android.hidl.safe_union@1.0":                       true,
1103	"android.hidl.token@1.0":                            true,
1104	"android.system.net.netd@1.0":                       true,
1105	"android.system.net.netd@1.1":                       true,
1106	"android.system.suspend@1.0":                        true,
1107	"android.system.wifi.keystore@1.0":                  true,
1108}
1109