From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Alexander Grund <flamefire89@gmail.com>
Date: Mon, 14 Aug 2023 13:04:21 +0200
Subject: [PATCH] Add `PackageParser.Package getPackage(int uid)`

Partial backport of ca1ea17a3eacf71a64dc501c4374a4eeb6246451

Change-Id: I8adb1ffac1ebe3d419c1fcf2c14b22a50b31fd5b
---
 .../android/content/pm/PackageManagerInternal.java  |  6 ++++++
 .../android/server/pm/PackageManagerService.java    | 13 +++++++++++++
 2 files changed, 19 insertions(+)

diff --git a/core/java/android/content/pm/PackageManagerInternal.java b/core/java/android/content/pm/PackageManagerInternal.java
index 84d9743eec9e..9f9ff88c1541 100644
--- a/core/java/android/content/pm/PackageManagerInternal.java
+++ b/core/java/android/content/pm/PackageManagerInternal.java
@@ -667,6 +667,12 @@ public abstract class PackageManagerInternal {
      */
     public abstract @Nullable PackageParser.Package getPackage(@NonNull String packageName);
 
+    /**
+     * Returns a package for the given UID. If the UID is part of a shared user ID, one
+     * of the packages will be chosen to be returned.
+     */
+    public abstract @Nullable PackageParser.Package getPackage(int uid);
+
     /**
      * Returns a list without a change observer.
      *
diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java
index 27282c0a2dda..5bd1b4ac0195 100644
--- a/services/core/java/com/android/server/pm/PackageManagerService.java
+++ b/services/core/java/com/android/server/pm/PackageManagerService.java
@@ -24648,6 +24648,19 @@ public class PackageManagerService extends IPackageManager.Stub
             }
         }
 
+        @Override
+        public PackageParser.Package getPackage(int uid) {
+            synchronized (mPackages) {
+                final String[] packageNames = getPackagesForUid(uid);
+                PackageParser.Package pkg = null;
+                final int numPackages = packageNames == null ? 0 : packageNames.length;
+                for (int i = 0; pkg == null && i < numPackages; i++) {
+                    pkg = mPackages.get(packageNames[i]);
+                }
+                return pkg;
+            }
+        }
+
         @Override
         public PackageList getPackageList(PackageListObserver observer) {
             synchronized (mPackages) {
