Search in sources :

Example 36 with ApplicationInfo

use of android.content.pm.ApplicationInfo in project platform_frameworks_base by android.

the class Settings method writePackageListLPr.

void writePackageListLPr(int creatingUserId) {
    // Only derive GIDs for active users (not dying)
    final List<UserInfo> users = UserManagerService.getInstance().getUsers(true);
    int[] userIds = new int[users.size()];
    for (int i = 0; i < userIds.length; i++) {
        userIds[i] = users.get(i).id;
    }
    if (creatingUserId != -1) {
        userIds = ArrayUtils.appendInt(userIds, creatingUserId);
    }
    // Write package list file now, use a JournaledFile.
    File tempFile = new File(mPackageListFilename.getAbsolutePath() + ".tmp");
    JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
    final File writeTarget = journal.chooseForWrite();
    FileOutputStream fstr;
    BufferedWriter writer = null;
    try {
        fstr = new FileOutputStream(writeTarget);
        writer = new BufferedWriter(new OutputStreamWriter(fstr, Charset.defaultCharset()));
        FileUtils.setPermissions(fstr.getFD(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
        StringBuilder sb = new StringBuilder();
        for (final PackageSetting pkg : mPackages.values()) {
            if (pkg.pkg == null || pkg.pkg.applicationInfo == null || pkg.pkg.applicationInfo.dataDir == null) {
                if (!"android".equals(pkg.name)) {
                    Slog.w(TAG, "Skipping " + pkg + " due to missing metadata");
                }
                continue;
            }
            final ApplicationInfo ai = pkg.pkg.applicationInfo;
            final String dataPath = ai.dataDir;
            final boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
            final int[] gids = pkg.getPermissionsState().computeGids(userIds);
            // Avoid any application that has a space in its path.
            if (dataPath.indexOf(' ') >= 0)
                continue;
            // we store on each line the following information for now:
            //
            // pkgName    - package name
            // userId     - application-specific user id
            // debugFlag  - 0 or 1 if the package is debuggable.
            // dataPath   - path to package's data path
            // seinfo     - seinfo label for the app (assigned at install time)
            // gids       - supplementary gids this app launches with
            //
            // NOTE: We prefer not to expose all ApplicationInfo flags for now.
            //
            // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
            // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
            //   frameworks/base/libs/packagelistparser
            //   system/core/run-as/run-as.c
            //
            sb.setLength(0);
            sb.append(ai.packageName);
            sb.append(" ");
            sb.append(ai.uid);
            sb.append(isDebug ? " 1 " : " 0 ");
            sb.append(dataPath);
            sb.append(" ");
            sb.append(ai.seinfo);
            sb.append(" ");
            if (gids != null && gids.length > 0) {
                sb.append(gids[0]);
                for (int i = 1; i < gids.length; i++) {
                    sb.append(",");
                    sb.append(gids[i]);
                }
            } else {
                sb.append("none");
            }
            sb.append("\n");
            writer.append(sb);
        }
        writer.flush();
        FileUtils.sync(fstr);
        writer.close();
        journal.commit();
    } catch (Exception e) {
        Slog.wtf(TAG, "Failed to write packages.list", e);
        IoUtils.closeQuietly(writer);
        journal.rollback();
    }
}
Also used : JournaledFile(com.android.internal.util.JournaledFile) ApplicationInfo(android.content.pm.ApplicationInfo) UserInfo(android.content.pm.UserInfo) InstallerException(com.android.server.pm.Installer.InstallerException) FileNotFoundException(java.io.FileNotFoundException) XmlPullParserException(org.xmlpull.v1.XmlPullParserException) IOException(java.io.IOException) BufferedWriter(java.io.BufferedWriter) FileOutputStream(java.io.FileOutputStream) OutputStreamWriter(java.io.OutputStreamWriter) AtomicFile(android.util.AtomicFile) File(java.io.File) JournaledFile(com.android.internal.util.JournaledFile)

Example 37 with ApplicationInfo

use of android.content.pm.ApplicationInfo in project platform_frameworks_base by android.

the class DexManager method reconcileSecondaryDexFiles.

/**
     * Reconcile the information we have about the secondary dex files belonging to
     * {@code packagName} and the actual dex files. For all dex files that were
     * deleted, update the internal records and delete any generated oat files.
     */
public void reconcileSecondaryDexFiles(String packageName) {
    PackageUseInfo useInfo = getPackageUseInfo(packageName);
    if (useInfo == null || useInfo.getDexUseInfoMap().isEmpty()) {
        if (DEBUG) {
            Slog.d(TAG, "No secondary dex use for package:" + packageName);
        }
        // Nothing to reconcile.
        return;
    }
    Set<String> dexFilesToRemove = new HashSet<>();
    boolean updated = false;
    for (Map.Entry<String, DexUseInfo> entry : useInfo.getDexUseInfoMap().entrySet()) {
        String dexPath = entry.getKey();
        DexUseInfo dexUseInfo = entry.getValue();
        PackageInfo pkg = null;
        try {
            // Note that we look for the package in the PackageManager just to be able
            // to get back the real app uid and its storage kind. These are only used
            // to perform extra validation in installd.
            // TODO(calin): maybe a bit overkill.
            pkg = mPackageManager.getPackageInfo(packageName, /*flags*/
            0, dexUseInfo.getOwnerUserId());
        } catch (RemoteException ignore) {
        // Can't happen, DexManager is local.
        }
        if (pkg == null) {
            // It may be that the package was uninstalled while we process the secondary
            // dex files.
            Slog.d(TAG, "Could not find package when compiling secondary dex " + packageName + " for user " + dexUseInfo.getOwnerUserId());
            // Update the usage and continue, another user might still have the package.
            updated = mPackageDexUsage.removeUserPackage(packageName, dexUseInfo.getOwnerUserId()) || updated;
            continue;
        }
        ApplicationInfo info = pkg.applicationInfo;
        int flags = 0;
        if (info.dataDir.equals(info.deviceProtectedDataDir)) {
            flags |= StorageManager.FLAG_STORAGE_DE;
        } else if (info.dataDir.equals(info.credentialProtectedDataDir)) {
            flags |= StorageManager.FLAG_STORAGE_CE;
        } else {
            Slog.e(TAG, "Could not infer CE/DE storage for package " + info.packageName);
            updated = mPackageDexUsage.removeUserPackage(packageName, dexUseInfo.getOwnerUserId()) || updated;
            continue;
        }
        boolean dexStillExists = true;
        synchronized (mInstallLock) {
            try {
                String[] isas = dexUseInfo.getLoaderIsas().toArray(new String[0]);
                dexStillExists = mInstaller.reconcileSecondaryDexFile(dexPath, packageName, pkg.applicationInfo.uid, isas, pkg.applicationInfo.volumeUuid, flags);
            } catch (InstallerException e) {
                Slog.e(TAG, "Got InstallerException when reconciling dex " + dexPath + " : " + e.getMessage());
            }
        }
        if (!dexStillExists) {
            updated = mPackageDexUsage.removeDexFile(packageName, dexPath, dexUseInfo.getOwnerUserId()) || updated;
        }
    }
    if (updated) {
        mPackageDexUsage.maybeWriteAsync();
    }
}
Also used : PackageInfo(android.content.pm.PackageInfo) ApplicationInfo(android.content.pm.ApplicationInfo) DexUseInfo(com.android.server.pm.dex.PackageDexUsage.DexUseInfo) InstallerException(com.android.server.pm.Installer.InstallerException) RemoteException(android.os.RemoteException) PackageUseInfo(com.android.server.pm.dex.PackageDexUsage.PackageUseInfo) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet)

Example 38 with ApplicationInfo

use of android.content.pm.ApplicationInfo in project platform_frameworks_base by android.

the class DevicePolicyManagerTest method testApplicationRestrictionsManagingApp.

public void testApplicationRestrictionsManagingApp() throws Exception {
    setAsProfileOwner(admin1);
    final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
    final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
    final int appRestrictionsManagerAppId = 20987;
    final int appRestrictionsManagerUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, appRestrictionsManagerAppId);
    doReturn(appRestrictionsManagerUid).when(mContext.packageManager).getPackageUidAsUser(eq(appRestrictionsManagerPackage), eq(DpmMockContext.CALLER_USER_HANDLE));
    mContext.binder.callingUid = appRestrictionsManagerUid;
    final PackageInfo pi = new PackageInfo();
    pi.applicationInfo = new ApplicationInfo();
    pi.applicationInfo.flags = ApplicationInfo.FLAG_HAS_CODE;
    doReturn(pi).when(mContext.ipackageManager).getPackageInfo(eq(appRestrictionsManagerPackage), anyInt(), eq(DpmMockContext.CALLER_USER_HANDLE));
    // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
    // delegated that permission yet.
    assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
    Bundle rest = new Bundle();
    rest.putString("KEY_STRING", "Foo1");
    try {
        dpm.setApplicationRestrictions(null, "pkg1", rest);
        fail("Didn't throw expected SecurityException");
    } catch (SecurityException expected) {
        MoreAsserts.assertContainsRegex("caller cannot manage application restrictions", expected.getMessage());
    }
    try {
        dpm.getApplicationRestrictions(null, "pkg1");
        fail("Didn't throw expected SecurityException");
    } catch (SecurityException expected) {
        MoreAsserts.assertContainsRegex("caller cannot manage application restrictions", expected.getMessage());
    }
    // Check via the profile owner that no restrictions were set.
    mContext.binder.callingUid = DpmMockContext.CALLER_UID;
    assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
    // Check the API does not allow setting a non-existent package
    try {
        dpm.setApplicationRestrictionsManagingPackage(admin1, nonExistAppRestrictionsManagerPackage);
        fail("Non-existent app set as app restriction manager.");
    } catch (PackageManager.NameNotFoundException expected) {
        MoreAsserts.assertContainsRegex(nonExistAppRestrictionsManagerPackage, expected.getMessage());
    }
    // Let appRestrictionsManagerPackage manage app restrictions
    dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
    assertEquals(appRestrictionsManagerPackage, dpm.getApplicationRestrictionsManagingPackage(admin1));
    // Now that package should be able to set and retrieve app restrictions.
    mContext.binder.callingUid = appRestrictionsManagerUid;
    assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
    dpm.setApplicationRestrictions(null, "pkg1", rest);
    Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
    assertEquals(1, returned.size(), 1);
    assertEquals("Foo1", returned.get("KEY_STRING"));
    // The same app running on a separate user shouldn't be able to manage app restrictions.
    mContext.binder.callingUid = UserHandle.getUid(UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
    assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
    try {
        dpm.setApplicationRestrictions(null, "pkg1", rest);
        fail("Didn't throw expected SecurityException");
    } catch (SecurityException expected) {
        MoreAsserts.assertContainsRegex("caller cannot manage application restrictions", expected.getMessage());
    }
    // The DPM is still able to manage app restrictions, even if it allowed another app to do it
    // too.
    mContext.binder.callingUid = DpmMockContext.CALLER_UID;
    assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
    dpm.setApplicationRestrictions(admin1, "pkg1", null);
    assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
    // Removing the ability for the package to manage app restrictions.
    dpm.setApplicationRestrictionsManagingPackage(admin1, null);
    assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
    mContext.binder.callingUid = appRestrictionsManagerUid;
    assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
    try {
        dpm.setApplicationRestrictions(null, "pkg1", null);
        fail("Didn't throw expected SecurityException");
    } catch (SecurityException expected) {
        MoreAsserts.assertContainsRegex("caller cannot manage application restrictions", expected.getMessage());
    }
}
Also used : PackageManager(android.content.pm.PackageManager) PackageInfo(android.content.pm.PackageInfo) Bundle(android.os.Bundle) ApplicationInfo(android.content.pm.ApplicationInfo) Matchers.anyString(org.mockito.Matchers.anyString)

Example 39 with ApplicationInfo

use of android.content.pm.ApplicationInfo in project platform_frameworks_base by android.

the class NetworkPolicyManagerServiceTest method callSystemReady.

@Before
public void callSystemReady() throws Exception {
    MockitoAnnotations.initMocks(this);
    final Context context = InstrumentationRegistry.getContext();
    setCurrentTimeMillis(TEST_START);
    // intercept various broadcasts, and pretend that uids have packages
    mServiceContext = new BroadcastInterceptingContext(context) {

        @Override
        public PackageManager getPackageManager() {
            return mPackageManager;
        }

        @Override
        public void startActivity(Intent intent) {
        // ignored
        }
    };
    mPolicyDir = context.getFilesDir();
    if (mPolicyDir.exists()) {
        IoUtils.deleteContents(mPolicyDir);
    }
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            mUidObserver = (IUidObserver) invocation.getArguments()[0];
            Log.d(TAG, "set mUidObserver to " + mUidObserver);
            return null;
        }
    }).when(mActivityManager).registerUidObserver(any(), anyInt());
    mService = new NetworkPolicyManagerService(mServiceContext, mActivityManager, mStatsService, mNetworkManager, mTime, mPolicyDir, true);
    mService.bindConnectivityManager(mConnManager);
    mService.bindNotificationManager(mNotifManager);
    mPolicyListener = new NetworkPolicyListenerAnswer(mService);
    // Sets some common expectations.
    when(mPackageManager.getPackageInfo(anyString(), anyInt())).thenAnswer(new Answer<PackageInfo>() {

        @Override
        public PackageInfo answer(InvocationOnMock invocation) throws Throwable {
            final String packageName = (String) invocation.getArguments()[0];
            final PackageInfo info = new PackageInfo();
            final Signature signature;
            if ("android".equals(packageName)) {
                signature = new Signature("F00D");
            } else {
                signature = new Signature("DEAD");
            }
            info.signatures = new Signature[] { signature };
            return info;
        }
    });
    when(mPackageManager.getApplicationInfoAsUser(anyString(), anyInt(), anyInt())).thenReturn(new ApplicationInfo());
    when(mPackageManager.getPackagesForUid(UID_A)).thenReturn(new String[] { PKG_NAME_A });
    when(mNetworkManager.isBandwidthControlEnabled()).thenReturn(true);
    expectCurrentTime();
    // Prepare NPMS.
    mService.systemReady();
    // catch INetworkManagementEventObserver during systemReady()
    ArgumentCaptor<INetworkManagementEventObserver> networkObserver = ArgumentCaptor.forClass(INetworkManagementEventObserver.class);
    verify(mNetworkManager).registerObserver(networkObserver.capture());
    mNetworkObserver = networkObserver.getValue();
}
Also used : BroadcastInterceptingContext(com.android.internal.util.test.BroadcastInterceptingContext) Context(android.content.Context) PackageInfo(android.content.pm.PackageInfo) BroadcastInterceptingContext(com.android.internal.util.test.BroadcastInterceptingContext) ApplicationInfo(android.content.pm.ApplicationInfo) Intent(android.content.Intent) Matchers.anyString(org.mockito.Matchers.anyString) IUidObserver(android.app.IUidObserver) NetworkPolicyManagerService(com.android.server.net.NetworkPolicyManagerService) PackageManager(android.content.pm.PackageManager) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Signature(android.content.pm.Signature) INetworkManagementEventObserver(android.net.INetworkManagementEventObserver) Before(org.junit.Before)

Example 40 with ApplicationInfo

use of android.content.pm.ApplicationInfo in project platform_frameworks_base by android.

the class MediaSessions method getControllerName.

protected String getControllerName(MediaController controller) {
    final PackageManager pm = mContext.getPackageManager();
    final String pkg = controller.getPackageName();
    try {
        if (USE_SERVICE_LABEL) {
            final List<ResolveInfo> ris = pm.queryIntentServices(new Intent("android.media.MediaRouteProviderService").setPackage(pkg), 0);
            if (ris != null) {
                for (ResolveInfo ri : ris) {
                    if (ri.serviceInfo == null)
                        continue;
                    if (pkg.equals(ri.serviceInfo.packageName)) {
                        final String serviceLabel = Objects.toString(ri.serviceInfo.loadLabel(pm), "").trim();
                        if (serviceLabel.length() > 0) {
                            return serviceLabel;
                        }
                    }
                }
            }
        }
        final ApplicationInfo ai = pm.getApplicationInfo(pkg, 0);
        final String appLabel = Objects.toString(ai.loadLabel(pm), "").trim();
        if (appLabel.length() > 0) {
            return appLabel;
        }
    } catch (NameNotFoundException e) {
    }
    return pkg;
}
Also used : ResolveInfo(android.content.pm.ResolveInfo) PackageManager(android.content.pm.PackageManager) NameNotFoundException(android.content.pm.PackageManager.NameNotFoundException) ApplicationInfo(android.content.pm.ApplicationInfo) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent)

Aggregations

ApplicationInfo (android.content.pm.ApplicationInfo)921 PackageManager (android.content.pm.PackageManager)345 NameNotFoundException (android.content.pm.PackageManager.NameNotFoundException)274 RemoteException (android.os.RemoteException)204 Intent (android.content.Intent)103 ArrayList (java.util.ArrayList)98 IPackageManager (android.content.pm.IPackageManager)96 IOException (java.io.IOException)80 PackageInfo (android.content.pm.PackageInfo)79 ResolveInfo (android.content.pm.ResolveInfo)72 File (java.io.File)64 ComponentName (android.content.ComponentName)52 Context (android.content.Context)51 Bundle (android.os.Bundle)50 PendingIntent (android.app.PendingIntent)45 Drawable (android.graphics.drawable.Drawable)43 UserInfo (android.content.pm.UserInfo)40 ActivityInfo (android.content.pm.ActivityInfo)35 ServiceInfo (android.content.pm.ServiceInfo)35 Resources (android.content.res.Resources)33