Merge "bootanimation: add empty lines parsing skip for desc.txt"
diff --git a/core/java/android/graphics/fonts/FontManager.java b/core/java/android/graphics/fonts/FontManager.java
index 24480e9..beb7f36 100644
--- a/core/java/android/graphics/fonts/FontManager.java
+++ b/core/java/android/graphics/fonts/FontManager.java
@@ -198,6 +198,15 @@
      */
     public static final int RESULT_ERROR_INVALID_XML = -10007;
 
+    /**
+     * Indicates a failure due to invalid debug certificate file.
+     *
+     * This error code is only used with the shell command interaction.
+     *
+     * @hide
+     */
+    public static final int RESULT_ERROR_INVALID_DEBUG_CERTIFICATE = -10008;
+
     private FontManager(@NonNull IFontManager iFontManager) {
         mIFontManager = iFontManager;
     }
diff --git a/core/java/android/service/autofill/augmented/AugmentedAutofillService.java b/core/java/android/service/autofill/augmented/AugmentedAutofillService.java
index d9a310f..745f36d 100644
--- a/core/java/android/service/autofill/augmented/AugmentedAutofillService.java
+++ b/core/java/android/service/autofill/augmented/AugmentedAutofillService.java
@@ -332,7 +332,6 @@
     }
 
     @Override
-    /** @hide */
     protected final void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
         pw.print("Service component: "); pw.println(
                 ComponentName.flattenToShortString(mServiceComponentName));
diff --git a/core/java/android/window/WindowContainerToken.java b/core/java/android/window/WindowContainerToken.java
index 22b90b2..b914cb0 100644
--- a/core/java/android/window/WindowContainerToken.java
+++ b/core/java/android/window/WindowContainerToken.java
@@ -48,7 +48,6 @@
     }
 
     @Override
-    /** @hide */
     public void writeToParcel(@NonNull Parcel dest, int flags) {
         dest.writeStrongBinder(mRealToken.asBinder());
     }
@@ -68,7 +67,6 @@
             };
 
     @Override
-    /** @hide */
     public int describeContents() {
         return 0;
     }
diff --git a/core/java/android/window/WindowContainerTransaction.java b/core/java/android/window/WindowContainerTransaction.java
index 7dc039d..ce1e7d2 100644
--- a/core/java/android/window/WindowContainerTransaction.java
+++ b/core/java/android/window/WindowContainerTransaction.java
@@ -781,7 +781,6 @@
     }
 
     @Override
-    /** @hide */
     public void writeToParcel(@NonNull Parcel dest, int flags) {
         dest.writeMap(mChanges);
         dest.writeTypedList(mHierarchyOps);
@@ -790,7 +789,6 @@
     }
 
     @Override
-    /** @hide */
     public int describeContents() {
         return 0;
     }
diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml
index f244ce4..83d6816 100644
--- a/core/res/res/values/config.xml
+++ b/core/res/res/values/config.xml
@@ -5775,4 +5775,8 @@
     <string-array name="config_serviceStateLocationAllowedPackages">
         <item>"com.android.phone"</item>
     </string-array>
+
+    <!-- List of certificate to be used for font fs-verity integrity verification -->
+    <string-array translatable="false" name="config_fontManagerServiceCerts">
+    </string-array>
 </resources>
diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml
index 596d89a..bc2191e 100644
--- a/core/res/res/values/symbols.xml
+++ b/core/res/res/values/symbols.xml
@@ -2273,6 +2273,7 @@
   <java-symbol type="id" name="media_actions" />
 
   <java-symbol type="dimen" name="config_mediaMetadataBitmapMaxSize" />
+  <java-symbol type="array" name="config_fontManagerServiceCerts" />
 
     <!-- From SystemUI -->
   <java-symbol type="anim" name="push_down_in" />
diff --git a/media/java/android/media/AudioPresentation.java b/media/java/android/media/AudioPresentation.java
index 47358be..05f3c5a 100644
--- a/media/java/android/media/AudioPresentation.java
+++ b/media/java/android/media/AudioPresentation.java
@@ -54,7 +54,11 @@
     private final int mProgramId;
     private final ULocale mLanguage;
 
-    /** @hide */
+    /**
+     * The ContentClassifier int definitions represent the AudioPresentation content
+     * classifier (as per TS 103 190-1 v1.2.1 4.3.3.8.1)
+     * @hide
+     */
     @IntDef(
         value = {
         CONTENT_UNKNOWN,
@@ -67,11 +71,6 @@
         CONTENT_EMERGENCY,
         CONTENT_VOICEOVER,
     })
-
-    /**
-     * The ContentClassifier int definitions represent the AudioPresentation content
-     * classifier (as per TS 103 190-1 v1.2.1 4.3.3.8.1)
-    */
     @Retention(RetentionPolicy.SOURCE)
     public @interface ContentClassifier {}
 
diff --git a/media/java/android/media/ImageReader.java b/media/java/android/media/ImageReader.java
index 472586b..7f970f7 100644
--- a/media/java/android/media/ImageReader.java
+++ b/media/java/android/media/ImageReader.java
@@ -277,7 +277,7 @@
     }
 
     private void initializeImageReader(int width, int height, int imageFormat, int maxImages,
-            long usage, int hardwareBufferFormat, int dataSpace, boolean useLegacyImageFormat) {
+            long usage, int hardwareBufferFormat, int dataSpace) {
         if (width < 1 || height < 1) {
             throw new IllegalArgumentException(
                 "The image dimensions must be positive");
@@ -306,8 +306,7 @@
         // complex, and 1 buffer is enough for the VM to treat the ImageReader as being of some
         // size.
         mEstimatedNativeAllocBytes = ImageUtils.getEstimatedNativeAllocBytes(
-            width, height, useLegacyImageFormat ? imageFormat : hardwareBufferFormat,
-            /*buffer count*/ 1);
+                width, height, imageFormat, /*buffer count*/ 1);
         VMRuntime.getRuntime().registerNativeAllocation(mEstimatedNativeAllocBytes);
     }
 
@@ -322,28 +321,26 @@
         // retrieve hal Format and hal dataspace from imageFormat
         mHardwareBufferFormat = PublicFormatUtils.getHalFormat(mFormat);
         mDataSpace = PublicFormatUtils.getHalDataspace(mFormat);
-        mUseLegacyImageFormat = true;
         mNumPlanes = ImageUtils.getNumPlanesForFormat(mFormat);
 
         initializeImageReader(width, height, imageFormat, maxImages, usage, mHardwareBufferFormat,
-                mDataSpace, mUseLegacyImageFormat);
+                mDataSpace);
     }
 
     private ImageReader(int width, int height, int maxImages, long usage,
             MultiResolutionImageReader parent, int hardwareBufferFormat, int dataSpace) {
         mWidth = width;
         mHeight = height;
-        mFormat = ImageFormat.UNKNOWN; // set default image format value as UNKNOWN
         mUsage = usage;
         mMaxImages = maxImages;
         mParent = parent;
         mHardwareBufferFormat = hardwareBufferFormat;
         mDataSpace = dataSpace;
-        mUseLegacyImageFormat = false;
         mNumPlanes = ImageUtils.getNumPlanesForHardwareBufferFormat(mHardwareBufferFormat);
+        mFormat = PublicFormatUtils.getPublicFormat(hardwareBufferFormat, dataSpace);
 
         initializeImageReader(width, height, mFormat, maxImages, usage, hardwareBufferFormat,
-                dataSpace, mUseLegacyImageFormat);
+                dataSpace);
     }
 
     /**
@@ -537,12 +534,7 @@
      * @hide
      */
     public Image acquireNextImageNoThrowISE() {
-        SurfaceImage si;
-        if (mUseLegacyImageFormat) {
-            si = new SurfaceImage(mFormat);
-        } else {
-            si = new SurfaceImage(mHardwareBufferFormat, mDataSpace);
-        }
+        SurfaceImage si = new SurfaceImage(mFormat);
         return acquireNextSurfaceImage(si) == ACQUIRE_SUCCESS ? si : null;
     }
 
@@ -565,7 +557,7 @@
             // A null image will eventually be returned if ImageReader is already closed.
             int status = ACQUIRE_NO_BUFS;
             if (mIsReaderValid) {
-                status = nativeImageSetup(si, mUseLegacyImageFormat);
+                status = nativeImageSetup(si);
             }
 
             switch (status) {
@@ -619,11 +611,7 @@
         // Initialize with reader format, but can be overwritten by native if the image
         // format is different from the reader format.
         SurfaceImage si;
-        if (mUseLegacyImageFormat) {
-            si = new SurfaceImage(mFormat);
-        } else {
-            si = new SurfaceImage(mHardwareBufferFormat, mDataSpace);
-        }
+        si = new SurfaceImage(mFormat);
         int status = acquireNextSurfaceImage(si);
 
         switch (status) {
@@ -1094,8 +1082,6 @@
 
     private final @NamedDataSpace int mDataSpace;
 
-    private final boolean mUseLegacyImageFormat;
-
     /**
      * This field is used by native code, do not access or modify.
      */
@@ -1136,12 +1122,6 @@
             mDataSpace = ImageReader.this.mDataSpace;
         }
 
-        SurfaceImage(int hardwareBufferFormat, int dataSpace) {
-            mHardwareBufferFormat = hardwareBufferFormat;
-            mDataSpace = dataSpace;
-            mFormat = PublicFormatUtils.getPublicFormat(mHardwareBufferFormat, mDataSpace);
-        }
-
         @Override
         public void close() {
             synchronized (this.mCloseLock) {
@@ -1159,12 +1139,10 @@
             // update mFormat only if ImageReader is initialized by factory pattern.
             // if using builder pattern, mFormat has been updated upon initialization.
             // no need update here.
-            if (ImageReader.this.mUseLegacyImageFormat) {
-                int readerFormat = ImageReader.this.getImageFormat();
-                // Assume opaque reader always produce opaque images.
-                mFormat = (readerFormat == ImageFormat.PRIVATE) ? readerFormat :
-                    nativeGetFormat(readerFormat);
-            }
+            int readerFormat = ImageReader.this.getImageFormat();
+            // Assume opaque reader always produce opaque images.
+            mFormat = (readerFormat == ImageFormat.PRIVATE) ? readerFormat :
+                nativeGetFormat(readerFormat);
             return mFormat;
         }
 
@@ -1263,8 +1241,8 @@
             throwISEIfImageIsInvalid();
 
             if (mPlanes == null) {
-                mPlanes = nativeCreatePlanes(ImageReader.this.mNumPlanes, ImageReader.this.mFormat,
-                        ImageReader.this.mUsage);
+                mPlanes = nativeCreatePlanes(ImageReader.this.mNumPlanes,
+                        ImageReader.this.mHardwareBufferFormat, ImageReader.this.mUsage);
             }
             // Shallow copy is fine.
             return mPlanes.clone();
@@ -1395,7 +1373,7 @@
         private AtomicBoolean mIsDetached = new AtomicBoolean(false);
 
         private synchronized native SurfacePlane[] nativeCreatePlanes(int numPlanes,
-                int readerFormat, long readerUsage);
+                int hardwareBufferFormat, long readerUsage);
         private synchronized native int nativeGetWidth();
         private synchronized native int nativeGetHeight();
         private synchronized native int nativeGetFormat(int readerFormat);
@@ -1418,7 +1396,7 @@
      * @see #ACQUIRE_NO_BUFS
      * @see #ACQUIRE_MAX_IMAGES
      */
-    private synchronized native int nativeImageSetup(Image i, boolean legacyValidateImageFormat);
+    private synchronized native int nativeImageSetup(Image i);
 
     /**
      * @hide
diff --git a/media/java/android/media/ImageWriter.java b/media/java/android/media/ImageWriter.java
index 9f52bf1..0291f64 100644
--- a/media/java/android/media/ImageWriter.java
+++ b/media/java/android/media/ImageWriter.java
@@ -29,7 +29,6 @@
 import android.hardware.HardwareBuffer;
 import android.hardware.HardwareBuffer.Usage;
 import android.hardware.SyncFence;
-import android.hardware.camera2.params.StreamConfigurationMap;
 import android.hardware.camera2.utils.SurfaceUtils;
 import android.os.Handler;
 import android.os.Looper;
@@ -249,7 +248,7 @@
     }
 
     private void initializeImageWriter(Surface surface, int maxImages,
-            boolean useSurfaceImageFormatInfo, boolean useLegacyImageFormat, int imageFormat,
+            boolean useSurfaceImageFormatInfo, int imageFormat,
             int hardwareBufferFormat, int dataSpace, int width, int height, long usage) {
         if (surface == null || maxImages < 1) {
             throw new IllegalArgumentException("Illegal input argument: surface " + surface
@@ -265,32 +264,11 @@
         if (useSurfaceImageFormatInfo) {
             // nativeInit internally overrides UNKNOWN format. So does surface format query after
             // nativeInit and before getEstimatedNativeAllocBytes().
-            imageFormat = SurfaceUtils.getSurfaceFormat(surface);
-            mHardwareBufferFormat = PublicFormatUtils.getHalFormat(imageFormat);
-            mDataSpace = PublicFormatUtils.getHalDataspace(imageFormat);
+            mHardwareBufferFormat = hardwareBufferFormat = SurfaceUtils.getSurfaceFormat(surface);
+            mDataSpace = dataSpace = SurfaceUtils.getSurfaceDataspace(surface);
+            imageFormat = PublicFormatUtils.getPublicFormat(hardwareBufferFormat, dataSpace);
         }
 
-        // Several public formats use the same native HAL_PIXEL_FORMAT_BLOB. The native
-        // allocation estimation sequence depends on the public formats values. To avoid
-        // possible errors, convert where necessary.
-        if (imageFormat == StreamConfigurationMap.HAL_PIXEL_FORMAT_BLOB) {
-            int surfaceDataspace = SurfaceUtils.getSurfaceDataspace(surface);
-            switch (surfaceDataspace) {
-                case StreamConfigurationMap.HAL_DATASPACE_DEPTH:
-                    imageFormat = ImageFormat.DEPTH_POINT_CLOUD;
-                    break;
-                case StreamConfigurationMap.HAL_DATASPACE_DYNAMIC_DEPTH:
-                    imageFormat = ImageFormat.DEPTH_JPEG;
-                    break;
-                case StreamConfigurationMap.HAL_DATASPACE_HEIF:
-                    imageFormat = ImageFormat.HEIC;
-                    break;
-                default:
-                    imageFormat = ImageFormat.JPEG;
-            }
-            mHardwareBufferFormat = PublicFormatUtils.getHalFormat(imageFormat);
-            mDataSpace = PublicFormatUtils.getHalDataspace(imageFormat);
-        }
         // Estimate the native buffer allocation size and register it so it gets accounted for
         // during GC. Note that this doesn't include the buffers required by the buffer queue
         // itself and the buffers requested by the producer.
@@ -301,19 +279,20 @@
         mWidth = width == -1 ? surfSize.getWidth() : width;
         mHeight = height == -1 ? surfSize.getHeight() : height;
 
-        mEstimatedNativeAllocBytes =
-            ImageUtils.getEstimatedNativeAllocBytes(mWidth, mHeight,
-                useLegacyImageFormat ? imageFormat : hardwareBufferFormat, /*buffer count*/ 1);
+        mEstimatedNativeAllocBytes = ImageUtils.getEstimatedNativeAllocBytes(mWidth, mHeight,
+                imageFormat, /*buffer count*/ 1);
         VMRuntime.getRuntime().registerNativeAllocation(mEstimatedNativeAllocBytes);
     }
 
     private ImageWriter(Surface surface, int maxImages, boolean useSurfaceImageFormatInfo,
             int imageFormat, int width, int height) {
         mMaxImages = maxImages;
-        mHardwareBufferFormat = PublicFormatUtils.getHalFormat(imageFormat);
-        mDataSpace = PublicFormatUtils.getHalDataspace(imageFormat);
+        if (!useSurfaceImageFormatInfo) {
+            mHardwareBufferFormat = PublicFormatUtils.getHalFormat(imageFormat);
+            mDataSpace = PublicFormatUtils.getHalDataspace(imageFormat);
+        }
 
-        initializeImageWriter(surface, maxImages, useSurfaceImageFormatInfo, true,
+        initializeImageWriter(surface, maxImages, useSurfaceImageFormatInfo,
                 imageFormat, mHardwareBufferFormat, mDataSpace, width, height, mUsage);
     }
 
@@ -321,10 +300,12 @@
             int imageFormat, int width, int height, long usage) {
         mMaxImages = maxImages;
         mUsage = usage;
-        mHardwareBufferFormat = PublicFormatUtils.getHalFormat(imageFormat);
-        mDataSpace = PublicFormatUtils.getHalDataspace(imageFormat);
+        if (!useSurfaceImageFormatInfo) {
+            mHardwareBufferFormat = PublicFormatUtils.getHalFormat(imageFormat);
+            mDataSpace = PublicFormatUtils.getHalDataspace(imageFormat);
+        }
 
-        initializeImageWriter(surface, maxImages, useSurfaceImageFormatInfo, true,
+        initializeImageWriter(surface, maxImages, useSurfaceImageFormatInfo,
                 imageFormat, mHardwareBufferFormat, mDataSpace, width, height, usage);
     }
 
@@ -337,15 +318,13 @@
         // and retrieve corresponding hardwareBufferFormat and dataSpace here.
         if (useSurfaceImageFormatInfo) {
             imageFormat = ImageFormat.UNKNOWN;
-            mHardwareBufferFormat = PublicFormatUtils.getHalFormat(imageFormat);
-            mDataSpace = PublicFormatUtils.getHalDataspace(imageFormat);
         } else {
             imageFormat = PublicFormatUtils.getPublicFormat(hardwareBufferFormat, dataSpace);
             mHardwareBufferFormat = hardwareBufferFormat;
             mDataSpace = dataSpace;
         }
 
-        initializeImageWriter(surface, maxImages, useSurfaceImageFormatInfo, false,
+        initializeImageWriter(surface, maxImages, useSurfaceImageFormatInfo,
                 imageFormat, hardwareBufferFormat, dataSpace, width, height, usage);
     }
 
@@ -764,13 +743,15 @@
         // need do some cleanup to make sure no orphaned
         // buffer caused leak.
         Rect crop = image.getCropRect();
+        int hardwareBufferFormat = PublicFormatUtils.getHalFormat(image.getFormat());
         if (image.getNativeContext() != 0) {
-            nativeAttachAndQueueImage(mNativeContext, image.getNativeContext(), image.getFormat(),
-                    image.getTimestamp(), image.getDataSpace(), crop.left, crop.top, crop.right,
-                    crop.bottom, image.getTransform(), image.getScalingMode());
+            nativeAttachAndQueueImage(mNativeContext, image.getNativeContext(),
+                    hardwareBufferFormat, image.getTimestamp(), image.getDataSpace(),
+                    crop.left, crop.top, crop.right, crop.bottom, image.getTransform(),
+                    image.getScalingMode());
         } else {
             GraphicBuffer gb = GraphicBuffer.createFromHardwareBuffer(image.getHardwareBuffer());
-            nativeAttachAndQueueGraphicBuffer(mNativeContext, gb, image.getFormat(),
+            nativeAttachAndQueueGraphicBuffer(mNativeContext, gb, hardwareBufferFormat,
                     image.getTimestamp(), image.getDataSpace(), crop.left, crop.top, crop.right,
                     crop.bottom, image.getTransform(), image.getScalingMode());
             gb.destroy();
@@ -1161,8 +1142,7 @@
 
             if (mPlanes == null) {
                 int numPlanes = ImageUtils.getNumPlanesForFormat(getFormat());
-                mPlanes = nativeCreatePlanes(numPlanes, getOwner().getFormat(),
-                        getOwner().getDataSpace());
+                mPlanes = nativeCreatePlanes(numPlanes, getOwner().getFormat());
             }
 
             return mPlanes.clone();
@@ -1270,8 +1250,7 @@
         }
 
         // Create the SurfacePlane object and fill the information
-        private synchronized native SurfacePlane[] nativeCreatePlanes(int numPlanes, int writerFmt,
-                int dataSpace);
+        private synchronized native SurfacePlane[] nativeCreatePlanes(int numPlanes, int writerFmt);
 
         private synchronized native int nativeGetWidth();
 
@@ -1298,10 +1277,10 @@
             int transform, int scalingMode);
 
     private synchronized native int nativeAttachAndQueueImage(long nativeCtx,
-            long imageNativeBuffer, int imageFormat, long timestampNs, int dataSpace,
+            long imageNativeBuffer, int hardwareBufferFormat, long timestampNs, int dataSpace,
             int left, int top, int right, int bottom, int transform, int scalingMode);
     private synchronized native int nativeAttachAndQueueGraphicBuffer(long nativeCtx,
-            GraphicBuffer graphicBuffer, int imageFormat, long timestampNs, int dataSpace,
+            GraphicBuffer graphicBuffer, int hardwareBufferFormat, long timestampNs, int dataSpace,
             int left, int top, int right, int bottom, int transform, int scalingMode);
 
     private synchronized native void cancelImage(long nativeCtx, Image image);
diff --git a/media/jni/android_media_ImageReader.cpp b/media/jni/android_media_ImageReader.cpp
index 62c0d55..3b93b07 100644
--- a/media/jni/android_media_ImageReader.cpp
+++ b/media/jni/android_media_ImageReader.cpp
@@ -375,11 +375,11 @@
 }
 
 static void ImageReader_init(JNIEnv* env, jobject thiz, jobject weakThiz, jint width, jint height,
-                             jint maxImages, jlong ndkUsage, jint nativeFormat, jint dataSpace) {
+                             jint maxImages, jlong ndkUsage, jint nativeHalFormat, jint dataSpace) {
     status_t res;
 
-    ALOGV("%s: width:%d, height: %d, nativeFormat: %d, maxImages:%d",
-          __FUNCTION__, width, height, nativeFormat, maxImages);
+    ALOGV("%s: width:%d, height: %d, nativeHalFormat: %d, maxImages:%d",
+          __FUNCTION__, width, height, nativeHalFormat, maxImages);
 
     android_dataspace nativeDataspace = static_cast<android_dataspace>(dataSpace);
 
@@ -395,7 +395,7 @@
     BufferQueue::createBufferQueue(&gbProducer, &gbConsumer);
     sp<BufferItemConsumer> bufferConsumer;
     String8 consumerName = String8::format("ImageReader-%dx%df%xm%d-%d-%d",
-            width, height, nativeFormat, maxImages, getpid(),
+            width, height, nativeHalFormat, maxImages, getpid(),
             createProcessUniqueId());
     uint64_t consumerUsage =
             android_hardware_HardwareBuffer_convertToGrallocUsageBits(ndkUsage);
@@ -404,8 +404,8 @@
             /*controlledByApp*/true);
     if (bufferConsumer == nullptr) {
         jniThrowExceptionFmt(env, "java/lang/RuntimeException",
-                "Failed to allocate native buffer consumer for format 0x%x and usage 0x%x",
-                nativeFormat, consumerUsage);
+                "Failed to allocate native buffer consumer for hal format 0x%x and usage 0x%x",
+                nativeHalFormat, consumerUsage);
         return;
     }
 
@@ -419,7 +419,7 @@
     ctx->setProducer(gbProducer);
     bufferConsumer->setFrameAvailableListener(ctx);
     ImageReader_setNativeContext(env, thiz, ctx);
-    ctx->setBufferFormat(nativeFormat);
+    ctx->setBufferFormat(nativeHalFormat);
     ctx->setBufferDataspace(nativeDataspace);
     ctx->setBufferWidth(width);
     ctx->setBufferHeight(height);
@@ -428,14 +428,14 @@
     res = bufferConsumer->setDefaultBufferSize(width, height);
     if (res != OK) {
         jniThrowExceptionFmt(env, "java/lang/IllegalStateException",
-                          "Failed to set buffer consumer default size (%dx%d) for format 0x%x",
-                          width, height, nativeFormat);
+                          "Failed to set buffer consumer default size (%dx%d) for Hal format 0x%x",
+                          width, height, nativeHalFormat);
         return;
     }
-    res = bufferConsumer->setDefaultBufferFormat(nativeFormat);
+    res = bufferConsumer->setDefaultBufferFormat(nativeHalFormat);
     if (res != OK) {
         jniThrowExceptionFmt(env, "java/lang/IllegalStateException",
-                          "Failed to set buffer consumer default format 0x%x", nativeFormat);
+                          "Failed to set buffer consumer default Halformat 0x%x", nativeHalFormat);
         return;
     }
     res = bufferConsumer->setDefaultBufferDataSpace(nativeDataspace);
@@ -522,8 +522,7 @@
     ALOGV("%s: Image (format: 0x%x) has been released", __FUNCTION__, ctx->getBufferFormat());
 }
 
-static jint ImageReader_imageSetup(JNIEnv* env, jobject thiz, jobject image,
-                                   jboolean legacyValidateImageFormat) {
+static jint ImageReader_imageSetup(JNIEnv* env, jobject thiz, jobject image) {
     ALOGV("%s:", __FUNCTION__);
     JNIImageReaderContext* ctx = ImageReader_getContext(env, thiz);
     if (ctx == NULL) {
@@ -577,29 +576,29 @@
         int outputWidth = getBufferWidth(buffer);
         int outputHeight = getBufferHeight(buffer);
 
-        int imgReaderFmt = ctx->getBufferFormat();
+        int imgReaderHalFmt = ctx->getBufferFormat();
         int imageReaderWidth = ctx->getBufferWidth();
         int imageReaderHeight = ctx->getBufferHeight();
         int bufferFormat = buffer->mGraphicBuffer->getPixelFormat();
-        if ((bufferFormat != HAL_PIXEL_FORMAT_BLOB) && (imgReaderFmt != HAL_PIXEL_FORMAT_BLOB) &&
+        if ((bufferFormat != HAL_PIXEL_FORMAT_BLOB) && (imgReaderHalFmt != HAL_PIXEL_FORMAT_BLOB) &&
                 (imageReaderWidth != outputWidth || imageReaderHeight != outputHeight)) {
             ALOGV("%s: Producer buffer size: %dx%d, doesn't match ImageReader configured size: %dx%d",
                     __FUNCTION__, outputWidth, outputHeight, imageReaderWidth, imageReaderHeight);
         }
-        if (legacyValidateImageFormat && imgReaderFmt != bufferFormat) {
-            if (imgReaderFmt == HAL_PIXEL_FORMAT_YCbCr_420_888 &&
+        if (imgReaderHalFmt != bufferFormat) {
+            if (imgReaderHalFmt == HAL_PIXEL_FORMAT_YCbCr_420_888 &&
                     isPossiblyYUV(bufferFormat)) {
                 // Treat formats that are compatible with flexible YUV
                 // (HAL_PIXEL_FORMAT_YCbCr_420_888) as HAL_PIXEL_FORMAT_YCbCr_420_888.
                 ALOGV("%s: Treat buffer format to 0x%x as HAL_PIXEL_FORMAT_YCbCr_420_888",
                         __FUNCTION__, bufferFormat);
-            } else if (imgReaderFmt == HAL_PIXEL_FORMAT_YCBCR_P010 &&
+            } else if (imgReaderHalFmt == HAL_PIXEL_FORMAT_YCBCR_P010 &&
                     isPossibly10BitYUV(bufferFormat)) {
                 // Treat formats that are compatible with flexible 10-bit YUV
                 // (HAL_PIXEL_FORMAT_YCBCR_P010) as HAL_PIXEL_FORMAT_YCBCR_P010.
                 ALOGV("%s: Treat buffer format to 0x%x as HAL_PIXEL_FORMAT_YCBCR_P010",
                         __FUNCTION__, bufferFormat);
-            } else if (imgReaderFmt == HAL_PIXEL_FORMAT_BLOB &&
+            } else if (imgReaderHalFmt == HAL_PIXEL_FORMAT_BLOB &&
                     bufferFormat == HAL_PIXEL_FORMAT_RGBA_8888) {
                 // Using HAL_PIXEL_FORMAT_RGBA_8888 Gralloc buffers containing JPEGs to get around
                 // SW write limitations for (b/17379185).
@@ -842,7 +841,7 @@
 }
 
 static jobjectArray Image_createSurfacePlanes(JNIEnv* env, jobject thiz,
-        int numPlanes, int readerFormat, uint64_t ndkReaderUsage)
+        int numPlanes, int halReaderFormat, uint64_t ndkReaderUsage)
 {
     ALOGV("%s: create SurfacePlane array with size %d", __FUNCTION__, numPlanes);
     int rowStride = 0;
@@ -851,9 +850,6 @@
     uint32_t dataSize = 0;
     jobject byteBuffer = NULL;
 
-    PublicFormat publicReaderFormat = static_cast<PublicFormat>(readerFormat);
-    int halReaderFormat = mapPublicFormatToHalFormat(publicReaderFormat);
-
     if (isFormatOpaque(halReaderFormat) && numPlanes > 0) {
         String8 msg;
         msg.appendFormat("Format 0x%x is opaque, thus not writable, the number of planes (%d)"
@@ -963,7 +959,7 @@
     {"nativeInit",             "(Ljava/lang/Object;IIIJII)V",   (void*)ImageReader_init },
     {"nativeClose",            "()V",                        (void*)ImageReader_close },
     {"nativeReleaseImage",     "(Landroid/media/Image;)V",   (void*)ImageReader_imageRelease },
-    {"nativeImageSetup",       "(Landroid/media/Image;Z)I",   (void*)ImageReader_imageSetup },
+    {"nativeImageSetup",       "(Landroid/media/Image;)I",   (void*)ImageReader_imageSetup },
     {"nativeGetSurface",       "()Landroid/view/Surface;",   (void*)ImageReader_getSurface },
     {"nativeDetachImage",      "(Landroid/media/Image;)I",   (void*)ImageReader_detachImage },
     {"nativeCreateImagePlanes",
diff --git a/media/jni/android_media_ImageWriter.cpp b/media/jni/android_media_ImageWriter.cpp
index 6c6fccb..2c498e5 100644
--- a/media/jni/android_media_ImageWriter.cpp
+++ b/media/jni/android_media_ImageWriter.cpp
@@ -415,7 +415,9 @@
 
     // Get the dimension and format of the producer.
     sp<ANativeWindow> anw = producer;
-    int32_t width, height, surfaceFormat;
+    int32_t width, height, surfaceHalFormat;
+    int32_t surfaceFormat = 0;
+    int32_t surfaceDataspace = 0;
     if (userWidth < 0) {
         if ((res = anw->query(anw.get(), NATIVE_WINDOW_WIDTH, &width)) != OK) {
             ALOGE("%s: Query Surface width failed: %s (%d)", __FUNCTION__, strerror(-res), res);
@@ -451,11 +453,18 @@
     // Query surface format if no valid user format is specified, otherwise, override surface format
     // with user format.
     if (useSurfaceImageFormatInfo) {
-        if ((res = anw->query(anw.get(), NATIVE_WINDOW_FORMAT, &surfaceFormat)) != OK) {
+        // retrieve hal format
+        if ((res = anw->query(anw.get(), NATIVE_WINDOW_FORMAT, &surfaceHalFormat)) != OK) {
             ALOGE("%s: Query Surface format failed: %s (%d)", __FUNCTION__, strerror(-res), res);
             jniThrowRuntimeException(env, "Failed to query Surface format");
             return 0;
         }
+        if ((res = anw->query(
+                anw.get(), NATIVE_WINDOW_DEFAULT_DATASPACE, &surfaceDataspace)) != OK) {
+            ALOGE("%s: Query Surface dataspace failed: %s (%d)", __FUNCTION__, strerror(-res), res);
+            jniThrowRuntimeException(env, "Failed to query Surface dataspace");
+            return 0;
+        }
     } else {
         // Set consumer buffer format to user specified format
         android_dataspace nativeDataspace = static_cast<android_dataspace>(dataSpace);
@@ -475,17 +484,22 @@
             return 0;
         }
         ctx->setBufferDataSpace(nativeDataspace);
-        surfaceFormat = static_cast<int32_t>(mapHalFormatDataspaceToPublicFormat(
-            hardwareBufferFormat, nativeDataspace));
+        surfaceDataspace = dataSpace;
+        surfaceHalFormat = hardwareBufferFormat;
     }
 
-    ctx->setBufferFormat(surfaceFormat);
+    ctx->setBufferFormat(surfaceHalFormat);
+    ctx->setBufferDataSpace(static_cast<android_dataspace>(surfaceDataspace));
+
+    // update class.mWriterFormat
+    surfaceFormat = static_cast<int32_t>(mapHalFormatDataspaceToPublicFormat(
+                surfaceHalFormat, static_cast<android_dataspace>(surfaceDataspace)));
     env->SetIntField(thiz,
             gImageWriterClassInfo.mWriterFormat, reinterpret_cast<jint>(surfaceFormat));
 
     // ndkUsage == -1 means setUsage in ImageWriter class is not called.
     // skip usage setting if setUsage in ImageWriter is not called and imageformat is opaque.
-    if (!(ndkUsage == -1 && isFormatOpaque(surfaceFormat))) {
+    if (!(ndkUsage == -1 && isFormatOpaque(surfaceHalFormat))) {
         if (ndkUsage == -1) {
             ndkUsage = GRALLOC_USAGE_SW_WRITE_OFTEN;
         }
@@ -809,7 +823,7 @@
 }
 
 static jint ImageWriter_attachAndQueueImage(JNIEnv* env, jobject thiz, jlong nativeCtx,
-        jlong nativeBuffer, jint imageFormat, jlong timestampNs, jint dataSpace,
+        jlong nativeBuffer, jint nativeHalFormat, jlong timestampNs, jint dataSpace,
         jint left, jint top, jint right, jint bottom, jint transform, jint scalingMode) {
     ALOGV("%s", __FUNCTION__);
     JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
@@ -820,7 +834,7 @@
     }
 
     sp<Surface> surface = ctx->getProducer();
-    if (isFormatOpaque(imageFormat) != isFormatOpaque(ctx->getBufferFormat())) {
+    if (isFormatOpaque(ctx->getBufferFormat()) != isFormatOpaque(nativeHalFormat)) {
         jniThrowException(env, "java/lang/IllegalStateException",
                 "Trying to attach an opaque image into a non-opaque ImageWriter, or vice versa");
         return -1;
@@ -840,8 +854,8 @@
 }
 
 static jint ImageWriter_attachAndQueueGraphicBuffer(JNIEnv* env, jobject thiz, jlong nativeCtx,
-        jobject buffer, jint format, jlong timestampNs, jint dataSpace, jint left, jint top,
-        jint right, jint bottom, jint transform, jint scalingMode) {
+        jobject buffer, jint nativeHalFormat, jlong timestampNs, jint dataSpace,
+        jint left, jint top, jint right, jint bottom, jint transform, jint scalingMode) {
     ALOGV("%s", __FUNCTION__);
     JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
     if (ctx == NULL || thiz == NULL) {
@@ -851,7 +865,7 @@
     }
 
     sp<Surface> surface = ctx->getProducer();
-    if (isFormatOpaque(format) != isFormatOpaque(ctx->getBufferFormat())) {
+    if (isFormatOpaque(ctx->getBufferFormat()) != isFormatOpaque(nativeHalFormat)) {
         jniThrowException(env, "java/lang/IllegalStateException",
                 "Trying to attach an opaque image into a non-opaque ImageWriter, or vice versa");
         return -1;
@@ -1028,32 +1042,32 @@
 }
 
 static bool Image_getLockedImageInfo(JNIEnv* env, LockedImage* buffer, int idx,
-        int32_t writerFormat, uint8_t **base, uint32_t *size, int *pixelStride, int *rowStride) {
+        int32_t halFormat, uint8_t **base, uint32_t *size, int *pixelStride, int *rowStride) {
     ALOGV("%s", __FUNCTION__);
 
-    status_t res = getLockedImageInfo(buffer, idx, writerFormat, base, size,
+    status_t res = getLockedImageInfo(buffer, idx, halFormat, base, size,
             pixelStride, rowStride);
     if (res != OK) {
         jniThrowExceptionFmt(env, "java/lang/UnsupportedOperationException",
-                             "Pixel format: 0x%x is unsupported", writerFormat);
+                             "Pixel format: 0x%x is unsupported", halFormat);
         return false;
     }
     return true;
 }
 
 static jobjectArray Image_createSurfacePlanes(JNIEnv* env, jobject thiz,
-        int numPlanes, int writerFormat, int dataSpace) {
+        int numPlanes, int writerFormat) {
     ALOGV("%s: create SurfacePlane array with size %d", __FUNCTION__, numPlanes);
     int rowStride, pixelStride;
     uint8_t *pData;
     uint32_t dataSize;
     jobject byteBuffer;
+    int halFormat = mapPublicFormatToHalFormat(static_cast<PublicFormat>(writerFormat));
 
-    int format = Image_getFormat(env, thiz, dataSpace);
-    if (isFormatOpaque(format) && numPlanes > 0) {
+    if (isFormatOpaque(halFormat) && numPlanes > 0) {
         String8 msg;
         msg.appendFormat("Format 0x%x is opaque, thus not writable, the number of planes (%d)"
-                " must be 0", format, numPlanes);
+                " must be 0", writerFormat, numPlanes);
         jniThrowException(env, "java/lang/IllegalArgumentException", msg.string());
         return NULL;
     }
@@ -1065,7 +1079,8 @@
                 " probably out of memory");
         return NULL;
     }
-    if (isFormatOpaque(format)) {
+
+    if (isFormatOpaque(halFormat)) {
         return surfacePlanes;
     }
 
@@ -1074,10 +1089,8 @@
     Image_getLockedImage(env, thiz, &lockedImg);
 
     // Create all SurfacePlanes
-    PublicFormat publicWriterFormat = static_cast<PublicFormat>(writerFormat);
-    writerFormat = mapPublicFormatToHalFormat(publicWriterFormat);
     for (int i = 0; i < numPlanes; i++) {
-        if (!Image_getLockedImageInfo(env, &lockedImg, i, writerFormat,
+        if (!Image_getLockedImageInfo(env, &lockedImg, i, halFormat,
                 &pData, &dataSize, &pixelStride, &rowStride)) {
             return NULL;
         }
@@ -1119,7 +1132,7 @@
 };
 
 static JNINativeMethod gImageMethods[] = {
-    {"nativeCreatePlanes",      "(III)[Landroid/media/ImageWriter$WriterSurfaceImage$SurfacePlane;",
+    {"nativeCreatePlanes",      "(II)[Landroid/media/ImageWriter$WriterSurfaceImage$SurfacePlane;",
                                                                (void*)Image_createSurfacePlanes },
     {"nativeGetWidth",          "()I",                         (void*)Image_getWidth },
     {"nativeGetHeight",         "()I",                         (void*)Image_getHeight },
diff --git a/services/core/java/com/android/server/graphics/fonts/FontManagerService.java b/services/core/java/com/android/server/graphics/fonts/FontManagerService.java
index ae9c64b..ad27c45 100644
--- a/services/core/java/com/android/server/graphics/fonts/FontManagerService.java
+++ b/services/core/java/com/android/server/graphics/fonts/FontManagerService.java
@@ -26,6 +26,7 @@
 import android.graphics.fonts.FontManager;
 import android.graphics.fonts.FontUpdateRequest;
 import android.graphics.fonts.SystemFonts;
+import android.os.Build;
 import android.os.ParcelFileDescriptor;
 import android.os.ResultReceiver;
 import android.os.SharedMemory;
@@ -35,8 +36,10 @@
 import android.util.AndroidException;
 import android.util.ArrayMap;
 import android.util.IndentingPrintWriter;
+import android.util.Log;
 import android.util.Slog;
 
+import com.android.internal.R;
 import com.android.internal.annotations.GuardedBy;
 import com.android.internal.graphics.fonts.IFontManager;
 import com.android.internal.security.VerityUtils;
@@ -47,7 +50,9 @@
 
 import java.io.File;
 import java.io.FileDescriptor;
+import java.io.FileInputStream;
 import java.io.IOException;
+import java.io.InputStream;
 import java.io.PrintWriter;
 import java.nio.ByteBuffer;
 import java.nio.DirectByteBuffer;
@@ -154,9 +159,30 @@
     }
 
     private static class FsverityUtilImpl implements UpdatableFontDir.FsverityUtil {
+
+        private final String[] mDerCertPaths;
+
+        FsverityUtilImpl(String[] derCertPaths) {
+            mDerCertPaths = derCertPaths;
+        }
+
         @Override
-        public boolean hasFsverity(String filePath) {
-            return VerityUtils.hasFsverity(filePath);
+        public boolean isFromTrustedProvider(String fontPath, byte[] pkcs7Signature) {
+            final byte[] digest = VerityUtils.getFsverityDigest(fontPath);
+            if (digest == null) {
+                Log.w(TAG, "Failed to get fs-verity digest for " + fontPath);
+                return false;
+            }
+            for (String certPath : mDerCertPaths) {
+                try (InputStream is = new FileInputStream(certPath)) {
+                    if (VerityUtils.verifyPkcs7DetachedSignature(pkcs7Signature, digest, is)) {
+                        return true;
+                    }
+                } catch (IOException e) {
+                    Log.w(TAG, "Failed to read certificate file: " + certPath);
+                }
+            }
+            return false;
         }
 
         @Override
@@ -174,11 +200,15 @@
     @NonNull
     private final Context mContext;
 
+    private final boolean mIsSafeMode;
+
     private final Object mUpdatableFontDirLock = new Object();
 
+    private String mDebugCertFilePath = null;
+
     @GuardedBy("mUpdatableFontDirLock")
     @Nullable
-    private final UpdatableFontDir mUpdatableFontDir;
+    private UpdatableFontDir mUpdatableFontDir;
 
     // mSerializedFontMapLock can be acquired while holding mUpdatableFontDirLock.
     // mUpdatableFontDirLock should not be newly acquired while holding mSerializedFontMapLock.
@@ -194,22 +224,43 @@
             UpdatableFontDir.deleteAllFiles(new File(FONT_FILES_DIR), new File(CONFIG_XML_FILE));
         }
         mContext = context;
-        mUpdatableFontDir = createUpdatableFontDir(safeMode);
+        mIsSafeMode = safeMode;
         initialize();
     }
 
     @Nullable
-    private static UpdatableFontDir createUpdatableFontDir(boolean safeMode) {
+    private UpdatableFontDir createUpdatableFontDir() {
         // Never read updatable font files in safe mode.
-        if (safeMode) return null;
+        if (mIsSafeMode) return null;
         // If apk verity is supported, fs-verity should be available.
         if (!VerityUtils.isFsVeritySupported()) return null;
+
+        String[] certs = mContext.getResources().getStringArray(
+                R.array.config_fontManagerServiceCerts);
+
+        if (mDebugCertFilePath != null && (Build.IS_USERDEBUG || Build.IS_ENG)) {
+            String[] tmp = new String[certs.length + 1];
+            System.arraycopy(certs, 0, tmp, 0, certs.length);
+            tmp[certs.length] = mDebugCertFilePath;
+            certs = tmp;
+        }
+
         return new UpdatableFontDir(new File(FONT_FILES_DIR), new OtfFontFileParser(),
-                new FsverityUtilImpl(), new File(CONFIG_XML_FILE));
+                new FsverityUtilImpl(certs), new File(CONFIG_XML_FILE));
+    }
+
+    /**
+     * Add debug certificate to the cert list. This must be called only on userdebug/eng
+     * build.
+     * @param debugCertPath a debug certificate file path
+     */
+    public void addDebugCertificate(@Nullable String debugCertPath) {
+        mDebugCertFilePath = debugCertPath;
     }
 
     private void initialize() {
         synchronized (mUpdatableFontDirLock) {
+            mUpdatableFontDir = createUpdatableFontDir();
             if (mUpdatableFontDir == null) {
                 setSerializedFontMap(serializeSystemServerFontMap());
                 return;
@@ -232,12 +283,12 @@
 
     /* package */ void update(int baseVersion, List<FontUpdateRequest> requests)
             throws SystemFontException {
-        if (mUpdatableFontDir == null) {
-            throw new SystemFontException(
-                    FontManager.RESULT_ERROR_FONT_UPDATER_DISABLED,
-                    "The font updater is disabled.");
-        }
         synchronized (mUpdatableFontDirLock) {
+            if (mUpdatableFontDir == null) {
+                throw new SystemFontException(
+                        FontManager.RESULT_ERROR_FONT_UPDATER_DISABLED,
+                        "The font updater is disabled.");
+            }
             // baseVersion == -1 only happens from shell command. This is filtered and treated as
             // error from SystemApi call.
             if (baseVersion != -1 && mUpdatableFontDir.getConfigVersion() != baseVersion) {
@@ -272,10 +323,10 @@
     }
 
     /* package */ Map<String, File> getFontFileMap() {
-        if (mUpdatableFontDir == null) {
-            return Collections.emptyMap();
-        }
         synchronized (mUpdatableFontDirLock) {
+            if (mUpdatableFontDir == null) {
+                return Collections.emptyMap();
+            }
             return mUpdatableFontDir.getPostScriptMap();
         }
     }
@@ -301,10 +352,10 @@
      * Returns an active system font configuration.
      */
     public @NonNull FontConfig getSystemFontConfig() {
-        if (mUpdatableFontDir == null) {
-            return SystemFonts.getSystemPreinstalledFontConfig();
-        }
         synchronized (mUpdatableFontDirLock) {
+            if (mUpdatableFontDir == null) {
+                return SystemFonts.getSystemPreinstalledFontConfig();
+            }
             return mUpdatableFontDir.getSystemFontConfig();
         }
     }
diff --git a/services/core/java/com/android/server/graphics/fonts/FontManagerShellCommand.java b/services/core/java/com/android/server/graphics/fonts/FontManagerShellCommand.java
index 3fecef7..9478344 100644
--- a/services/core/java/com/android/server/graphics/fonts/FontManagerShellCommand.java
+++ b/services/core/java/com/android/server/graphics/fonts/FontManagerShellCommand.java
@@ -28,6 +28,7 @@
 import android.graphics.fonts.FontVariationAxis;
 import android.graphics.fonts.SystemFonts;
 import android.os.Binder;
+import android.os.Build;
 import android.os.ParcelFileDescriptor;
 import android.os.Process;
 import android.os.ShellCommand;
@@ -103,6 +104,10 @@
         w.println("update-family [family definition XML path]");
         w.println("    Update font families with the new definitions.");
         w.println();
+        w.println("install-debug-cert [cert file path]");
+        w.println("    Install debug certificate file. This command can be used only on userdebug");
+        w.println("    or eng device with root user.");
+        w.println();
         w.println("clear");
         w.println("    Remove all installed font files and reset to the initial state.");
         w.println();
@@ -322,6 +327,33 @@
         return 0;
     }
 
+    private int installCert(ShellCommand shell) throws SystemFontException {
+        if (!(Build.IS_USERDEBUG || Build.IS_ENG)) {
+            throw new SecurityException("Only userdebug/eng device can add debug certificate");
+        }
+        if (Binder.getCallingUid() != Process.ROOT_UID) {
+            throw new SecurityException("Only root can add debug certificate");
+        }
+
+        String certPath = shell.getNextArg();
+        if (certPath == null) {
+            throw new SystemFontException(
+                    FontManager.RESULT_ERROR_INVALID_DEBUG_CERTIFICATE,
+                    "Cert file path argument is required.");
+        }
+        File file = new File(certPath);
+        if (!file.isFile()) {
+            throw new SystemFontException(
+                    FontManager.RESULT_ERROR_INVALID_DEBUG_CERTIFICATE,
+                    "Cert file (" + file + ") is not found");
+        }
+
+        mService.addDebugCertificate(certPath);
+        mService.restart();
+        shell.getOutPrintWriter().println("Success");
+        return 0;
+    }
+
     private int update(ShellCommand shell) throws SystemFontException {
         String fontPath = shell.getNextArg();
         if (fontPath == null) {
@@ -494,6 +526,8 @@
                     return restart(shell);
                 case "status":
                     return status(shell);
+                case "install-debug-cert":
+                    return installCert(shell);
                 default:
                     return shell.handleDefaultCommands(cmd);
             }
diff --git a/services/core/java/com/android/server/graphics/fonts/UpdatableFontDir.java b/services/core/java/com/android/server/graphics/fonts/UpdatableFontDir.java
index 743b4d9..457d5b7 100644
--- a/services/core/java/com/android/server/graphics/fonts/UpdatableFontDir.java
+++ b/services/core/java/com/android/server/graphics/fonts/UpdatableFontDir.java
@@ -40,6 +40,8 @@
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
 import java.security.SecureRandom;
 import java.util.ArrayList;
 import java.util.HashMap;
@@ -59,6 +61,8 @@
     private static final String TAG = "UpdatableFontDir";
     private static final String RANDOM_DIR_PREFIX = "~~";
 
+    private static final String FONT_SIGNATURE_FILE = "font.fsv_sig";
+
     /** Interface to mock font file access in tests. */
     interface FontFileParser {
         String getPostScriptName(File file) throws IOException;
@@ -72,7 +76,7 @@
 
     /** Interface to mock fs-verity in tests. */
     interface FsverityUtil {
-        boolean hasFsverity(String path);
+        boolean isFromTrustedProvider(String path, byte[] pkcs7Signature);
 
         void setUpFsverity(String path, byte[] pkcs7Signature) throws IOException;
 
@@ -188,12 +192,35 @@
                     FileUtils.deleteContentsAndDir(dir);
                     continue;
                 }
+
+                File signatureFile = new File(dir, FONT_SIGNATURE_FILE);
+                if (!signatureFile.exists()) {
+                    Slog.i(TAG, "The signature file is missing.");
+                    FileUtils.deleteContentsAndDir(dir);
+                    continue;
+                }
+                byte[] signature;
+                try {
+                    signature = Files.readAllBytes(Paths.get(signatureFile.getAbsolutePath()));
+                } catch (IOException e) {
+                    Slog.e(TAG, "Failed to read signature file.");
+                    return;
+                }
+
                 File[] files = dir.listFiles();
-                if (files == null || files.length != 1) {
+                if (files == null || files.length != 2) {
                     Slog.e(TAG, "Unexpected files in dir: " + dir);
                     return;
                 }
-                FontFileInfo fontFileInfo = validateFontFile(files[0]);
+
+                File fontFile;
+                if (files[0].equals(signatureFile)) {
+                    fontFile = files[1];
+                } else {
+                    fontFile = files[0];
+                }
+
+                FontFileInfo fontFileInfo = validateFontFile(fontFile, signature);
                 if (fontConfig == null) {
                     fontConfig = getSystemFontConfig();
                 }
@@ -359,9 +386,25 @@
             } catch (ErrnoException e) {
                 throw new SystemFontException(
                         FontManager.RESULT_ERROR_FAILED_TO_WRITE_FONT_FILE,
-                        "Failed to change mode to 711", e);
+                        "Failed to change font file mode to 644", e);
             }
-            FontFileInfo fontFileInfo = validateFontFile(newFontFile);
+            File signatureFile = new File(newDir, FONT_SIGNATURE_FILE);
+            try (FileOutputStream out = new FileOutputStream(signatureFile)) {
+                out.write(pkcs7Signature);
+            } catch (IOException e) {
+                // TODO: Do we need new error code for signature write failure?
+                throw new SystemFontException(
+                        FontManager.RESULT_ERROR_FAILED_TO_WRITE_FONT_FILE,
+                        "Failed to write font signature file to storage.", e);
+            }
+            try {
+                Os.chmod(signatureFile.getAbsolutePath(), 0600);
+            } catch (ErrnoException e) {
+                throw new SystemFontException(
+                        FontManager.RESULT_ERROR_FAILED_TO_WRITE_FONT_FILE,
+                        "Failed to change the signature file mode to 600", e);
+            }
+            FontFileInfo fontFileInfo = validateFontFile(newFontFile, pkcs7Signature);
 
             // Try to create Typeface and treat as failure something goes wrong.
             try {
@@ -478,8 +521,9 @@
      * is higher than the currently used font.
      */
     @NonNull
-    private FontFileInfo validateFontFile(File file) throws SystemFontException {
-        if (!mFsverityUtil.hasFsverity(file.getAbsolutePath())) {
+    private FontFileInfo validateFontFile(File file, byte[] pkcs7Signature)
+            throws SystemFontException {
+        if (!mFsverityUtil.isFromTrustedProvider(file.getAbsolutePath(), pkcs7Signature)) {
             throw new SystemFontException(
                     FontManager.RESULT_ERROR_VERIFICATION_FAILURE,
                     "Font validation failed. Fs-verity is not enabled: " + file);
diff --git a/services/tests/servicestests/src/com/android/server/graphics/fonts/UpdatableFontDirTest.java b/services/tests/servicestests/src/com/android/server/graphics/fonts/UpdatableFontDirTest.java
index f9b8373..9672085 100644
--- a/services/tests/servicestests/src/com/android/server/graphics/fonts/UpdatableFontDirTest.java
+++ b/services/tests/servicestests/src/com/android/server/graphics/fonts/UpdatableFontDirTest.java
@@ -108,7 +108,7 @@
         }
 
         @Override
-        public boolean hasFsverity(String path) {
+        public boolean isFromTrustedProvider(String path, byte[] signature) {
             return mHasFsverityPaths.contains(path);
         }
 
@@ -291,6 +291,32 @@
     }
 
     @Test
+    public void construct_missingSignatureFile() throws Exception {
+        UpdatableFontDir dirForPreparation = new UpdatableFontDir(
+                mUpdatableFontFilesDir, mParser, mFakeFsverityUtil,
+                mConfigFile, mCurrentTimeSupplier, mConfigSupplier);
+        dirForPreparation.loadFontFileMap();
+        dirForPreparation.update(Arrays.asList(
+                newFontUpdateRequest("foo.ttf,1,foo", GOOD_SIGNATURE)));
+        assertThat(mUpdatableFontFilesDir.list()).hasLength(1);
+
+        // Remove signature file next to the font file.
+        File fontDir = dirForPreparation.getPostScriptMap().get("foo");
+        File sigFile = new File(fontDir.getParentFile(), "font.fsv_sig");
+        assertThat(sigFile.exists()).isTrue();
+        sigFile.delete();
+
+        UpdatableFontDir dir = new UpdatableFontDir(
+                mUpdatableFontFilesDir, mParser, mFakeFsverityUtil,
+                mConfigFile, mCurrentTimeSupplier, mConfigSupplier);
+        dir.loadFontFileMap();
+        // The font file should be removed and should not be loaded.
+        assertThat(dir.getPostScriptMap()).isEmpty();
+        assertThat(mUpdatableFontFilesDir.list()).hasLength(0);
+        assertThat(dir.getFontFamilyMap()).isEmpty();
+    }
+
+    @Test
     public void construct_olderThanPreinstalledFont() throws Exception {
         Function<Map<String, File>, FontConfig> configSupplier = (map) -> {
             FontConfig.Font fooFont = new FontConfig.Font(
@@ -782,8 +808,8 @@
         UpdatableFontDir.FsverityUtil fakeFsverityUtil = new UpdatableFontDir.FsverityUtil() {
 
             @Override
-            public boolean hasFsverity(String path) {
-                return mFakeFsverityUtil.hasFsverity(path);
+            public boolean isFromTrustedProvider(String path, byte[] signature) {
+                return mFakeFsverityUtil.isFromTrustedProvider(path, signature);
             }
 
             @Override
diff --git a/telephony/java/android/service/euicc/EuiccProfileInfo.java b/telephony/java/android/service/euicc/EuiccProfileInfo.java
index 8ec500b..7eccd1a 100644
--- a/telephony/java/android/service/euicc/EuiccProfileInfo.java
+++ b/telephony/java/android/service/euicc/EuiccProfileInfo.java
@@ -49,7 +49,6 @@
             POLICY_RULE_DO_NOT_DELETE,
             POLICY_RULE_DELETE_AFTER_DISABLING
     })
-    /** @hide */
     public @interface PolicyRule {}
     /** Once this profile is enabled, it cannot be disabled. */
     public static final int POLICY_RULE_DO_NOT_DISABLE = 1;
@@ -66,7 +65,6 @@
             PROFILE_CLASS_OPERATIONAL,
             PROFILE_CLASS_UNSET
     })
-    /** @hide */
     public @interface ProfileClass {}
     /** Testing profiles */
     public static final int PROFILE_CLASS_TESTING = 0;
@@ -87,7 +85,6 @@
             PROFILE_STATE_ENABLED,
             PROFILE_STATE_UNSET
     })
-    /** @hide */
     public @interface ProfileState {}
     /** Disabled profiles */
     public static final int PROFILE_STATE_DISABLED = 0;
diff --git a/telephony/java/android/telephony/euicc/EuiccCardManager.java b/telephony/java/android/telephony/euicc/EuiccCardManager.java
index 0a2bb3d..2f8316e 100644
--- a/telephony/java/android/telephony/euicc/EuiccCardManager.java
+++ b/telephony/java/android/telephony/euicc/EuiccCardManager.java
@@ -75,7 +75,6 @@
             CANCEL_REASON_TIMEOUT,
             CANCEL_REASON_PPR_NOT_ALLOWED
     })
-    /** @hide */
     public @interface CancelReason {
     }
 
@@ -105,7 +104,6 @@
             RESET_OPTION_DELETE_FIELD_LOADED_TEST_PROFILES,
             RESET_OPTION_RESET_DEFAULT_SMDP_ADDRESS
     })
-    /** @hide */
     public @interface ResetOption {
     }
 
diff --git a/telephony/java/android/telephony/euicc/EuiccNotification.java b/telephony/java/android/telephony/euicc/EuiccNotification.java
index c348cff..be0048f 100644
--- a/telephony/java/android/telephony/euicc/EuiccNotification.java
+++ b/telephony/java/android/telephony/euicc/EuiccNotification.java
@@ -44,7 +44,6 @@
             EVENT_DISABLE,
             EVENT_DELETE
     })
-    /** @hide */
     public @interface Event {}
 
     /** A profile is downloaded and installed. */
diff --git a/telephony/java/android/telephony/euicc/EuiccRulesAuthTable.java b/telephony/java/android/telephony/euicc/EuiccRulesAuthTable.java
index d5a05ae..1c6b6b6 100644
--- a/telephony/java/android/telephony/euicc/EuiccRulesAuthTable.java
+++ b/telephony/java/android/telephony/euicc/EuiccRulesAuthTable.java
@@ -42,7 +42,6 @@
     @IntDef(flag = true, prefix = { "POLICY_RULE_FLAG_" }, value = {
             POLICY_RULE_FLAG_CONSENT_REQUIRED
     })
-    /** @hide */
     public @interface PolicyRuleFlag {}
 
     /** User consent is required to install the profile. */
diff --git a/tests/UpdatableSystemFontTest/src/com/android/updatablesystemfont/UpdatableSystemFontTest.java b/tests/UpdatableSystemFontTest/src/com/android/updatablesystemfont/UpdatableSystemFontTest.java
index cbe13d9..650686f 100644
--- a/tests/UpdatableSystemFontTest/src/com/android/updatablesystemfont/UpdatableSystemFontTest.java
+++ b/tests/UpdatableSystemFontTest/src/com/android/updatablesystemfont/UpdatableSystemFontTest.java
@@ -373,6 +373,10 @@
         try (InputStream is = new FileInputStream(certPath)) {
             result = runShellCommand("mini-keyctl padd asymmetric fsv_test .fs-verity", is);
         }
+        // /data/local/tmp is not readable by system server. Copy a cert file to /data/fonts
+        final String copiedCert = "/data/fonts/debug_cert.der";
+        runShellCommand("cp " + certPath + " " + copiedCert, null);
+        runShellCommand("cmd font install-debug-cert " + copiedCert, null);
         // Assert that there are no errors.
         assertThat(result.second).isEmpty();
         String keyId = result.first.trim();
diff --git a/tests/utils/testutils/java/com/android/internal/util/test/BroadcastInterceptingContext.java b/tests/utils/testutils/java/com/android/internal/util/test/BroadcastInterceptingContext.java
index 133c176..cc3781a 100644
--- a/tests/utils/testutils/java/com/android/internal/util/test/BroadcastInterceptingContext.java
+++ b/tests/utils/testutils/java/com/android/internal/util/test/BroadcastInterceptingContext.java
@@ -246,6 +246,12 @@
     }
 
     @Override
+    public void sendBroadcastAsUser(Intent intent, UserHandle user,
+            String receiverPermission, Bundle options) {
+        sendBroadcast(intent);
+    }
+
+    @Override
     public void sendStickyBroadcast(Intent intent) {
         sendBroadcast(intent);
     }