Merge "Use BaseModuleName() + SubName as apexFile.moduleName"
diff --git a/android/Android.bp b/android/Android.bp
index 96f0983..6ddcc14 100644
--- a/android/Android.bp
+++ b/android/Android.bp
@@ -39,7 +39,6 @@
         "paths.go",
         "phony.go",
         "prebuilt.go",
-        "prebuilt_build_tool.go",
         "proto.go",
         "register.go",
         "rule_builder.go",
diff --git a/android/config.go b/android/config.go
index d680b65..cafc71b 100644
--- a/android/config.go
+++ b/android/config.go
@@ -1252,10 +1252,6 @@
 	return c.productVariables.MissingUsesLibraries
 }
 
-func (c *deviceConfig) BoardVndkRuntimeDisable() bool {
-	return Bool(c.config.productVariables.BoardVndkRuntimeDisable)
-}
-
 func (c *deviceConfig) DeviceArch() string {
 	return String(c.config.productVariables.DeviceArch)
 }
diff --git a/android/defs.go b/android/defs.go
index 83daa03..4552224 100644
--- a/android/defs.go
+++ b/android/defs.go
@@ -69,7 +69,7 @@
 	// A symlink rule.
 	Symlink = pctx.AndroidStaticRule("Symlink",
 		blueprint.RuleParams{
-			Command:     "rm -f $out && ln -f -s $fromPath $out",
+			Command:     "ln -f -s $fromPath $out",
 			Description: "symlink $out",
 		},
 		"fromPath")
diff --git a/android/prebuilt_build_tool.go b/android/prebuilt_build_tool.go
deleted file mode 100644
index d457da4..0000000
--- a/android/prebuilt_build_tool.go
+++ /dev/null
@@ -1,100 +0,0 @@
-// Copyright 2020 Google Inc. All rights reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//     http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package android
-
-import (
-	"path"
-	"path/filepath"
-)
-
-func init() {
-	RegisterModuleType("prebuilt_build_tool", prebuiltBuildToolFactory)
-}
-
-type prebuiltBuildToolProperties struct {
-	// Source file to be executed for this build tool
-	Src *string `android:"path,arch_variant"`
-
-	// Extra files that should trigger rules using this tool to rebuild
-	Deps []string `android:"path,arch_variant"`
-}
-
-type prebuiltBuildTool struct {
-	ModuleBase
-	prebuilt Prebuilt
-
-	properties prebuiltBuildToolProperties
-
-	toolPath OptionalPath
-}
-
-func (t *prebuiltBuildTool) Name() string {
-	return t.prebuilt.Name(t.ModuleBase.Name())
-}
-
-func (t *prebuiltBuildTool) Prebuilt() *Prebuilt {
-	return &t.prebuilt
-}
-
-func (t *prebuiltBuildTool) DepsMutator(ctx BottomUpMutatorContext) {
-	if t.properties.Src == nil {
-		ctx.PropertyErrorf("src", "missing prebuilt source file")
-	}
-}
-
-func (t *prebuiltBuildTool) GenerateAndroidBuildActions(ctx ModuleContext) {
-	sourcePath := t.prebuilt.SingleSourcePath(ctx)
-	installedPath := PathForModuleOut(ctx, t.ModuleBase.Name())
-	deps := PathsForModuleSrc(ctx, t.properties.Deps)
-
-	var relPath string
-	if filepath.IsAbs(installedPath.String()) {
-		relPath = filepath.Join(absSrcDir, sourcePath.String())
-	} else {
-		var err error
-		relPath, err = filepath.Rel(path.Dir(installedPath.String()), sourcePath.String())
-		if err != nil {
-			ctx.ModuleErrorf("Unable to generate symlink between %q and %q: %s", installedPath.String(), sourcePath.String(), err)
-		}
-	}
-
-	ctx.Build(pctx, BuildParams{
-		Rule:      Symlink,
-		Output:    installedPath,
-		Input:     sourcePath,
-		Implicits: deps,
-		Args: map[string]string{
-			"fromPath": relPath,
-		},
-	})
-
-	t.toolPath = OptionalPathForPath(installedPath)
-}
-
-func (t *prebuiltBuildTool) HostToolPath() OptionalPath {
-	return t.toolPath
-}
-
-var _ HostToolProvider = &prebuiltBuildTool{}
-
-// prebuilt_build_tool is to declare prebuilts to be used during the build, particularly for use
-// in genrules with the "tools" property.
-func prebuiltBuildToolFactory() Module {
-	module := &prebuiltBuildTool{}
-	module.AddProperties(&module.properties)
-	InitSingleSourcePrebuiltModule(module, &module.properties, "Src")
-	InitAndroidArchModule(module, HostSupportedNoCross, MultilibFirst)
-	return module
-}
diff --git a/android/variable.go b/android/variable.go
index 2c8bd07..5826138 100644
--- a/android/variable.go
+++ b/android/variable.go
@@ -308,8 +308,6 @@
 	BoardPlatPrivateSepolicyDirs []string `json:",omitempty"`
 	BoardSepolicyM4Defs          []string `json:",omitempty"`
 
-	BoardVndkRuntimeDisable *bool `json:",omitempty"`
-
 	VendorVars map[string]map[string]string `json:",omitempty"`
 
 	Ndk_abis               *bool `json:",omitempty"`
diff --git a/cc/cc.go b/cc/cc.go
index bea851f..57fe9ba 100644
--- a/cc/cc.go
+++ b/cc/cc.go
@@ -116,8 +116,6 @@
 	// Used for host bionic
 	LinkerFlagsFile string
 	DynamicLinker   string
-
-	Tools []string
 }
 
 type PathDeps struct {
@@ -160,8 +158,6 @@
 
 	// Path to the dynamic linker binary
 	DynamicLinker android.OptionalPath
-
-	Tools map[string]android.Path
 }
 
 // LocalOrGlobalFlags contains flags that need to have values set globally by the build system or locally by the module
@@ -429,12 +425,6 @@
 	XrefCcFiles() android.Paths
 }
 
-type ToolDependencyTag struct {
-	blueprint.BaseDependencyTag
-
-	Name string
-}
-
 var (
 	dataLibDepTag         = DependencyTag{Name: "data_lib", Library: true, Shared: true}
 	sharedExportDepTag    = DependencyTag{Name: "shared", Library: true, Shared: true, ReexportFlags: true}
@@ -1704,7 +1694,6 @@
 	deps.LateSharedLibs = android.LastUniqueStrings(deps.LateSharedLibs)
 	deps.HeaderLibs = android.LastUniqueStrings(deps.HeaderLibs)
 	deps.RuntimeLibs = android.LastUniqueStrings(deps.RuntimeLibs)
-	deps.Tools = android.LastUniqueStrings(deps.Tools)
 
 	for _, lib := range deps.ReexportSharedLibHeaders {
 		if !inList(lib, deps.SharedLibs) {
@@ -2048,11 +2037,6 @@
 			}, vndkExtDepTag, vndkdep.getVndkExtendsModuleName())
 		}
 	}
-
-	for _, tool := range deps.Tools {
-		actx.AddFarVariationDependencies(ctx.Config().BuildOSTarget.Variations(),
-			ToolDependencyTag{Name: tool}, tool)
-	}
 }
 
 func BeginMutator(ctx android.BottomUpMutatorContext) {
@@ -2248,21 +2232,6 @@
 		depName := ctx.OtherModuleName(dep)
 		depTag := ctx.OtherModuleDependencyTag(dep)
 
-		if toolDep, ok := depTag.(ToolDependencyTag); ok {
-			if toolMod, ok := dep.(android.HostToolProvider); ok {
-				if depPaths.Tools == nil {
-					depPaths.Tools = make(map[string]android.Path)
-				}
-				toolPath := toolMod.HostToolPath()
-				if !toolPath.Valid() {
-					ctx.ModuleErrorf("Failed to find path for host tool %q", toolDep.Name)
-				}
-				depPaths.Tools[toolDep.Name] = toolPath.Path()
-			} else {
-				ctx.ModuleErrorf("Found module, but not host tool for %q", toolDep.Name)
-			}
-		}
-
 		ccDep, ok := dep.(LinkableInterface)
 		if !ok {
 
diff --git a/cc/compiler.go b/cc/compiler.go
index ba14dd5..d5ea2c3 100644
--- a/cc/compiler.go
+++ b/cc/compiler.go
@@ -251,14 +251,6 @@
 		deps.StaticLibs = append(deps.StaticLibs, "libomp")
 	}
 
-	if compiler.hasSrcExt(".y") || compiler.hasSrcExt(".yy") {
-		deps.Tools = append(deps.Tools, "bison", "m4")
-	}
-
-	if compiler.hasSrcExt(".l") || compiler.hasSrcExt(".ll") {
-		deps.Tools = append(deps.Tools, "flex", "m4")
-	}
-
 	return deps
 }
 
@@ -589,7 +581,7 @@
 
 	srcs := append(android.Paths(nil), compiler.srcsBeforeGen...)
 
-	srcs, genDeps := genSources(ctx, srcs, buildFlags, deps.Tools)
+	srcs, genDeps := genSources(ctx, srcs, buildFlags)
 	pathDeps = append(pathDeps, genDeps...)
 
 	compiler.pathDeps = pathDeps
diff --git a/cc/gen.go b/cc/gen.go
index 6f9036b..b0aadc6 100644
--- a/cc/gen.go
+++ b/cc/gen.go
@@ -24,6 +24,7 @@
 )
 
 func init() {
+	pctx.SourcePathVariable("lexCmd", "prebuilts/build-tools/${config.HostPrebuiltTag}/bin/flex")
 	pctx.SourcePathVariable("m4Cmd", "prebuilts/build-tools/${config.HostPrebuiltTag}/bin/m4")
 
 	pctx.HostBinToolVariable("aidlCmd", "aidl-cpp")
@@ -31,6 +32,12 @@
 }
 
 var (
+	lex = pctx.AndroidStaticRule("lex",
+		blueprint.RuleParams{
+			Command:     "M4=$m4Cmd $lexCmd -o$out $in",
+			CommandDeps: []string{"$lexCmd", "$m4Cmd"},
+		})
+
 	sysprop = pctx.AndroidStaticRule("sysprop",
 		blueprint.RuleParams{
 			Command: "$syspropCmd --header-dir=$headerOutDir --public-header-dir=$publicOutDir " +
@@ -59,8 +66,7 @@
 }
 
 func genYacc(ctx android.ModuleContext, rule *android.RuleBuilder, yaccFile android.Path,
-	outFile android.ModuleGenPath, props *YaccProperties,
-	tools map[string]android.Path) (headerFiles android.Paths) {
+	outFile android.ModuleGenPath, props *YaccProperties) (headerFiles android.Paths) {
 
 	outDir := android.PathForModuleGen(ctx, "yacc")
 	headerFile := android.GenPathWithExt(ctx, "yacc", yaccFile, "h")
@@ -91,17 +97,9 @@
 		}
 	}
 
-	bison, ok := tools["bison"]
-	if !ok {
-		ctx.ModuleErrorf("Unable to find bison")
-	}
-	m4, ok := tools["m4"]
-	if !ok {
-		ctx.ModuleErrorf("Unable to find m4")
-	}
-
-	cmd.FlagWithInput("M4=", m4).
-		Tool(bison).
+	cmd.Text("BISON_PKGDATADIR=prebuilts/build-tools/common/bison").
+		FlagWithInput("M4=", ctx.Config().PrebuiltBuildTool(ctx, "m4")).
+		PrebuiltBuildTool(ctx, "bison").
 		Flag("-d").
 		Flags(flags).
 		FlagWithOutput("--defines=", headerFile).
@@ -155,23 +153,13 @@
 	}
 }
 
-func genLex(ctx android.ModuleContext, rule *android.RuleBuilder, lexFile android.Path,
-	outFile android.ModuleGenPath, tools map[string]android.Path) {
-
-	flex, ok := tools["flex"]
-	if !ok {
-		ctx.ModuleErrorf("Unable to find flex")
-	}
-	m4, ok := tools["m4"]
-	if !ok {
-		ctx.ModuleErrorf("Unable to find m4")
-	}
-
-	rule.Command().
-		FlagWithInput("M4=", m4).
-		Tool(flex).
-		FlagWithOutput("-o", outFile).
-		Input(lexFile)
+func genLex(ctx android.ModuleContext, lexFile android.Path, outFile android.ModuleGenPath) {
+	ctx.Build(pctx, android.BuildParams{
+		Rule:        lex,
+		Description: "lex " + lexFile.Rel(),
+		Output:      outFile,
+		Input:       lexFile,
+	})
 }
 
 func genSysprop(ctx android.ModuleContext, syspropFile android.Path) (android.Path, android.Paths) {
@@ -218,22 +206,14 @@
 	return rcFile, headerFile
 }
 
-func genSources(ctx android.ModuleContext, srcFiles android.Paths, buildFlags builderFlags,
-	tools map[string]android.Path) (android.Paths, android.Paths) {
+func genSources(ctx android.ModuleContext, srcFiles android.Paths,
+	buildFlags builderFlags) (android.Paths, android.Paths) {
 
 	var deps android.Paths
 	var rsFiles android.Paths
 
 	var aidlRule *android.RuleBuilder
 
-	var lexRule_ *android.RuleBuilder
-	lexRule := func() *android.RuleBuilder {
-		if lexRule_ == nil {
-			lexRule_ = android.NewRuleBuilder().Sbox(android.PathForModuleGen(ctx, "lex"))
-		}
-		return lexRule_
-	}
-
 	var yaccRule_ *android.RuleBuilder
 	yaccRule := func() *android.RuleBuilder {
 		if yaccRule_ == nil {
@@ -247,19 +227,19 @@
 		case ".y":
 			cFile := android.GenPathWithExt(ctx, "yacc", srcFile, "c")
 			srcFiles[i] = cFile
-			deps = append(deps, genYacc(ctx, yaccRule(), srcFile, cFile, buildFlags.yacc, tools)...)
+			deps = append(deps, genYacc(ctx, yaccRule(), srcFile, cFile, buildFlags.yacc)...)
 		case ".yy":
 			cppFile := android.GenPathWithExt(ctx, "yacc", srcFile, "cpp")
 			srcFiles[i] = cppFile
-			deps = append(deps, genYacc(ctx, yaccRule(), srcFile, cppFile, buildFlags.yacc, tools)...)
+			deps = append(deps, genYacc(ctx, yaccRule(), srcFile, cppFile, buildFlags.yacc)...)
 		case ".l":
 			cFile := android.GenPathWithExt(ctx, "lex", srcFile, "c")
 			srcFiles[i] = cFile
-			genLex(ctx, lexRule(), srcFile, cFile, tools)
+			genLex(ctx, srcFile, cFile)
 		case ".ll":
 			cppFile := android.GenPathWithExt(ctx, "lex", srcFile, "cpp")
 			srcFiles[i] = cppFile
-			genLex(ctx, lexRule(), srcFile, cppFile, tools)
+			genLex(ctx, srcFile, cppFile)
 		case ".proto":
 			ccFile, headerFile := genProto(ctx, srcFile, buildFlags)
 			srcFiles[i] = ccFile
@@ -291,10 +271,6 @@
 		aidlRule.Build(pctx, ctx, "aidl", "gen aidl")
 	}
 
-	if lexRule_ != nil {
-		lexRule_.Build(pctx, ctx, "lex", "gen lex")
-	}
-
 	if yaccRule_ != nil {
 		yaccRule_.Build(pctx, ctx, "yacc", "gen yacc")
 	}
diff --git a/cc/vndk.go b/cc/vndk.go
index 4adf9d2..15843c6 100644
--- a/cc/vndk.go
+++ b/cc/vndk.go
@@ -559,10 +559,6 @@
 		return
 	}
 
-	if ctx.DeviceConfig().BoardVndkRuntimeDisable() {
-		return
-	}
-
 	var snapshotOutputs android.Paths
 
 	/*
diff --git a/rust/binary.go b/rust/binary.go
index 48f51db..1e9e119 100644
--- a/rust/binary.go
+++ b/rust/binary.go
@@ -106,8 +106,7 @@
 func (binary *binaryDecorator) compile(ctx ModuleContext, flags Flags, deps PathDeps) android.Path {
 	fileName := binary.getStem(ctx) + ctx.toolchain().ExecutableSuffix()
 
-	srcPath, paths := srcPathFromModuleSrcs(ctx, binary.baseCompiler.Properties.Srcs)
-	deps.SrcDeps = append(deps.SrcDeps, paths...)
+	srcPath, _ := srcPathFromModuleSrcs(ctx, binary.baseCompiler.Properties.Srcs)
 
 	outputFile := android.PathForModuleOut(ctx, fileName)
 	binary.unstrippedOutputFile = outputFile
diff --git a/rust/bindgen.go b/rust/bindgen.go
index 132b1fd..83ad560 100644
--- a/rust/bindgen.go
+++ b/rust/bindgen.go
@@ -49,6 +49,7 @@
 
 func init() {
 	android.RegisterModuleType("rust_bindgen", RustBindgenFactory)
+	android.RegisterModuleType("rust_bindgen_host", RustBindgenHostFactory)
 }
 
 var _ SourceProvider = (*bindgenDecorator)(nil)
@@ -156,6 +157,11 @@
 	return module.Init()
 }
 
+func RustBindgenHostFactory() android.Module {
+	module, _ := NewRustBindgen(android.HostSupported)
+	return module.Init()
+}
+
 func NewRustBindgen(hod android.HostOrDeviceSupported) (*Module, *bindgenDecorator) {
 	module := newModule(hod, android.MultilibBoth)
 
diff --git a/rust/library.go b/rust/library.go
index acca256..ac725d7 100644
--- a/rust/library.go
+++ b/rust/library.go
@@ -368,8 +368,7 @@
 func (library *libraryDecorator) compile(ctx ModuleContext, flags Flags, deps PathDeps) android.Path {
 	var outputFile android.WritablePath
 
-	srcPath, paths := srcPathFromModuleSrcs(ctx, library.baseCompiler.Properties.Srcs)
-	deps.SrcDeps = append(deps.SrcDeps, paths...)
+	srcPath, _ := srcPathFromModuleSrcs(ctx, library.baseCompiler.Properties.Srcs)
 
 	flags.RustFlags = append(flags.RustFlags, deps.depFlags...)
 
diff --git a/rust/proc_macro.go b/rust/proc_macro.go
index 2752dc3..3dd2521 100644
--- a/rust/proc_macro.go
+++ b/rust/proc_macro.go
@@ -65,8 +65,7 @@
 	fileName := procMacro.getStem(ctx) + ctx.toolchain().ProcMacroSuffix()
 	outputFile := android.PathForModuleOut(ctx, fileName)
 
-	srcPath, paths := srcPathFromModuleSrcs(ctx, procMacro.baseCompiler.Properties.Srcs)
-	deps.SrcDeps = append(deps.SrcDeps, paths...)
+	srcPath, _ := srcPathFromModuleSrcs(ctx, procMacro.baseCompiler.Properties.Srcs)
 
 	procMacro.unstrippedOutputFile = outputFile
 
diff --git a/rust/rust.go b/rust/rust.go
index 28f8e1a..89b89e2 100644
--- a/rust/rust.go
+++ b/rust/rust.go
@@ -743,6 +743,8 @@
 	directProcMacroDeps := []*Module{}
 	directSharedLibDeps := [](cc.LinkableInterface){}
 	directStaticLibDeps := [](cc.LinkableInterface){}
+	directSrcProvidersDeps := []*Module{}
+	directSrcDeps := [](android.SourceFileProducer){}
 
 	ctx.VisitDirectDeps(func(dep android.Module) {
 		depName := ctx.OtherModuleName(dep)
@@ -776,6 +778,24 @@
 			case procMacroDepTag:
 				directProcMacroDeps = append(directProcMacroDeps, rustDep)
 				mod.Properties.AndroidMkProcMacroLibs = append(mod.Properties.AndroidMkProcMacroLibs, depName)
+			case android.SourceDepTag:
+				// Since these deps are added in path_properties.go via AddDependencies, we need to ensure the correct
+				// OS/Arch variant is used.
+				var helper string
+				if ctx.Host() {
+					helper = "missing 'host_supported'?"
+				} else {
+					helper = "device module defined?"
+				}
+
+				if dep.Target().Os != ctx.Os() {
+					ctx.ModuleErrorf("OS mismatch on dependency %q (%s)", dep.Name(), helper)
+					return
+				} else if dep.Target().Arch.ArchType != ctx.Arch().ArchType {
+					ctx.ModuleErrorf("Arch mismatch on dependency %q (%s)", dep.Name(), helper)
+					return
+				}
+				directSrcProvidersDeps = append(directSrcProvidersDeps, rustDep)
 			}
 
 			//Append the dependencies exportedDirs
@@ -793,6 +813,14 @@
 
 		}
 
+		if srcDep, ok := dep.(android.SourceFileProducer); ok {
+			switch depTag {
+			case android.SourceDepTag:
+				// These are usually genrules which don't have per-target variants.
+				directSrcDeps = append(directSrcDeps, srcDep)
+			}
+		}
+
 		if ccDep, ok := dep.(cc.LinkableInterface); ok {
 			//Handle C dependencies
 			if _, ok := ccDep.(*Module); !ok {
@@ -868,11 +896,22 @@
 		sharedLibDepFiles = append(sharedLibDepFiles, dep.OutputFile().Path())
 	}
 
+	var srcProviderDepFiles android.Paths
+	for _, dep := range directSrcProvidersDeps {
+		srcs, _ := dep.OutputFiles("")
+		srcProviderDepFiles = append(srcProviderDepFiles, srcs...)
+	}
+	for _, dep := range directSrcDeps {
+		srcs := dep.Srcs()
+		srcProviderDepFiles = append(srcProviderDepFiles, srcs...)
+	}
+
 	depPaths.RLibs = append(depPaths.RLibs, rlibDepFiles...)
 	depPaths.DyLibs = append(depPaths.DyLibs, dylibDepFiles...)
 	depPaths.SharedLibs = append(depPaths.SharedLibs, sharedLibDepFiles...)
 	depPaths.StaticLibs = append(depPaths.StaticLibs, staticLibDepFiles...)
 	depPaths.ProcMacros = append(depPaths.ProcMacros, procMacroDepFiles...)
+	depPaths.SrcDeps = append(depPaths.SrcDeps, srcProviderDepFiles...)
 
 	// Dedup exported flags from dependencies
 	depPaths.linkDirs = android.FirstUniqueStrings(depPaths.linkDirs)
diff --git a/rust/rust_test.go b/rust/rust_test.go
index 89dfb67..b3bbddb 100644
--- a/rust/rust_test.go
+++ b/rust/rust_test.go
@@ -291,6 +291,26 @@
 	}
 }
 
+func TestSourceProviderTargetMismatch(t *testing.T) {
+	// This might error while building the dependency tree or when calling depsToPaths() depending on the lunched
+	// target, which results in two different errors. So don't check the error, just confirm there is one.
+	testRustError(t, ".*", `
+		rust_proc_macro {
+			name: "libprocmacro",
+			srcs: [
+				"foo.rs",
+				":libbindings",
+			],
+			crate_name: "procmacro",
+		}
+		rust_bindgen {
+			name: "libbindings",
+			stem: "bindings",
+			wrapper_src: "src/any.h",
+		}
+	`)
+}
+
 // Test to make sure proc_macros use host variants when building device modules.
 func TestProcMacroDeviceDeps(t *testing.T) {
 	ctx := testRust(t, `