Search in sources :

Example 36 with ErrnoException

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

the class MemoryMappedFile_Delegate method mmapRO.

@LayoutlibDelegate
static MemoryMappedFile mmapRO(String path) throws ErrnoException {
    if (!path.startsWith(TARGET_PATH)) {
        throw new ErrnoException("Custom timezone data files are not supported.", 1);
    }
    if (sRootPath == null) {
        throw new ErrnoException("Bridge has not been initialized properly.", 1);
    }
    path = path.substring(TARGET_PATH.length());
    try {
        File f = new File(sRootPath, path);
        if (!f.exists()) {
            throw new ErrnoException("File not found: " + f.getPath(), 1);
        }
        RandomAccessFile file = new RandomAccessFile(f, "r");
        try {
            long size = file.length();
            MemoryMappedFile_Delegate newDelegate = new MemoryMappedFile_Delegate(file);
            long filePointer = file.getFilePointer();
            MemoryMappedFile mmFile = new MemoryMappedFile(filePointer, size);
            long delegateIndex = sManager.addNewDelegate(newDelegate);
            sMemoryMappedFileMap.put(mmFile, delegateIndex);
            return mmFile;
        } finally {
            file.close();
        }
    } catch (IOException e) {
        throw new ErrnoException("mmapRO", 1, e);
    }
}
Also used : ErrnoException(android.system.ErrnoException) RandomAccessFile(java.io.RandomAccessFile) IOException(java.io.IOException) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) LayoutlibDelegate(com.android.tools.layoutlib.annotations.LayoutlibDelegate)

Example 37 with ErrnoException

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

the class DocumentsContract method getDocumentThumbnail.

/** {@hide} */
public static Bitmap getDocumentThumbnail(ContentProviderClient client, Uri documentUri, Point size, CancellationSignal signal) throws RemoteException, IOException {
    final Bundle openOpts = new Bundle();
    openOpts.putParcelable(ContentResolver.EXTRA_SIZE, size);
    AssetFileDescriptor afd = null;
    Bitmap bitmap = null;
    try {
        afd = client.openTypedAssetFileDescriptor(documentUri, "image/*", openOpts, signal);
        final FileDescriptor fd = afd.getFileDescriptor();
        final long offset = afd.getStartOffset();
        // Try seeking on the returned FD, since it gives us the most
        // optimal decode path; otherwise fall back to buffering.
        BufferedInputStream is = null;
        try {
            Os.lseek(fd, offset, SEEK_SET);
        } catch (ErrnoException e) {
            is = new BufferedInputStream(new FileInputStream(fd), THUMBNAIL_BUFFER_SIZE);
            is.mark(THUMBNAIL_BUFFER_SIZE);
        }
        // We requested a rough thumbnail size, but the remote size may have
        // returned something giant, so defensively scale down as needed.
        final BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        if (is != null) {
            BitmapFactory.decodeStream(is, null, opts);
        } else {
            BitmapFactory.decodeFileDescriptor(fd, null, opts);
        }
        final int widthSample = opts.outWidth / size.x;
        final int heightSample = opts.outHeight / size.y;
        opts.inJustDecodeBounds = false;
        opts.inSampleSize = Math.min(widthSample, heightSample);
        if (is != null) {
            is.reset();
            bitmap = BitmapFactory.decodeStream(is, null, opts);
        } else {
            try {
                Os.lseek(fd, offset, SEEK_SET);
            } catch (ErrnoException e) {
                e.rethrowAsIOException();
            }
            bitmap = BitmapFactory.decodeFileDescriptor(fd, null, opts);
        }
        // Transform the bitmap if requested. We use a side-channel to
        // communicate the orientation, since EXIF thumbnails don't contain
        // the rotation flags of the original image.
        final Bundle extras = afd.getExtras();
        final int orientation = (extras != null) ? extras.getInt(EXTRA_ORIENTATION, 0) : 0;
        if (orientation != 0) {
            final int width = bitmap.getWidth();
            final int height = bitmap.getHeight();
            final Matrix m = new Matrix();
            m.setRotate(orientation, width / 2, height / 2);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, m, false);
        }
    } finally {
        IoUtils.closeQuietly(afd);
    }
    return bitmap;
}
Also used : AssetFileDescriptor(android.content.res.AssetFileDescriptor) Bundle(android.os.Bundle) AssetFileDescriptor(android.content.res.AssetFileDescriptor) ParcelFileDescriptor(android.os.ParcelFileDescriptor) FileDescriptor(java.io.FileDescriptor) FileInputStream(java.io.FileInputStream) Point(android.graphics.Point) Bitmap(android.graphics.Bitmap) ErrnoException(android.system.ErrnoException) Matrix(android.graphics.Matrix) BufferedInputStream(java.io.BufferedInputStream) BitmapFactory(android.graphics.BitmapFactory)

Example 38 with ErrnoException

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

the class ZygoteConnection method handleChildProc.

/**
     * Handles post-fork setup of child proc, closing sockets as appropriate,
     * reopen stdio as appropriate, and ultimately throwing MethodAndArgsCaller
     * if successful or returning if failed.
     *
     * @param parsedArgs non-null; zygote args
     * @param descriptors null-ok; new file descriptors for stdio if available.
     * @param pipeFd null-ok; pipe for communication back to Zygote.
     * @param newStderr null-ok; stream to use for stderr until stdio
     * is reopened.
     *
     * @throws ZygoteInit.MethodAndArgsCaller on success to
     * trampoline to code that invokes static main.
     */
private void handleChildProc(Arguments parsedArgs, FileDescriptor[] descriptors, FileDescriptor pipeFd, PrintStream newStderr) throws ZygoteInit.MethodAndArgsCaller {
    /**
         * By the time we get here, the native code has closed the two actual Zygote
         * socket connections, and substituted /dev/null in their place.  The LocalSocket
         * objects still need to be closed properly.
         */
    closeSocket();
    ZygoteInit.closeServerSocket();
    if (descriptors != null) {
        try {
            Os.dup2(descriptors[0], STDIN_FILENO);
            Os.dup2(descriptors[1], STDOUT_FILENO);
            Os.dup2(descriptors[2], STDERR_FILENO);
            for (FileDescriptor fd : descriptors) {
                IoUtils.closeQuietly(fd);
            }
            newStderr = System.err;
        } catch (ErrnoException ex) {
            Log.e(TAG, "Error reopening stdio", ex);
        }
    }
    if (parsedArgs.niceName != null) {
        Process.setArgV0(parsedArgs.niceName);
    }
    // End of the postFork event.
    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
    if (parsedArgs.invokeWith != null) {
        WrapperInit.execApplication(parsedArgs.invokeWith, parsedArgs.niceName, parsedArgs.targetSdkVersion, VMRuntime.getCurrentInstructionSet(), pipeFd, parsedArgs.remainingArgs);
    } else {
        RuntimeInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs, null);
    }
}
Also used : ErrnoException(android.system.ErrnoException) FileDescriptor(java.io.FileDescriptor)

Example 39 with ErrnoException

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

the class ZygoteConnection method runOnce.

/**
     * Reads one start command from the command socket. If successful,
     * a child is forked and a {@link ZygoteInit.MethodAndArgsCaller}
     * exception is thrown in that child while in the parent process,
     * the method returns normally. On failure, the child is not
     * spawned and messages are printed to the log and stderr. Returns
     * a boolean status value indicating whether an end-of-file on the command
     * socket has been encountered.
     *
     * @return false if command socket should continue to be read from, or
     * true if an end-of-file has been encountered.
     * @throws ZygoteInit.MethodAndArgsCaller trampoline to invoke main()
     * method in child process
     */
boolean runOnce() throws ZygoteInit.MethodAndArgsCaller {
    String[] args;
    Arguments parsedArgs = null;
    FileDescriptor[] descriptors;
    try {
        args = readArgumentList();
        descriptors = mSocket.getAncillaryFileDescriptors();
    } catch (IOException ex) {
        Log.w(TAG, "IOException on command socket " + ex.getMessage());
        closeSocket();
        return true;
    }
    if (args == null) {
        // EOF reached.
        closeSocket();
        return true;
    }
    /** the stderr of the most recent request, if avail */
    PrintStream newStderr = null;
    if (descriptors != null && descriptors.length >= 3) {
        newStderr = new PrintStream(new FileOutputStream(descriptors[2]));
    }
    int pid = -1;
    FileDescriptor childPipeFd = null;
    FileDescriptor serverPipeFd = null;
    try {
        parsedArgs = new Arguments(args);
        if (parsedArgs.abiListQuery) {
            return handleAbiListQuery();
        }
        if (parsedArgs.permittedCapabilities != 0 || parsedArgs.effectiveCapabilities != 0) {
            throw new ZygoteSecurityException("Client may not specify capabilities: " + "permitted=0x" + Long.toHexString(parsedArgs.permittedCapabilities) + ", effective=0x" + Long.toHexString(parsedArgs.effectiveCapabilities));
        }
        applyUidSecurityPolicy(parsedArgs, peer);
        applyInvokeWithSecurityPolicy(parsedArgs, peer);
        applyDebuggerSystemProperty(parsedArgs);
        applyInvokeWithSystemProperty(parsedArgs);
        int[][] rlimits = null;
        if (parsedArgs.rlimits != null) {
            rlimits = parsedArgs.rlimits.toArray(intArray2d);
        }
        if (parsedArgs.invokeWith != null) {
            FileDescriptor[] pipeFds = Os.pipe2(O_CLOEXEC);
            childPipeFd = pipeFds[1];
            serverPipeFd = pipeFds[0];
            Os.fcntlInt(childPipeFd, F_SETFD, 0);
        }
        if (parsedArgs.refreshTheme) {
            Typeface.recreateDefaults();
        }
        /**
             * In order to avoid leaking descriptors to the Zygote child,
             * the native code must close the two Zygote socket descriptors
             * in the child process before it switches from Zygote-root to
             * the UID and privileges of the application being launched.
             *
             * In order to avoid "bad file descriptor" errors when the
             * two LocalSocket objects are closed, the Posix file
             * descriptors are released via a dup2() call which closes
             * the socket and substitutes an open descriptor to /dev/null.
             */
        int[] fdsToClose = { -1, -1 };
        FileDescriptor fd = mSocket.getFileDescriptor();
        if (fd != null) {
            fdsToClose[0] = fd.getInt$();
        }
        fd = ZygoteInit.getServerSocketFileDescriptor();
        if (fd != null) {
            fdsToClose[1] = fd.getInt$();
        }
        fd = null;
        pid = Zygote.forkAndSpecialize(parsedArgs.uid, parsedArgs.gid, parsedArgs.gids, parsedArgs.debugFlags, rlimits, parsedArgs.mountExternal, parsedArgs.seInfo, parsedArgs.niceName, fdsToClose, parsedArgs.instructionSet, parsedArgs.appDataDir);
    } catch (ErrnoException ex) {
        logAndPrintError(newStderr, "Exception creating pipe", ex);
    } catch (IllegalArgumentException ex) {
        logAndPrintError(newStderr, "Invalid zygote arguments", ex);
    } catch (ZygoteSecurityException ex) {
        logAndPrintError(newStderr, "Zygote security policy prevents request: ", ex);
    }
    try {
        if (pid == 0) {
            // in child
            IoUtils.closeQuietly(serverPipeFd);
            serverPipeFd = null;
            handleChildProc(parsedArgs, descriptors, childPipeFd, newStderr);
            // throw ZygoteInit.MethodAndArgsCaller or exec().
            return true;
        } else {
            // in parent...pid of < 0 means failure
            IoUtils.closeQuietly(childPipeFd);
            childPipeFd = null;
            return handleParentProc(pid, descriptors, serverPipeFd, parsedArgs);
        }
    } finally {
        IoUtils.closeQuietly(childPipeFd);
        IoUtils.closeQuietly(serverPipeFd);
    }
}
Also used : PrintStream(java.io.PrintStream) IOException(java.io.IOException) FileDescriptor(java.io.FileDescriptor) ErrnoException(android.system.ErrnoException) FileOutputStream(java.io.FileOutputStream)

Example 40 with ErrnoException

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

the class ZygoteInit method closeServerSocket.

/**
     * Close and clean up zygote sockets. Called on shutdown and on the
     * child's exit path.
     */
static void closeServerSocket() {
    try {
        if (sServerSocket != null) {
            FileDescriptor fd = sServerSocket.getFileDescriptor();
            sServerSocket.close();
            if (fd != null) {
                Os.close(fd);
            }
        }
    } catch (IOException ex) {
        Log.e(TAG, "Zygote:  error closing sockets", ex);
    } catch (ErrnoException ex) {
        Log.e(TAG, "Zygote:  error closing descriptor", ex);
    }
    sServerSocket = null;
}
Also used : ErrnoException(android.system.ErrnoException) IOException(java.io.IOException) FileDescriptor(java.io.FileDescriptor)

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