Merge "Use monotonic clock instead of wall time clock for metrics."
diff --git a/android/prebuilt.go b/android/prebuilt.go
index 9f4df28..269ad5d 100644
--- a/android/prebuilt.go
+++ b/android/prebuilt.go
@@ -225,7 +225,7 @@
 // PrebuiltSourceDepsMutator adds dependencies to the prebuilt module from the
 // corresponding source module, if one exists for the same variant.
 func PrebuiltSourceDepsMutator(ctx BottomUpMutatorContext) {
-	if m, ok := ctx.Module().(PrebuiltInterface); ok && m.Prebuilt() != nil {
+	if m, ok := ctx.Module().(PrebuiltInterface); ok && m.Enabled() && m.Prebuilt() != nil {
 		p := m.Prebuilt()
 		if !p.properties.PrebuiltRenamedToSource {
 			name := m.base().BaseModuleName()
diff --git a/android/prebuilt_test.go b/android/prebuilt_test.go
index 8029b85..6c3cd9e 100644
--- a/android/prebuilt_test.go
+++ b/android/prebuilt_test.go
@@ -22,9 +22,10 @@
 )
 
 var prebuiltsTests = []struct {
-	name     string
-	modules  string
-	prebuilt []OsClass
+	name      string
+	replaceBp bool // modules is added to default bp boilerplate if false.
+	modules   string
+	prebuilt  []OsType
 }{
 	{
 		name: "no prebuilt",
@@ -42,7 +43,7 @@
 				prefer: false,
 				srcs: ["prebuilt_file"],
 			}`,
-		prebuilt: []OsClass{Device, Host},
+		prebuilt: []OsType{Android, BuildOs},
 	},
 	{
 		name: "no source prebuilt preferred",
@@ -52,7 +53,7 @@
 				prefer: true,
 				srcs: ["prebuilt_file"],
 			}`,
-		prebuilt: []OsClass{Device, Host},
+		prebuilt: []OsType{Android, BuildOs},
 	},
 	{
 		name: "prebuilt not preferred",
@@ -80,7 +81,7 @@
 				prefer: true,
 				srcs: ["prebuilt_file"],
 			}`,
-		prebuilt: []OsClass{Device, Host},
+		prebuilt: []OsType{Android, BuildOs},
 	},
 	{
 		name: "prebuilt no file not preferred",
@@ -120,7 +121,7 @@
 				prefer: true,
 				srcs: [":fg"],
 			}`,
-		prebuilt: []OsClass{Device, Host},
+		prebuilt: []OsType{Android, BuildOs},
 	},
 	{
 		name: "prebuilt module for device only",
@@ -135,7 +136,7 @@
 				prefer: true,
 				srcs: ["prebuilt_file"],
 			}`,
-		prebuilt: []OsClass{Device},
+		prebuilt: []OsType{Android},
 	},
 	{
 		name: "prebuilt file for host only",
@@ -153,7 +154,7 @@
 					},
 				},
 			}`,
-		prebuilt: []OsClass{Host},
+		prebuilt: []OsType{BuildOs},
 	},
 	{
 		name: "prebuilt override not preferred",
@@ -191,7 +192,72 @@
 				prefer: true,
 				srcs: ["prebuilt_file"],
 			}`,
-		prebuilt: []OsClass{Device, Host},
+		prebuilt: []OsType{Android, BuildOs},
+	},
+	{
+		name:      "prebuilt including default-disabled OS",
+		replaceBp: true,
+		modules: `
+			source {
+				name: "foo",
+				deps: [":bar"],
+				target: {
+					windows: {
+						enabled: true,
+					},
+				},
+			}
+
+			source {
+				name: "bar",
+				target: {
+					windows: {
+						enabled: true,
+					},
+				},
+			}
+
+			prebuilt {
+				name: "bar",
+				prefer: true,
+				srcs: ["prebuilt_file"],
+				target: {
+					windows: {
+						enabled: true,
+					},
+				},
+			}`,
+		prebuilt: []OsType{Android, BuildOs, Windows},
+	},
+	{
+		name:      "fall back to source for default-disabled OS",
+		replaceBp: true,
+		modules: `
+			source {
+				name: "foo",
+				deps: [":bar"],
+				target: {
+					windows: {
+						enabled: true,
+					},
+				},
+			}
+
+			source {
+				name: "bar",
+				target: {
+					windows: {
+						enabled: true,
+					},
+				},
+			}
+
+			prebuilt {
+				name: "bar",
+				prefer: true,
+				srcs: ["prebuilt_file"],
+			}`,
+		prebuilt: []OsType{Android, BuildOs},
 	},
 }
 
@@ -203,14 +269,25 @@
 
 	for _, test := range prebuiltsTests {
 		t.Run(test.name, func(t *testing.T) {
-			bp := `
-				source {
-					name: "foo",
-					deps: [":bar"],
-				}
-				` + test.modules
+			bp := test.modules
+			if !test.replaceBp {
+				bp = bp + `
+					source {
+						name: "foo",
+						deps: [":bar"],
+					}`
+			}
 			config := TestArchConfig(buildDir, nil, bp, fs)
 
+			// Add windows to the target list to test the logic when a variant is
+			// disabled by default.
+			if !Windows.DefaultDisabled {
+				t.Errorf("windows is assumed to be disabled by default")
+			}
+			config.config.Targets[Windows] = []Target{
+				{Windows, Arch{ArchType: X86_64}, NativeBridgeDisabled, "", ""},
+			}
+
 			ctx := NewTestArchContext()
 			registerTestPrebuiltBuildComponents(ctx)
 			ctx.RegisterModuleType("filegroup", FileGroupFactory)
@@ -223,7 +300,7 @@
 
 			for _, variant := range ctx.ModuleVariantsForTests("foo") {
 				foo := ctx.ModuleForTests("foo", variant)
-				t.Run(foo.Module().Target().Os.Class.String(), func(t *testing.T) {
+				t.Run(foo.Module().Target().Os.String(), func(t *testing.T) {
 					var dependsOnSourceModule, dependsOnPrebuiltModule bool
 					ctx.VisitDirectDeps(foo.Module(), func(m blueprint.Module) {
 						if _, ok := m.(*sourceModule); ok {
@@ -237,26 +314,38 @@
 						}
 					})
 
+					moduleIsDisabled := !foo.Module().Enabled()
 					deps := foo.Module().(*sourceModule).deps
-					if deps == nil || len(deps) != 1 {
-						t.Errorf("deps does not have single path, but is %v", deps)
+					if moduleIsDisabled {
+						if len(deps) > 0 {
+							t.Errorf("disabled module got deps: %v", deps)
+						}
+					} else {
+						if len(deps) != 1 {
+							t.Errorf("deps does not have single path, but is %v", deps)
+						}
 					}
+
 					var usingSourceFile, usingPrebuiltFile bool
-					if deps[0].String() == "source_file" {
+					if len(deps) > 0 && deps[0].String() == "source_file" {
 						usingSourceFile = true
 					}
-					if deps[0].String() == "prebuilt_file" {
+					if len(deps) > 0 && deps[0].String() == "prebuilt_file" {
 						usingPrebuiltFile = true
 					}
 
 					prebuilt := false
 					for _, os := range test.prebuilt {
-						if os == foo.Module().Target().Os.Class {
+						if os == foo.Module().Target().Os {
 							prebuilt = true
 						}
 					}
 
 					if prebuilt {
+						if moduleIsDisabled {
+							t.Errorf("dependent module for prebuilt is disabled")
+						}
+
 						if !dependsOnPrebuiltModule {
 							t.Errorf("doesn't depend on prebuilt module")
 						}
@@ -270,7 +359,7 @@
 						if usingSourceFile {
 							t.Errorf("using source_file")
 						}
-					} else {
+					} else if !moduleIsDisabled {
 						if dependsOnPrebuiltModule {
 							t.Errorf("depends on prebuilt module")
 						}
diff --git a/java/droiddoc.go b/java/droiddoc.go
index 99bfb6d..08865b6 100644
--- a/java/droiddoc.go
+++ b/java/droiddoc.go
@@ -112,13 +112,20 @@
 	// local files that are used within user customized droiddoc options.
 	Arg_files []string `android:"path"`
 
-	// user customized droiddoc args.
+	// user customized droiddoc args. Deprecated, use flags instead.
 	// Available variables for substitution:
 	//
 	//  $(location <label>): the path to the arg_files with name <label>
 	//  $$: a literal $
 	Args *string
 
+	// user customized droiddoc args. Not compatible with property args.
+	// Available variables for substitution:
+	//
+	//  $(location <label>): the path to the arg_files with name <label>
+	//  $$: a literal $
+	Flags []string
+
 	// names of the output files used in args that will be generated
 	Out []string
 
@@ -382,7 +389,7 @@
 	argFiles    android.Paths
 	implicits   android.Paths
 
-	args string
+	args []string
 
 	docZip      android.WritablePath
 	stubsSrcJar android.WritablePath
@@ -619,8 +626,8 @@
 	}
 	srcFiles = filterHtml(srcFiles)
 
-	flags := j.collectAidlFlags(ctx, deps)
-	srcFiles = j.genSources(ctx, srcFiles, flags)
+	aidlFlags := j.collectAidlFlags(ctx, deps)
+	srcFiles = j.genSources(ctx, srcFiles, aidlFlags)
 
 	// srcs may depend on some genrule output.
 	j.srcJars = srcFiles.FilterByExt(".srcjar")
@@ -649,24 +656,38 @@
 		}
 	}
 
-	var err error
-	j.args, err = android.Expand(String(j.properties.Args), func(name string) (string, error) {
-		if strings.HasPrefix(name, "location ") {
-			label := strings.TrimSpace(strings.TrimPrefix(name, "location "))
-			if paths, ok := argFilesMap[label]; ok {
-				return paths, nil
-			} else {
-				return "", fmt.Errorf("unknown location label %q, expecting one of %q",
-					label, strings.Join(argFileLabels, ", "))
-			}
-		} else if name == "genDir" {
-			return android.PathForModuleGen(ctx).String(), nil
-		}
-		return "", fmt.Errorf("unknown variable '$(%s)'", name)
-	})
+	var argsPropertyName string
+	flags := make([]string, 0)
+	if j.properties.Args != nil && j.properties.Flags != nil {
+		ctx.PropertyErrorf("args", "flags is set. Cannot set args")
+	} else if args := proptools.String(j.properties.Args); args != "" {
+		flags = append(flags, args)
+		argsPropertyName = "args"
+	} else {
+		flags = append(flags, j.properties.Flags...)
+		argsPropertyName = "flags"
+	}
 
-	if err != nil {
-		ctx.PropertyErrorf("args", "%s", err.Error())
+	for _, flag := range flags {
+		args, err := android.Expand(flag, func(name string) (string, error) {
+			if strings.HasPrefix(name, "location ") {
+				label := strings.TrimSpace(strings.TrimPrefix(name, "location "))
+				if paths, ok := argFilesMap[label]; ok {
+					return paths, nil
+				} else {
+					return "", fmt.Errorf("unknown location label %q, expecting one of %q",
+						label, strings.Join(argFileLabels, ", "))
+				}
+			} else if name == "genDir" {
+				return android.PathForModuleGen(ctx).String(), nil
+			}
+			return "", fmt.Errorf("unknown variable '$(%s)'", name)
+		})
+
+		if err != nil {
+			ctx.PropertyErrorf(argsPropertyName, "%s", err.Error())
+		}
+		j.args = append(j.args, args)
 	}
 
 	return deps
@@ -1010,7 +1031,7 @@
 
 	d.stubsFlags(ctx, cmd, stubsDir)
 
-	cmd.Flag(d.Javadoc.args).Implicits(d.Javadoc.argFiles)
+	cmd.Flag(strings.Join(d.Javadoc.args, " ")).Implicits(d.Javadoc.argFiles)
 
 	if d.properties.Compat_config != nil {
 		compatConfig := android.PathForModuleSrc(ctx, String(d.properties.Compat_config))
@@ -1327,7 +1348,7 @@
 		cmd.Flag("--include-annotations")
 
 		validatingNullability :=
-			strings.Contains(d.Javadoc.args, "--validate-nullability-from-merged-stubs") ||
+			android.InList("--validate-nullability-from-merged-stubs", d.Javadoc.args) ||
 				String(d.properties.Validate_nullability_from_list) != ""
 
 		migratingNullability := String(d.properties.Previous_api) != ""
@@ -1539,14 +1560,14 @@
 	d.apiLevelsAnnotationsFlags(ctx, cmd)
 	d.apiToXmlFlags(ctx, cmd)
 
-	if strings.Contains(d.Javadoc.args, "--generate-documentation") {
+	if android.InList("--generate-documentation", d.Javadoc.args) {
 		// Currently Metalava have the ability to invoke Javadoc in a seperate process.
 		// Pass "-nodocs" to suppress the Javadoc invocation when Metalava receives
 		// "--generate-documentation" arg. This is not needed when Metalava removes this feature.
-		d.Javadoc.args = d.Javadoc.args + " -nodocs "
+		d.Javadoc.args = append(d.Javadoc.args, "-nodocs")
 	}
 
-	cmd.Flag(d.Javadoc.args).Implicits(d.Javadoc.argFiles)
+	cmd.Flag(strings.Join(d.Javadoc.args, " ")).Implicits(d.Javadoc.argFiles)
 	for _, o := range d.Javadoc.properties.Out {
 		cmd.ImplicitOutput(android.PathForModuleGen(ctx, o))
 	}
diff --git a/java/java_test.go b/java/java_test.go
index fb00361..db3f187 100644
--- a/java/java_test.go
+++ b/java/java_test.go
@@ -1097,7 +1097,7 @@
 		    ],
 		    proofread_file: "libcore-proofread.txt",
 		    todo_file: "libcore-docs-todo.html",
-		    args: "-offlinemode -title \"libcore\"",
+		    flags: ["-offlinemode -title \"libcore\""],
 		}
 		`,
 		map[string][]byte{
@@ -1124,6 +1124,42 @@
 	}
 }
 
+func TestDroiddocArgsAndFlagsCausesError(t *testing.T) {
+	testJavaError(t, "flags is set. Cannot set args", `
+		droiddoc_exported_dir {
+		    name: "droiddoc-templates-sdk",
+		    path: ".",
+		}
+		filegroup {
+		    name: "bar-doc-aidl-srcs",
+		    srcs: ["bar-doc/IBar.aidl"],
+		    path: "bar-doc",
+		}
+		droiddoc {
+		    name: "bar-doc",
+		    srcs: [
+		        "bar-doc/a.java",
+		        "bar-doc/IFoo.aidl",
+		        ":bar-doc-aidl-srcs",
+		    ],
+		    exclude_srcs: [
+		        "bar-doc/b.java"
+		    ],
+		    custom_template: "droiddoc-templates-sdk",
+		    hdf: [
+		        "android.whichdoc offline",
+		    ],
+		    knowntags: [
+		        "bar-doc/known_oj_tags.txt",
+		    ],
+		    proofread_file: "libcore-proofread.txt",
+		    todo_file: "libcore-docs-todo.html",
+		    flags: ["-offlinemode -title \"libcore\""],
+		    args: "-offlinemode -title \"libcore\"",
+		}
+		`)
+}
+
 func TestDroidstubsWithSystemModules(t *testing.T) {
 	ctx, _ := testJava(t, `
 		droidstubs {
diff --git a/java/lint.go b/java/lint.go
index b73d6a5..6fbef18 100644
--- a/java/lint.go
+++ b/java/lint.go
@@ -220,12 +220,21 @@
 	rule.Command().Text("rm -rf").Flag(cacheDir.String()).Flag(homeDir.String())
 	rule.Command().Text("mkdir -p").Flag(cacheDir.String()).Flag(homeDir.String())
 
+	var annotationsZipPath, apiVersionsXMLPath android.Path
+	if ctx.Config().UnbundledBuildUsePrebuiltSdks() {
+		annotationsZipPath = android.PathForSource(ctx, "prebuilts/sdk/current/public/data/annotations.zip")
+		apiVersionsXMLPath = android.PathForSource(ctx, "prebuilts/sdk/current/public/data/api-versions.xml")
+	} else {
+		annotationsZipPath = copiedAnnotationsZipPath(ctx)
+		apiVersionsXMLPath = copiedAPIVersionsXmlPath(ctx)
+	}
+
 	rule.Command().
 		Text("(").
 		Flag("JAVA_OPTS=-Xmx2048m").
 		FlagWithArg("ANDROID_SDK_HOME=", homeDir.String()).
-		FlagWithInput("SDK_ANNOTATIONS=", annotationsZipPath(ctx)).
-		FlagWithInput("LINT_OPTS=-DLINT_API_DATABASE=", apiVersionsXmlPath(ctx)).
+		FlagWithInput("SDK_ANNOTATIONS=", annotationsZipPath).
+		FlagWithInput("LINT_OPTS=-DLINT_API_DATABASE=", apiVersionsXMLPath).
 		Tool(android.PathForSource(ctx, "prebuilts/cmdline-tools/tools/bin/lint")).
 		Implicit(android.PathForSource(ctx, "prebuilts/cmdline-tools/tools/lib/lint-classpath.jar")).
 		Flag("--quiet").
@@ -271,7 +280,7 @@
 }
 
 func (l *lintSingleton) copyLintDependencies(ctx android.SingletonContext) {
-	if ctx.Config().UnbundledBuild() {
+	if ctx.Config().UnbundledBuildUsePrebuiltSdks() {
 		return
 	}
 
@@ -297,25 +306,29 @@
 	ctx.Build(pctx, android.BuildParams{
 		Rule:   android.Cp,
 		Input:  android.OutputFileForModule(ctx, frameworkDocStubs, ".annotations.zip"),
-		Output: annotationsZipPath(ctx),
+		Output: copiedAnnotationsZipPath(ctx),
 	})
 
 	ctx.Build(pctx, android.BuildParams{
 		Rule:   android.Cp,
 		Input:  android.OutputFileForModule(ctx, frameworkDocStubs, ".api_versions.xml"),
-		Output: apiVersionsXmlPath(ctx),
+		Output: copiedAPIVersionsXmlPath(ctx),
 	})
 }
 
-func annotationsZipPath(ctx android.PathContext) android.WritablePath {
+func copiedAnnotationsZipPath(ctx android.PathContext) android.WritablePath {
 	return android.PathForOutput(ctx, "lint", "annotations.zip")
 }
 
-func apiVersionsXmlPath(ctx android.PathContext) android.WritablePath {
+func copiedAPIVersionsXmlPath(ctx android.PathContext) android.WritablePath {
 	return android.PathForOutput(ctx, "lint", "api_versions.xml")
 }
 
 func (l *lintSingleton) generateLintReportZips(ctx android.SingletonContext) {
+	if ctx.Config().UnbundledBuild() {
+		return
+	}
+
 	var outputs []*lintOutputs
 	var dirs []string
 	ctx.VisitAllModules(func(m android.Module) {
@@ -370,7 +383,9 @@
 }
 
 func (l *lintSingleton) MakeVars(ctx android.MakeVarsContext) {
-	ctx.DistForGoal("lint-check", l.htmlZip, l.textZip, l.xmlZip)
+	if !ctx.Config().UnbundledBuild() {
+		ctx.DistForGoal("lint-check", l.htmlZip, l.textZip, l.xmlZip)
+	}
 }
 
 var _ android.SingletonMakeVarsProvider = (*lintSingleton)(nil)