下面列出了android.os.Process#myUid ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
if (!param.hasThrowable())
try {
if (Process.myUid() <= 0)
return;
if (InstrumentationManager.TRACE)
traceMethod(param);
else
monitorMethod(param);
} catch (Throwable ex) {
throw ex;
}
}
@Override
protected final void intercept(@NonNull final HttpRequestChain chain,
@NonNull ByteBuffer buffer, int index) throws IOException {
if (chain.request().uid() == Process.myUid()) {
chain.process(buffer);
return;
}
if (index == 0) {
mShouldInjectRequest = mHttpInjector.sniffRequest(chain.request());
}
if (!mShouldInjectRequest) {
chain.process(buffer);
return;
}
if (index == 0) {
mHttpInjector.onRequestInject(buildHeader(chain.request()), new HttpRequestInjectorCallback(chain));
} else {
mHttpInjector.onRequestInject(chain.request(), new HttpRawBody(buffer), new HttpRequestInjectorCallback(chain));
}
}
@Override
public Resources getResourcesForApplication(@NonNull ApplicationInfo app)
throws NameNotFoundException {
if (app.packageName.equals("system")) {
return mContext.mMainThread.getSystemUiContext().getResources();
}
final boolean sameUid = (app.uid == Process.myUid());
final Resources r = mContext.mMainThread.getTopLevelResources(
sameUid ? app.sourceDir : app.publicSourceDir,
sameUid ? app.splitSourceDirs : app.splitPublicSourceDirs,
app.resourceDirs, app.sharedLibraryFiles, Display.DEFAULT_DISPLAY,
mContext.mPackageInfo);
if (r != null) {
return r;
}
throw new NameNotFoundException("Unable to open " + app.publicSourceDir);
}
@org.xwalk.core.JavascriptInterface
@android.webkit.JavascriptInterface
public String getDataUsage() {
try {
int uid = Process.myUid();
return new JSONObject()
.put("system", getDataUsage(
TrafficStats.getTotalRxBytes(),
TrafficStats.getTotalTxBytes()))
.put("app", getDataUsage(
TrafficStats.getUidRxBytes(uid),
TrafficStats.getUidTxBytes(uid)))
.toString();
} catch(Exception ex) {
return jsonError("Problem fetching data usage stats.");
}
}
@VisibleForTesting
protected void applyRestrictions(boolean mute, int usage, int code) {
final String[] exceptionPackages = null; // none (for now)
// Only do this if we are executing within the system process... otherwise
// we are running as test code, so don't have access to the protected call.
if (Process.myUid() == Process.SYSTEM_UID) {
final long ident = Binder.clearCallingIdentity();
try {
mAppOps.setRestriction(code, usage,
mute ? AppOpsManager.MODE_IGNORED : AppOpsManager.MODE_ALLOWED,
exceptionPackages);
} finally {
Binder.restoreCallingIdentity(ident);
}
}
}
@Override
public Resources getResourcesForApplication(@NonNull ApplicationInfo app)
throws NameNotFoundException {
if (app.packageName.equals("system")) {
return mContext.mMainThread.getSystemUiContext().getResources();
}
final boolean sameUid = (app.uid == Process.myUid());
final Resources r = mContext.mMainThread.getTopLevelResources(
sameUid ? app.sourceDir : app.publicSourceDir,
sameUid ? app.splitSourceDirs : app.splitPublicSourceDirs,
app.resourceDirs, app.sharedLibraryFiles, Display.DEFAULT_DISPLAY,
mContext.mPackageInfo);
if (r != null) {
return r;
}
throw new NameNotFoundException("Unable to open " + app.publicSourceDir);
}
static boolean hasGeolocationPermission(Context context) {
int pid = Process.myPid();
int uid = Process.myUid();
if (ApiCompatibilityUtils.checkPermission(
context, Manifest.permission.ACCESS_COARSE_LOCATION, pid, uid)
!= PackageManager.PERMISSION_GRANTED) {
return false;
}
// Work around a bug in OnePlus2 devices running Lollipop, where the NETWORK_PROVIDER
// incorrectly requires FINE_LOCATION permission (it should only require COARSE_LOCATION
// permission). http://crbug.com/580733
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M
&& ApiCompatibilityUtils.checkPermission(
context, Manifest.permission.ACCESS_FINE_LOCATION, pid, uid)
!= PackageManager.PERMISSION_GRANTED) {
return false;
}
return true;
}
final void handleLowMemory() {
ArrayList<ComponentCallbacks2> callbacks;
synchronized (mPackages) {
callbacks = collectComponentCallbacksLocked(true, null);
}
final int N = callbacks.size();
for (int i=0; i<N; i++) {
callbacks.get(i).onLowMemory();
}
// Ask SQLite to free up as much memory as it can, mostly from its page caches.
if (Process.myUid() != Process.SYSTEM_UID) {
int sqliteReleased = SQLiteDatabase.releaseMemory();
EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
}
// Ask graphics to free up as much as possible (font/image caches)
Canvas.freeCaches();
BinderInternal.forceGc("mem");
}
/**
* @return true when inside a Binder transaction and the caller is in the
* foreground or self. Don't use outside a Binder transaction.
*/
private boolean isCallerForegroundOrSelf() {
int uid = Binder.getCallingUid();
if (uid == Process.myUid()) return true;
// Starting with L MR1, AM.getRunningAppProcesses doesn't return all the
// processes. We use a workaround in this case.
boolean useWorkaround = true;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) {
ActivityManager am =
(ActivityManager) mApplication.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> running = am.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo rpi : running) {
boolean matchingUid = rpi.uid == uid;
boolean isForeground = rpi.importance
== ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
useWorkaround &= !matchingUid;
if (matchingUid && isForeground) return true;
}
}
return useWorkaround ? !isBackgroundProcess(Binder.getCallingPid()) : false;
}
public void handleLoadPackage(final XC_LoadPackage.LoadPackageParam lpparam) throws Throwable {
int uid = Process.myUid();
Log.i(TAG, "Loaded " + lpparam.packageName + ":" + uid);
if ("android".equals(lpparam.packageName))
hookAndroid(lpparam);
if ("com.android.providers.settings".equals(lpparam.packageName))
hookSettings(lpparam);
if (!"android".equals(lpparam.packageName) &&
!lpparam.packageName.startsWith(BuildConfig.APPLICATION_ID))
hookApplication(lpparam);
}
@Override
public boolean beforeCall(Object who, Method method, Object... args) {
int index = ArrayUtils.indexOfLast(args, Integer.class);
if (index != -1) {
int uid = (int) args[index];
if (uid == Process.myUid()) {
args[index] = getRealUid();
}
}
return super.beforeCall(who, method, args);
}
@Override
public BrowserRoot onGetRoot(String clientPackageName, int clientUid, Bundle rootHints) {
if (clientPackageName == null || Process.SYSTEM_UID != clientUid && Process.myUid() != clientUid && !clientPackageName.equals("com.google.android.mediasimulator") && !clientPackageName.equals("com.google.android.projection.gearhead")) {
return null;
}
return new BrowserRoot(MEDIA_ID_ROOT, null);
}
public static String onChoosePrivateKeyAlias(Context context, int uid) {
if (uid == Process.myUid()) {
// Always show the chooser if we were the one requesting the cert.
return null;
}
String chosenAlias = PreferenceManager.getDefaultSharedPreferences(context)
.getString(OVERRIDE_KEY_SELECTION_KEY, null);
if (!TextUtils.isEmpty(chosenAlias)) {
showToast(context, "Substituting private key alias: \"" + chosenAlias + "\"");
return chosenAlias;
} else {
return null;
}
}
@Test
public void onTaskRun() throws Exception {
TrafficTaskEntity entity = new TrafficTaskEntity(200);
entity.onTaskRun();
PowerMockito.verifyStatic(times(2));
Process.myUid();
PowerMockito.verifyStatic();
TrafficSampler.getUidRxBytes(anyInt());
PowerMockito.verifyStatic();
TrafficSampler.getUidTxBytes(anyInt());
}
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
try {
// Do not restrict Zygote
if (Process.myUid() <= 0)
return;
// Pre processing
XParam xparam = XParam.fromXposed(param);
long start = System.currentTimeMillis();
// Execute hook
mHook.before(xparam);
long ms = System.currentTimeMillis() - start;
if (ms > PrivacyManager.cWarnHookDelayMs)
Util.log(mHook, Log.WARN, String.format("%s %d ms", param.method.getName(), ms));
// Post processing
if (xparam.hasResult())
param.setResult(xparam.getResult());
if (xparam.hasThrowable())
param.setThrowable(xparam.getThrowable());
param.setObjectExtra("xextra", xparam.getExtras());
} catch (Throwable ex) {
Util.bug(null, ex);
}
}
private void setupJitProfileSupport() {
if (!SystemProperties.getBoolean("dalvik.vm.usejitprofiles", false)) {
return;
}
// Only set up profile support if the loaded apk has the same uid as the
// current process.
// Currently, we do not support profiling across different apps.
// (e.g. application's uid might be different when the code is
// loaded by another app via createApplicationContext)
if (mApplicationInfo.uid != Process.myUid()) {
return;
}
final List<String> codePaths = new ArrayList<>();
if ((mApplicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0) {
codePaths.add(mApplicationInfo.sourceDir);
}
if (mApplicationInfo.splitSourceDirs != null) {
Collections.addAll(codePaths, mApplicationInfo.splitSourceDirs);
}
if (codePaths.isEmpty()) {
// If there are no code paths there's no need to setup a profile file and register with
// the runtime,
return;
}
final File profileFile = getPrimaryProfileFile(mPackageName);
VMRuntime.registerAppInfo(profileFile.getPath(),
codePaths.toArray(new String[codePaths.size()]));
// Register the app data directory with the reporter. It will
// help deciding whether or not a dex file is the primary apk or a
// secondary dex.
DexLoadReporter.getInstance().registerAppDataDir(mPackageName, mDataDir);
}
private void setupJitProfileSupport() {
if (!SystemProperties.getBoolean("dalvik.vm.usejitprofiles", false)) {
return;
}
// Only set up profile support if the loaded apk has the same uid as the
// current process.
// Currently, we do not support profiling across different apps.
// (e.g. application's uid might be different when the code is
// loaded by another app via createApplicationContext)
if (mApplicationInfo.uid != Process.myUid()) {
return;
}
final List<String> codePaths = new ArrayList<>();
if ((mApplicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0) {
codePaths.add(mApplicationInfo.sourceDir);
}
if (mApplicationInfo.splitSourceDirs != null) {
Collections.addAll(codePaths, mApplicationInfo.splitSourceDirs);
}
if (codePaths.isEmpty()) {
// If there are no code paths there's no need to setup a profile file and register with
// the runtime,
return;
}
for (int i = codePaths.size() - 1; i >= 0; i--) {
String splitName = i == 0 ? null : mApplicationInfo.splitNames[i - 1];
String profileFile = ArtManager.getCurrentProfilePath(
mPackageName, UserHandle.myUserId(), splitName);
VMRuntime.registerAppInfo(profileFile, new String[] {codePaths.get(i)});
}
// Register the app data directory with the reporter. It will
// help deciding whether or not a dex file is the primary apk or a
// secondary dex.
DexLoadReporter.getInstance().registerAppDataDir(mPackageName, mDataDir);
}
@Override
protected void before(XParam param) throws Throwable {
switch (mMethod) {
case exec:
// Get programs
String[] progs = null;
if (param.args.length > 0 && param.args[0] != null)
if (String.class.isAssignableFrom(param.args[0].getClass()))
progs = new String[] { (String) param.args[0] };
else
progs = (String[]) param.args[0];
// Check programs
if (progs != null) {
String command = TextUtils.join(" ", progs);
if (matches(command, mCommand) && isRestrictedExtra(param, command))
param.setThrowable(new IOException("XPrivacy"));
}
break;
case load:
case loadLibrary:
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP || Process.myUid() != Process.SYSTEM_UID)
if (param.args.length > 0) {
String libName = (String) param.args[0];
if (isRestrictedExtra(param, libName))
param.setThrowable(new UnsatisfiedLinkError("XPrivacy"));
}
break;
}
}
/**
* @return true when inside a Binder transaction and the caller is in the
* foreground or self. Don't use outside a Binder transaction.
*/
private boolean isCallerForegroundOrSelf() {
int uid = Binder.getCallingUid();
if (uid == Process.myUid()) return true;
// Starting with L MR1, AM.getRunningAppProcesses doesn't return all the
// processes. We use a workaround in this case.
boolean useWorkaround = true;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) {
do {
ActivityManager am =
(ActivityManager) mApplication.getSystemService(Context.ACTIVITY_SERVICE);
// Extra paranoia here and below, some L 5.0.x devices seem to throw NPE somewhere
// in this code.
// See https://crbug.com/654705.
if (am == null) break;
List<ActivityManager.RunningAppProcessInfo> running = am.getRunningAppProcesses();
if (running == null) break;
for (ActivityManager.RunningAppProcessInfo rpi : running) {
if (rpi == null) continue;
boolean matchingUid = rpi.uid == uid;
boolean isForeground = rpi.importance
== ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
useWorkaround &= !matchingUid;
if (matchingUid && isForeground) return true;
}
} while (false);
}
return useWorkaround ? !isBackgroundProcess(Binder.getCallingPid()) : false;
}
/**
* @param display The Display that the window being dragged is on.
*/
void register(DisplayContent displayContent) {
final Display display = displayContent.getDisplay();
if (DEBUG_TASK_POSITIONING) {
Slog.d(TAG, "Registering task positioner");
}
if (mClientChannel != null) {
Slog.e(TAG, "Task positioner already registered");
return;
}
mDisplay = display;
mDisplay.getMetrics(mDisplayMetrics);
final InputChannel[] channels = InputChannel.openInputChannelPair(TAG);
mServerChannel = channels[0];
mClientChannel = channels[1];
mService.mInputManager.registerInputChannel(mServerChannel, null);
mInputEventReceiver = new WindowPositionerEventReceiver(
mClientChannel, mService.mAnimationHandler.getLooper(),
mService.mAnimator.getChoreographer());
mDragApplicationHandle = new InputApplicationHandle(null);
mDragApplicationHandle.name = TAG;
mDragApplicationHandle.dispatchingTimeoutNanos =
WindowManagerService.DEFAULT_INPUT_DISPATCHING_TIMEOUT_NANOS;
mDragWindowHandle = new InputWindowHandle(mDragApplicationHandle, null, null,
mDisplay.getDisplayId());
mDragWindowHandle.name = TAG;
mDragWindowHandle.inputChannel = mServerChannel;
mDragWindowHandle.layer = mService.getDragLayerLocked();
mDragWindowHandle.layoutParamsFlags = 0;
mDragWindowHandle.layoutParamsType = WindowManager.LayoutParams.TYPE_DRAG;
mDragWindowHandle.dispatchingTimeoutNanos =
WindowManagerService.DEFAULT_INPUT_DISPATCHING_TIMEOUT_NANOS;
mDragWindowHandle.visible = true;
mDragWindowHandle.canReceiveKeys = false;
mDragWindowHandle.hasFocus = true;
mDragWindowHandle.hasWallpaper = false;
mDragWindowHandle.paused = false;
mDragWindowHandle.ownerPid = Process.myPid();
mDragWindowHandle.ownerUid = Process.myUid();
mDragWindowHandle.inputFeatures = 0;
mDragWindowHandle.scaleFactor = 1.0f;
// The drag window cannot receive new touches.
mDragWindowHandle.touchableRegion.setEmpty();
// The drag window covers the entire display
mDragWindowHandle.frameLeft = 0;
mDragWindowHandle.frameTop = 0;
final Point p = new Point();
mDisplay.getRealSize(p);
mDragWindowHandle.frameRight = p.x;
mDragWindowHandle.frameBottom = p.y;
// Pause rotations before a drag.
if (DEBUG_ORIENTATION) {
Slog.d(TAG, "Pausing rotation during re-position");
}
mService.pauseRotationLocked();
mSideMargin = dipToPixel(SIDE_MARGIN_DIP, mDisplayMetrics);
mMinVisibleWidth = dipToPixel(MINIMUM_VISIBLE_WIDTH_IN_DP, mDisplayMetrics);
mMinVisibleHeight = dipToPixel(MINIMUM_VISIBLE_HEIGHT_IN_DP, mDisplayMetrics);
mDisplay.getRealSize(mMaxVisibleSize);
mDragEnded = false;
}