Java Code Examples for android.os.Process#myUid()

The following examples show how to use android.os.Process#myUid() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HttpInjectInterceptor.java    From NetBare with MIT License 6 votes vote down vote up
@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));
    }
}
 
Example 2
Source File: CustomTabsConnection.java    From delion with Apache License 2.0 6 votes vote down vote up
/**
 * @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;
}
 
Example 3
Source File: ActivityThread.java    From AndroidComponentPlugin with Apache License 2.0 6 votes vote down vote up
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");
}
 
Example 4
Source File: GeolocationHeader.java    From AndroidChromium with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 5
Source File: ApplicationPackageManager.java    From AndroidComponentPlugin with Apache License 2.0 6 votes vote down vote up
@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);

}
 
Example 6
Source File: ZenModeHelper.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@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);
        }
    }
}
 
Example 7
Source File: MedicAndroidJavascript.java    From medic-android with GNU Affero General Public License v3.0 6 votes vote down vote up
@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.");
	}
}
 
Example 8
Source File: ApplicationPackageManager.java    From AndroidComponentPlugin with Apache License 2.0 6 votes vote down vote up
@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);

}
 
Example 9
Source File: MethodHookImpl.java    From droidmon with GNU General Public License v3.0 6 votes vote down vote up
@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;
		}
}
 
Example 10
Source File: CommonReceiverOperations.java    From android-testdpc with Apache License 2.0 5 votes vote down vote up
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;
    }
}
 
Example 11
Source File: MusicBrowserService.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
@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);
}
 
Example 12
Source File: TrafficTaskEntityTest.java    From analyzer-of-android-for-Apache-Weex with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example 13
Source File: XPrivacy.java    From XPrivacy with GNU General Public License v3.0 5 votes vote down vote up
@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);
	}
}
 
Example 14
Source File: LoadedApk.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 15
Source File: LoadedApk.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 16
Source File: XRuntime.java    From XPrivacy with GNU General Public License v3.0 5 votes vote down vote up
@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;
	}
}
 
Example 17
Source File: ReplaceLastUidHook.java    From container with GNU General Public License v3.0 5 votes vote down vote up
@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);
}
 
Example 18
Source File: XLua.java    From XPrivacyLua with GNU General Public License v3.0 5 votes vote down vote up
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);
}
 
Example 19
Source File: CustomTabsConnection.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/**
 * @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;
}
 
Example 20
Source File: TaskPositioner.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
/**
 * @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;
}