android.system.Os Java Examples

The following examples show how to use android.system.Os. 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: PackageInstallerSession.java    From container with GNU General Public License v3.0 6 votes vote down vote up
private ParcelFileDescriptor openReadInternal(String name) throws IOException {
    assertPreparedAndNotSealed("openRead");

    try {
        if (!FileUtils.isValidExtFilename(name)) {
            throw new IllegalArgumentException("Invalid name: " + name);
        }
        final File target = new File(resolveStageDir(), name);

        final FileDescriptor targetFd = Os.open(target.getAbsolutePath(), O_RDONLY, 0);
        return ParcelFileDescriptor.dup(targetFd);

    } catch (ErrnoException e) {
        throw new IOException(e);
    }
}
 
Example #2
Source File: StrictJarFile.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException {
    synchronized (this.fd) {
        final long length = endOffset - offset;
        if (byteCount > length) {
            byteCount = (int) length;
        }
        try {
            Os.lseek(fd, offset, OsConstants.SEEK_SET);
        } catch (ErrnoException e) {
            throw new IOException(e);
        }
        int count = IoBridge.read(fd, buffer, byteOffset, byteCount);
        if (count > 0) {
            offset += count;
            return count;
        } else {
            return -1;
        }
    }
}
 
Example #3
Source File: ContextImpl.java    From AndroidComponentPlugin with Apache License 2.0 6 votes vote down vote up
/**
 * Common-path handling of app data dir creation
 */
private static File ensurePrivateDirExists(File file) {
    if (!file.exists()) {
        try {
            Os.mkdir(file.getAbsolutePath(), 0771);
            Os.chmod(file.getAbsolutePath(), 0771);
        } catch (ErrnoException e) {
            if (e.errno == OsConstants.EEXIST) {
                // We must have raced with someone; that's okay
            } else {
                Log.w(TAG, "Failed to ensure " + file + ": " + e.getMessage());
            }
        }
    }
    return file;
}
 
Example #4
Source File: PinnerService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Close FD, swallowing irrelevant errors.
 */
private static void safeClose(@Nullable FileDescriptor fd) {
    if (fd != null && fd.valid()) {
        try {
            Os.close(fd);
        } catch (ErrnoException ex) {
            // Swallow the exception: non-EBADF errors in close(2)
            // indicate deferred paging write errors, which we
            // don't care about here. The underlying file
            // descriptor is always closed.
            if (ex.errno == OsConstants.EBADF) {
                throw new AssertionError(ex);
            }
        }
    }
}
 
Example #5
Source File: PackageInstallerSession.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Determine if creating hard links between source and destination is
 * possible. That is, do they all live on the same underlying device.
 */
private boolean isLinkPossible(List<File> fromFiles, File toDir) {
    try {
        final StructStat toStat = Os.stat(toDir.getAbsolutePath());
        for (File fromFile : fromFiles) {
            final StructStat fromStat = Os.stat(fromFile.getAbsolutePath());
            if (fromStat.st_dev != toStat.st_dev) {
                return false;
            }
        }
    } catch (ErrnoException e) {
        Slog.w(TAG, "Failed to detect if linking possible: " + e);
        return false;
    }
    return true;
}
 
Example #6
Source File: PackageInstaller.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Ensure that any outstanding data for given stream has been committed
 * to disk. This is only valid for streams returned from
 * {@link #openWrite(String, long, long)}.
 */
public void fsync(@NonNull OutputStream out) throws IOException {
    if (ENABLE_REVOCABLE_FD) {
        if (out instanceof ParcelFileDescriptor.AutoCloseOutputStream) {
            try {
                Os.fsync(((ParcelFileDescriptor.AutoCloseOutputStream) out).getFD());
            } catch (ErrnoException e) {
                throw e.rethrowAsIOException();
            }
        } else {
            throw new IllegalArgumentException("Unrecognized stream");
        }
    } else {
        if (out instanceof FileBridge.FileBridgeOutputStream) {
            ((FileBridge.FileBridgeOutputStream) out).fsync();
        } else {
            throw new IllegalArgumentException("Unrecognized stream");
        }
    }
}
 
Example #7
Source File: PackageInstallerService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
static void prepareStageDir(File stageDir) throws IOException {
    if (stageDir.exists()) {
        throw new IOException("Session dir already exists: " + stageDir);
    }

    try {
        Os.mkdir(stageDir.getAbsolutePath(), 0755);
        Os.chmod(stageDir.getAbsolutePath(), 0755);
    } catch (ErrnoException e) {
        // This purposefully throws if directory already exists
        throw new IOException("Failed to prepare session dir: " + stageDir, e);
    }

    if (!SELinux.restorecon(stageDir)) {
        throw new IOException("Failed to restorecon session dir: " + stageDir);
    }
}
 
Example #8
Source File: PackageManagerServiceUtils.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
public static int decompressFile(File srcFile, File dstFile) throws ErrnoException {
    if (DEBUG_COMPRESSION) {
        Slog.i(TAG, "Decompress file"
                + "; src: " + srcFile.getAbsolutePath()
                + ", dst: " + dstFile.getAbsolutePath());
    }
    try (
            InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile));
            OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/);
    ) {
        FileUtils.copy(fileIn, fileOut);
        Os.chmod(dstFile.getAbsolutePath(), 0644);
        return PackageManager.INSTALL_SUCCEEDED;
    } catch (IOException e) {
        logCriticalInfo(Log.ERROR, "Failed to decompress file"
                + "; src: " + srcFile.getAbsolutePath()
                + ", dst: " + dstFile.getAbsolutePath());
    }
    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
}
 
Example #9
Source File: NetworkDiagnostics.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
protected void setupSocket(
        int sockType, int protocol, long writeTimeout, long readTimeout, int dstPort)
        throws ErrnoException, IOException {
    final int oldTag = TrafficStats.getAndSetThreadStatsTag(TrafficStats.TAG_SYSTEM_PROBE);
    try {
        mFileDescriptor = Os.socket(mAddressFamily, sockType, protocol);
    } finally {
        TrafficStats.setThreadStatsTag(oldTag);
    }
    // Setting SNDTIMEO is purely for defensive purposes.
    Os.setsockoptTimeval(mFileDescriptor,
            SOL_SOCKET, SO_SNDTIMEO, StructTimeval.fromMillis(writeTimeout));
    Os.setsockoptTimeval(mFileDescriptor,
            SOL_SOCKET, SO_RCVTIMEO, StructTimeval.fromMillis(readTimeout));
    // TODO: Use IP_RECVERR/IPV6_RECVERR, pending OsContants availability.
    mNetwork.bindSocket(mFileDescriptor);
    if (mSource != null) {
        Os.bind(mFileDescriptor, mSource, 0);
    }
    Os.connect(mFileDescriptor, mTarget, dstPort);
    mSocketAddress = Os.getsockname(mFileDescriptor);
}
 
Example #10
Source File: NativeCrashListener.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    try {
        CrashInfo ci = new CrashInfo();
        ci.exceptionClassName = "Native crash";
        ci.exceptionMessage = Os.strsignal(mSignal);
        ci.throwFileName = "unknown";
        ci.throwClassName = "unknown";
        ci.throwMethodName = "unknown";
        ci.stackTrace = mCrashReport;

        if (DEBUG) Slog.v(TAG, "Calling handleApplicationCrash()");
        mAm.handleApplicationCrashInner("native_crash", mApp, mApp.processName, ci);
        if (DEBUG) Slog.v(TAG, "<-- handleApplicationCrash() returned");
    } catch (Exception e) {
        Slog.e(TAG, "Unable to report native crash", e);
    }
}
 
Example #11
Source File: ContextImpl.java    From AndroidComponentPlugin with Apache License 2.0 6 votes vote down vote up
/**
 * Common-path handling of app data dir creation
 */
private static File ensurePrivateDirExists(File file) {
    if (!file.exists()) {
        try {
            Os.mkdir(file.getAbsolutePath(), 0771);
            Os.chmod(file.getAbsolutePath(), 0771);
        } catch (ErrnoException e) {
            if (e.errno == OsConstants.EEXIST) {
                // We must have raced with someone; that's okay
            } else {
                Log.w(TAG, "Failed to ensure " + file + ": " + e.getMessage());
            }
        }
    }
    return file;
}
 
Example #12
Source File: FileUtils.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    final FileDescriptor fd = getInternalFD();
    try {
        int i = 0;
        while (i < data.length) {
            if (sink) {
                i += Os.read(fd, data, i, data.length - i);
            } else {
                i += Os.write(fd, data, i, data.length - i);
            }
        }
    } catch (IOException | ErrnoException e) {
        // Ignored
    } finally {
        if (sink) {
            SystemClock.sleep(TimeUnit.SECONDS.toMillis(1));
        }
        IoUtils.closeQuietly(fd);
    }
}
 
Example #13
Source File: FileUtils.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Copy the contents of one FD to another.
 * <p>
 * Attempts to use several optimization strategies to copy the data in the
 * kernel before falling back to a userspace copy as a last resort.
 *
 * @param listener to be periodically notified as the copy progresses.
 * @param signal to signal if the copy should be cancelled early.
 * @param count the number of bytes to copy.
 * @return number of bytes copied.
 */
public static long copy(@NonNull FileDescriptor in, @NonNull FileDescriptor out,
        @Nullable ProgressListener listener, @Nullable CancellationSignal signal, long count)
        throws IOException {
    if (ENABLE_COPY_OPTIMIZATIONS) {
        try {
            final StructStat st_in = Os.fstat(in);
            final StructStat st_out = Os.fstat(out);
            if (S_ISREG(st_in.st_mode) && S_ISREG(st_out.st_mode)) {
                return copyInternalSendfile(in, out, listener, signal, count);
            } else if (S_ISFIFO(st_in.st_mode) || S_ISFIFO(st_out.st_mode)) {
                return copyInternalSplice(in, out, listener, signal, count);
            }
        } catch (ErrnoException e) {
            throw e.rethrowAsIOException();
        }
    }

    // Worse case fallback to userspace
    return copyInternalUserspace(in, out, listener, signal, count);
}
 
Example #14
Source File: FileBridge.java    From container with GNU General Public License v3.0 6 votes vote down vote up
/**
 * java.io always writes every byte it's asked to, or fails with an error. (That is, unlike
 * Unix it never just writes as many bytes as happens to be convenient.)
 */
public static void write(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount) throws IOException {
    ArrayUtils.checkOffsetAndCount(bytes.length, byteOffset, byteCount);
    if (byteCount == 0) {
        return;
    }
    try {
        while (byteCount > 0) {
            int bytesWritten = Os.write(fd, bytes, byteOffset, byteCount);
            byteCount -= bytesWritten;
            byteOffset += bytesWritten;
        }
    } catch (ErrnoException errnoException) {
        throw new IOException(errnoException);
    }
}
 
Example #15
Source File: ParcelFileDescriptor.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Return the total size of the file representing this fd, as determined by
 * {@code stat()}. Returns -1 if the fd is not a file.
 */
public long getStatSize() {
    if (mWrapped != null) {
        return mWrapped.getStatSize();
    } else {
        try {
            final StructStat st = Os.fstat(mFd);
            if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)) {
                return st.st_size;
            } else {
                return -1;
            }
        } catch (ErrnoException e) {
            Log.w(TAG, "fstat() failed: " + e);
            return -1;
        }
    }
}
 
Example #16
Source File: SharedMemory.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an mmap of the SharedMemory with the specified prot, offset, and length. This will
 * always produce a new ByteBuffer window to the backing shared memory region. Every call
 * to map() may be paired with a call to {@link #unmap(ByteBuffer)} when the ByteBuffer
 * returned by map() is no longer needed.
 *
 * @param prot A bitwise-or'd combination of PROT_READ, PROT_WRITE, PROT_EXEC, or PROT_NONE.
 * @param offset The offset into the shared memory to begin mapping. Must be >= 0 and less than
 *         getSize().
 * @param length The length of the region to map. Must be > 0 and offset + length must not
 *         exceed getSize().
 * @return A ByteBuffer mapping.
 * @throws ErrnoException if the mmap call failed.
 */
public @NonNull ByteBuffer map(int prot, int offset, int length) throws ErrnoException {
    checkOpen();
    validateProt(prot);
    if (offset < 0) {
        throw new IllegalArgumentException("Offset must be >= 0");
    }
    if (length <= 0) {
        throw new IllegalArgumentException("Length must be > 0");
    }
    if (offset + length > mSize) {
        throw new IllegalArgumentException("offset + length must not exceed getSize()");
    }
    long address = Os.mmap(0, length, prot, OsConstants.MAP_SHARED, mFileDescriptor, offset);
    boolean readOnly = (prot & OsConstants.PROT_WRITE) == 0;
    Runnable unmapper = new Unmapper(address, length, mMemoryRegistration.acquire());
    return new DirectByteBuffer(length, address, mFileDescriptor, unmapper, readOnly);
}
 
Example #17
Source File: NativeCrashListener.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
static int readExactly(FileDescriptor fd, byte[] buffer, int offset, int numBytes)
        throws ErrnoException, InterruptedIOException {
    int totalRead = 0;
    while (numBytes > 0) {
        int n = Os.read(fd, buffer, offset + totalRead, numBytes);
        if (n <= 0) {
            if (DEBUG) {
                Slog.w(TAG, "Needed " + numBytes + " but saw " + n);
            }
            return -1;  // premature EOF or timeout
        }
        numBytes -= n;
        totalRead += n;
    }
    return totalRead;
}
 
Example #18
Source File: IpSecService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * This function finds and forcibly binds to a random system port, ensuring that the port cannot
 * be unbound.
 *
 * <p>A socket cannot be un-bound from a port if it was bound to that port by number. To select
 * a random open port and then bind by number, this function creates a temp socket, binds to a
 * random port (specifying 0), gets that port number, and then uses is to bind the user's UDP
 * Encapsulation Socket forcibly, so that it cannot be un-bound by the user with the returned
 * FileHandle.
 *
 * <p>The loop in this function handles the inherent race window between un-binding to a port
 * and re-binding, during which the system could *technically* hand that port out to someone
 * else.
 */
private int bindToRandomPort(FileDescriptor sockFd) throws IOException {
    for (int i = MAX_PORT_BIND_ATTEMPTS; i > 0; i--) {
        try {
            FileDescriptor probeSocket = Os.socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
            Os.bind(probeSocket, INADDR_ANY, 0);
            int port = ((InetSocketAddress) Os.getsockname(probeSocket)).getPort();
            Os.close(probeSocket);
            Log.v(TAG, "Binding to port " + port);
            Os.bind(sockFd, INADDR_ANY, port);
            return port;
        } catch (ErrnoException e) {
            // Someone miraculously claimed the port just after we closed probeSocket.
            if (e.errno == OsConstants.EADDRINUSE) {
                continue;
            }
            throw e.rethrowAsIOException();
        }
    }
    throw new IOException("Failed " + MAX_PORT_BIND_ATTEMPTS + " attempts to bind to a port");
}
 
Example #19
Source File: FLog.java    From AppOpsX with MIT License 5 votes vote down vote up
private static void chown(String path, int uid, int gid){
  try {
    if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
      Os.chown(path,uid,gid);
    }else {
      Runtime.getRuntime().exec("chown "+uid+":"+gid+" "+path).destroy();
    }
  } catch (Exception e) {
    e.printStackTrace();
  }
}
 
Example #20
Source File: ParcelFileDescriptor.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * @hide
 */
public static ParcelFileDescriptor[] createReliableSocketPair(int type) throws IOException {
    try {
        final FileDescriptor[] comm = createCommSocketPair();
        final FileDescriptor fd0 = new FileDescriptor();
        final FileDescriptor fd1 = new FileDescriptor();
        Os.socketpair(AF_UNIX, type, 0, fd0, fd1);
        return new ParcelFileDescriptor[] {
                new ParcelFileDescriptor(fd0, comm[0]),
                new ParcelFileDescriptor(fd1, comm[1]) };
    } catch (ErrnoException e) {
        throw e.rethrowAsIOException();
    }
}
 
Example #21
Source File: PackageInstallerSession.java    From container with GNU General Public License v3.0 5 votes vote down vote up
private void createRemoveSplitMarker(String splitName) throws IOException {
    try {
        final String markerName = splitName + REMOVE_SPLIT_MARKER_EXTENSION;
        if (!FileUtils.isValidExtFilename(markerName)) {
            throw new IllegalArgumentException("Invalid marker: " + markerName);
        }
        final File target = new File(resolveStageDir(), markerName);
        target.createNewFile();
        Os.chmod(target.getAbsolutePath(), 0 /*mode*/);
    } catch (ErrnoException e) {
        throw new IOException(e);
    }
}
 
Example #22
Source File: ParcelFileDescriptor.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Create two ParcelFileDescriptors structured as a data pipe. The first
 * ParcelFileDescriptor in the returned array is the read side; the second
 * is the write side.
 * <p>
 * The write end has the ability to deliver an error message through
 * {@link #closeWithError(String)} which can be handled by the read end
 * calling {@link #checkError()}, usually after detecting an EOF.
 * This can also be used to detect remote crashes.
 */
public static ParcelFileDescriptor[] createReliablePipe() throws IOException {
    try {
        final FileDescriptor[] comm = createCommSocketPair();
        final FileDescriptor[] fds = Os.pipe();
        return new ParcelFileDescriptor[] {
                new ParcelFileDescriptor(fds[0], comm[0]),
                new ParcelFileDescriptor(fds[1], comm[1]) };
    } catch (ErrnoException e) {
        throw e.rethrowAsIOException();
    }
}
 
Example #23
Source File: OpenVpnManagementThread.java    From bitmask_android with GNU General Public License v3.0 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void fdCloseLollipop(FileDescriptor fd) {
    try {
        Os.close(fd);
    } catch (Exception e) {
        VpnStatus.logException("Failed to close fd (" + fd + ")", e);
    }
}
 
Example #24
Source File: SysUtil.java    From SoLoader with Apache License 2.0 5 votes vote down vote up
@DoNotOptimize
public static void fallocateIfSupported(FileDescriptor fd, long length) throws IOException {
  try {
    Os.posix_fallocate(fd, 0, length);
  } catch (ErrnoException ex) {
    if (ex.errno != OsConstants.EOPNOTSUPP
        && ex.errno != OsConstants.ENOSYS
        && ex.errno != OsConstants.EINVAL) {
      throw new IOException(ex.toString(), ex);
    }
  }
}
 
Example #25
Source File: ParcelFileDescriptor.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new ParcelFileDescriptor that is a dup of an existing
 * FileDescriptor.  This obeys standard POSIX semantics, where the
 * new file descriptor shared state such as file position with the
 * original file descriptor.
 */
public static ParcelFileDescriptor dup(FileDescriptor orig) throws IOException {
    try {
        final FileDescriptor fd = Os.dup(orig);
        return new ParcelFileDescriptor(fd);
    } catch (ErrnoException e) {
        throw e.rethrowAsIOException();
    }
}
 
Example #26
Source File: StatFs.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * @throws IllegalArgumentException if the file system access fails
 */
private static StructStatVfs doStat(String path) {
    try {
        return Os.statvfs(path);
    } catch (ErrnoException e) {
        throw new IllegalArgumentException("Invalid path: " + path, e);
    }
}
 
Example #27
Source File: FileBridge.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
public FileBridge() {
    try {
        Os.socketpair(AF_UNIX, SOCK_STREAM, 0, mServer, mClient);
    } catch (ErrnoException e) {
        throw new RuntimeException("Failed to create bridge");
    }
}
 
Example #28
Source File: FileBridge.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    final byte[] temp = new byte[8192];
    try {
        while (IoBridge.read(mServer, temp, 0, MSG_LENGTH) == MSG_LENGTH) {
            final int cmd = Memory.peekInt(temp, 0, ByteOrder.BIG_ENDIAN);
            if (cmd == CMD_WRITE) {
                // Shuttle data into local file
                int len = Memory.peekInt(temp, 4, ByteOrder.BIG_ENDIAN);
                while (len > 0) {
                    int n = IoBridge.read(mServer, temp, 0, Math.min(temp.length, len));
                    if (n == -1) {
                        throw new IOException(
                                "Unexpected EOF; still expected " + len + " bytes");
                    }
                    IoBridge.write(mTarget, temp, 0, n);
                    len -= n;
                }

            } else if (cmd == CMD_FSYNC) {
                // Sync and echo back to confirm
                Os.fsync(mTarget);
                IoBridge.write(mServer, temp, 0, MSG_LENGTH);

            } else if (cmd == CMD_CLOSE) {
                // Close and echo back to confirm
                Os.fsync(mTarget);
                Os.close(mTarget);
                mClosed = true;
                IoBridge.write(mServer, temp, 0, MSG_LENGTH);
                break;
            }
        }

    } catch (ErrnoException | IOException e) {
        Log.wtf(TAG, "Failed during bridge", e);
    } finally {
        forceClose();
    }
}
 
Example #29
Source File: Utils.java    From Ezalor with Apache License 2.0 5 votes vote down vote up
public static String getPathByFD(int fd) {
    try {
        if (Build.VERSION.SDK_INT >= 21) {
            return Os.readlink(String.format("/proc/%d/fd/%d", android.os.Process.myPid(), fd));
        }
        return readlink(fd);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #30
Source File: PackageInstallerSession.java    From container with GNU General Public License v3.0 5 votes vote down vote up
private ParcelFileDescriptor openWriteInternal(String name, long offsetBytes, long lengthBytes)
        throws IOException {
    // Quick sanity check of state, and allocate a pipe for ourselves. We
    // then do heavy disk allocation outside the lock, but this open pipe
    // will block any attempted install transitions.
    final FileBridge bridge;
    synchronized (mLock) {
        assertPreparedAndNotSealed("openWrite");

        bridge = new FileBridge();
        mBridges.add(bridge);
    }
    try {
        final File target = new File(resolveStageDir(), name);
        // TODO: this should delegate to DCS so the system process avoids
        // holding open FDs into containers.
        final FileDescriptor targetFd = Os.open(target.getAbsolutePath(),
                O_CREAT | O_WRONLY, 0644);
        // If caller specified a total length, allocate it for them. Free up
        // cache space to grow, if needed.
        if (lengthBytes > 0) {
            Os.posix_fallocate(targetFd, 0, lengthBytes);
        }
        if (offsetBytes > 0) {
            Os.lseek(targetFd, offsetBytes, OsConstants.SEEK_SET);
        }
        bridge.setTargetFile(targetFd);
        bridge.start();
        return ParcelFileDescriptor.dup(bridge.getClientSocket());

    } catch (ErrnoException e) {
        throw new IOException(e);
    }
}