Search in sources :

Example 71 with ErrnoException

use of android.system.ErrnoException in project android_frameworks_base by AOSPA.

the class DefaultContainerService method copyPackageToContainerInner.

private String copyPackageToContainerInner(PackageLite pkg, NativeLibraryHelper.Handle handle, String newCid, String key, boolean isExternal, boolean isForwardLocked, String abiOverride) throws IOException {
    // Calculate container size, rounding up to nearest MB and adding an
    // extra MB for filesystem overhead
    final long sizeBytes = PackageHelper.calculateInstalledSize(pkg, handle, isForwardLocked, abiOverride);
    // Create new container
    final String newMountPath = PackageHelper.createSdDir(sizeBytes, newCid, key, Process.myUid(), isExternal);
    if (newMountPath == null) {
        throw new IOException("Failed to create container " + newCid);
    }
    final File targetDir = new File(newMountPath);
    try {
        // Copy all APKs
        copyFile(pkg.baseCodePath, targetDir, "base.apk", isForwardLocked);
        if (!ArrayUtils.isEmpty(pkg.splitNames)) {
            for (int i = 0; i < pkg.splitNames.length; i++) {
                copyFile(pkg.splitCodePaths[i], targetDir, "split_" + pkg.splitNames[i] + ".apk", isForwardLocked);
            }
        }
        // Extract native code
        final File libraryRoot = new File(targetDir, LIB_DIR_NAME);
        final int res = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, abiOverride);
        if (res != PackageManager.INSTALL_SUCCEEDED) {
            throw new IOException("Failed to extract native code, res=" + res);
        }
        if (!PackageHelper.finalizeSdDir(newCid)) {
            throw new IOException("Failed to finalize " + newCid);
        }
        if (PackageHelper.isContainerMounted(newCid)) {
            PackageHelper.unMountSdDir(newCid);
        }
    } catch (ErrnoException e) {
        PackageHelper.destroySdDir(newCid);
        throw e.rethrowAsIOException();
    } catch (IOException e) {
        PackageHelper.destroySdDir(newCid);
        throw e;
    }
    return newMountPath;
}
Also used : ErrnoException(android.system.ErrnoException) IOException(java.io.IOException) File(java.io.File)

Example 72 with ErrnoException

use of android.system.ErrnoException in project android_frameworks_base by AOSPA.

the class LocalTransport method performBackup.

@Override
public int performBackup(PackageInfo packageInfo, ParcelFileDescriptor data) {
    if (DEBUG) {
        try {
            StructStat ss = Os.fstat(data.getFileDescriptor());
            Log.v(TAG, "performBackup() pkg=" + packageInfo.packageName + " size=" + ss.st_size);
        } catch (ErrnoException e) {
            Log.w(TAG, "Unable to stat input file in performBackup() on " + packageInfo.packageName);
        }
    }
    File packageDir = new File(mCurrentSetIncrementalDir, packageInfo.packageName);
    packageDir.mkdirs();
    // Each 'record' in the restore set is kept in its own file, named by
    // the record key.  Wind through the data file, extracting individual
    // record operations and building a set of all the updates to apply
    // in this update.
    BackupDataInput changeSet = new BackupDataInput(data.getFileDescriptor());
    try {
        int bufSize = 512;
        byte[] buf = new byte[bufSize];
        while (changeSet.readNextHeader()) {
            String key = changeSet.getKey();
            String base64Key = new String(Base64.encode(key.getBytes()));
            File entityFile = new File(packageDir, base64Key);
            int dataSize = changeSet.getDataSize();
            if (DEBUG)
                Log.v(TAG, "Got change set key=" + key + " size=" + dataSize + " key64=" + base64Key);
            if (dataSize >= 0) {
                if (entityFile.exists()) {
                    entityFile.delete();
                }
                FileOutputStream entity = new FileOutputStream(entityFile);
                if (dataSize > bufSize) {
                    bufSize = dataSize;
                    buf = new byte[bufSize];
                }
                changeSet.readEntityData(buf, 0, dataSize);
                if (DEBUG) {
                    try {
                        long cur = Os.lseek(data.getFileDescriptor(), 0, SEEK_CUR);
                        Log.v(TAG, "  read entity data; new pos=" + cur);
                    } catch (ErrnoException e) {
                        Log.w(TAG, "Unable to stat input file in performBackup() on " + packageInfo.packageName);
                    }
                }
                try {
                    entity.write(buf, 0, dataSize);
                } catch (IOException e) {
                    Log.e(TAG, "Unable to update key file " + entityFile.getAbsolutePath());
                    return TRANSPORT_ERROR;
                } finally {
                    entity.close();
                }
            } else {
                entityFile.delete();
            }
        }
        return TRANSPORT_OK;
    } catch (IOException e) {
        // oops, something went wrong.  abort the operation and return error.
        Log.v(TAG, "Exception reading backup input:", e);
        return TRANSPORT_ERROR;
    }
}
Also used : BackupDataInput(android.app.backup.BackupDataInput) StructStat(android.system.StructStat) ErrnoException(android.system.ErrnoException) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) File(java.io.File)

Example 73 with ErrnoException

use of android.system.ErrnoException in project android_frameworks_base by AOSPA.

the class PackageManagerTests method assertDirOwnerGroupPermsIfExists.

private void assertDirOwnerGroupPermsIfExists(String reason, int uid, int gid, int perms, String path) {
    if (!new File(path).exists()) {
        return;
    }
    final StructStat stat;
    try {
        stat = Os.lstat(path);
    } catch (ErrnoException e) {
        throw new AssertionError(reason + "\n" + "Got: " + path + " does not exist");
    }
    StringBuilder sb = new StringBuilder();
    if (!S_ISDIR(stat.st_mode)) {
        sb.append("\nExpected type: ");
        sb.append(S_IFDIR);
        sb.append("\ngot type: ");
        sb.append((stat.st_mode & S_IFMT));
    }
    if (stat.st_uid != uid) {
        sb.append("\nExpected owner: ");
        sb.append(uid);
        sb.append("\nGot owner: ");
        sb.append(stat.st_uid);
    }
    if (stat.st_gid != gid) {
        sb.append("\nExpected group: ");
        sb.append(gid);
        sb.append("\nGot group: ");
        sb.append(stat.st_gid);
    }
    if ((stat.st_mode & ~S_IFMT) != perms) {
        sb.append("\nExpected permissions: ");
        sb.append(Integer.toOctalString(perms));
        sb.append("\nGot permissions: ");
        sb.append(Integer.toOctalString(stat.st_mode & ~S_IFMT));
    }
    if (sb.length() > 0) {
        throw new AssertionError(reason + sb.toString());
    }
}
Also used : StructStat(android.system.StructStat) ErrnoException(android.system.ErrnoException) File(java.io.File)

Example 74 with ErrnoException

use of android.system.ErrnoException in project android_frameworks_base by AOSPA.

the class ParcelFileDescriptor method createSocketPair.

/**
     * @hide
     */
public static ParcelFileDescriptor[] createSocketPair(int type) throws IOException {
    try {
        final FileDescriptor fd0 = new FileDescriptor();
        final FileDescriptor fd1 = new FileDescriptor();
        Os.socketpair(AF_UNIX, type, 0, fd0, fd1);
        return new ParcelFileDescriptor[] { new ParcelFileDescriptor(fd0), new ParcelFileDescriptor(fd1) };
    } catch (ErrnoException e) {
        throw e.rethrowAsIOException();
    }
}
Also used : ErrnoException(android.system.ErrnoException) FileDescriptor(java.io.FileDescriptor)

Example 75 with ErrnoException

use of android.system.ErrnoException in project android_frameworks_base by AOSPA.

the class ZygoteInit method preloadClasses.

/**
     * Performs Zygote process initialization. Loads and initializes
     * commonly used classes.
     *
     * Most classes only cause a few hundred bytes to be allocated, but
     * a few will allocate a dozen Kbytes (in one case, 500+K).
     */
private static void preloadClasses() {
    final VMRuntime runtime = VMRuntime.getRuntime();
    InputStream is;
    try {
        is = new FileInputStream(PRELOADED_CLASSES);
    } catch (FileNotFoundException e) {
        Log.e(TAG, "Couldn't find " + PRELOADED_CLASSES + ".");
        return;
    }
    Log.i(TAG, "Preloading classes...");
    long startTime = SystemClock.uptimeMillis();
    // Drop root perms while running static initializers.
    final int reuid = Os.getuid();
    final int regid = Os.getgid();
    // We need to drop root perms only if we're already root. In the case of "wrapped"
    // processes (see WrapperInit), this function is called from an unprivileged uid
    // and gid.
    boolean droppedPriviliges = false;
    if (reuid == ROOT_UID && regid == ROOT_GID) {
        try {
            Os.setregid(ROOT_GID, UNPRIVILEGED_GID);
            Os.setreuid(ROOT_UID, UNPRIVILEGED_UID);
        } catch (ErrnoException ex) {
            throw new RuntimeException("Failed to drop root", ex);
        }
        droppedPriviliges = true;
    }
    // Alter the target heap utilization.  With explicit GCs this
    // is not likely to have any effect.
    float defaultUtilization = runtime.getTargetHeapUtilization();
    runtime.setTargetHeapUtilization(0.8f);
    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(is), 256);
        int count = 0;
        String line;
        while ((line = br.readLine()) != null) {
            // Skip comments and blank lines.
            line = line.trim();
            if (line.startsWith("#") || line.equals("")) {
                continue;
            }
            Trace.traceBegin(Trace.TRACE_TAG_DALVIK, line);
            try {
                if (false) {
                    Log.v(TAG, "Preloading " + line + "...");
                }
                // Load and explicitly initialize the given class. Use
                // Class.forName(String, boolean, ClassLoader) to avoid repeated stack lookups
                // (to derive the caller's class-loader). Use true to force initialization, and
                // null for the boot classpath class-loader (could as well cache the
                // class-loader of this class in a variable).
                Class.forName(line, true, null);
                count++;
            } catch (ClassNotFoundException e) {
                Log.w(TAG, "Class not found for preloading: " + line);
            } catch (UnsatisfiedLinkError e) {
                Log.w(TAG, "Problem preloading " + line + ": " + e);
            } catch (Throwable t) {
                Log.e(TAG, "Error preloading " + line + ".", t);
                if (t instanceof Error) {
                    throw (Error) t;
                }
                if (t instanceof RuntimeException) {
                    throw (RuntimeException) t;
                }
                throw new RuntimeException(t);
            }
            Trace.traceEnd(Trace.TRACE_TAG_DALVIK);
        }
        Log.i(TAG, "...preloaded " + count + " classes in " + (SystemClock.uptimeMillis() - startTime) + "ms.");
    } catch (IOException e) {
        Log.e(TAG, "Error reading " + PRELOADED_CLASSES + ".", e);
    } finally {
        IoUtils.closeQuietly(is);
        // Restore default.
        runtime.setTargetHeapUtilization(defaultUtilization);
        // Fill in dex caches with classes, fields, and methods brought in by preloading.
        Trace.traceBegin(Trace.TRACE_TAG_DALVIK, "PreloadDexCaches");
        runtime.preloadDexCaches();
        Trace.traceEnd(Trace.TRACE_TAG_DALVIK);
        // Bring back root. We'll need it later if we're in the zygote.
        if (droppedPriviliges) {
            try {
                Os.setreuid(ROOT_UID, ROOT_UID);
                Os.setregid(ROOT_GID, ROOT_GID);
            } catch (ErrnoException ex) {
                throw new RuntimeException("Failed to restore root", ex);
            }
        }
    }
}
Also used : VMRuntime(dalvik.system.VMRuntime) InputStreamReader(java.io.InputStreamReader) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) ErrnoException(android.system.ErrnoException) BufferedReader(java.io.BufferedReader)

Aggregations

ErrnoException (android.system.ErrnoException)215 IOException (java.io.IOException)99 FileDescriptor (java.io.FileDescriptor)95 File (java.io.File)74 StructStat (android.system.StructStat)45 FileInputStream (java.io.FileInputStream)40 FileOutputStream (java.io.FileOutputStream)29 ParcelFileDescriptor (android.os.ParcelFileDescriptor)17 SocketException (java.net.SocketException)17 BufferedInputStream (java.io.BufferedInputStream)15 InputStream (java.io.InputStream)11 AssetFileDescriptor (android.content.res.AssetFileDescriptor)10 ExifInterface (android.media.ExifInterface)10 StructLinger (android.system.StructLinger)10 StructTimeval (android.system.StructTimeval)10 FileNotFoundException (java.io.FileNotFoundException)10 StructPollfd (android.system.StructPollfd)9 InterruptedIOException (java.io.InterruptedIOException)9 PacketSocketAddress (android.system.PacketSocketAddress)8 XmlPullParserException (org.xmlpull.v1.XmlPullParserException)8