Merge "Revert^4 "Enforce <uses-library> check for Android.mk modules."" into sc-dev
diff --git a/core/Makefile b/core/Makefile
index 2fb54f2..3a66b92 100644
--- a/core/Makefile
+++ b/core/Makefile
@@ -5319,6 +5319,19 @@
 	$(hide) find $(PRODUCT_OUT)/appcompat | sort >$(PRIVATE_LIST_FILE)
 	$(hide) $(SOONG_ZIP) -d -o $@ -C $(PRODUCT_OUT)/appcompat -l $(PRIVATE_LIST_FILE)
 
+# The mac build doesn't build dex2oat, so create the zip file only if the build OS is linux.
+ifeq ($(BUILD_OS),linux)
+ifneq ($(DEX2OAT),)
+dexpreopt_tools_deps := $(DEXPREOPT_GEN_DEPS) $(DEXPREOPT_GEN) $(AAPT2)
+DEXPREOPT_TOOLS_ZIP := $(PRODUCT_OUT)/dexpreopt_tools.zip
+$(DEXPREOPT_TOOLS_ZIP): $(dexpreopt_tools_deps)
+$(DEXPREOPT_TOOLS_ZIP): PRIVATE_DEXPREOPT_TOOLS_DEPS := $(dexpreopt_tools_deps)
+$(DEXPREOPT_TOOLS_ZIP): $(SOONG_ZIP)
+	$(hide) mkdir -p $(dir $@)
+	$(hide) $(SOONG_ZIP) -d -o $@ -j $(addprefix -f ,$(PRIVATE_DEXPREOPT_TOOLS_DEPS)) -f $$(realpath $(DEX2OAT))
+endif # DEX2OAT is set
+endif # BUILD_OS == linux
+
 DEXPREOPT_CONFIG_ZIP := $(PRODUCT_OUT)/dexpreopt_config.zip
 $(DEXPREOPT_CONFIG_ZIP): $(FULL_SYSTEMIMAGE_DEPS) \
 	    $(INTERNAL_RAMDISK_FILES) \
diff --git a/core/app_prebuilt_internal.mk b/core/app_prebuilt_internal.mk
index 86a4adf..79639a8 100644
--- a/core/app_prebuilt_internal.mk
+++ b/core/app_prebuilt_internal.mk
@@ -183,6 +183,30 @@
 	$(transform-prebuilt-to-target)
 
 else  # ! LOCAL_REPLACE_PREBUILT_APK_INSTALLED
+
+# If the SDK version is 30 or higher, the apk is signed with a v2+ scheme.
+# Altering it will invalidate the signature. Just do error checks instead.
+do_not_alter_apk :=
+ifeq (PRESIGNED,$(LOCAL_CERTIFICATE))
+  ifneq (,$(LOCAL_SDK_VERSION))
+    ifeq ($(call math_is_number,$(LOCAL_SDK_VERSION)),true)
+      ifeq ($(call math_gt,$(LOCAL_SDK_VERSION),29),true)
+        do_not_alter_apk := true
+      endif
+    endif
+    # TODO: Add system_current after fixing the existing modules.
+    ifneq ($(filter current test_current core_current,$(LOCAL_SDK_VERSION)),)
+        do_not_alter_apk := true
+    endif
+  endif
+endif
+
+ifeq ($(do_not_alter_apk),true)
+$(built_module) : $(my_prebuilt_src_file) | $(ZIPALIGN)
+	$(transform-prebuilt-to-target)
+	$(check-jni-dex-compression)
+	$(check-package-alignment)
+else
 # Sign and align non-presigned .apks.
 # The embedded prebuilt jni to uncompress.
 ifeq ($(LOCAL_CERTIFICATE),PRESIGNED)
@@ -229,6 +253,7 @@
 ifdef LOCAL_COMPRESSED_MODULE
 	$(compress-package)
 endif  # LOCAL_COMPRESSED_MODULE
+endif  # ! do_not_alter_apk
 endif  # ! LOCAL_REPLACE_PREBUILT_APK_INSTALLED
 
 
diff --git a/core/definitions.mk b/core/definitions.mk
index 7f2cc42..c5fe76b 100644
--- a/core/definitions.mk
+++ b/core/definitions.mk
@@ -2380,6 +2380,15 @@
   fi
 endef
 
+# Verifies ZIP alignment of a package.
+#
+define check-package-alignment
+$(hide) if ! $(ZIPALIGN) -c -p 4 $@ >/dev/null ; then \
+    $(call echo-error,$@,Improper package alignment); \
+    exit 1; \
+  fi
+endef
+
 # Compress a package using the standard gzip algorithm.
 define compress-package
 $(hide) \
@@ -2448,6 +2457,15 @@
   fi
 endef
 
+# Verifies shared JNI libraries and dex files in an apk are uncompressed.
+#
+define check-jni-dex-compression
+  if (zipinfo $@ 'lib/*.so' '*.dex' 2>/dev/null | grep -v ' stor ' >/dev/null) ; then \
+    $(call echo-error,$@,Contains compressed JNI libraries and/or dex files); \
+    exit 1; \
+  fi
+endef
+
 # Remove unwanted shared JNI libraries embedded in an apk.
 #
 define remove-unwanted-prebuilt-embedded-jni-libs
diff --git a/core/main.mk b/core/main.mk
index e84b4fc..8e18138 100644
--- a/core/main.mk
+++ b/core/main.mk
@@ -1711,6 +1711,7 @@
     $(COVERAGE_ZIP) \
     $(APPCOMPAT_ZIP) \
     $(DEXPREOPT_CONFIG_ZIP) \
+    $(DEXPREOPT_TOOLS_ZIP) \
     $(INSTALLED_FILES_FILE) \
     $(INSTALLED_FILES_JSON) \
     $(INSTALLED_FILES_FILE_VENDOR) \
diff --git a/target/board/BoardConfigGsiCommon.mk b/target/board/BoardConfigGsiCommon.mk
index c577870..95ba1d0 100644
--- a/target/board/BoardConfigGsiCommon.mk
+++ b/target/board/BoardConfigGsiCommon.mk
@@ -30,6 +30,14 @@
 # the devices with metadata parition
 BOARD_USES_METADATA_PARTITION := true
 
+# Enable GKI 2.0 signing.
+BOARD_GKI_SIGNING_KEY_PATH := build/make/target/product/gsi/testkey_rsa2048.pem
+BOARD_GKI_SIGNING_ALGORITHM := SHA256_RSA2048
+# The following is needed to allow release signing process appends more extra
+# args, e.g., passing --signing_helper_with_files from mkbootimg to avbtool.
+# See b/178559811 for more details.
+BOARD_GKI_SIGNING_SIGNATURE_ARGS := --prop foo:bar
+
 # Android Verified Boot (AVB):
 #   Set the rollback index to zero, to prevent the device bootloader from
 #   updating the last seen rollback index in the tamper-evident storage.
diff --git a/target/board/generic_arm64/BoardConfig.mk b/target/board/generic_arm64/BoardConfig.mk
index 1229327..1dbce1e 100644
--- a/target/board/generic_arm64/BoardConfig.mk
+++ b/target/board/generic_arm64/BoardConfig.mk
@@ -77,10 +77,6 @@
 BOARD_BOOT_HEADER_VERSION := 4
 BOARD_MKBOOTIMG_ARGS += --header_version $(BOARD_BOOT_HEADER_VERSION)
 
-# Enable GKI 2.0 signing.
-BOARD_GKI_SIGNING_KEY_PATH := build/make/target/product/gsi/testkey_rsa2048.pem
-BOARD_GKI_SIGNING_ALGORITHM := SHA256_RSA2048
-
 BOARD_KERNEL_BINARIES := \
     kernel-4.19-gz \
     kernel-5.4 kernel-5.4-gz kernel-5.4-lz4 \
@@ -98,9 +94,9 @@
 BOARD_USES_RECOVERY_AS_BOOT :=
 TARGET_NO_KERNEL := false
 BOARD_USES_GENERIC_KERNEL_IMAGE := true
-# TODO(b/187432172): Add 5.10-android12-unstable
 BOARD_KERNEL_MODULE_INTERFACE_VERSIONS := \
-    5.4-android12-0 \
+    5.4-android12-unstable \
+    5.10-android12-unstable \
 
 # Copy boot image in $OUT to target files. This is defined for targets where
 # the installed GKI APEXes are built from source.
diff --git a/target/product/base_system.mk b/target/product/base_system.mk
index f927d8d..f6a6104 100644
--- a/target/product/base_system.mk
+++ b/target/product/base_system.mk
@@ -357,9 +357,6 @@
 PRODUCT_SYSTEM_PROPERTIES += debug.atrace.tags.enableflags=0
 PRODUCT_SYSTEM_PROPERTIES += persist.traced.enable=1
 
-# ANGLE is not enabled by default
-PRODUCT_PROPERTY_OVERRIDES += ro.gfx.angle.supported=false
-
 # Packages included only for eng or userdebug builds, previously debug tagged
 PRODUCT_PACKAGES_DEBUG := \
     adb_keys \
diff --git a/target/product/gsi_release.mk b/target/product/gsi_release.mk
index 82af45f..25fa68b 100644
--- a/target/product/gsi_release.mk
+++ b/target/product/gsi_release.mk
@@ -42,9 +42,6 @@
 # Enable dynamic partition size
 PRODUCT_USE_DYNAMIC_PARTITION_SIZE := true
 
-# Enable various debugfs restrictions
-PRODUCT_SET_DEBUGFS_RESTRICTIONS := true
-
 # GSI targets should install "unflattened" APEXes in /system
 TARGET_FLATTEN_APEX := false
 
diff --git a/tools/releasetools/add_img_to_target_files.py b/tools/releasetools/add_img_to_target_files.py
index 2aceb78..c583d01 100644
--- a/tools/releasetools/add_img_to_target_files.py
+++ b/tools/releasetools/add_img_to_target_files.py
@@ -420,8 +420,9 @@
     image_props["block_list"] = block_list.name
 
   # Use repeatable ext4 FS UUID and hash_seed UUID (based on partition name and
-  # build fingerprint).
-  build_info = common.BuildInfo(info_dict)
+  # build fingerprint). Also use the legacy build id, because the vbmeta digest
+  # isn't available at this point.
+  build_info = common.BuildInfo(info_dict, use_legacy_id=True)
   uuid_seed = what + "-" + build_info.GetPartitionFingerprint(what)
   image_props["uuid"] = str(uuid.uuid5(uuid.NAMESPACE_URL, uuid_seed))
   hash_seed = "hash_seed-" + uuid_seed
diff --git a/tools/releasetools/common.py b/tools/releasetools/common.py
index b397fd0..5e2a50d 100644
--- a/tools/releasetools/common.py
+++ b/tools/releasetools/common.py
@@ -372,7 +372,10 @@
       "product", "product_services", "odm", "vendor", "system"]
   _RO_PRODUCT_PROPS_DEFAULT_SOURCE_ORDER_LEGACY = []
 
-  def __init__(self, info_dict, oem_dicts=None):
+  # The length of vbmeta digest to append to the fingerprint
+  _VBMETA_DIGEST_SIZE_USED = 8
+
+  def __init__(self, info_dict, oem_dicts=None, use_legacy_id=False):
     """Initializes a BuildInfo instance with the given dicts.
 
     Note that it only wraps up the given dicts, without making copies.
@@ -383,6 +386,9 @@
           that it always uses the first dict to calculate the fingerprint or the
           device name. The rest would be used for asserting OEM properties only
           (e.g. one package can be installed on one of these devices).
+      use_legacy_id: Use the legacy build id to construct the fingerprint. This
+          is used when we need a BuildInfo class, while the vbmeta digest is
+          unavailable.
 
     Raises:
       ValueError: On invalid inputs.
@@ -391,6 +397,7 @@
     self.oem_dicts = oem_dicts
 
     self._is_ab = info_dict.get("ab_update") == "true"
+    self.use_legacy_id = use_legacy_id
 
     # Skip _oem_props if oem_dicts is None to use BuildInfo in
     # sign_target_files_apks
@@ -491,6 +498,9 @@
     if prop in BuildInfo._RO_PRODUCT_RESOLVE_PROPS:
       return self._ResolveRoProductBuildProp(prop)
 
+    if prop == "ro.build.id":
+      return self._GetBuildId()
+
     prop_val = self._GetRawBuildProp(prop, None)
     if prop_val is not None:
       return prop_val
@@ -557,6 +567,34 @@
 
     return self.GetBuildProp("ro.build.version.release")
 
+  def _GetBuildId(self):
+    build_id = self._GetRawBuildProp("ro.build.id", None)
+    if build_id:
+      return build_id
+
+    legacy_build_id = self.GetBuildProp("ro.build.legacy.id")
+    if not legacy_build_id:
+      raise ExternalError("Couldn't find build id in property file")
+
+    if self.use_legacy_id:
+      return legacy_build_id
+
+    # Append the top 8 chars of vbmeta digest to the existing build id. The
+    # logic needs to match the one in init, so that OTA can deliver correctly.
+    avb_enable = self.info_dict.get("avb_enable") == "true"
+    if not avb_enable:
+      raise ExternalError("AVB isn't enabled when using legacy build id")
+
+    vbmeta_digest = self.info_dict.get("vbmeta_digest")
+    if not vbmeta_digest:
+      raise ExternalError("Vbmeta digest isn't provided when using legacy build"
+                          " id")
+    if len(vbmeta_digest) < self._VBMETA_DIGEST_SIZE_USED:
+      raise ExternalError("Invalid vbmeta digest " + vbmeta_digest)
+
+    digest_prefix = vbmeta_digest[:self._VBMETA_DIGEST_SIZE_USED]
+    return legacy_build_id + '.' + digest_prefix
+
   def _GetPartitionPlatformVersion(self, partition):
     try:
       return self.GetPartitionBuildProp("ro.build.version.release_or_codename",
@@ -790,12 +828,19 @@
   # Set up the salt (based on fingerprint) that will be used when adding AVB
   # hash / hashtree footers.
   if d.get("avb_enable") == "true":
-    build_info = BuildInfo(d)
+    build_info = BuildInfo(d, use_legacy_id=True)
     for partition in PARTITIONS_WITH_BUILD_PROP:
       fingerprint = build_info.GetPartitionFingerprint(partition)
       if fingerprint:
         d["avb_{}_salt".format(partition)] = sha256(
             fingerprint.encode()).hexdigest()
+
+    # Set the vbmeta digest if exists
+    try:
+      d["vbmeta_digest"] = read_helper("META/vbmeta_digest.txt").rstrip()
+    except KeyError:
+      pass
+
   try:
     d["ab_partitions"] = read_helper("META/ab_partitions.txt").split("\n")
   except KeyError:
@@ -1339,7 +1384,7 @@
 
   vbmeta_image = MakeTempFile()
   os.rename(output_image, vbmeta_image)
-  build_info = BuildInfo(OPTIONS.info_dict)
+  build_info = BuildInfo(OPTIONS.info_dict, use_legacy_id=True)
   version_incremental = build_info.GetBuildProp("ro.build.version.incremental")
   aftltool = OPTIONS.aftl_tool_path
   server_argument_list = [OPTIONS.aftl_server, OPTIONS.aftl_key_path]
diff --git a/tools/releasetools/sign_target_files_apks.py b/tools/releasetools/sign_target_files_apks.py
index f0110ea..dd2de36 100755
--- a/tools/releasetools/sign_target_files_apks.py
+++ b/tools/releasetools/sign_target_files_apks.py
@@ -1033,9 +1033,8 @@
 
   extra_args = OPTIONS.gki_signing_extra_args
   if extra_args:
-    print('Setting extra GKI signing args: "%s"' % (extra_args))
-    misc_info["gki_signing_signature_args"] = (
-        misc_info.get("gki_signing_signature_args", '') + ' ' + extra_args)
+    print('Setting GKI signing args: "%s"' % (extra_args))
+    misc_info["gki_signing_signature_args"] = extra_args
 
 
 def BuildKeyMap(misc_info, key_mapping_options):
diff --git a/tools/releasetools/test_common.py b/tools/releasetools/test_common.py
index a516366..1a00549 100644
--- a/tools/releasetools/test_common.py
+++ b/tools/releasetools/test_common.py
@@ -48,6 +48,22 @@
 
 class BuildInfoTest(test_utils.ReleaseToolsTestCase):
 
+  TEST_INFO_FINGERPRINT_DICT = {
+      'build.prop': common.PartitionBuildProps.FromDictionary(
+          'system', {
+              'ro.product.brand': 'product-brand',
+              'ro.product.name': 'product-name',
+              'ro.product.device': 'product-device',
+              'ro.build.version.release': 'version-release',
+              'ro.build.id': 'build-id',
+              'ro.build.version.incremental': 'version-incremental',
+              'ro.build.type': 'build-type',
+              'ro.build.tags': 'build-tags',
+              'ro.build.version.sdk': 30,
+          }
+      ),
+  }
+
   TEST_INFO_DICT = {
       'build.prop': common.PartitionBuildProps.FromDictionary(
           'system', {
@@ -202,6 +218,33 @@
         'ro.build.fingerprint'] = 'bad\x80fingerprint'
     self.assertRaises(ValueError, common.BuildInfo, info_dict, None)
 
+  def test_init_goodFingerprint(self):
+    info_dict = copy.deepcopy(self.TEST_INFO_FINGERPRINT_DICT)
+    build_info = common.BuildInfo(info_dict)
+    self.assertEqual(
+      'product-brand/product-name/product-device:version-release/build-id/'
+      'version-incremental:build-type/build-tags', build_info.fingerprint)
+
+    build_props = info_dict['build.prop'].build_props
+    del build_props['ro.build.id']
+    build_props['ro.build.legacy.id'] = 'legacy-build-id'
+    build_info = common.BuildInfo(info_dict, use_legacy_id=True)
+    self.assertEqual(
+      'product-brand/product-name/product-device:version-release/'
+      'legacy-build-id/version-incremental:build-type/build-tags',
+      build_info.fingerprint)
+
+    self.assertRaises(common.ExternalError, common.BuildInfo, info_dict, None,
+                      False)
+
+    info_dict['avb_enable'] = 'true'
+    info_dict['vbmeta_digest'] = 'abcde12345'
+    build_info = common.BuildInfo(info_dict, use_legacy_id=False)
+    self.assertEqual(
+      'product-brand/product-name/product-device:version-release/'
+      'legacy-build-id.abcde123/version-incremental:build-type/build-tags',
+      build_info.fingerprint)
+
   def test___getitem__(self):
     target_info = common.BuildInfo(self.TEST_INFO_DICT, None)
     self.assertEqual('value1', target_info['property1'])
diff --git a/tools/releasetools/test_sign_target_files_apks.py b/tools/releasetools/test_sign_target_files_apks.py
index 64e27a2..ad9e657 100644
--- a/tools/releasetools/test_sign_target_files_apks.py
+++ b/tools/releasetools/test_sign_target_files_apks.py
@@ -602,7 +602,7 @@
     expected_dict = {
         'gki_signing_key_path': 'release_gki_key',
         'gki_signing_algorithm': 'release_gki_algorithm',
-        'gki_signing_signature_args': 'default_gki_signature_args release_gki_signature_extra_args',
+        'gki_signing_signature_args': 'release_gki_signature_extra_args',
     }
     ReplaceGkiSigningKey(misc_info)
     self.assertDictEqual(expected_dict, misc_info)