Skip to content

Commit 617f1aa

Browse files
committed
Merge tag 'android-security-11.0.0_r49' into staging/lineage-18.1_merge-android-security-11.0.0_r49
Android security 11.0.0 release 49 * tag 'android-security-11.0.0_r49': Changed INTERACT_ACROSS_PROFILES appop to be set per UID TIF: fix issue of using caller-aware methods after clearCallingIdentity() Backporting the change of ag/15629060 to rvc-dev Bluetooth: Fix formatting in getAlias() Fix parsing code parcelling errors camera2: Fix exception swallowing in params classes createFromParcel Revert "BG-FGS-start while-in-use permission restriction improve..." Make sure that only the owner can call stopVpnProfile() DO NOT MERGE Apply a maximum char count to the load label api Send targeted broadcasts to prevent other apps from receiving them. Guard DISABLE_PLUGIN with PLUGIN permission. Fix a potential thread safety issue in VectorDrawable Fix background bypass via notifications Change ownership of the account request notification. Revert "wifidisplay: restrict broadcast by the proper permission" Use IntentFilter CREATOR directly for serializing ParsedIntentInfo Don't export HeapDumpProvider. Don't attach private Notification to A11yEvent when user locked Avoid locking profile task when it is already lock Improve ellipsize performance Fix side effects of trace-ipc and dumpheap commands DO NOT MERGE Add cross-user check for getDefaultSmsPackage(). BG-FGS-start while-in-use permission restriction improvement. Remove ParsedIntentInfo CREATOR Fix race condition between lockNow() and updateLockscreenTimeout [security] SubscriptionGroup is exposed to unprivileged callers Block SAF directory access to /sdcard/Android [RESTRICT AUTOMERGE] Fix OOB write in noteAtomLogged Remove sendNetworkConditionsBroadcast Ensure storage permission revoke happens for all users Restrict alarm broadcast Detects all activities for whether showing work challenge DO NOT MERGE - Disallow deletion of channels with FGS notifications Increase maximum allowed size for status bar icons [DO NOT MERGE] Make PendingIntents in screenshots immutable wifidisplay: restrict broadcast by the proper permission Fix legacy APIs when VPN switches to suspended underlying network. Backport test coverage from aosp/1547496. Backport some helpers in ConnectivityServiceTest. Test for bugs with suspended VPN underlying networks. Add a test for getDefaultNetworkCapabilitiesForUser. Improve testing of CONNECTIVITY_ACTION broadcasts. Test passing an underlying network array with null network in it. Make testVpnNetworkActive more deterministic. Make MockVpn more realistic and easier to use. Increase test coverage for VPN info sent to NetworkStatsService. Simplify MockVpn. Test a VPN with an underlying network that does not yet exist. Limit maximum allowed size for a status bar icon Adds caller check to getAllPackages() Restrict the overridden min size for PiP Add pkg target to snoozing alarm Allow empty tokens in strict grammar Allow empty tokens in strict grammar [DO NOT MERGE] Make screenshot error notification PendingIntent immutable DO NOT MERGE: Associate notif cancels with notif posts [RESTRICT AUTOMERGE] Use userId instead of USER_CURRENT in shouldLockKeyguard. Revoke storage on SDK downgrade or new full storage request [DO NOT MERGE] Close screenshot process on user switched Fix thread safety issue on clearing cache [SettingsProvider] extend font size scale range DO NOT MERGE: Do not inject mock location to chipset [RESTRICT AUTOMERGE] Fix potential out of bounds writes in LogEvent. Check mode/boost index before accessing cached support value Only update native InputApplicationHandle once Allow CDM to hide overlays Prevent non-system overlays from showing over CDM UI RESTRICT AUTOMERGE: Set mAllowWhileInUsePermissionInFgs correctly when bindService() from background. Protect account chooser activities against overlay. [SettingsProvider] fix font size scale validator Ensure caller identity is restored in CP quick-path. Remove updateIntentVerificationStatusAsUser from ResolverActivity Revoke the uri permission when the file is deleted Ignore GrantCredentials call with unexpected calling uid. Protect GrantCredentialsPermissionActivity against overlay. Revoke permission on non-runtime -> runtime upgrade Ensure permissions are revoked on state changes Hide overlays over uninstall confirm dialog RESTRICT AUTOMERGE Fix CDM package check remove sensitive pii from safetynet logging Revoke install permissions when the permission defining app is uninstalled. DO NOT MERGE Check fingerprint client against top activity in auth callback Fix the issue provider can be wrong when requesting slice permission Enforce permission checks in getting app exit reasons Fix storing the wrong value of mLockdown in setting [BACKPORT] Improve location checks in TelephonyRegistry Do not re-initialize synthetic password Fix VrDisplayTest failure Require permission to create trusted displays Accept repeated locale as an input of LocaleList construction. Sanitize more of the notification text fields DO NOT MERGE Fix NPE in executeDeletePackageLIF. DO NOT MERGE Don't allow non-instant permissions for instant apps. Mark implicit PendingIntents as immutable Add missing isShellUser check Decouple FUSE mount from main thread for demo user Set the NetworkInfo subtype to 0. Reduce demo user FUSE volume mount timeout Propagate AudioAttributes flags to VibrationAttributes Allow network stack UID caller to retrieve cell identity Ignore GONE views in shade when processing sections Fix unintended preferred activity reset Skip bg PSS collection for apps using a camera Fix missing IME switcher icon (w/ a hardware keyboard) Java docs update: Advise not to include PII in setProcessStateSummary Grant visibility even when not granting URI perm Fix NavigationBarColorTest Prevent exception when surrounding text retrieval Resume-on-Reboot: remove special string Wait for remote animation to stop freezing display Remove incorrect optimization in visibility cache Early exit when target app ID < FIRST_APP_UID Fixes broadcast filtering for multi-user sys apps Repopulate cache with sibling visibility on remove Revert "Hide bubbles' IME after screenshot is taken." Ensure we always bind to overview service when starting up Fix missing icon for one-to-one convos Fix missing icon for one-to-one convos Revert "Exception if receive move withouth down" Revert "Consolidating MODIFY_AUDIO_SETTINGS permission checks" Revert "Flip ENABLE_DYNAMIC_PERMISSIONS, attempt #5." Revert "Flip ENABLE_DYNAMIC_PERMISSIONS, attempt #4." Revert "Flip ENABLE_DYNAMIC_PERMISSIONS." Revert "Flip ENABLE_DYNAMIC_PERMISSIONS." Revert "System Bars animation for fixed rotation transform" Revert "Don't readd pending notifs to NEM's allNotifs list" Fixed a bug where the brighness mirror would make everything invisible Fix crash caused by unhandled bucket Adding UiModeManager Custom Tests Revert "Fix missing animation when launch activity from notification." Revert "Prevent NPE in PulseExpansionHandler" Revert "Fix missing animation when launch activity from notification." Revert "Prevent NPE in PulseExpansionHandler" Revert "Fix missing animation when launch activity from notification." Check URI is valid for loading images Add READ_PHONE_STATE back to pregranted phone permissions Add delay between quota check alarms. Add READ_PHONE_STATE back to pregranted phone permissions Add READ_PHONE_STATE back to pregranted phone permissions Fix Ime consumer isRequestedVisible Disable overflow menu on lock screen. Ensure power menu overflow dismissed when dialog dismissed. Fix NPE when ranking update causes reinflation Only give DisplayInsetsController control over IME in split-screen Re-send the IME control after IME is re-created Update destination bounds if rotation finishes first Reboot the soundtrigger HAL on failure Add /apex to the list of allowed SystemServer paths Revert "Fix exception handling in getState() binder cache" Only use the IME target from IMMS to update the IME control target WindowInsetsAnimation: Fix app driven closing of IME WindowInsetsAnimation: Synchronously dispatch window insets animation callbacks WindowInsets: Ignore consumeStableInsets() Request fit system windows if soft input mode updates Update insets state for each window if its mBehindIme is changed Fixes NPE and adds @nullable to PackageSetting.pkg startop: Fix a string format bug in EventSequenceValidator. Work around for display info mismatch during the PiP transition Work around for display info mismatch during the PiP transition Give tethering bluetooth privilege permission Make canBeImeTarget be compatible with legacy behavior Give tethering bluetooth privilege permission Revert "Don't override activity display adjustments with app config" Make canBeImeTarget be compatible with legacy behavior fix enrollment application permission check add KEYPHRASE_ENROLLMENT_APPLICATION permission Make canBeImeTarget be compatible with legacy behavior Fixes query logic when not instant Fixes query logic when not instant Make canBeImeTarget be compatible with legacy behavior Call setAdapter from handleLayoutChanged. Use BIND_INCLUDE_CAPABILITIES for SoundTriggerService Assign a BluetoothAdapter on creation of LMM Use the bounds received in taskAppeared Assign a BluetoothAdapter on creation of LMM Revert "Do not block autofill on waiting for the IME response" Revert "Fix bouncer race condition" Null-check notif chan when ident people notifs Don't apply ime adjustments/dims if split is not active Restores PiP to its original app bounds Revert "media: lazy MediaCodec.release()" Some clean-up of divider code in preparation for bugfixes Revert "Some clean-up of divider code in preparation for bugfixes" Revert "Don't apply ime adjustments/dims if split is not active" Don't apply ime adjustments/dims if split is not active Some clean-up of divider code in preparation for bugfixes Revert "media: lazy MediaCodec.release()" InsetController: Release leashes from RenderThread Fix instances of ContentObserver#onChange in SystemUI Adjust users of hidden APIs. Revert "Turn on QS media player by default" Dark theme upgrade broken Change animation-leash to be a container layer Dark theme upgrade broken Reset controls when playback state is NONE Relax permission checks in sound trigger middleware Revert "Turn on QS media player by default" Dark theme not working bug Dark theme not working bug Revert "Fix permission check for get/setSmscAddress." Ignore unchecked IME show/hide when no root Initialize PackageManagerService ApplicationInfo instances to system user Ensures display rotation triggers PiP re-position DO NOT MERGE: Fix FLAG_NOT_FOCUSABLE ime target Revert "Avoid creating new instance on top when started for resu..." Don't crash if NSSL gets incomplete gesture DO NOT MERGE: Fix FLAG_NOT_FOCUSABLE ime target Revert "Avoid creating new instance on top when started for resu..." Don't crash if NSSL gets incomplete gesture Revert "Avoid creating new instance on top when started for resu..." Don't crash if NSSL gets incomplete gesture Fix PackageSetting isUpdatedSystemApp and SYSTEM_EXT rescan Revert "Avoid creating new instance on top when started for resu..." Do not attempt to special case uncompressed font assets. Fix crash during SysUI dumpsys Re-add compile_multilib to statsd apex Revert "Limit metricslogger call into statsdw for events" Revert "Remove libstats_jni from the platform" Revert "Move libstatspull to the apex" Revert "Require user pass in a non-null BluetoothDevice to all B..." Fail silently on MediaScannerConnection#onScanCompleted Revert "Prevents an NPE when content provider is slow to start" Fix content views not updating Fix content views not updating Fix the NPE when reading the call log or SMS if a device has multiple user profiles Fix Keyboard won't display when RemoteInput active Revert "Add permissions for using PlatformCompat methods" Revert "API for Inline Presentation Renderer in ExtServices." Fixup SDCARD_RW GID for multi-user. Revert "Move text toast creation to system UI" MediaSessionRecord: fix volume stream query Always set NetworkInfo objects to available. Fix emergency button overlap with nav bar Revert "Convert NotificationContentInflater to singleton" Revert "Move a bunch of row setters into an init method." Remove resource overlayable configuration AudioService: log result of AudioSystem calls for A2DP devices AudioService: fix A2DP disconnection / reconnection AudioService: fix A2DP disconnection / reconnection Revert "Rmove @UnsupportedAppUsage" Revert "Merge "switch to new SkPathDirection enum"" RecoverySystem: do not check if socket is closed Fix swiping down on the notch. Add synchronization for PermissionData. Revert "Replace framework-annotation-proc java lib with framework-all" Freeup lock when IME is set inactive and unbound Revert submission Revert "Clean up visibility related flags in ActivityRecord" Revert "Clean up visibility related flags in WindowToken" Revert "Clean up visibility related flags in ActivityRecord" Call appOps changed from main thread Revert "Create unit tests for GnssManagerService" Initialize AppCompatCallbacks in system server Prevent crash when invoking GNSS apis Return resume result in resumeFocusedStacksTopActivities Prevent crash when invoking GNSS apis Return resume result in resumeFocusedStacksTopActivities Return resume result in resumeFocusedStacksTopActivities Revert "Move DozeServiceHost out of StatusBar." Ensure next home activity is ready before finish FallbackHome Temporarily do not remove biometric view when animating to credential Revert "Move DozeServiceHost out of StatusBar." Ensure next home activity is ready before finish FallbackHome Mark BiometricUnlockController as @singleton Add userId to the package name API. Revert "Example for disabling changes at test time" Revert "Drop all caches in UI_HIDDEN" Make KeyguardUpdateMonitor a singleton Ensure that view is initialized properlly upon inflation. Revert "Remove many (most) of the calls to Dependency.get() from StatusBar." Fix NavigationBarController NPE Fix NavigationBarController NPE SurfaceView: Release Surfaces where SurfaceControl are released. Breaks isInstantApp into public and internal Clears calling identity when calling isInstantApp Workaround multiple instance of AppComponentFactory. Ensure that the Application is constructed before any Service. Remove KeyguardUpdateMonitor.getInstance(). Fixes regression caused by ag/9259064 Fix regression in updating gesture exclusion rects Fix regression in updating gesture exclusion rects Fix regression in updating gesture exclusion rects Fix regression in updating gesture exclusion rects Clear calling identity as broadcast needs permission WifiManager: Return dummy values when wifi service is not up Adding null checks Revert SurfaceView back to Q's version Revert "Use the SubId in the TM.getNetworkType if Valid" Retire unused android::nio_{get,release}Buffer functions Skip idmap1 generation if target defines overlayable Ensure all fields of AutoBufferPointer are initialized Change-Id: I4838416fa76f01643eccb8c6689c10499f5862d4
2 parents f24635e + 3947290 commit 617f1aa

15 files changed

Lines changed: 112 additions & 169 deletions

File tree

core/java/android/bluetooth/BluetoothDevice.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1230,7 +1230,10 @@ public String getAlias() {
12301230
if (alias == null) {
12311231
return getName();
12321232
}
1233-
return alias;
1233+
return alias
1234+
.replace('\t', ' ')
1235+
.replace('\n', ' ')
1236+
.replace('\r', ' ');
12341237
} catch (RemoteException e) {
12351238
Log.e(TAG, "", e);
12361239
}

core/java/android/content/pm/parsing/ParsingPackageImpl.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1007,7 +1007,7 @@ public void writeToParcel(Parcel dest, int flags) {
10071007
sForInternedStringList.parcel(this.requestedPermissions, dest, flags);
10081008
sForInternedStringList.parcel(this.implicitPermissions, dest, flags);
10091009
sForStringSet.parcel(this.upgradeKeySets, dest, flags);
1010-
dest.writeMap(this.keySetMapping);
1010+
ParsingPackageUtils.writeKeySetMapping(dest, this.keySetMapping);
10111011
sForInternedStringList.parcel(this.protectedBroadcasts, dest, flags);
10121012
dest.writeTypedList(this.activities);
10131013
dest.writeTypedList(this.receivers);
@@ -1026,7 +1026,7 @@ public void writeToParcel(Parcel dest, int flags) {
10261026
dest.writeBoolean(this.use32BitAbi);
10271027
dest.writeBoolean(this.visibleToInstantApps);
10281028
dest.writeBoolean(this.forceQueryable);
1029-
dest.writeParcelableList(this.queriesIntents, flags);
1029+
dest.writeTypedList(this.queriesIntents, flags);
10301030
sForInternedStringList.parcel(this.queriesPackages, dest, flags);
10311031
sForInternedStringSet.parcel(this.queriesProviders, dest, flags);
10321032
dest.writeString(this.appComponentFactory);
@@ -1169,7 +1169,7 @@ public ParsingPackageImpl(Parcel in) {
11691169
this.requestedPermissions = sForInternedStringList.unparcel(in);
11701170
this.implicitPermissions = sForInternedStringList.unparcel(in);
11711171
this.upgradeKeySets = sForStringSet.unparcel(in);
1172-
this.keySetMapping = in.readHashMap(boot);
1172+
this.keySetMapping = ParsingPackageUtils.readKeySetMapping(in);
11731173
this.protectedBroadcasts = sForInternedStringList.unparcel(in);
11741174

11751175
this.activities = in.createTypedArrayList(ParsedActivity.CREATOR);

core/java/android/content/pm/parsing/ParsingPackageUtils.java

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@
8484
import android.os.Build;
8585
import android.os.Bundle;
8686
import android.os.FileUtils;
87+
import android.os.Parcel;
8788
import android.os.RemoteException;
8889
import android.os.Trace;
8990
import android.os.ext.SdkExtensions;
@@ -2834,6 +2835,68 @@ private static String nonResString(@StyleableRes int index, TypedArray sa) {
28342835
return sa.getNonResourceString(index);
28352836
}
28362837

2838+
/**
2839+
* Writes the keyset mapping to the provided package. {@code null} mappings are permitted.
2840+
*/
2841+
public static void writeKeySetMapping(@NonNull Parcel dest,
2842+
@NonNull Map<String, ArraySet<PublicKey>> keySetMapping) {
2843+
if (keySetMapping == null) {
2844+
dest.writeInt(-1);
2845+
return;
2846+
}
2847+
2848+
final int N = keySetMapping.size();
2849+
dest.writeInt(N);
2850+
2851+
for (String key : keySetMapping.keySet()) {
2852+
dest.writeString(key);
2853+
ArraySet<PublicKey> keys = keySetMapping.get(key);
2854+
if (keys == null) {
2855+
dest.writeInt(-1);
2856+
continue;
2857+
}
2858+
2859+
final int M = keys.size();
2860+
dest.writeInt(M);
2861+
for (int j = 0; j < M; j++) {
2862+
dest.writeSerializable(keys.valueAt(j));
2863+
}
2864+
}
2865+
}
2866+
2867+
/**
2868+
* Reads a keyset mapping from the given parcel at the given data position. May return
2869+
* {@code null} if the serialized mapping was {@code null}.
2870+
*/
2871+
@NonNull
2872+
public static ArrayMap<String, ArraySet<PublicKey>> readKeySetMapping(@NonNull Parcel in) {
2873+
final int N = in.readInt();
2874+
if (N == -1) {
2875+
return null;
2876+
}
2877+
2878+
ArrayMap<String, ArraySet<PublicKey>> keySetMapping = new ArrayMap<>();
2879+
for (int i = 0; i < N; ++i) {
2880+
String key = in.readString();
2881+
final int M = in.readInt();
2882+
if (M == -1) {
2883+
keySetMapping.put(key, null);
2884+
continue;
2885+
}
2886+
2887+
ArraySet<PublicKey> keys = new ArraySet<>(M);
2888+
for (int j = 0; j < M; ++j) {
2889+
PublicKey pk = (PublicKey) in.readSerializable();
2890+
keys.add(pk);
2891+
}
2892+
2893+
keySetMapping.put(key, keys);
2894+
}
2895+
2896+
return keySetMapping;
2897+
}
2898+
2899+
28372900
/**
28382901
* Callback interface for retrieving information that may be needed while parsing
28392902
* a package.

core/java/android/hardware/camera2/params/OutputConfiguration.java

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -631,13 +631,7 @@ public int getSurfaceGroupId() {
631631
new Parcelable.Creator<OutputConfiguration>() {
632632
@Override
633633
public OutputConfiguration createFromParcel(Parcel source) {
634-
try {
635-
OutputConfiguration outputConfiguration = new OutputConfiguration(source);
636-
return outputConfiguration;
637-
} catch (Exception e) {
638-
Log.e(TAG, "Exception creating OutputConfiguration from parcel", e);
639-
return null;
640-
}
634+
return new OutputConfiguration(source);
641635
}
642636

643637
@Override

core/java/android/hardware/camera2/params/SessionConfiguration.java

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -143,13 +143,7 @@ private SessionConfiguration(@NonNull Parcel source) {
143143
new Parcelable.Creator<SessionConfiguration> () {
144144
@Override
145145
public SessionConfiguration createFromParcel(Parcel source) {
146-
try {
147-
SessionConfiguration sessionConfiguration = new SessionConfiguration(source);
148-
return sessionConfiguration;
149-
} catch (Exception e) {
150-
Log.e(TAG, "Exception creating SessionConfiguration from parcel", e);
151-
return null;
152-
}
146+
return new SessionConfiguration(source);
153147
}
154148

155149
@Override

core/java/android/hardware/camera2/params/VendorTagDescriptor.java

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -36,13 +36,7 @@ private VendorTagDescriptor(Parcel source) {
3636
new Parcelable.Creator<VendorTagDescriptor>() {
3737
@Override
3838
public VendorTagDescriptor createFromParcel(Parcel source) {
39-
try {
40-
VendorTagDescriptor vendorDescriptor = new VendorTagDescriptor(source);
41-
return vendorDescriptor;
42-
} catch (Exception e) {
43-
Log.e(TAG, "Exception creating VendorTagDescriptor from parcel", e);
44-
return null;
45-
}
39+
return new VendorTagDescriptor(source);
4640
}
4741

4842
@Override

core/java/android/hardware/camera2/params/VendorTagDescriptorCache.java

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -36,13 +36,7 @@ private VendorTagDescriptorCache(Parcel source) {
3636
new Parcelable.Creator<VendorTagDescriptorCache>() {
3737
@Override
3838
public VendorTagDescriptorCache createFromParcel(Parcel source) {
39-
try {
40-
VendorTagDescriptorCache vendorDescriptorCache = new VendorTagDescriptorCache(source);
41-
return vendorDescriptorCache;
42-
} catch (Exception e) {
43-
Log.e(TAG, "Exception creating VendorTagDescriptorCache from parcel", e);
44-
return null;
45-
}
39+
return new VendorTagDescriptorCache(source);
4640
}
4741

4842
@Override

core/java/android/hardware/display/DisplayManager.java

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -61,9 +61,6 @@ public final class DisplayManager {
6161
* {@link #EXTRA_WIFI_DISPLAY_STATUS} extra.
6262
* </p><p>
6363
* This broadcast is only sent to registered receivers and can only be sent by the system.
64-
* </p><p>
65-
* {@link android.Manifest.permission#ACCESS_FINE_LOCATION} permission is required to
66-
* receive this broadcast.
6764
* </p>
6865
* @hide
6966
*/

packages/CompanionDeviceManager/src/com/android/companiondevicemanager/DeviceChooserActivity.java

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -66,8 +66,8 @@ public void onCreate(Bundle savedInstanceState) {
6666
final DeviceFilterPair selectedDevice = getService().mDevicesFound.get(0);
6767
setTitle(Html.fromHtml(getString(
6868
R.string.confirmation_title,
69-
getCallingAppName(),
70-
selectedDevice.getDisplayName()), 0));
69+
Html.escapeHtml(getCallingAppName()),
70+
Html.escapeHtml(selectedDevice.getDisplayName())), 0));
7171
mPairButton = findViewById(R.id.button_pair);
7272
mPairButton.setOnClickListener(v -> onDeviceConfirmed(getService().mSelectedDevice));
7373
getService().mSelectedDevice = selectedDevice;
@@ -76,7 +76,8 @@ public void onCreate(Bundle savedInstanceState) {
7676
setContentView(R.layout.device_chooser);
7777
mPairButton = findViewById(R.id.button_pair);
7878
mPairButton.setVisibility(View.GONE);
79-
setTitle(Html.fromHtml(getString(R.string.chooser_title, getCallingAppName()), 0));
79+
setTitle(Html.fromHtml(getString(R.string.chooser_title,
80+
Html.escapeHtml(getCallingAppName())), 0));
8081
mDeviceListView = findViewById(R.id.device_list);
8182
final DeviceDiscoveryService.DevicesAdapter adapter = getService().mDevicesAdapter;
8283
mDeviceListView.setAdapter(adapter);

services/core/java/com/android/server/am/ActiveServices.java

Lines changed: 21 additions & 86 deletions
Original file line numberDiff line numberDiff line change
@@ -734,8 +734,11 @@ ComponentName startServiceLocked(IApplicationThread caller, Intent service, Stri
734734
}
735735
ComponentName cmp = startServiceInnerLocked(smap, service, r, callerFg, addToStarting);
736736

737-
setFgsRestrictionLocked(callingPackage, callingPid, callingUid, r,
738-
allowBackgroundActivityStarts);
737+
if (!r.mAllowWhileInUsePermissionInFgs) {
738+
r.mAllowWhileInUsePermissionInFgs =
739+
shouldAllowWhileInUsePermissionInFgsLocked(callingPackage, callingPid,
740+
callingUid, service, r, allowBackgroundActivityStarts);
741+
}
739742

740743
return cmp;
741744
}
@@ -1408,6 +1411,14 @@ private void setServiceForegroundInnerLocked(final ServiceRecord r, int id,
14081411
+ String.format("0x%08X", manifestType)
14091412
+ " in service element of manifest file");
14101413
}
1414+
// If the foreground service is not started from TOP process, do not allow it to
1415+
// have while-in-use location/camera/microphone access.
1416+
if (!r.mAllowWhileInUsePermissionInFgs) {
1417+
Slog.w(TAG,
1418+
"Foreground service started from background can not have "
1419+
+ "location/camera/microphone access: service "
1420+
+ r.shortInstanceName);
1421+
}
14111422
}
14121423
boolean alreadyStartedOp = false;
14131424
boolean stopProcStatsOp = false;
@@ -1455,57 +1466,6 @@ && appRestrictedAnyInBackground(r.appInfo.uid, r.packageName)) {
14551466
ignoreForeground = true;
14561467
}
14571468

1458-
if (!ignoreForeground) {
1459-
if (r.mStartForegroundCount == 0) {
1460-
/*
1461-
If the service was started with startService(), not
1462-
startForegroundService(), and if startForeground() isn't called within
1463-
mFgsStartForegroundTimeoutMs, then we check the state of the app
1464-
(who owns the service, which is the app that called startForeground())
1465-
again. If the app is in the foreground, or in any other cases where
1466-
FGS-starts are allowed, then we still allow the FGS to be started.
1467-
Otherwise, startForeground() would fail.
1468-
1469-
If the service was started with startForegroundService(), then the service
1470-
must call startForeground() within a timeout anyway, so we don't need this
1471-
check.
1472-
*/
1473-
if (!r.fgRequired) {
1474-
final long delayMs = SystemClock.elapsedRealtime() - r.createRealTime;
1475-
if (delayMs > mAm.mConstants.mFgsStartForegroundTimeoutMs) {
1476-
resetFgsRestrictionLocked(r);
1477-
setFgsRestrictionLocked(r.serviceInfo.packageName, r.app.pid,
1478-
r.appInfo.uid, r, false);
1479-
EventLog.writeEvent(0x534e4554, "183147114",
1480-
r.appInfo.uid,
1481-
"call setFgsRestrictionLocked again due to "
1482-
+ "startForegroundTimeout");
1483-
}
1484-
}
1485-
} else if (r.mStartForegroundCount >= 1) {
1486-
// The second or later time startForeground() is called after service is
1487-
// started. Check for app state again.
1488-
final long delayMs = SystemClock.elapsedRealtime() -
1489-
r.mLastSetFgsRestrictionTime;
1490-
if (delayMs > mAm.mConstants.mFgsStartForegroundTimeoutMs) {
1491-
resetFgsRestrictionLocked(r);
1492-
setFgsRestrictionLocked(r.serviceInfo.packageName, r.app.pid,
1493-
r.appInfo.uid, r, false);
1494-
EventLog.writeEvent(0x534e4554, "183147114", r.appInfo.uid,
1495-
"call setFgsRestrictionLocked for "
1496-
+ (r.mStartForegroundCount + 1) + "th startForeground");
1497-
}
1498-
}
1499-
// If the foreground service is not started from TOP process, do not allow it to
1500-
// have while-in-use location/camera/microphone access.
1501-
if (!r.mAllowWhileInUsePermissionInFgs) {
1502-
Slog.w(TAG,
1503-
"Foreground service started from background can not have "
1504-
+ "location/camera/microphone access: service "
1505-
+ r.shortInstanceName);
1506-
}
1507-
}
1508-
15091469
// Apps under strict background restrictions simply don't get to have foreground
15101470
// services, so now that we've enforced the startForegroundService() contract
15111471
// we only do the machinery of making the service foreground when the app
@@ -1541,7 +1501,6 @@ must call startForeground() within a timeout anyway, so we don't need this
15411501
active.mNumActive++;
15421502
}
15431503
r.isForeground = true;
1544-
r.mStartForegroundCount++;
15451504
if (!stopProcStatsOp) {
15461505
ServiceState stracker = r.getTracker();
15471506
if (stracker != null) {
@@ -1600,7 +1559,6 @@ must call startForeground() within a timeout anyway, so we don't need this
16001559
decActiveForegroundAppLocked(smap, r);
16011560
}
16021561
r.isForeground = false;
1603-
resetFgsRestrictionLocked(r);
16041562
ServiceState stracker = r.getTracker();
16051563
if (stracker != null) {
16061564
stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(),
@@ -2160,7 +2118,12 @@ public void run() {
21602118
}
21612119
}
21622120

2163-
setFgsRestrictionLocked(callingPackage, callingPid, callingUid, s, false);
2121+
if (!s.mAllowWhileInUsePermissionInFgs) {
2122+
s.mAllowWhileInUsePermissionInFgs =
2123+
shouldAllowWhileInUsePermissionInFgsLocked(callingPackage,
2124+
callingPid, callingUid,
2125+
service, s, false);
2126+
}
21642127

21652128
if (s.app != null) {
21662129
if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
@@ -3456,7 +3419,7 @@ private final void bringDownServiceLocked(ServiceRecord r) {
34563419
r.isForeground = false;
34573420
r.foregroundId = 0;
34583421
r.foregroundNoti = null;
3459-
resetFgsRestrictionLocked(r);
3422+
r.mAllowWhileInUsePermissionInFgs = false;
34603423

34613424
// Clear start entries.
34623425
r.clearDeliveredStartsLocked();
@@ -4937,7 +4900,7 @@ private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
49374900
* @return true if allow, false otherwise.
49384901
*/
49394902
private boolean shouldAllowWhileInUsePermissionInFgsLocked(String callingPackage,
4940-
int callingPid, int callingUid, ServiceRecord r,
4903+
int callingPid, int callingUid, Intent intent, ServiceRecord r,
49414904
boolean allowBackgroundActivityStarts) {
49424905
// Is the background FGS start restriction turned on?
49434906
if (!mAm.mConstants.mFlagBackgroundFgsStartRestrictionEnabled) {
@@ -5019,32 +4982,4 @@ private boolean shouldAllowWhileInUsePermissionInFgsLocked(String callingPackage
50194982
}
50204983
return false;
50214984
}
5022-
5023-
boolean canAllowWhileInUsePermissionInFgsLocked(int callingPid, int callingUid,
5024-
String callingPackage) {
5025-
return shouldAllowWhileInUsePermissionInFgsLocked(
5026-
callingPackage, callingPid, callingUid, null, false);
5027-
}
5028-
5029-
/**
5030-
* In R, mAllowWhileInUsePermissionInFgs is to allow while-in-use permissions in foreground
5031-
* service or not. while-in-use permissions in FGS started from background might be restricted.
5032-
* @param callingPackage caller app's package name.
5033-
* @param callingUid caller app's uid.
5034-
* @param r the service to start.
5035-
* @return true if allow, false otherwise.
5036-
*/
5037-
private void setFgsRestrictionLocked(String callingPackage,
5038-
int callingPid, int callingUid, ServiceRecord r,
5039-
boolean allowBackgroundActivityStarts) {
5040-
r.mLastSetFgsRestrictionTime = SystemClock.elapsedRealtime();
5041-
if (!r.mAllowWhileInUsePermissionInFgs) {
5042-
r.mAllowWhileInUsePermissionInFgs = shouldAllowWhileInUsePermissionInFgsLocked(
5043-
callingPackage, callingPid, callingUid, r, allowBackgroundActivityStarts);
5044-
}
5045-
}
5046-
5047-
private void resetFgsRestrictionLocked(ServiceRecord r) {
5048-
r.mAllowWhileInUsePermissionInFgs = false;
5049-
}
50504985
}

0 commit comments

Comments
 (0)