Merge "Avoid creating sp<> from a pointer"
diff --git a/WEAR_OWNERS b/WEAR_OWNERS
new file mode 100644
index 0000000..4f3bc27
--- /dev/null
+++ b/WEAR_OWNERS
@@ -0,0 +1,6 @@
+yzj@google.com
+shreerag@google.com
+yeabkal@google.com
+adsule@google.com
+andriyn@google.com
+yfz@google.com
diff --git a/cmds/hid/jni/com_android_commands_hid_Device.cpp b/cmds/hid/jni/com_android_commands_hid_Device.cpp
index 2cda57d..8b8d361 100644
--- a/cmds/hid/jni/com_android_commands_hid_Device.cpp
+++ b/cmds/hid/jni/com_android_commands_hid_Device.cpp
@@ -18,24 +18,22 @@
 
 #include "com_android_commands_hid_Device.h"
 
-#include <linux/uhid.h>
-
+#include <android-base/stringprintf.h>
+#include <android/looper.h>
 #include <fcntl.h>
 #include <inttypes.h>
-#include <unistd.h>
-#include <cstdio>
-#include <cstring>
-#include <memory>
-
-#include <android/looper.h>
 #include <jni.h>
+#include <linux/uhid.h>
 #include <log/log.h>
 #include <nativehelper/JNIHelp.h>
 #include <nativehelper/ScopedLocalRef.h>
 #include <nativehelper/ScopedPrimitiveArray.h>
 #include <nativehelper/ScopedUtfChars.h>
+#include <unistd.h>
 
-#include <android-base/stringprintf.h>
+#include <cstdio>
+#include <cstring>
+#include <memory>
 
 // Log debug messages about the output.
 static constexpr bool DEBUG_OUTPUT = false;
@@ -109,15 +107,15 @@
 
 void DeviceCallback::onDeviceGetReport(uint32_t requestId, uint8_t reportId) {
     JNIEnv* env = getJNIEnv();
-    env->CallVoidMethod(mCallbackObject, gDeviceCallbackClassInfo.onDeviceGetReport,
-            requestId, reportId);
+    env->CallVoidMethod(mCallbackObject, gDeviceCallbackClassInfo.onDeviceGetReport, requestId,
+                        reportId);
     checkAndClearException(env, "onDeviceGetReport");
 }
 
-void DeviceCallback::onDeviceSetReport(uint8_t rType,
-                                    const std::vector<uint8_t>& data) {
+void DeviceCallback::onDeviceSetReport(uint32_t id, uint8_t rType,
+                                       const std::vector<uint8_t>& data) {
     JNIEnv* env = getJNIEnv();
-    env->CallVoidMethod(mCallbackObject, gDeviceCallbackClassInfo.onDeviceSetReport, rType,
+    env->CallVoidMethod(mCallbackObject, gDeviceCallbackClassInfo.onDeviceSetReport, id, rType,
                         toJbyteArray(env, data).get());
     checkAndClearException(env, "onDeviceSetReport");
 }
@@ -236,6 +234,14 @@
     writeEvent(mFd, ev, "UHID_GET_REPORT_REPLY");
 }
 
+void Device::sendSetReportReply(uint32_t id, bool success) const {
+    struct uhid_event ev = {};
+    ev.type = UHID_SET_REPORT_REPLY;
+    ev.u.set_report_reply.id = id;
+    ev.u.set_report_reply.err = success ? 0 : EIO;
+    writeEvent(mFd, ev, "UHID_SET_REPORT_REPLY");
+}
+
 int Device::handleEvents(int events) {
     if (events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP)) {
         ALOGE("uhid node was closed or an error occurred. events=0x%x", events);
@@ -249,7 +255,6 @@
         mDeviceCallback->onDeviceError();
         return 0;
     }
-
     switch (ev.type) {
         case UHID_OPEN: {
             mDeviceCallback->onDeviceOpen();
@@ -271,7 +276,7 @@
                 ALOGD("Received SET_REPORT: id=%" PRIu32 " rnum=%" PRIu8 " data=%s", set_report.id,
                       set_report.rnum, toString(data).c_str());
             }
-            mDeviceCallback->onDeviceSetReport(set_report.rtype, data);
+            mDeviceCallback->onDeviceSetReport(set_report.id, set_report.rtype, data);
             break;
         }
         case UHID_OUTPUT: {
@@ -347,6 +352,15 @@
     }
 }
 
+static void sendSetReportReply(JNIEnv*, jclass /* clazz */, jlong ptr, jint id, jboolean success) {
+    uhid::Device* d = reinterpret_cast<uhid::Device*>(ptr);
+    if (d) {
+        d->sendSetReportReply(id, success);
+    } else {
+        ALOGE("Could not send set report reply, Device* is null!");
+    }
+}
+
 static void closeDevice(JNIEnv* /* env */, jclass /* clazz */, jlong ptr) {
     uhid::Device* d = reinterpret_cast<uhid::Device*>(ptr);
     if (d) {
@@ -362,6 +376,7 @@
         {"nativeSendReport", "(J[B)V", reinterpret_cast<void*>(sendReport)},
         {"nativeSendGetFeatureReportReply", "(JI[B)V",
          reinterpret_cast<void*>(sendGetFeatureReportReply)},
+        {"nativeSendSetReportReply", "(JIZ)V", reinterpret_cast<void*>(sendSetReportReply)},
         {"nativeCloseDevice", "(J)V", reinterpret_cast<void*>(closeDevice)},
 };
 
@@ -376,7 +391,7 @@
     uhid::gDeviceCallbackClassInfo.onDeviceGetReport =
             env->GetMethodID(clazz, "onDeviceGetReport", "(II)V");
     uhid::gDeviceCallbackClassInfo.onDeviceSetReport =
-            env->GetMethodID(clazz, "onDeviceSetReport", "(B[B)V");
+            env->GetMethodID(clazz, "onDeviceSetReport", "(IB[B)V");
     uhid::gDeviceCallbackClassInfo.onDeviceOutput =
             env->GetMethodID(clazz, "onDeviceOutput", "(B[B)V");
     uhid::gDeviceCallbackClassInfo.onDeviceError =
diff --git a/cmds/hid/jni/com_android_commands_hid_Device.h b/cmds/hid/jni/com_android_commands_hid_Device.h
index d10a9aa..9c6060d 100644
--- a/cmds/hid/jni/com_android_commands_hid_Device.h
+++ b/cmds/hid/jni/com_android_commands_hid_Device.h
@@ -14,12 +14,11 @@
  * limitations under the License.
  */
 
-#include <memory>
-#include <vector>
-
+#include <android-base/unique_fd.h>
 #include <jni.h>
 
-#include <android-base/unique_fd.h>
+#include <memory>
+#include <vector>
 
 namespace android {
 namespace uhid {
@@ -31,7 +30,7 @@
 
     void onDeviceOpen();
     void onDeviceGetReport(uint32_t requestId, uint8_t reportId);
-    void onDeviceSetReport(uint8_t rType, const std::vector<uint8_t>& data);
+    void onDeviceSetReport(uint32_t id, uint8_t rType, const std::vector<uint8_t>& data);
     void onDeviceOutput(uint8_t rType, const std::vector<uint8_t>& data);
     void onDeviceError();
 
@@ -50,9 +49,9 @@
     ~Device();
 
     void sendReport(const std::vector<uint8_t>& report) const;
+    void sendSetReportReply(uint32_t id, bool success) const;
     void sendGetFeatureReportReply(uint32_t id, const std::vector<uint8_t>& report) const;
     void close();
-
     int handleEvents(int events);
 
 private:
diff --git a/cmds/hid/src/com/android/commands/hid/Device.java b/cmds/hid/src/com/android/commands/hid/Device.java
index 95b1e9a..0415037 100644
--- a/cmds/hid/src/com/android/commands/hid/Device.java
+++ b/cmds/hid/src/com/android/commands/hid/Device.java
@@ -42,7 +42,8 @@
     private static final int MSG_OPEN_DEVICE = 1;
     private static final int MSG_SEND_REPORT = 2;
     private static final int MSG_SEND_GET_FEATURE_REPORT_REPLY = 3;
-    private static final int MSG_CLOSE_DEVICE = 4;
+    private static final int MSG_SEND_SET_REPORT_REPLY = 4;
+    private static final int MSG_CLOSE_DEVICE = 5;
 
     // Sync with linux uhid_event_type::UHID_OUTPUT
     private static final byte UHID_EVENT_TYPE_UHID_OUTPUT = 6;
@@ -56,21 +57,45 @@
     private final Map<ByteBuffer, byte[]> mOutputs;
     private final OutputStream mOutputStream;
     private long mTimeToSend;
-
     private final Object mCond = new Object();
+    /**
+     * The report id of the report received in UHID_EVENT_TYPE_SET_REPORT.
+     * Used for SET_REPORT_REPLY.
+     * This field gets overridden each time SET_REPORT is received.
+     */
+    private int mResponseId;
 
     static {
         System.loadLibrary("hidcommand_jni");
     }
 
-    private static native long nativeOpenDevice(String name, int id, int vid, int pid, int bus,
-            byte[] descriptor, DeviceCallback callback);
+    private static native long nativeOpenDevice(
+            String name,
+            int id,
+            int vid,
+            int pid,
+            int bus,
+            byte[] descriptor,
+            DeviceCallback callback);
+
     private static native void nativeSendReport(long ptr, byte[] data);
+
     private static native void nativeSendGetFeatureReportReply(long ptr, int id, byte[] data);
+
+    private static native void nativeSendSetReportReply(long ptr, int id, boolean success);
+
     private static native void nativeCloseDevice(long ptr);
 
-    public Device(int id, String name, int vid, int pid, int bus, byte[] descriptor,
-            byte[] report, SparseArray<byte[]> featureReports, Map<ByteBuffer, byte[]> outputs) {
+    public Device(
+            int id,
+            String name,
+            int vid,
+            int pid,
+            int bus,
+            byte[] descriptor,
+            byte[] report,
+            SparseArray<byte[]> featureReports,
+            Map<ByteBuffer, byte[]> outputs) {
         mId = id;
         mThread = new HandlerThread("HidDeviceHandler");
         mThread.start();
@@ -100,6 +125,17 @@
         mHandler.sendMessageAtTime(msg, mTimeToSend);
     }
 
+    public void setGetReportResponse(byte[] report) {
+        mFeatureReports.put(report[0], report);
+    }
+
+    public void sendSetReportReply(boolean success) {
+        Message msg =
+                mHandler.obtainMessage(MSG_SEND_SET_REPORT_REPLY, mResponseId, success ? 1 : 0);
+
+        mHandler.sendMessageAtTime(msg, mTimeToSend);
+    }
+
     public void addDelay(int delay) {
         mTimeToSend = Math.max(SystemClock.uptimeMillis(), mTimeToSend) + delay;
     }
@@ -111,7 +147,8 @@
             synchronized (mCond) {
                 mCond.wait();
             }
-        } catch (InterruptedException ignore) {}
+        } catch (InterruptedException ignore) {
+        }
     }
 
     private class DeviceHandler extends Handler {
@@ -127,8 +164,15 @@
             switch (msg.what) {
                 case MSG_OPEN_DEVICE:
                     SomeArgs args = (SomeArgs) msg.obj;
-                    mPtr = nativeOpenDevice((String) args.arg1, args.argi1, args.argi2, args.argi3,
-                            args.argi4, (byte[]) args.arg2, new DeviceCallback());
+                    mPtr =
+                            nativeOpenDevice(
+                                    (String) args.arg1,
+                                    args.argi1,
+                                    args.argi2,
+                                    args.argi3,
+                                    args.argi4,
+                                    (byte[]) args.arg2,
+                                    new DeviceCallback());
                     pauseEvents();
                     break;
                 case MSG_SEND_REPORT:
@@ -145,6 +189,14 @@
                         Log.e(TAG, "Tried to send feature report reply to closed device.");
                     }
                     break;
+                case MSG_SEND_SET_REPORT_REPLY:
+                    if (mPtr != 0) {
+                        final boolean success = msg.arg2 == 1;
+                        nativeSendSetReportReply(mPtr, msg.arg1, success);
+                    } else {
+                        Log.e(TAG, "Tried to send set report reply to closed device.");
+                    }
+                    break;
                 case MSG_CLOSE_DEVICE:
                     if (mPtr != 0) {
                         nativeCloseDevice(mPtr);
@@ -173,14 +225,18 @@
     }
 
     private class DeviceCallback {
+
         public void onDeviceOpen() {
             mHandler.resumeEvents();
         }
 
         public void onDeviceGetReport(int requestId, int reportId) {
             if (mFeatureReports == null) {
-                Log.e(TAG, "Received GET_REPORT request for reportId=" + reportId
-                        + ", but 'feature_reports' section is not found");
+                Log.e(
+                        TAG,
+                        "Received GET_REPORT request for reportId="
+                                + reportId
+                                + ", but 'feature_reports' section is not found");
                 return;
             }
             byte[] report = mFeatureReports.get(reportId);
@@ -220,14 +276,15 @@
             } catch (IOException e) {
                 throw new RuntimeException(e);
             }
-
         }
 
         // native callback
-        public void onDeviceSetReport(byte rtype, byte[] data) {
+        public void onDeviceSetReport(int id, byte rType, byte[] data) {
+            // Used by sendSetReportReply()
+            mResponseId = id;
             // We don't need to reply for the SET_REPORT but just send it to HID output for test
             // verification.
-            sendReportOutput(UHID_EVENT_TYPE_SET_REPORT, rtype, data);
+            sendReportOutput(UHID_EVENT_TYPE_SET_REPORT, rType, data);
         }
 
         // native callback
@@ -239,7 +296,8 @@
             }
             byte[] response = mOutputs.get(ByteBuffer.wrap(data));
             if (response == null) {
-                Log.i(TAG,
+                Log.i(
+                        TAG,
                         "Requested response for output " + Arrays.toString(data) + " is not found");
                 return;
             }
diff --git a/cmds/hid/src/com/android/commands/hid/Event.java b/cmds/hid/src/com/android/commands/hid/Event.java
index d4bf1d8..3efb797 100644
--- a/cmds/hid/src/com/android/commands/hid/Event.java
+++ b/cmds/hid/src/com/android/commands/hid/Event.java
@@ -35,6 +35,8 @@
     public static final String COMMAND_REGISTER = "register";
     public static final String COMMAND_DELAY = "delay";
     public static final String COMMAND_REPORT = "report";
+    public static final String COMMAND_SET_GET_REPORT_RESPONSE = "set_get_report_response";
+    public static final String COMMAND_SEND_SET_REPORT_REPLY = "send_set_report_reply";
 
     // These constants come from "include/uapi/linux/input.h" in the kernel
     enum Bus {
@@ -62,6 +64,7 @@
     private SparseArray<byte[]> mFeatureReports;
     private Map<ByteBuffer, byte[]> mOutputs;
     private int mDuration;
+    private Boolean mReply;
 
     public int getId() {
         return mId;
@@ -107,6 +110,10 @@
         return mDuration;
     }
 
+    public Boolean getReply() {
+        return mReply;
+    }
+
     public String toString() {
         return "Event{id=" + mId
             + ", command=" + String.valueOf(mCommand)
@@ -119,6 +126,7 @@
             + ", feature_reports=" + mFeatureReports.toString()
             + ", outputs=" + mOutputs.toString()
             + ", duration=" + mDuration
+            + ", success=" + mReply.toString()
             + "}";
     }
 
@@ -173,6 +181,10 @@
             mEvent.mDuration = duration;
         }
 
+        public void setReply(boolean success) {
+            mEvent.mReply = success;
+        }
+
         public Event build() {
             if (mEvent.mId == -1) {
                 throw new IllegalStateException("No event id");
@@ -183,6 +195,16 @@
                 if (mEvent.mDescriptor == null) {
                     throw new IllegalStateException("Device registration is missing descriptor");
                 }
+            }
+            if (COMMAND_SET_GET_REPORT_RESPONSE.equals(mEvent.mCommand)) {
+                if (mEvent.mReport == null) {
+                    throw new IllegalStateException("Report command is missing response data");
+                }
+            }
+            if (COMMAND_SEND_SET_REPORT_REPLY.equals(mEvent.mCommand)) {
+                if (mEvent.mReply == null) {
+                    throw new IllegalStateException("Reply command is missing reply");
+                }
             } else if (COMMAND_DELAY.equals(mEvent.mCommand)) {
                 if (mEvent.mDuration <= 0) {
                     throw new IllegalStateException("Delay has missing or invalid duration");
@@ -246,6 +268,9 @@
                             case "duration":
                                 eb.setDuration(readInt());
                                 break;
+                            case "success":
+                                eb.setReply(readBool());
+                                break;
                             default:
                                 mReader.skipValue();
                         }
@@ -292,6 +317,11 @@
             return Integer.decode(val);
         }
 
+        private boolean readBool() throws IOException {
+            String val = mReader.nextString();
+            return Boolean.parseBoolean(val);
+        }
+
         private Bus readBus() throws IOException {
             String val = mReader.nextString();
             return Bus.valueOf(val.toUpperCase());
diff --git a/cmds/hid/src/com/android/commands/hid/Hid.java b/cmds/hid/src/com/android/commands/hid/Hid.java
index fac0ab2..2db791fe 100644
--- a/cmds/hid/src/com/android/commands/hid/Hid.java
+++ b/cmds/hid/src/com/android/commands/hid/Hid.java
@@ -93,6 +93,10 @@
                 d.addDelay(e.getDuration());
             } else if (Event.COMMAND_REPORT.equals(e.getCommand())) {
                 d.sendReport(e.getReport());
+            } else if (Event.COMMAND_SET_GET_REPORT_RESPONSE.equals(e.getCommand())) {
+                d.setGetReportResponse(e.getReport());
+            } else if (Event.COMMAND_SEND_SET_REPORT_REPLY.equals(e.getCommand())) {
+                d.sendSetReportReply(e.getReply());
             } else {
                 if (Event.COMMAND_REGISTER.equals(e.getCommand())) {
                     error("Device id=" + e.getId() + " is already registered. Ignoring event.");
diff --git a/core/api/system-current.txt b/core/api/system-current.txt
index ec4ad8b..0126199 100644
--- a/core/api/system-current.txt
+++ b/core/api/system-current.txt
@@ -5956,7 +5956,7 @@
     method public int getEphemerisSource();
     method @FloatRange public double getIonoDelayMeters();
     method @IntRange(from=0, to=1023) public int getIssueOfDataClock();
-    method @IntRange(from=0, to=255) public int getIssueOfDataEphemeris();
+    method @IntRange(from=0, to=1023) public int getIssueOfDataEphemeris();
     method @Nullable public android.location.SatellitePvt.PositionEcef getPositionEcef();
     method @IntRange(from=0) public long getTimeOfClockSeconds();
     method @IntRange(from=0) public long getTimeOfEphemerisSeconds();
@@ -5984,7 +5984,7 @@
     method @NonNull public android.location.SatellitePvt.Builder setEphemerisSource(int);
     method @NonNull public android.location.SatellitePvt.Builder setIonoDelayMeters(@FloatRange(from=0.0f, to=100.0f) double);
     method @NonNull public android.location.SatellitePvt.Builder setIssueOfDataClock(@IntRange(from=0, to=1023) int);
-    method @NonNull public android.location.SatellitePvt.Builder setIssueOfDataEphemeris(@IntRange(from=0, to=255) int);
+    method @NonNull public android.location.SatellitePvt.Builder setIssueOfDataEphemeris(@IntRange(from=0, to=1023) int);
     method @NonNull public android.location.SatellitePvt.Builder setPositionEcef(@NonNull android.location.SatellitePvt.PositionEcef);
     method @NonNull public android.location.SatellitePvt.Builder setTimeOfClockSeconds(@IntRange(from=0) long);
     method @NonNull public android.location.SatellitePvt.Builder setTimeOfEphemerisSeconds(@IntRange(from=0) long);
diff --git a/core/java/android/app/ActivityThread.java b/core/java/android/app/ActivityThread.java
index ae8809d..bbcf138 100644
--- a/core/java/android/app/ActivityThread.java
+++ b/core/java/android/app/ActivityThread.java
@@ -7836,7 +7836,7 @@
                         Files.move(new File(oldPath).toPath(), new File(newPath).toPath(),
                                 StandardCopyOption.REPLACE_EXISTING);
                     } catch (IOException e2) {
-                        Log.e(TAG, "Rename recovery failed ", e);
+                        Log.e(TAG, "Rename recovery failed ", e2);
                         throw e;
                     }
                 } else {
diff --git a/core/java/android/ddm/OWNERS b/core/java/android/ddm/OWNERS
new file mode 100644
index 0000000..369025b
--- /dev/null
+++ b/core/java/android/ddm/OWNERS
@@ -0,0 +1 @@
+per-file DdmHandleViewDebug.java = michschn@google.com
diff --git a/core/java/com/android/internal/os/Zygote.java b/core/java/com/android/internal/os/Zygote.java
index b1e7d15..ea5f0b2 100644
--- a/core/java/com/android/internal/os/Zygote.java
+++ b/core/java/com/android/internal/os/Zygote.java
@@ -1001,16 +1001,24 @@
     }
 
     /**
+     * This will enable jdwp by default for all apps. It is OK to cache this property
+     * because we expect to reboot the system whenever this property changes
+     */
+    private static final boolean ENABLE_JDWP = SystemProperties.get(
+                          "persist.debuggable.dalvik.vm.jdwp.enabled").equals("1");
+
+    /**
      * Applies debugger system properties to the zygote arguments.
      *
-     * If "ro.debuggable" is "1", all apps are debuggable. Otherwise,
-     * the debugger state is specified via the "--enable-jdwp" flag
-     * in the spawn request.
+     * For eng builds all apps are debuggable. On userdebug and user builds
+     * if persist.debuggable.dalvik.vm.jdwp.enabled is 1 all apps are
+     * debuggable. Otherwise, the debugger state is specified via the
+     * "--enable-jdwp" flag in the spawn request.
      *
      * @param args non-null; zygote spawner args
      */
     static void applyDebuggerSystemProperty(ZygoteArguments args) {
-        if (RoSystemProperties.DEBUGGABLE) {
+        if (Build.IS_ENG || ENABLE_JDWP) {
             args.mRuntimeFlags |= Zygote.DEBUG_ENABLE_JDWP;
         }
     }
diff --git a/core/res/OWNERS b/core/res/OWNERS
index c54638a..d8fc218 100644
--- a/core/res/OWNERS
+++ b/core/res/OWNERS
@@ -37,7 +37,7 @@
 per-file res/values/dimens_car.xml = file:/platform/packages/services/Car:/OWNERS
 
 # Wear
-per-file res/*-watch/* = file:/platform/frameworks/opt/wear:/OWNERS
+per-file res/*-watch/* = file:/WEAR_OWNERS
 
 # PowerProfile
 per-file res/xml/power_profile.xml = file:/BATTERY_STATS_OWNERS
diff --git a/core/tests/coretests/src/android/ddm/OWNERS b/core/tests/coretests/src/android/ddm/OWNERS
new file mode 100644
index 0000000..c8be191
--- /dev/null
+++ b/core/tests/coretests/src/android/ddm/OWNERS
@@ -0,0 +1 @@
+michschn@google.com
diff --git a/location/java/android/location/SatellitePvt.java b/location/java/android/location/SatellitePvt.java
index f3e1508..2031929 100644
--- a/location/java/android/location/SatellitePvt.java
+++ b/location/java/android/location/SatellitePvt.java
@@ -539,7 +539,7 @@
      *
      * <p>This field is valid if {@link #hasIssueOfDataEphemeris()} is true.
      */
-    @IntRange(from = 0, to = 255)
+    @IntRange(from = 0, to = 1023)
     public int getIssueOfDataEphemeris() {
         return mIssueOfDataEphemeris;
     }
@@ -847,8 +847,8 @@
          */
         @NonNull
         public Builder setIssueOfDataEphemeris(
-                @IntRange(from = 0, to = 255) int issueOfDataEphemeris) {
-            Preconditions.checkArgumentInRange(issueOfDataEphemeris, 0, 255,
+                @IntRange(from = 0, to = 1023) int issueOfDataEphemeris) {
+            Preconditions.checkArgumentInRange(issueOfDataEphemeris, 0, 1023,
                     "issueOfDataEphemeris");
             mIssueOfDataEphemeris = issueOfDataEphemeris;
             mFlags = (byte) (mFlags | HAS_ISSUE_OF_DATA_EPHEMERIS);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelViewController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelViewController.java
index 82ca842..5d417e0 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelViewController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelViewController.java
@@ -599,9 +599,7 @@
             float collapseSpeedUpFactor, boolean expandBecauseOfFalsing) {
         if (target == mExpandedHeight && mOverExpansion == 0.0f) {
             // We're at the target and didn't fling and there's no overshoot
-            endJankMonitoring(CUJ_NOTIFICATION_SHADE_EXPAND_COLLAPSE);
-            mKeyguardStateController.notifyPanelFlingEnd();
-            notifyExpandingFinished();
+            onFlingEnd(false /* cancelled */);
             return;
         }
         mIsFlinging = true;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationPanelViewControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationPanelViewControllerTest.java
index d47644f..8900d8f 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationPanelViewControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationPanelViewControllerTest.java
@@ -986,6 +986,21 @@
     }
 
     @Test
+    public void testSwipe_exactlyToTarget_notifiesNssl() {
+        // No over-expansion
+        mNotificationPanelViewController.setOverExpansion(0f);
+        // Fling to a target that is equal to the current position (i.e. a no-op fling).
+        mNotificationPanelViewController.flingToHeight(
+                0f,
+                true,
+                mNotificationPanelViewController.mExpandedHeight,
+                1f,
+                false);
+        // Verify that the NSSL is notified that the panel is *not* flinging.
+        verify(mNotificationStackScrollLayoutController).setPanelFlinging(false);
+    }
+
+    @Test
     public void testDoubleTapRequired_Keyguard() {
         FalsingManager.FalsingTapListener listener = getFalsingTapListener();
         mStatusBarStateController.setState(KEYGUARD);
diff --git a/services/appprediction/java/com/android/server/appprediction/AppPredictionPerUserService.java b/services/appprediction/java/com/android/server/appprediction/AppPredictionPerUserService.java
index 1af8ad3..84707a8 100644
--- a/services/appprediction/java/com/android/server/appprediction/AppPredictionPerUserService.java
+++ b/services/appprediction/java/com/android/server/appprediction/AppPredictionPerUserService.java
@@ -398,18 +398,7 @@
         final IBinder.DeathRecipient mDeathRecipient;
 
         private final RemoteCallbackList<IPredictionCallback> mCallbacks =
-                new RemoteCallbackList<IPredictionCallback>() {
-                    @Override
-                    public void onCallbackDied(IPredictionCallback callback) {
-                        if (DEBUG) {
-                            Slog.d(TAG, "Binder died for session Id=" + mSessionId
-                                    + " and callback=" + callback.asBinder());
-                        }
-                        if (mCallbacks.getRegisteredCallbackCount() == 0) {
-                            destroy();
-                        }
-                    }
-                };
+                new RemoteCallbackList<>();
 
         AppPredictionSessionInfo(
                 @NonNull final AppPredictionSessionId id,
diff --git a/services/core/java/com/android/server/audio/AudioService.java b/services/core/java/com/android/server/audio/AudioService.java
index a51b187..56874f7 100644
--- a/services/core/java/com/android/server/audio/AudioService.java
+++ b/services/core/java/com/android/server/audio/AudioService.java
@@ -1517,6 +1517,7 @@
         }
 
         synchronized (mAudioPolicies) {
+            ArrayList<AudioPolicyProxy> invalidProxies = new ArrayList<>();
             for (AudioPolicyProxy policy : mAudioPolicies.values()) {
                 final int status = policy.connectMixes();
                 if (status != AudioSystem.SUCCESS) {
@@ -1524,7 +1525,7 @@
                     Log.e(TAG, "onAudioServerDied: error "
                             + AudioSystem.audioSystemErrorToString(status)
                             + " when connecting mixes for policy " + policy.toLogFriendlyString());
-                    policy.release();
+                    invalidProxies.add(policy);
                 } else {
                     final int deviceAffinitiesStatus = policy.setupDeviceAffinities();
                     if (deviceAffinitiesStatus != AudioSystem.SUCCESS) {
@@ -1532,10 +1533,12 @@
                                 + AudioSystem.audioSystemErrorToString(deviceAffinitiesStatus)
                                 + " when connecting device affinities for policy "
                                 + policy.toLogFriendlyString());
-                        policy.release();
+                        invalidProxies.add(policy);
                     }
                 }
             }
+            invalidProxies.forEach((policy) -> policy.release());
+
         }
 
         // Restore capture policies
diff --git a/services/core/java/com/android/server/connectivity/Vpn.java b/services/core/java/com/android/server/connectivity/Vpn.java
index 9cb1f1d..431be88 100644
--- a/services/core/java/com/android/server/connectivity/Vpn.java
+++ b/services/core/java/com/android/server/connectivity/Vpn.java
@@ -1198,7 +1198,7 @@
                 mContext.unbindService(mConnection);
                 cleanupVpnStateLocked();
             } else if (mVpnRunner != null) {
-                stopVpnRunnerAndNotifyAppLocked(mPackage);
+                stopVpnRunnerAndNotifyAppLocked();
             }
 
             try {
@@ -4061,7 +4061,7 @@
     }
 
     @GuardedBy("this")
-    private void stopVpnRunnerAndNotifyAppLocked(@NonNull String packageName) {
+    private void stopVpnRunnerAndNotifyAppLocked() {
         // Build intent first because the sessionKey will be reset after performing
         // VpnRunner.exit(). Also, cache mOwnerUID even if ownerUID will not be changed in
         // VpnRunner.exit() to prevent design being changed in the future.
@@ -4069,17 +4069,17 @@
         //  ConnectivityServiceTest.
         final int ownerUid = mOwnerUID;
         Intent intent = null;
-        if (SdkLevel.isAtLeastT() && isVpnApp(packageName)) {
+        if (SdkLevel.isAtLeastT() && isVpnApp(mPackage)) {
             intent = buildVpnManagerEventIntent(
                     VpnManager.CATEGORY_EVENT_DEACTIVATED_BY_USER,
-                    -1 /* errorClass */, -1 /* errorCode*/, packageName,
+                    -1 /* errorClass */, -1 /* errorCode*/, mPackage,
                     getSessionKeyLocked(), makeVpnProfileStateLocked(),
                     null /* underlyingNetwork */, null /* nc */, null /* lp */);
         }
         // cleanupVpnStateLocked() is called from mVpnRunner.exit()
         mVpnRunner.exit();
-        if (intent != null && isVpnApp(packageName)) {
-            notifyVpnManagerVpnStopped(packageName, ownerUid, intent);
+        if (intent != null && isVpnApp(mPackage)) {
+            notifyVpnManagerVpnStopped(mPackage, ownerUid, intent);
         }
     }
 
@@ -4099,7 +4099,7 @@
         // To stop the VPN profile, the caller must be the current prepared package and must be
         // running an Ikev2VpnProfile.
         if (isCurrentIkev2VpnLocked(packageName)) {
-            stopVpnRunnerAndNotifyAppLocked(packageName);
+            stopVpnRunnerAndNotifyAppLocked();
         }
     }
 
diff --git a/services/core/java/com/android/server/pm/AppsFilterBase.java b/services/core/java/com/android/server/pm/AppsFilterBase.java
index 7ca1978..5de7674 100644
--- a/services/core/java/com/android/server/pm/AppsFilterBase.java
+++ b/services/core/java/com/android/server/pm/AppsFilterBase.java
@@ -323,7 +323,8 @@
                 return false;
             } else if (Process.isSdkSandboxUid(callingAppId)) {
                 // we only allow sdk sandbox processes access to forcequeryable packages
-                return !isForceQueryable(targetPkgSetting.getAppId());
+                return !isForceQueryable(targetPkgSetting.getAppId())
+                      && !isImplicitlyQueryable(callingAppId, targetPkgSetting.getAppId());
             }
             if (mCacheReady) { // use cache
                 if (!shouldFilterApplicationUsingCache(callingUid,
diff --git a/services/core/java/com/android/server/pm/InstallPackageHelper.java b/services/core/java/com/android/server/pm/InstallPackageHelper.java
index e90a5db..7da5f51 100644
--- a/services/core/java/com/android/server/pm/InstallPackageHelper.java
+++ b/services/core/java/com/android/server/pm/InstallPackageHelper.java
@@ -3701,8 +3701,9 @@
                     parsedPackage.getPackageName());
 
             boolean ignoreSharedUserId = false;
-            if (installedPkgSetting == null) {
-                // We can directly ignore sharedUserSetting for new installs
+            if (installedPkgSetting == null || !installedPkgSetting.hasSharedUser()) {
+                // Directly ignore sharedUserSetting for new installs, or if the app has
+                // already left shared UID
                 ignoreSharedUserId = parsedPackage.isLeavingSharedUid();
             }
 
diff --git a/services/core/java/com/android/server/pm/pkg/component/ParsedPermissionUtils.java b/services/core/java/com/android/server/pm/pkg/component/ParsedPermissionUtils.java
index 281e1bd..1366de7 100644
--- a/services/core/java/com/android/server/pm/pkg/component/ParsedPermissionUtils.java
+++ b/services/core/java/com/android/server/pm/pkg/component/ParsedPermissionUtils.java
@@ -313,8 +313,7 @@
                 final ParsedPermission perm = checkDuplicatePerm.get(name);
                 if (isMalformedDuplicate(parsedPermission, perm)) {
                     // Fix for b/213323615
-                    EventLog.writeEvent(0x534e4554, "213323615",
-                            "The package " + pkg.getPackageName() + " seems malicious");
+                    EventLog.writeEvent(0x534e4554, "213323615");
                     return true;
                 }
                 checkDuplicatePerm.put(name, parsedPermission);
diff --git a/services/core/java/com/android/server/wm/Session.java b/services/core/java/com/android/server/wm/Session.java
index 30b5083..c5f21eb 100644
--- a/services/core/java/com/android/server/wm/Session.java
+++ b/services/core/java/com/android/server/wm/Session.java
@@ -322,7 +322,7 @@
         final int callingPid = Binder.getCallingPid();
         // Validate and resolve ClipDescription data before clearing the calling identity
         validateAndResolveDragMimeTypeExtras(data, callingUid, callingPid, mPackageName);
-        validateDragFlags(flags, callingUid);
+        validateDragFlags(flags);
         final long ident = Binder.clearCallingIdentity();
         try {
             return mDragDropController.performDrag(mPid, mUid, window, flags, surface, touchSource,
@@ -347,11 +347,7 @@
      * Validates the given drag flags.
      */
     @VisibleForTesting
-    void validateDragFlags(int flags, int callingUid) {
-        if (callingUid == Process.SYSTEM_UID) {
-            throw new IllegalStateException("Need to validate before calling identify is cleared");
-        }
-
+    void validateDragFlags(int flags) {
         if ((flags & View.DRAG_FLAG_REQUEST_SURFACE_FOR_RETURN_ANIMATION) != 0) {
             if (!mCanStartTasksFromRecents) {
                 throw new SecurityException("Requires START_TASKS_FROM_RECENTS permission");
@@ -365,9 +361,6 @@
     @VisibleForTesting
     void validateAndResolveDragMimeTypeExtras(ClipData data, int callingUid, int callingPid,
             String callingPackage) {
-        if (callingUid == Process.SYSTEM_UID) {
-            throw new IllegalStateException("Need to validate before calling identify is cleared");
-        }
         final ClipDescription desc = data != null ? data.getDescription() : null;
         if (desc == null) {
             return;
diff --git a/services/smartspace/java/com/android/server/smartspace/SmartspacePerUserService.java b/services/smartspace/java/com/android/server/smartspace/SmartspacePerUserService.java
index dcffc9e..f041fbd 100644
--- a/services/smartspace/java/com/android/server/smartspace/SmartspacePerUserService.java
+++ b/services/smartspace/java/com/android/server/smartspace/SmartspacePerUserService.java
@@ -334,18 +334,7 @@
         @NonNull
         private final SmartspaceConfig mSmartspaceConfig;
         private final RemoteCallbackList<ISmartspaceCallback> mCallbacks =
-                new RemoteCallbackList<ISmartspaceCallback>() {
-                    @Override
-                    public void onCallbackDied(ISmartspaceCallback callback) {
-                        if (DEBUG) {
-                            Slog.d(TAG, "Binder died for session Id=" + mSessionId
-                                    + " and callback=" + callback.asBinder());
-                        }
-                        if (mCallbacks.getRegisteredCallbackCount() == 0) {
-                            destroy();
-                        }
-                    }
-                };
+                new RemoteCallbackList<>();
 
         SmartspaceSessionInfo(
                 @NonNull final SmartspaceSessionId id,
diff --git a/services/tests/servicestests/src/com/android/server/pm/AppsFilterImplTest.java b/services/tests/servicestests/src/com/android/server/pm/AppsFilterImplTest.java
index facbe80..92443c5 100644
--- a/services/tests/servicestests/src/com/android/server/pm/AppsFilterImplTest.java
+++ b/services/tests/servicestests/src/com/android/server/pm/AppsFilterImplTest.java
@@ -1376,6 +1376,39 @@
                         null /* callingSetting */, target, SYSTEM_USER));
     }
 
+    @Test
+    public void testSdkSandbox_implicitAccessGranted_canSeePackage() throws Exception {
+        final AppsFilterImpl appsFilter =
+                new AppsFilterImpl(mFeatureConfigMock, new String[]{}, false, null,
+                        mMockHandler);
+        final WatchableTester watcher = new WatchableTester(appsFilter, "onChange");
+        watcher.register();
+        simulateAddBasicAndroid(appsFilter);
+        watcher.verifyChangeReported("addBasic");
+        appsFilter.onSystemReady(mPmInternal);
+        watcher.verifyChangeReported("systemReady");
+
+        PackageSetting target = simulateAddPackage(appsFilter,
+                pkg("com.some.package"), DUMMY_TARGET_APPID,
+                setting -> setting.setPkgFlags(ApplicationInfo.FLAG_SYSTEM));
+
+        int callingUid = 20123;
+        assertTrue(Process.isSdkSandboxUid(callingUid));
+
+        // Without granting the implicit access the app shouldn't be visible to the sdk sandbox uid.
+        assertTrue(
+                appsFilter.shouldFilterApplication(mSnapshot, callingUid,
+                        null /* callingSetting */, target, SYSTEM_USER));
+
+        appsFilter.grantImplicitAccess(callingUid, target.getAppId(), false /* retainOnUpdate */);
+        watcher.verifyChangeReported("grantImplicitAccess");
+
+        // After implicit access was granted the app should be visible to the sdk sandbox uid.
+        assertFalse(
+                appsFilter.shouldFilterApplication(mSnapshot, callingUid,
+                        null /* callingSetting */, target, SYSTEM_USER));
+    }
+
     private List<Integer> toList(int[] array) {
         ArrayList<Integer> ret = new ArrayList<>(array.length);
         for (int i = 0; i < array.length; i++) {
diff --git a/services/tests/wmtests/src/com/android/server/wm/DragDropControllerTests.java b/services/tests/wmtests/src/com/android/server/wm/DragDropControllerTests.java
index 28fc352..4526d18 100644
--- a/services/tests/wmtests/src/com/android/server/wm/DragDropControllerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/DragDropControllerTests.java
@@ -467,8 +467,7 @@
             public void onAnimatorScaleChanged(float scale) {}
         });
         try {
-            session.validateDragFlags(View.DRAG_FLAG_REQUEST_SURFACE_FOR_RETURN_ANIMATION,
-                    TEST_UID);
+            session.validateDragFlags(View.DRAG_FLAG_REQUEST_SURFACE_FOR_RETURN_ANIMATION);
             fail("Expected failure without permission");
         } catch (SecurityException e) {
             // Expected failure
@@ -484,8 +483,7 @@
             public void onAnimatorScaleChanged(float scale) {}
         });
         try {
-            session.validateDragFlags(View.DRAG_FLAG_REQUEST_SURFACE_FOR_RETURN_ANIMATION,
-                    TEST_UID);
+            session.validateDragFlags(View.DRAG_FLAG_REQUEST_SURFACE_FOR_RETURN_ANIMATION);
             // Expected pass
         } catch (SecurityException e) {
             fail("Expected no failure with permission");
diff --git a/tools/codegen/BUILD.bazel b/tools/codegen/BUILD.bazel
new file mode 100644
index 0000000..c14046d
--- /dev/null
+++ b/tools/codegen/BUILD.bazel
@@ -0,0 +1,21 @@
+# TODO(b/245731902): auto-generate these with bp2build.
+load("@rules_kotlin//kotlin:jvm_library.bzl", "kt_jvm_library")
+
+java_binary(
+    name = "codegen_cli",
+    main_class = "com.android.codegen.MainKt",
+    runtime_deps = [
+        ":codegen_cli_kt_lib",
+    ],
+)
+
+kt_jvm_library(
+    name = "codegen_cli_kt_lib",
+    srcs = glob(["src/**/*.kt"]),
+    deps = ["//external/javaparser"],
+)
+
+kt_jvm_library(
+    name = "codegen-version-info",
+    srcs = glob(["src/**/SharedConstants.kt"]),
+)