dalvik.system.BlockGuard Java Examples

The following examples show how to use dalvik.system.BlockGuard. 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: StrictMode.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Called from Parcel.readException() when the exception is EX_STRICT_MODE_VIOLATIONS, we here
 * read back all the encoded violations.
 */
/* package */ static void readAndHandleBinderCallViolations(Parcel p) {
    Throwable localCallSite = new Throwable();
    final int policyMask = getThreadPolicyMask();
    final boolean currentlyGathering = (policyMask & PENALTY_GATHER) != 0;

    final int size = p.readInt();
    for (int i = 0; i < size; i++) {
        final ViolationInfo info = new ViolationInfo(p, !currentlyGathering);
        info.addLocalStack(localCallSite);
        BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
        if (policy instanceof AndroidBlockGuardPolicy) {
            ((AndroidBlockGuardPolicy) policy).handleViolationWithTimingAttempt(info);
        }
    }
}
 
Example #2
Source File: SharedPreferencesImpl.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * 检查 sp 文件是否加载完成,未完成则阻塞
 */
@GuardedBy("mLock")
private void awaitLoadedLocked() {
    if (!mLoaded) {
        // Raise an explicit StrictMode onReadFromDisk for this
        // thread, since the real read will be in a different
        // thread and otherwise ignored by StrictMode.
        BlockGuard.getThreadPolicy().onReadFromDisk();
    }
    while (!mLoaded) { // sp 文件尚未加载完成时,调用 wait()
        try {
            mLock.wait();
        } catch (InterruptedException unused) {
        }
    }
    if (mThrowable != null) {
        throw new IllegalStateException(mThrowable);
    }
}
 
Example #3
Source File: SharedPreferencesImpl.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private boolean hasFileChangedUnexpectedly() {
    synchronized (mLock) {
        if (mDiskWritesInFlight > 0) {
            // If we know we caused it, it's not unexpected.
            if (DEBUG) Log.d(TAG, "disk write in flight, not unexpected.");
            return false;
        }
    }

    final StructStat stat;
    try {
        /*
         * Metadata operations don't usually count as a block guard
         * violation, but we explicitly want this one.
         */
        BlockGuard.getThreadPolicy().onReadFromDisk();
        stat = Os.stat(mFile.getPath());
    } catch (ErrnoException e) {
        return true;
    }

    synchronized (mLock) {
        return !stat.st_mtim.equals(mStatTimestamp) || mStatSize != stat.st_size;
    }
}
 
Example #4
Source File: StrictMode.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private static void setBlockGuardPolicy(final int policyMask) {
    if (policyMask == 0) {
        BlockGuard.setThreadPolicy(BlockGuard.LAX_POLICY);
        return;
    }
    final BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
    final AndroidBlockGuardPolicy androidPolicy;
    if (policy instanceof AndroidBlockGuardPolicy) {
        androidPolicy = (AndroidBlockGuardPolicy) policy;
    } else {
        androidPolicy = THREAD_ANDROID_POLICY.get();
        BlockGuard.setThreadPolicy(androidPolicy);
    }
    androidPolicy.setPolicyMask(policyMask);
}
 
Example #5
Source File: URLTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testHashCodeAndEqualsDoesNotPerformNetworkIo() throws Exception {
    final BlockGuard.Policy oldPolicy = BlockGuard.getThreadPolicy();
    BlockGuard.setThreadPolicy(new BlockGuard.Policy() {
        @Override
        public void onWriteToDisk() {
            fail("Blockguard.Policy.onWriteToDisk");
        }

        @Override
        public void onReadFromDisk() {
            fail("Blockguard.Policy.onReadFromDisk");
        }

        @Override
        public void onNetwork() {
            fail("Blockguard.Policy.onNetwork");
        }

        @Override
        public int getPolicyMask() {
            return 0;
        }
    });

    try {
        URL url = new URL("http://www.google.com/");
        URL url2 = new URL("http://www.nest.com/");

        url.equals(url2);
        url2.hashCode();
    } finally {
        BlockGuard.setThreadPolicy(oldPolicy);
    }
}
 
Example #6
Source File: Net.java    From j2objc with Apache License 2.0 5 votes vote down vote up
static int connect(ProtocolFamily family, FileDescriptor fd, InetAddress remote, int remotePort)
    throws IOException
{
    BlockGuard.getThreadPolicy().onNetwork();

    boolean preferIPv6 = isIPv6Available() &&
        (family != StandardProtocolFamily.INET);
    return connect0(preferIPv6, fd, remote, remotePort);
}
 
Example #7
Source File: DatagramChannelImpl.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private int receive(FileDescriptor fd, ByteBuffer dst)
    throws IOException
{
    int pos = dst.position();
    int lim = dst.limit();
    assert (pos <= lim);
    int rem = (pos <= lim ? lim - pos : 0);
    if (dst instanceof DirectBuffer && rem > 0)
        return receiveIntoNativeBuffer(fd, dst, rem, pos);

    // Substitute a native buffer. If the supplied buffer is empty
    // we must instead use a nonempty buffer, otherwise the call
    // will not block waiting for a datagram on some platforms.
    int newSize = Math.max(rem, 1);
    ByteBuffer bb = Util.getTemporaryDirectBuffer(newSize);
    try {
        BlockGuard.getThreadPolicy().onNetwork();

        int n = receiveIntoNativeBuffer(fd, bb, newSize, 0);
        bb.flip();
        if (n > 0 && rem > 0)
            dst.put(bb);
        return n;
    } finally {
        Util.releaseTemporaryDirectBuffer(bb);
    }
}
 
Example #8
Source File: AbstractPlainSocketImpl.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * The workhorse of the connection operation.  Tries several times to
 * establish a connection to the given <host, port>.  If unsuccessful,
 * throws an IOException indicating what went wrong.
 */

synchronized void doConnect(InetAddress address, int port, int timeout) throws IOException {
    synchronized (fdLock) {
        if (!closePending && (socket == null || !socket.isBound())) {
            NetHooks.beforeTcpConnect(fd, address, port);
        }
    }
    try {
        BlockGuard.getThreadPolicy().onNetwork();
        socketConnect(address, port, timeout);
        /* socket may have been closed during poll/select */
        synchronized (fdLock) {
            if (closePending) {
                throw new SocketException ("Socket closed");
            }
        }
        // If we have a ref. to the Socket, then sets the flags
        // created, bound & connected to true.
        // This is normally done in Socket.connect() but some
        // subclasses of Socket may call impl.connect() directly!
        if (socket != null) {
            socket.setBound();
            socket.setConnected();
        }
    } catch (IOException e) {
        close();
        throw e;
    }
}
 
Example #9
Source File: AbstractPlainDatagramSocketImpl.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Connects a datagram socket to a remote destination. This associates the remote
 * address with the local socket so that datagrams may only be sent to this destination
 * and received from this destination.
 * @param address the remote InetAddress to connect to
 * @param port the remote port number
 */
protected void connect(InetAddress address, int port) throws SocketException {
    BlockGuard.getThreadPolicy().onNetwork();
    connect0(address, port);
    connectedAddress = address;
    connectedPort = port;
    connected = true;
}
 
Example #10
Source File: SocketOutputStream.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Writes to the socket with appropriate locking of the
 * FileDescriptor.
 * @param b the data to be written
 * @param off the start offset in the data
 * @param len the number of bytes that are written
 * @exception IOException If an I/O error has occurred.
 */
private void socketWrite(byte b[], int off, int len) throws IOException {

    if (len <= 0 || off < 0 || off + len > b.length) {
        if (len == 0) {
            return;
        }
        throw new ArrayIndexOutOfBoundsException();
    }

    Object traceContext = IoTrace.socketWriteBegin();
    int bytesWritten = 0;
    FileDescriptor fd = impl.acquireFD();
    try {
        BlockGuard.getThreadPolicy().onNetwork();
        socketWrite0(fd, b, off, len);
        bytesWritten = len;
    } catch (SocketException se) {
        if (se instanceof sun.net.ConnectionResetException) {
            impl.setConnectionResetPending();
            se = new SocketException("Connection reset");
        }
        if (impl.isClosedOrPending()) {
            throw new SocketException("Socket closed");
        } else {
            throw se;
        }
    } finally {
        IoTrace.socketWriteEnd(traceContext, impl.address, impl.port, bytesWritten);
    }
}
 
Example #11
Source File: StrictMode.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/** @hide */
public static void noteDiskWrite() {
    BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
    if (!(policy instanceof AndroidBlockGuardPolicy)) {
        // StrictMode not enabled.
        return;
    }
    policy.onWriteToDisk();
}
 
Example #12
Source File: ContextImpl.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
private File makeFilename(File base, String name) {
    if (name.indexOf(File.separatorChar) < 0) {
        final File res = new File(base, name);
        // We report as filesystem access here to give us the best shot at
        // detecting apps that will pass the path down to native code.
        BlockGuard.getVmPolicy().onPathAccess(res.getPath());
        return res;
    }
    throw new IllegalArgumentException(
            "File " + name + " contains a path separator");
}
 
Example #13
Source File: StrictMode.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * For code to note that it's slow. This is a no-op unless the current thread's {@link
 * android.os.StrictMode.ThreadPolicy} has {@link
 * android.os.StrictMode.ThreadPolicy.Builder#detectCustomSlowCalls} enabled.
 *
 * @param name a short string for the exception stack trace that's built if when this fires.
 */
public static void noteSlowCall(String name) {
    BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
    if (!(policy instanceof AndroidBlockGuardPolicy)) {
        // StrictMode not enabled.
        return;
    }
    ((AndroidBlockGuardPolicy) policy).onCustomSlowCall(name);
}
 
Example #14
Source File: StrictMode.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * For code to note that a resource was obtained using a type other than its defined type. This
 * is a no-op unless the current thread's {@link android.os.StrictMode.ThreadPolicy} has {@link
 * android.os.StrictMode.ThreadPolicy.Builder#detectResourceMismatches()} enabled.
 *
 * @param tag an object for the exception stack trace that's built if when this fires.
 * @hide
 */
public static void noteResourceMismatch(Object tag) {
    BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
    if (!(policy instanceof AndroidBlockGuardPolicy)) {
        // StrictMode not enabled.
        return;
    }
    ((AndroidBlockGuardPolicy) policy).onResourceMismatch(tag);
}
 
Example #15
Source File: StrictMode.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/** @hide */
public static void noteUnbufferedIO() {
    BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
    if (!(policy instanceof AndroidBlockGuardPolicy)) {
        // StrictMode not enabled.
        return;
    }
    policy.onUnbufferedIO();
}
 
Example #16
Source File: SQLiteConnection.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private void applyBlockGuardPolicy(PreparedStatement statement) {
    if (!mConfiguration.isInMemoryDb()) {
        if (statement.mReadOnly) {
            BlockGuard.getThreadPolicy().onReadFromDisk();
        } else {
            BlockGuard.getThreadPolicy().onWriteToDisk();
        }
    }
}
 
Example #17
Source File: StrictMode.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/** @hide */
public static void noteDiskRead() {
    BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
    if (!(policy instanceof AndroidBlockGuardPolicy)) {
        // StrictMode not enabled.
        return;
    }
    policy.onReadFromDisk();
}
 
Example #18
Source File: AbstractPlainSocketImpl.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * Accepts connections.
 * @param s the connection
 */
protected void accept(SocketImpl s) throws IOException {
    BlockGuard.getThreadPolicy().onNetwork();
    socketAccept(s);
}
 
Example #19
Source File: FileDispatcherImpl.java    From j2objc with Apache License 2.0 4 votes vote down vote up
void release(FileDescriptor fd, long pos, long size) throws IOException {
    BlockGuard.getThreadPolicy().onWriteToDisk();
    release0(fd, pos, size);
}
 
Example #20
Source File: FileDispatcherImpl.java    From j2objc with Apache License 2.0 4 votes vote down vote up
int lock(FileDescriptor fd, boolean blocking, long pos, long size,
         boolean shared) throws IOException
{
    BlockGuard.getThreadPolicy().onWriteToDisk();
    return lock0(fd, blocking, pos, size, shared);
}
 
Example #21
Source File: FileDispatcherImpl.java    From j2objc with Apache License 2.0 4 votes vote down vote up
long size(FileDescriptor fd) throws IOException {
    BlockGuard.getThreadPolicy().onReadFromDisk();
    return size0(fd);
}
 
Example #22
Source File: FileDispatcherImpl.java    From j2objc with Apache License 2.0 4 votes vote down vote up
int truncate(FileDescriptor fd, long size) throws IOException {
    BlockGuard.getThreadPolicy().onWriteToDisk();
    return truncate0(fd, size);
}
 
Example #23
Source File: FileDispatcherImpl.java    From j2objc with Apache License 2.0 4 votes vote down vote up
int force(FileDescriptor fd, boolean metaData) throws IOException {
    BlockGuard.getThreadPolicy().onWriteToDisk();
    return force0(fd, metaData);
}
 
Example #24
Source File: FileDispatcherImpl.java    From j2objc with Apache License 2.0 4 votes vote down vote up
long writev(FileDescriptor fd, long address, int len)
    throws IOException
{
    BlockGuard.getThreadPolicy().onWriteToDisk();
    return writev0(fd, address, len);
}
 
Example #25
Source File: FileDispatcherImpl.java    From j2objc with Apache License 2.0 4 votes vote down vote up
int pwrite(FileDescriptor fd, long address, int len, long position)
    throws IOException
{
    BlockGuard.getThreadPolicy().onWriteToDisk();
    return pwrite0(fd, address, len, position);
}
 
Example #26
Source File: FileDispatcherImpl.java    From j2objc with Apache License 2.0 4 votes vote down vote up
int write(FileDescriptor fd, long address, int len) throws IOException {
    BlockGuard.getThreadPolicy().onWriteToDisk();
    return write0(fd, address, len);
}
 
Example #27
Source File: FileDispatcherImpl.java    From j2objc with Apache License 2.0 4 votes vote down vote up
long readv(FileDescriptor fd, long address, int len) throws IOException {
    BlockGuard.getThreadPolicy().onReadFromDisk();
    return readv0(fd, address, len);
}
 
Example #28
Source File: FileDispatcherImpl.java    From j2objc with Apache License 2.0 4 votes vote down vote up
int pread(FileDescriptor fd, long address, int len, long position)
    throws IOException
{
    BlockGuard.getThreadPolicy().onReadFromDisk();
    return pread0(fd, address, len, position);
}
 
Example #29
Source File: FileDispatcherImpl.java    From j2objc with Apache License 2.0 4 votes vote down vote up
int read(FileDescriptor fd, long address, int len) throws IOException {
    BlockGuard.getThreadPolicy().onReadFromDisk();
    return read0(fd, address, len);
}
 
Example #30
Source File: FileChannelImpl.java    From j2objc with Apache License 2.0 4 votes vote down vote up
private long transferToDirectly(long position, int icount,
                                WritableByteChannel target)
    throws IOException
{
    if (!transferSupported)
        return IOStatus.UNSUPPORTED;

    FileDescriptor targetFD = null;
    if (target instanceof FileChannelImpl) {
        if (!fileSupported)
            return IOStatus.UNSUPPORTED_CASE;
        targetFD = ((FileChannelImpl)target).fd;
    } else if (target instanceof SelChImpl) {
        // Direct transfer to pipe causes EINVAL on some configurations
        if ((target instanceof SinkChannelImpl) && !pipeSupported)
            return IOStatus.UNSUPPORTED_CASE;
        targetFD = ((SelChImpl)target).getFD();
    }
    if (targetFD == null)
        return IOStatus.UNSUPPORTED;
    int thisFDVal = IOUtil.fdVal(fd);
    int targetFDVal = IOUtil.fdVal(targetFD);
    if (thisFDVal == targetFDVal) // Not supported on some configurations
        return IOStatus.UNSUPPORTED;

    long n = -1;
    int ti = -1;
    try {
        begin();
        ti = threads.add();
        if (!isOpen())
            return -1;
        BlockGuard.getThreadPolicy().onWriteToDisk();
        do {
            n = transferTo0(thisFDVal, position, icount, targetFDVal);
        } while ((n == IOStatus.INTERRUPTED) && isOpen());
        if (n == IOStatus.UNSUPPORTED_CASE) {
            if (target instanceof SinkChannelImpl)
                pipeSupported = false;
            if (target instanceof FileChannelImpl)
                fileSupported = false;
            return IOStatus.UNSUPPORTED_CASE;
        }
        if (n == IOStatus.UNSUPPORTED) {
            // Don't bother trying again
            transferSupported = false;
            return IOStatus.UNSUPPORTED;
        }
        return IOStatus.normalize(n);
    } finally {
        threads.remove(ti);
        end (n > -1);
    }
}