Merge "Consider only preferred modules for jdeps"
diff --git a/apex/apex.go b/apex/apex.go
index b9a3c8f..e99823b 100644
--- a/apex/apex.go
+++ b/apex/apex.go
@@ -1905,9 +1905,15 @@
 		return
 	}
 	a.installDir = android.PathForModuleInstall(ctx, "apex")
-	a.outputApexFile = android.PathForBazelOut(ctx, outputs.SignedOutput)
-	a.outputFile = a.outputApexFile
+
+	// Set the output file to .apex or .capex depending on the compression configuration.
 	a.setCompression(ctx)
+	if a.isCompressed {
+		a.outputApexFile = android.PathForBazelOut(ctx, outputs.SignedCompressedOutput)
+	} else {
+		a.outputApexFile = android.PathForBazelOut(ctx, outputs.SignedOutput)
+	}
+	a.outputFile = a.outputApexFile
 
 	// TODO(b/257829940): These are used by the apex_keys_text singleton; would probably be a clearer
 	// interface if these were set in a provider rather than the module itself
diff --git a/apex/bp2build_test.go b/apex/bp2build_test.go
index 58f30bd..01afa52 100644
--- a/apex/bp2build_test.go
+++ b/apex/bp2build_test.go
@@ -42,15 +42,16 @@
 				OutputBaseDir: outputBaseDir,
 				LabelToApexInfo: map[string]cquery.ApexInfo{
 					"//:foo": cquery.ApexInfo{
-						SignedOutput:          "signed_out.apex",
-						UnsignedOutput:        "unsigned_out.apex",
-						BundleKeyInfo:         []string{"public_key", "private_key"},
-						ContainerKeyInfo:      []string{"container_cert", "container_private"},
-						SymbolsUsedByApex:     "foo_using.txt",
-						JavaSymbolsUsedByApex: "foo_using.xml",
-						BundleFile:            "apex_bundle.zip",
-						InstalledFiles:        "installed-files.txt",
-						RequiresLibs:          []string{"//path/c:c", "//path/d:d"},
+						SignedOutput:           "signed_out.apex",
+						SignedCompressedOutput: "signed_out.capex",
+						UnsignedOutput:         "unsigned_out.apex",
+						BundleKeyInfo:          []string{"public_key", "private_key"},
+						ContainerKeyInfo:       []string{"container_cert", "container_private"},
+						SymbolsUsedByApex:      "foo_using.txt",
+						JavaSymbolsUsedByApex:  "foo_using.xml",
+						BundleFile:             "apex_bundle.zip",
+						InstalledFiles:         "installed-files.txt",
+						RequiresLibs:           []string{"//path/c:c", "//path/d:d"},
 
 						// unused
 						PackageName:  "pkg_name",
@@ -115,6 +116,68 @@
 	}
 }
 
+func TestCompressedApexImageInMixedBuilds(t *testing.T) {
+	bp := `
+apex_key{
+	name: "foo_key",
+}
+apex {
+	name: "foo",
+	key: "foo_key",
+	updatable: true,
+	min_sdk_version: "31",
+	file_contexts: ":myapex-file_contexts",
+	bazel_module: { label: "//:foo" },
+	test_only_force_compression: true, // force compression
+}`
+
+	outputBaseDir := "out/bazel"
+	result := android.GroupFixturePreparers(
+		prepareForApexTest,
+		android.FixtureModifyConfig(func(config android.Config) {
+			config.BazelContext = android.MockBazelContext{
+				OutputBaseDir: outputBaseDir,
+				LabelToApexInfo: map[string]cquery.ApexInfo{
+					"//:foo": cquery.ApexInfo{
+						SignedOutput:           "signed_out.apex",
+						SignedCompressedOutput: "signed_out.capex",
+						BundleKeyInfo:          []string{"public_key", "private_key"},
+						ContainerKeyInfo:       []string{"container_cert", "container_private"},
+					},
+				},
+			}
+		}),
+	).RunTestWithBp(t, bp)
+
+	m := result.ModuleForTests("foo", "android_common_foo_image").Module()
+	ab, ok := m.(*apexBundle)
+	if !ok {
+		t.Fatalf("Expected module to be an apexBundle, was not")
+	}
+
+	if w, g := "out/bazel/execroot/__main__/signed_out.capex", ab.outputFile.String(); w != g {
+		t.Errorf("Expected output file to be compressed apex %q, got %q", w, g)
+	}
+
+	mkData := android.AndroidMkDataForTest(t, result.TestContext, m)
+	var builder strings.Builder
+	mkData.Custom(&builder, "foo", "BAZEL_TARGET_", "", mkData)
+
+	data := builder.String()
+
+	expectedAndroidMk := []string{
+		"LOCAL_PREBUILT_MODULE_FILE := out/bazel/execroot/__main__/signed_out.capex",
+
+		// Check that the source install file is the capex. The dest is not important.
+		"LOCAL_SOONG_INSTALL_PAIRS := out/bazel/execroot/__main__/signed_out.capex:",
+	}
+	for _, androidMk := range expectedAndroidMk {
+		if !strings.Contains(data, androidMk) {
+			t.Errorf("Expected %q in androidmk data, but did not find %q", androidMk, data)
+		}
+	}
+}
+
 func TestOverrideApexImageInMixedBuilds(t *testing.T) {
 	bp := `
 apex_key{
diff --git a/bazel/cquery/request_type.go b/bazel/cquery/request_type.go
index 7c9ae3b..81c60d9 100644
--- a/bazel/cquery/request_type.go
+++ b/bazel/cquery/request_type.go
@@ -232,8 +232,14 @@
   fail("%s did not provide ApexInfo" % id_string)
 bundle_key_info = info.bundle_key_info
 container_key_info = info.container_key_info
+
+signed_compressed_output = "" # no .capex if the apex is not compressible, cannot be None as it needs to be json encoded.
+if info.signed_compressed_output:
+    signed_compressed_output = info.signed_compressed_output.path
+
 return json_encode({
     "signed_output": info.signed_output.path,
+    "signed_compressed_output": signed_compressed_output,
     "unsigned_output": info.unsigned_output.path,
     "provides_native_libs": [str(lib) for lib in info.provides_native_libs],
     "requires_native_libs": [str(lib) for lib in info.requires_native_libs],
@@ -249,18 +255,19 @@
 }
 
 type ApexInfo struct {
-	SignedOutput          string   `json:"signed_output"`
-	UnsignedOutput        string   `json:"unsigned_output"`
-	ProvidesLibs          []string `json:"provides_native_libs"`
-	RequiresLibs          []string `json:"requires_native_libs"`
-	BundleKeyInfo         []string `json:"bundle_key_info"`
-	ContainerKeyInfo      []string `json:"container_key_info"`
-	PackageName           string   `json:"package_name"`
-	SymbolsUsedByApex     string   `json:"symbols_used_by_apex"`
-	JavaSymbolsUsedByApex string   `json:"java_symbols_used_by_apex"`
-	BackingLibs           string   `json:"backing_libs"`
-	BundleFile            string   `json:"bundle_file"`
-	InstalledFiles        string   `json:"installed_files"`
+	SignedOutput           string   `json:"signed_output"`
+	SignedCompressedOutput string   `json:"signed_compressed_output"`
+	UnsignedOutput         string   `json:"unsigned_output"`
+	ProvidesLibs           []string `json:"provides_native_libs"`
+	RequiresLibs           []string `json:"requires_native_libs"`
+	BundleKeyInfo          []string `json:"bundle_key_info"`
+	ContainerKeyInfo       []string `json:"container_key_info"`
+	PackageName            string   `json:"package_name"`
+	SymbolsUsedByApex      string   `json:"symbols_used_by_apex"`
+	JavaSymbolsUsedByApex  string   `json:"java_symbols_used_by_apex"`
+	BackingLibs            string   `json:"backing_libs"`
+	BundleFile             string   `json:"bundle_file"`
+	InstalledFiles         string   `json:"installed_files"`
 }
 
 // ParseResult returns a value obtained by parsing the result of the request's Starlark function.
diff --git a/tests/apex_cc_module_arch_variant_tests.sh b/tests/apex_cc_module_arch_variant_tests.sh
new file mode 100755
index 0000000..97e6576
--- /dev/null
+++ b/tests/apex_cc_module_arch_variant_tests.sh
@@ -0,0 +1,94 @@
+#!/bin/bash
+
+# Copyright (C) 2022 The Android Open Source Project
+#
+# 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.
+
+set -uo pipefail
+
+# Integration test for verifying arch variant cflags set on cc modules included
+# in Bazel-built apexes in the real source tree.
+
+if [ ! -e "build/make/core/Makefile" ]; then
+  echo "$0 must be run from the top of the Android source tree."
+  exit 1
+fi
+
+############
+# Test Setup
+############
+
+OUTPUT_DIR="$(mktemp -d tmp.XXXXXX)"
+BAZEL_OUTPUT_DIR="$OUTPUT_DIR/bazel"
+
+export TARGET_PRODUCT="aosp_arm64"
+[ "$#" -ge 1 ] && export TARGET_PRODUCT="$1"
+ARCH_VARIANT_CFLAG="armv8-a"
+[ "$#" -ge 2 ] && ARCH_VARIANT_CFLAG="$2"
+CPU_VARIANT_CFLAG=""
+[ "$#" -ge 3 ] && CPU_VARIANT_CFLAG="$3"
+
+function call_bazel() {
+  build/bazel/bin/bazel --output_base="$BAZEL_OUTPUT_DIR" $@
+}
+
+function cleanup {
+  # call bazel clean because some bazel outputs don't have w bits.
+  call_bazel clean
+  rm -rf "${OUTPUT_DIR}"
+}
+trap cleanup EXIT
+
+######################
+# Run bp2build / Bazel
+######################
+build/soong/soong_ui.bash --make-mode BP2BUILD_VERBOSE=1 --skip-soong-tests bp2build
+
+# Number of CppCompile actions with arch variant flag
+actions_with_arch_variant_num=$(call_bazel aquery --config=bp2build --config=ci --config=android \
+  'mnemonic("CppCompile", deps(//build/bazel/examples/apex/minimal:build.bazel.examples.apex.minimal.apex))' | grep -c "\-march=$ARCH_VARIANT_CFLAG")
+
+# Number of all CppCompile actions
+all_cppcompile_actions_num=0
+aquery_summary=$(call_bazel aquery --config=bp2build --config=ci --config=android --output=summary \
+  'mnemonic("CppCompile", deps(//build/bazel/examples/apex/minimal:build.bazel.examples.apex.minimal.apex))' \
+  | egrep -o '.*opt-ST.*: ([0-9]+)$' \
+  | cut -d: -f2 -)
+
+while read -r num;
+do
+  all_cppcompile_actions_num=$(($all_cppcompile_actions_num + $num))
+done <<< "$aquery_summary"
+
+if [ $actions_with_arch_variant_num -eq $all_cppcompile_actions_num ]
+then
+  echo "Pass: arch variant is set."
+else
+  echo "Error: number of CppCompile actions with arch variant set: actual=$actions_with_arch_variant_num, expected=$all_cppcompile_actions_num"
+  exit 1
+fi
+
+if [ $CPU_VARIANT_CFLAG ]
+then
+  # Number of CppCompiler actions with cpu variant flag
+  actions_with_cpu_variant_num=$(call_bazel aquery --config=bp2build --config=ci --config=android \
+    'mnemonic("CppCompile", deps(//build/bazel/examples/apex/minimal:build.bazel.examples.apex.minimal.apex))' | grep -c "\-mcpu=$CPU_VARIANT_CFLAG")
+
+  if [ $actions_with_cpu_variant_num -eq $all_cppcompile_actions_num ]
+  then
+    echo "Pass: cpu variant is set."
+  else
+    echo "Error: number of CppCompile actions with cpu variant set: actual=$actions_with_cpu_variant_num, expected=$all_cppcompile_actions_num"
+    exit 1
+  fi
+fi
\ No newline at end of file
diff --git a/tests/run_integration_tests.sh b/tests/run_integration_tests.sh
index 7a71b27..eb76a46 100755
--- a/tests/run_integration_tests.sh
+++ b/tests/run_integration_tests.sh
@@ -14,3 +14,7 @@
 # mock client.
 "$TOP/build/soong/tests/apex_comparison_tests.sh"
 "$TOP/build/soong/tests/apex_comparison_tests.sh" "module_arm64only"
+
+"$TOP/build/soong/tests/apex_cc_module_arch_variant_tests.sh"
+"$TOP/build/soong/tests/apex_cc_module_arch_variant_tests.sh" "aosp_arm" "armv7-a"
+"$TOP/build/soong/tests/apex_cc_module_arch_variant_tests.sh" "aosp_cf_arm64_phone" "armv8-a" "cortex-a53"
\ No newline at end of file