下面列出了android.os.Binder#getCallingPid ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void setUserRestriction(int code, boolean restricted, IBinder token, int userHandle,
String[] exceptionPackages) {
if (Binder.getCallingPid() != Process.myPid()) {
mContext.enforcePermission(Manifest.permission.MANAGE_APP_OPS_RESTRICTIONS,
Binder.getCallingPid(), Binder.getCallingUid(), null);
}
if (userHandle != UserHandle.getCallingUserId()) {
if (mContext.checkCallingOrSelfPermission(Manifest.permission
.INTERACT_ACROSS_USERS_FULL) != PackageManager.PERMISSION_GRANTED
&& mContext.checkCallingOrSelfPermission(Manifest.permission
.INTERACT_ACROSS_USERS) != PackageManager.PERMISSION_GRANTED) {
throw new SecurityException("Need INTERACT_ACROSS_USERS_FULL or"
+ " INTERACT_ACROSS_USERS to interact cross user ");
}
}
verifyIncomingOp(code);
Preconditions.checkNotNull(token);
setUserRestrictionNoCheck(code, restricted, token, userHandle, exceptionPackages);
}
/**
* This is called from DeveloperSettings when the user changes WebView provider.
*/
@Override // Binder call
public String changeProviderAndSetting(String newProvider) {
if (getContext().checkCallingPermission(
android.Manifest.permission.WRITE_SECURE_SETTINGS)
!= PackageManager.PERMISSION_GRANTED) {
String msg = "Permission Denial: changeProviderAndSetting() from pid="
+ Binder.getCallingPid()
+ ", uid=" + Binder.getCallingUid()
+ " requires " + android.Manifest.permission.WRITE_SECURE_SETTINGS;
Slog.w(TAG, msg);
throw new SecurityException(msg);
}
long callingId = Binder.clearCallingIdentity();
try {
return WebViewUpdateService.this.mImpl.changeProviderAndSetting(
newProvider);
} finally {
Binder.restoreCallingIdentity(callingId);
}
}
UserInfo getCurrentUser() {
if ((mInjector.checkCallingPermission(INTERACT_ACROSS_USERS)
!= PackageManager.PERMISSION_GRANTED) && (
mInjector.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
!= PackageManager.PERMISSION_GRANTED)) {
String msg = "Permission Denial: getCurrentUser() from pid="
+ Binder.getCallingPid()
+ ", uid=" + Binder.getCallingUid()
+ " requires " + INTERACT_ACROSS_USERS;
Slog.w(TAG, msg);
throw new SecurityException(msg);
}
// Optimization - if there is no pending user switch, return current id
if (mTargetUserId == UserHandle.USER_NULL) {
return getUserInfo(mCurrentUserId);
}
synchronized (mLock) {
return getCurrentUserLU();
}
}
/**
* Returns true if the RPC caller is from the same application or if the
* "Allow access" setting indicates that another app can invoke this
* service's RPCs.
*/
private boolean canAccess() {
// As a precondition for access, must check if the service is available.
if (trackRecordingService == null) {
throw new IllegalStateException("The track recording service has been detached!");
}
if (Process.myPid() == Binder.getCallingPid()) {
return true;
} else {
return PreferencesUtils.getBoolean(trackRecordingService, R.string.allow_access_key,
PreferencesUtils.ALLOW_ACCESS_DEFAULT);
}
}
@Override
public void onActivityCreated(ComponentName component, ComponentName caller, IBinder token, Intent intent, String affinity, int taskId, int launchMode, int flags) {
int pid = Binder.getCallingPid();
ProcessRecord targetApp = findProcessLocked(pid);
if (targetApp != null) {
mUiEngine.enterActivity(targetApp.userId, targetApp.info.packageName);
mMainStack.onActivityCreated(targetApp, component, caller, token, intent, affinity, taskId, launchMode, flags);
}
}
@Override
public int loadLanguage(
IBinder caller, String lang, String country, String variant) {
if (!checkNonNull(lang)) {
return TextToSpeech.ERROR;
}
int retVal = onIsLanguageAvailable(lang, country, variant);
if (retVal == TextToSpeech.LANG_AVAILABLE
|| retVal == TextToSpeech.LANG_COUNTRY_AVAILABLE
|| retVal == TextToSpeech.LANG_COUNTRY_VAR_AVAILABLE) {
SpeechItem item =
new LoadLanguageItem(
caller,
Binder.getCallingUid(),
Binder.getCallingPid(),
lang,
country,
variant);
if (mSynthHandler.enqueueSpeechItem(TextToSpeech.QUEUE_ADD, item)
!= TextToSpeech.SUCCESS) {
return TextToSpeech.ERROR;
}
}
return retVal;
}
public void enforceCallingPermission() {
if (Binder.getCallingPid() == Process.myPid()) {
return;
}
mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
Binder.getCallingPid(), Binder.getCallingUid(), null);
}
private boolean isPermitted() {
// schedulerservice hidl
if (Binder.getCallingPid() == Process.myPid()) {
return true;
}
switch (Binder.getCallingUid()) {
case Process.AUDIOSERVER_UID: // fastcapture, fastmixer
case Process.CAMERASERVER_UID: // camera high frame rate recording
case Process.BLUETOOTH_UID: // Bluetooth audio playback
return true;
default:
return false;
}
}
@Override
public int checkCallingPermission(String permission) {
if (permission == null) {
throw new IllegalArgumentException("permission is null");
}
int pid = Binder.getCallingPid();
if (pid != Process.myPid()) {
return checkPermission(permission, pid, Binder.getCallingUid());
}
return PackageManager.PERMISSION_DENIED;
}
@Override
public int checkCallingUriPermission(Uri uri, int modeFlags) {
int pid = Binder.getCallingPid();
if (pid != Process.myPid()) {
return checkUriPermission(uri, pid,
Binder.getCallingUid(), modeFlags);
}
return PackageManager.PERMISSION_DENIED;
}
@Override
public int checkCallingUriPermission(Uri uri, int modeFlags) {
int pid = Binder.getCallingPid();
if (pid != Process.myPid()) {
return checkUriPermission(uri, pid,
Binder.getCallingUid(), modeFlags);
}
return PackageManager.PERMISSION_DENIED;
}
/**
* Returns true if the caller can access the content provider.
*/
private boolean canAccess() {
if (Binder.getCallingPid() == Process.myPid()) {
return true;
} else {
return PreferencesUtils.getBoolean(
getContext(), R.string.allow_access_key, PreferencesUtils.ALLOW_ACCESS_DEFAULT);
}
}
public void unregisterTaskStackListener(ITaskStackListener listener) {
synchronized (mService) {
if (listener != null) {
if (Binder.getCallingPid() == android.os.Process.myPid()) {
mLocalTaskStackListeners.remove(listener);
} else {
mRemoteTaskStackListeners.unregister(listener);
}
}
}
}
@Override
public int schedule(JobInfo job) throws RemoteException {
if (DEBUG) {
Slog.d(TAG, "Scheduling job: " + job.toString());
}
final int pid = Binder.getCallingPid();
final int uid = Binder.getCallingUid();
final int userId = UserHandle.getUserId(uid);
enforceValidJobRequest(uid, job);
if (job.isPersisted()) {
if (!canPersistJobs(pid, uid)) {
throw new IllegalArgumentException("Error: requested job be persisted without"
+ " holding RECEIVE_BOOT_COMPLETED permission.");
}
}
validateJobFlags(job, uid);
long ident = Binder.clearCallingIdentity();
try {
return JobSchedulerService.this.scheduleAsPackage(job, null, uid, null, userId,
null);
} finally {
Binder.restoreCallingIdentity(ident);
}
}
@Override
public void onNotificationClick(String key, NotificationVisibility nv) {
enforceStatusBarService();
final int callingUid = Binder.getCallingUid();
final int callingPid = Binder.getCallingPid();
long identity = Binder.clearCallingIdentity();
try {
mNotificationDelegate.onNotificationClick(callingUid, callingPid, key, nv);
} finally {
Binder.restoreCallingIdentity(identity);
}
}
@Override // Binder call
public void authenticate(final IBinder token, final long opId, final int groupId,
final IFingerprintServiceReceiver receiver, final int flags,
final String opPackageName, final Bundle bundle,
final IBiometricPromptReceiver dialogReceiver) {
final int callingUid = Binder.getCallingUid();
final int callingPid = Binder.getCallingPid();
final int callingUserId = UserHandle.getCallingUserId();
final boolean restricted = isRestricted();
if (!canUseFingerprint(opPackageName, true /* foregroundOnly */, callingUid, callingPid,
callingUserId)) {
if (DEBUG) Slog.v(TAG, "authenticate(): reject " + opPackageName);
return;
}
mHandler.post(new Runnable() {
@Override
public void run() {
MetricsLogger.histogram(mContext, "fingerprint_token", opId != 0L ? 1 : 0);
// Get performance stats object for this user.
HashMap<Integer, PerformanceStats> pmap
= (opId == 0) ? mPerformanceMap : mCryptoPerformanceMap;
PerformanceStats stats = pmap.get(mCurrentUserId);
if (stats == null) {
stats = new PerformanceStats();
pmap.put(mCurrentUserId, stats);
}
mPerformanceStats = stats;
startAuthentication(token, opId, callingUserId, groupId, receiver,
flags, restricted, opPackageName, bundle, dialogReceiver);
}
});
}
/**
* If the user id supplied is different to the calling user, the caller must hold the
* INTERACT_ACROSS_USERS_FULL permission.
*/
@Override
public void syncAsUser(SyncRequest request, int userId, String callingPackage) {
enforceCrossUserPermission(userId, "no permission to request sync as user: " + userId);
final int callingUid = Binder.getCallingUid();
final int callingPid = Binder.getCallingPid();
final Bundle extras = request.getBundle();
validateExtras(callingUid, extras);
final int syncExemption = getSyncExemptionAndCleanUpExtrasForCaller(callingUid, extras);
// This makes it so that future permission checks will be in the context of this
// process rather than the caller's process. We will restore this before returning.
long identityToken = clearCallingIdentity();
try {
SyncManager syncManager = getSyncManager();
if (syncManager == null) {
return;
}
long flextime = request.getSyncFlexTime();
long runAtTime = request.getSyncRunTime();
if (request.isPeriodic()) {
mContext.enforceCallingOrSelfPermission(
Manifest.permission.WRITE_SYNC_SETTINGS,
"no permission to write the sync settings");
SyncStorageEngine.EndPoint info;
info = new SyncStorageEngine.EndPoint(
request.getAccount(), request.getProvider(), userId);
runAtTime = clampPeriod(runAtTime);
// Schedule periodic sync.
getSyncManager().updateOrAddPeriodicSync(info, runAtTime,
flextime, extras);
} else {
syncManager.scheduleSync(
request.getAccount(), userId, callingUid, request.getProvider(), extras,
SyncStorageEngine.AuthorityInfo.UNDEFINED,
syncExemption, callingUid, callingPid, callingPackage);
}
} finally {
restoreCallingIdentity(identityToken);
}
}
/**
* Overrides options with options from a caller and records {@link Binder#getCallingPid}/
* {@link Binder#getCallingUid}. Thus, calling identity MUST NOT be cleared when calling this
* method.
*/
void setCallerOptions(@Nullable ActivityOptions options) {
mRealCallingPid = Binder.getCallingPid();
mRealCallingUid = Binder.getCallingUid();
mCallerOptions = options;
}
/**
* Notify observers of a particular user's view of the provider.
* @param userHandle the user whose view of the provider is to be notified. May be
* the calling user without requiring any permission, otherwise the caller needs to
* hold the INTERACT_ACROSS_USERS_FULL permission or hold a write uri grant to the uri.
* Pseudousers USER_ALL and USER_CURRENT are properly interpreted; no other pseudousers are
* allowed.
*/
@Override
public void notifyChange(Uri uri, IContentObserver observer,
boolean observerWantsSelfNotifications, int flags, int userHandle,
int targetSdkVersion) {
if (DEBUG) Slog.d(TAG, "Notifying update of " + uri + " for user " + userHandle
+ " from observer " + observer + ", flags " + Integer.toHexString(flags));
if (uri == null) {
throw new NullPointerException("Uri must not be null");
}
final int uid = Binder.getCallingUid();
final int pid = Binder.getCallingPid();
final int callingUserHandle = UserHandle.getCallingUserId();
userHandle = handleIncomingUser(uri, pid, uid,
Intent.FLAG_GRANT_WRITE_URI_PERMISSION, true, userHandle);
final String msg = LocalServices.getService(ActivityManagerInternal.class)
.checkContentProviderAccess(uri.getAuthority(), userHandle);
if (msg != null) {
if (targetSdkVersion >= Build.VERSION_CODES.O) {
throw new SecurityException(msg);
} else {
if (msg.startsWith("Failed to find provider")) {
// Sigh, we need to quietly let apps targeting older API
// levels notify on non-existent providers.
} else {
Log.w(TAG, "Ignoring notify for " + uri + " from " + uid + ": " + msg);
return;
}
}
}
// This makes it so that future permission checks will be in the context of this
// process rather than the caller's process. We will restore this before returning.
long identityToken = clearCallingIdentity();
try {
ArrayList<ObserverCall> calls = new ArrayList<ObserverCall>();
synchronized (mRootNode) {
mRootNode.collectObserversLocked(uri, 0, observer, observerWantsSelfNotifications,
flags, userHandle, calls);
}
final int numCalls = calls.size();
for (int i=0; i<numCalls; i++) {
ObserverCall oc = calls.get(i);
try {
oc.mObserver.onChange(oc.mSelfChange, uri, userHandle);
if (DEBUG) Slog.d(TAG, "Notified " + oc.mObserver + " of " + "update at "
+ uri);
} catch (RemoteException ex) {
synchronized (mRootNode) {
Log.w(TAG, "Found dead observer, removing");
IBinder binder = oc.mObserver.asBinder();
final ArrayList<ObserverNode.ObserverEntry> list
= oc.mNode.mObservers;
int numList = list.size();
for (int j=0; j<numList; j++) {
ObserverNode.ObserverEntry oe = list.get(j);
if (oe.observer.asBinder() == binder) {
list.remove(j);
j--;
numList--;
}
}
}
}
}
if ((flags&ContentResolver.NOTIFY_SYNC_TO_NETWORK) != 0) {
SyncManager syncManager = getSyncManager();
if (syncManager != null) {
syncManager.scheduleLocalSync(null /* all accounts */, callingUserHandle, uid,
uri.getAuthority(), getSyncExemptionForCaller(uid));
}
}
synchronized (mCache) {
final String providerPackageName = getProviderPackageName(uri);
invalidateCacheLocked(userHandle, providerPackageName, uri);
}
} finally {
restoreCallingIdentity(identityToken);
}
}
/**
* Constructs a new instance and records {@link Binder#getCallingPid}/
* {@link Binder#getCallingUid}. Thus, calling identity MUST NOT be cleared when constructing
* this object.
*
* @param options The options to wrap.
*/
SafeActivityOptions(@Nullable ActivityOptions options) {
mOriginalCallingPid = Binder.getCallingPid();
mOriginalCallingUid = Binder.getCallingUid();
mOriginalOptions = options;
}