下面列出了android.os.UserHandle#getAppId ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public int checkPermission(String permission, int pid, int uid) {
if (permission == null) {
throw new IllegalArgumentException("permission is null");
}
final IActivityManager am = ActivityManager.getService();
if (am == null) {
// Well this is super awkward; we somehow don't have an active
// ActivityManager instance. If we're testing a root or system
// UID, then they totally have whatever permission this is.
final int appId = UserHandle.getAppId(uid);
if (appId == Process.ROOT_UID || appId == Process.SYSTEM_UID) {
Slog.w(TAG, "Missing ActivityManager; assuming " + uid + " holds " + permission);
return PackageManager.PERMISSION_GRANTED;
}
}
try {
return am.checkPermission(permission, pid, uid);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
private boolean checkIfCallerIsForegroundUser() {
int foregroundUser;
int callingUser = UserHandle.getCallingUserId();
int callingUid = Binder.getCallingUid();
long callingIdentity = Binder.clearCallingIdentity();
UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
UserInfo ui = um.getProfileParent(callingUser);
int parentUser = (ui != null) ? ui.id : UserHandle.USER_NULL;
int callingAppId = UserHandle.getAppId(callingUid);
boolean valid = false;
try {
foregroundUser = ActivityManager.getCurrentUser();
valid = (callingUser == foregroundUser) || parentUser == foregroundUser
|| callingAppId == Process.NFC_UID || callingAppId == mSystemUiUid;
if (DBG && !valid) {
Slog.d(TAG, "checkIfCallerIsForegroundUser: valid=" + valid + " callingUser="
+ callingUser + " parentUser=" + parentUser + " foregroundUser="
+ foregroundUser);
}
} finally {
Binder.restoreCallingIdentity(callingIdentity);
}
return valid;
}
private boolean isSysComponentOrPersistentPlatformSignedPrivApp(PackageParser.Package pkg) {
if (UserHandle.getAppId(pkg.applicationInfo.uid) < FIRST_APPLICATION_UID) {
return true;
}
if (!pkg.isPrivileged()) {
return false;
}
final PackageParser.Package disabledPkg =
mServiceInternal.getDisabledPackage(pkg.packageName);
if (disabledPkg != null) {
if ((disabledPkg.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) == 0) {
return false;
}
} else if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) == 0) {
return false;
}
final String systemPackageName = mServiceInternal.getKnownPackageName(
PackageManagerInternal.PACKAGE_SYSTEM, UserHandle.USER_SYSTEM);
final PackageParser.Package systemPackage = getPackage(systemPackageName);
return pkg.mSigningDetails.hasAncestorOrSelf(systemPackage.mSigningDetails)
|| systemPackage.mSigningDetails.checkCapability(pkg.mSigningDetails,
PackageParser.SigningDetails.CertCapabilities.PERMISSION);
}
static BasePermission enforcePermissionTree(
Collection<BasePermission> permissionTrees, String permName, int callingUid) {
if (permName != null) {
BasePermission bp = findPermissionTree(permissionTrees, permName);
if (bp != null) {
if (bp.uid == UserHandle.getAppId(callingUid)) {
return bp;
}
throw new SecurityException("Calling uid " + callingUid
+ " is not allowed to add to permission tree "
+ bp.name + " owned by uid " + bp.uid);
}
}
throw new SecurityException("No permission tree found for " + permName);
}
@Override
public int checkPermission(String permission, int pid, int uid) {
if (permission == null) {
throw new IllegalArgumentException("permission is null");
}
final IActivityManager am = ActivityManager.getService();
if (am == null) {
// Well this is super awkward; we somehow don't have an active
// ActivityManager instance. If we're testing a root or system
// UID, then they totally have whatever permission this is.
final int appId = UserHandle.getAppId(uid);
if (appId == Process.ROOT_UID || appId == Process.SYSTEM_UID) {
Slog.w(TAG, "Missing ActivityManager; assuming " + uid + " holds " + permission);
return PackageManager.PERMISSION_GRANTED;
}
Slog.w(TAG, "Missing ActivityManager; assuming " + uid + " does not hold "
+ permission);
return PackageManager.PERMISSION_DENIED;
}
try {
return am.checkPermission(permission, pid, uid);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
/** @hide */
public static int checkComponentPermission(String permission, int uid,
int owningUid, boolean exported) {
// Root, system server get to do everything.
final int appId = UserHandle.getAppId(uid);
if (appId == Process.ROOT_UID || appId == Process.SYSTEM_UID) {
return PackageManager.PERMISSION_GRANTED;
}
// Isolated processes don't get any permissions.
if (UserHandle.isIsolated(uid)) {
return PackageManager.PERMISSION_DENIED;
}
// If there is a uid that owns whatever is being accessed, it has
// blanket access to it regardless of the permissions it requires.
if (owningUid >= 0 && UserHandle.isSameApp(uid, owningUid)) {
return PackageManager.PERMISSION_GRANTED;
}
// If the target is not exported, then nobody else can get to it.
if (!exported) {
/*
RuntimeException here = new RuntimeException("here");
here.fillInStackTrace();
Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid,
here);
*/
return PackageManager.PERMISSION_DENIED;
}
if (permission == null) {
return PackageManager.PERMISSION_GRANTED;
}
try {
return AppGlobals.getPackageManager()
.checkUidPermission(permission, uid);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
@Override
public int checkPermission(String permission, int pid, int uid) {
if (permission == null) {
throw new IllegalArgumentException("permission is null");
}
final IActivityManager am = ActivityManager.getService();
if (am == null) {
// Well this is super awkward; we somehow don't have an active
// ActivityManager instance. If we're testing a root or system
// UID, then they totally have whatever permission this is.
final int appId = UserHandle.getAppId(uid);
if (appId == Process.ROOT_UID || appId == Process.SYSTEM_UID) {
Slog.w(TAG, "Missing ActivityManager; assuming " + uid + " holds " + permission);
return PackageManager.PERMISSION_GRANTED;
}
Slog.w(TAG, "Missing ActivityManager; assuming " + uid + " does not hold "
+ permission);
return PackageManager.PERMISSION_DENIED;
}
try {
return am.checkPermission(permission, pid, uid);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
/** @hide */
public static int checkComponentPermission(String permission, int uid,
int owningUid, boolean exported) {
// Root, system server get to do everything.
final int appId = UserHandle.getAppId(uid);
if (appId == Process.ROOT_UID || appId == Process.SYSTEM_UID) {
return PackageManager.PERMISSION_GRANTED;
}
// Isolated processes don't get any permissions.
if (UserHandle.isIsolated(uid)) {
return PackageManager.PERMISSION_DENIED;
}
// If there is a uid that owns whatever is being accessed, it has
// blanket access to it regardless of the permissions it requires.
if (owningUid >= 0 && UserHandle.isSameApp(uid, owningUid)) {
return PackageManager.PERMISSION_GRANTED;
}
// If the target is not exported, then nobody else can get to it.
if (!exported) {
/*
RuntimeException here = new RuntimeException("here");
here.fillInStackTrace();
Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid,
here);
*/
return PackageManager.PERMISSION_DENIED;
}
if (permission == null) {
return PackageManager.PERMISSION_GRANTED;
}
try {
return AppGlobals.getPackageManager()
.checkUidPermission(permission, uid);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
void resetProcessCrashTimeLocked(boolean resetEntireUser, int appId, int userId) {
final ArrayMap<String, SparseArray<Long>> pmap = mProcessCrashTimes.getMap();
for (int ip = pmap.size() - 1; ip >= 0; ip--) {
SparseArray<Long> ba = pmap.valueAt(ip);
for (int i = ba.size() - 1; i >= 0; i--) {
boolean remove = false;
final int entUid = ba.keyAt(i);
if (!resetEntireUser) {
if (userId == UserHandle.USER_ALL) {
if (UserHandle.getAppId(entUid) == appId) {
remove = true;
}
} else {
if (entUid == UserHandle.getUid(userId, appId)) {
remove = true;
}
}
} else if (UserHandle.getUserId(entUid) == userId) {
remove = true;
}
if (remove) {
ba.removeAt(i);
}
}
if (ba.size() == 0) {
pmap.removeAt(ip);
}
}
}
/**
* Removes an app from the temporary whitelist and notifies the observers.
*/
private void removePowerSaveTempWhitelistAppInternal(String packageName, int userId) {
try {
final int uid = getContext().getPackageManager().getPackageUidAsUser(
packageName, userId);
final int appId = UserHandle.getAppId(uid);
removePowerSaveTempWhitelistAppDirectInternal(appId);
} catch (NameNotFoundException e) {
}
}
public void dumpHistory(ProtoOutputStream proto, long fieldId, int filterUid) {
final int size = mEventIndices.size();
if (size == 0) {
return;
}
final long token = proto.start(fieldId);
final long now = sElapsedRealtimeClock.millis();
for (int i = 0; i < size; i++) {
final int index = mEventIndices.indexOf(i);
final int uid = mEventUids[index];
if (filterUid != -1 && filterUid != UserHandle.getAppId(uid)) {
continue;
}
final int cmd = mEventCmds[index] & EVENT_CMD_MASK;
if (cmd == EVENT_NULL) {
continue;
}
final long heToken = proto.start(JobPackageHistoryProto.HISTORY_EVENT);
proto.write(JobPackageHistoryProto.HistoryEvent.EVENT, cmd);
proto.write(JobPackageHistoryProto.HistoryEvent.TIME_SINCE_EVENT_MS, now - mEventTimes[index]);
proto.write(JobPackageHistoryProto.HistoryEvent.UID, uid);
proto.write(JobPackageHistoryProto.HistoryEvent.JOB_ID, mEventJobIds[index]);
proto.write(JobPackageHistoryProto.HistoryEvent.TAG, mEventTags[index]);
if (cmd == EVENT_STOP_JOB || cmd == EVENT_STOP_PERIODIC_JOB) {
proto.write(JobPackageHistoryProto.HistoryEvent.STOP_REASON,
(mEventCmds[index] & EVENT_STOP_REASON_MASK) >> EVENT_STOP_REASON_SHIFT);
}
proto.end(heToken);
}
proto.end(token);
}
private static boolean isCallerSystemOrShellOrRootOnDebuggableBuild() {
final int appId = UserHandle.getAppId(Binder.getCallingUid());
return appId == SYSTEM_UID || (Build.IS_DEBUGGABLE
&& (appId == SHELL_UID || appId == ROOT_UID));
}
public Object createService(ContextImpl ctx) {
IBinder iBinder = ServiceManager.getService(Context.PRINT_SERVICE);
IPrintManager service = IPrintManager.Stub.asInterface(iBinder);
return new PrintManager(ctx.getOuterContext(), service, UserHandle.myUserId(),
UserHandle.getAppId(Process.myUid()));
}
public Object createService(ContextImpl ctx) {
IBinder iBinder = ServiceManager.getService(Context.PRINT_SERVICE);
IPrintManager service = IPrintManager.Stub.asInterface(iBinder);
return new PrintManager(ctx.getOuterContext(), service, UserHandle.myUserId(),
UserHandle.getAppId(Process.myUid()));
}
public boolean enable(String packageName) throws RemoteException {
final int callingUid = Binder.getCallingUid();
final boolean callerSystem = UserHandle.getAppId(callingUid) == Process.SYSTEM_UID;
if (isBluetoothDisallowed()) {
if (DBG) {
Slog.d(TAG, "enable(): not enabling - bluetooth disallowed");
}
return false;
}
if (!callerSystem) {
if (!checkIfCallerIsForegroundUser()) {
Slog.w(TAG, "enable(): not allowed for non-active and non system user");
return false;
}
mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
"Need BLUETOOTH ADMIN permission");
if (!isEnabled() && mPermissionReviewRequired && startConsentUiIfNeeded(packageName,
callingUid, BluetoothAdapter.ACTION_REQUEST_ENABLE)) {
return false;
}
}
if (DBG) {
Slog.d(TAG, "enable(" + packageName + "): mBluetooth =" + mBluetooth + " mBinding = "
+ mBinding + " mState = " + BluetoothAdapter.nameForState(mState));
}
synchronized (mReceiver) {
mQuietEnableExternal = false;
mEnableExternal = true;
// waive WRITE_SECURE_SETTINGS permission check
sendEnableMsg(false,
BluetoothProtoEnums.ENABLE_DISABLE_REASON_APPLICATION_REQUEST, packageName);
}
if (DBG) {
Slog.d(TAG, "enable returning");
}
return true;
}
void dump(PrintWriter pw, String header, String prefix, long now, long nowElapsed,
int filterUid) {
final long period = getTotalTime(now);
pw.print(prefix); pw.print(header); pw.print(" at ");
pw.print(DateFormat.format("yyyy-MM-dd-HH-mm-ss", mStartClockTime).toString());
pw.print(" (");
TimeUtils.formatDuration(mStartElapsedTime, nowElapsed, pw);
pw.print(") over ");
TimeUtils.formatDuration(period, pw);
pw.println(":");
final int NE = mEntries.size();
for (int i = 0; i < NE; i++) {
int uid = mEntries.keyAt(i);
if (filterUid != -1 && filterUid != UserHandle.getAppId(uid)) {
continue;
}
ArrayMap<String, PackageEntry> uidMap = mEntries.valueAt(i);
final int NP = uidMap.size();
for (int j = 0; j < NP; j++) {
PackageEntry pe = uidMap.valueAt(j);
pw.print(prefix); pw.print(" ");
UserHandle.formatUid(pw, uid);
pw.print(" / "); pw.print(uidMap.keyAt(j));
pw.println(":");
pw.print(prefix); pw.print(" ");
printDuration(pw, period, pe.getPendingTime(now), pe.pendingCount, "pending");
printDuration(pw, period, pe.getActiveTime(now), pe.activeCount, "active");
printDuration(pw, period, pe.getActiveTopTime(now), pe.activeTopCount,
"active-top");
if (pe.pendingNesting > 0 || pe.hadPending) {
pw.print(" (pending)");
}
if (pe.activeNesting > 0 || pe.hadActive) {
pw.print(" (active)");
}
if (pe.activeTopNesting > 0 || pe.hadActiveTop) {
pw.print(" (active-top)");
}
pw.println();
if (pe.stopReasons.size() > 0) {
pw.print(prefix); pw.print(" ");
for (int k = 0; k < pe.stopReasons.size(); k++) {
if (k > 0) {
pw.print(", ");
}
pw.print(pe.stopReasons.valueAt(k));
pw.print("x ");
pw.print(JobParameters.getReasonName(pe.stopReasons.keyAt(k)));
}
pw.println();
}
}
}
pw.print(prefix); pw.print(" Max concurrency: ");
pw.print(mMaxTotalActive); pw.print(" total, ");
pw.print(mMaxFgActive); pw.println(" foreground");
}
void dump(ProtoOutputStream proto, long fieldId, long now, long nowElapsed, int filterUid) {
final long token = proto.start(fieldId);
final long period = getTotalTime(now);
proto.write(DataSetProto.START_CLOCK_TIME_MS, mStartClockTime);
proto.write(DataSetProto.ELAPSED_TIME_MS, nowElapsed - mStartElapsedTime);
proto.write(DataSetProto.PERIOD_MS, period);
final int NE = mEntries.size();
for (int i = 0; i < NE; i++) {
int uid = mEntries.keyAt(i);
if (filterUid != -1 && filterUid != UserHandle.getAppId(uid)) {
continue;
}
ArrayMap<String, PackageEntry> uidMap = mEntries.valueAt(i);
final int NP = uidMap.size();
for (int j = 0; j < NP; j++) {
final long peToken = proto.start(DataSetProto.PACKAGE_ENTRIES);
PackageEntry pe = uidMap.valueAt(j);
proto.write(DataSetProto.PackageEntryProto.UID, uid);
proto.write(DataSetProto.PackageEntryProto.PACKAGE_NAME, uidMap.keyAt(j));
printPackageEntryState(proto, DataSetProto.PackageEntryProto.PENDING_STATE,
pe.getPendingTime(now), pe.pendingCount);
printPackageEntryState(proto, DataSetProto.PackageEntryProto.ACTIVE_STATE,
pe.getActiveTime(now), pe.activeCount);
printPackageEntryState(proto, DataSetProto.PackageEntryProto.ACTIVE_TOP_STATE,
pe.getActiveTopTime(now), pe.activeTopCount);
proto.write(DataSetProto.PackageEntryProto.PENDING,
pe.pendingNesting > 0 || pe.hadPending);
proto.write(DataSetProto.PackageEntryProto.ACTIVE,
pe.activeNesting > 0 || pe.hadActive);
proto.write(DataSetProto.PackageEntryProto.ACTIVE_TOP,
pe.activeTopNesting > 0 || pe.hadActiveTop);
for (int k = 0; k < pe.stopReasons.size(); k++) {
final long srcToken =
proto.start(DataSetProto.PackageEntryProto.STOP_REASONS);
proto.write(DataSetProto.PackageEntryProto.StopReasonCount.REASON,
pe.stopReasons.keyAt(k));
proto.write(DataSetProto.PackageEntryProto.StopReasonCount.COUNT,
pe.stopReasons.valueAt(k));
proto.end(srcToken);
}
proto.end(peToken);
}
}
proto.write(DataSetProto.MAX_CONCURRENCY, mMaxTotalActive);
proto.write(DataSetProto.MAX_FOREGROUND_CONCURRENCY, mMaxFgActive);
proto.end(token);
}
public boolean dumpHistory(PrintWriter pw, String prefix, int filterUid) {
final int size = mEventIndices.size();
if (size <= 0) {
return false;
}
pw.println(" Job history:");
final long now = sElapsedRealtimeClock.millis();
for (int i=0; i<size; i++) {
final int index = mEventIndices.indexOf(i);
final int uid = mEventUids[index];
if (filterUid != -1 && filterUid != UserHandle.getAppId(uid)) {
continue;
}
final int cmd = mEventCmds[index] & EVENT_CMD_MASK;
if (cmd == EVENT_NULL) {
continue;
}
final String label;
switch (cmd) {
case EVENT_START_JOB: label = " START"; break;
case EVENT_STOP_JOB: label = " STOP"; break;
case EVENT_START_PERIODIC_JOB: label = "START-P"; break;
case EVENT_STOP_PERIODIC_JOB: label = " STOP-P"; break;
default: label = " ??"; break;
}
pw.print(prefix);
TimeUtils.formatDuration(mEventTimes[index]-now, pw, TimeUtils.HUNDRED_DAY_FIELD_LEN);
pw.print(" ");
pw.print(label);
pw.print(": #");
UserHandle.formatUid(pw, uid);
pw.print("/");
pw.print(mEventJobIds[index]);
pw.print(" ");
pw.print(mEventTags[index]);
if (cmd == EVENT_STOP_JOB || cmd == EVENT_STOP_PERIODIC_JOB) {
pw.print(" ");
final String reason = mEventReasons[index];
if (reason != null) {
pw.print(mEventReasons[index]);
} else {
pw.print(JobParameters.getReasonName((mEventCmds[index] & EVENT_STOP_REASON_MASK)
>> EVENT_STOP_REASON_SHIFT));
}
}
pw.println();
}
return true;
}
void handleShowAppErrorUi(Message msg) {
AppErrorDialog.Data data = (AppErrorDialog.Data) msg.obj;
boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
AppErrorDialog dialogToShow = null;
final String packageName;
final int userId;
synchronized (mService) {
final ProcessRecord proc = data.proc;
final AppErrorResult res = data.result;
if (proc == null) {
Slog.e(TAG, "handleShowAppErrorUi: proc is null");
return;
}
packageName = proc.info.packageName;
userId = proc.userId;
if (proc.crashDialog != null) {
Slog.e(TAG, "App already has crash dialog: " + proc);
if (res != null) {
res.set(AppErrorDialog.ALREADY_SHOWING);
}
return;
}
boolean isBackground = (UserHandle.getAppId(proc.uid)
>= Process.FIRST_APPLICATION_UID
&& proc.pid != MY_PID);
for (int profileId : mService.mUserController.getCurrentProfileIds()) {
isBackground &= (userId != profileId);
}
if (isBackground && !showBackground) {
Slog.w(TAG, "Skipping crash dialog of " + proc + ": background");
if (res != null) {
res.set(AppErrorDialog.BACKGROUND_USER);
}
return;
}
final boolean showFirstCrash = Settings.Global.getInt(
mContext.getContentResolver(),
Settings.Global.SHOW_FIRST_CRASH_DIALOG, 0) != 0;
final boolean showFirstCrashDevOption = Settings.Secure.getIntForUser(
mContext.getContentResolver(),
Settings.Secure.SHOW_FIRST_CRASH_DIALOG_DEV_OPTION,
0,
mService.mUserController.getCurrentUserId()) != 0;
final boolean crashSilenced = mAppsNotReportingCrashes != null &&
mAppsNotReportingCrashes.contains(proc.info.packageName);
if ((mService.canShowErrorDialogs() || showBackground) && !crashSilenced
&& (showFirstCrash || showFirstCrashDevOption || data.repeating)) {
proc.crashDialog = dialogToShow = new AppErrorDialog(mContext, mService, data);
} else {
// The device is asleep, so just pretend that the user
// saw a crash dialog and hit "force quit".
if (res != null) {
res.set(AppErrorDialog.CANT_SHOW);
}
}
}
// If we've created a crash dialog, show it without the lock held
if (dialogToShow != null) {
Slog.i(TAG, "Showing crash dialog for package " + packageName + " u" + userId);
dialogToShow.show();
}
}
/**
* Set surface metadata.
*
* Currently these are window-types as per {@link WindowManager.LayoutParams} and
* owner UIDs. Child surfaces inherit their parents
* metadata so only the WindowManager needs to set this on root Surfaces.
*
* @param windowType A window-type
* @param ownerUid UID of the window owner.
*/
public Builder setMetadata(int windowType, int ownerUid) {
if (UserHandle.getAppId(Process.myUid()) != Process.SYSTEM_UID) {
throw new UnsupportedOperationException(
"It only makes sense to set Surface metadata from the WindowManager");
}
mWindowType = windowType;
mOwnerUid = ownerUid;
return this;
}