javatips.net counter

Java Examples for sun.misc.Unsafe

The following java examples will help you to understand the usage of sun.misc.Unsafe. These source code samples are taken from different open source projects.

Example 1
Project: android-15-master  File: ConcurrentLinkedDeque.java View source code
static long objectFieldOffset(sun.misc.Unsafe UNSAFE, String field, Class<?> klazz) {
    try {
        return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
    } catch (NoSuchFieldException e) {
        NoSuchFieldError error = new NoSuchFieldError(field);
        error.initCause(e);
        throw error;
    }
}
Example 2
Project: openjdk-master  File: InverseDeps.java View source code
@DataProvider(name = "classpath")
public Object[][] expected4() {
    return new Object[][] { // -regex and result
    { "sun.misc.Unsafe", new String[][] { new String[] { "jdk.unsupported", "unsafe.jar", "mVI.jar", "mVII.jar" }, new String[] { "jdk.unsupported", "unsafe.jar", "mVII.jar" } } }, { "org.safe.Lib", new String[][] { new String[] { "unsafe.jar", "mVII.jar" }, new String[] { "unsafe.jar", "mVI.jar", "mVII.jar" } } }, { "java.util.logging.*|org.safe.Lib", new String[][] { new String[] { "unsafe.jar", "mVII.jar" }, new String[] { "unsafe.jar", "mVI.jar", "mVII.jar" }, new String[] { "java.logging", "m5.jar" } } } };
}
Example 3
Project: gs-collections-master  File: ConcurrentHashMapUnsafe.java View source code
private static Unsafe getUnsafe() {
    try {
        return Unsafe.getUnsafe();
    } catch (SecurityException ignored) {
        try {
            return AccessController.doPrivileged(new PrivilegedExceptionAction<Unsafe>() {

                public Unsafe run() throws Exception {
                    Field f = Unsafe.class.getDeclaredField("theUnsafe");
                    f.setAccessible(true);
                    return (Unsafe) f.get(null);
                }
            });
        } catch (PrivilegedActionException e) {
            throw new RuntimeException("Could not initialize intrinsics", e.getCause());
        }
    }
}
Example 4
Project: Tank-master  File: SummaryReportObserverTest.java View source code
/**
     * Run the void observerJobEvents(JobEvent) method test.
     *
     * @throws Exception
     *
     * @generatedBy CodePro at 12/15/14 3:52 PM
     */
@Test
public void testObserverJobEvents_1() throws Exception {
    SummaryReportObserver fixture = new SummaryReportObserver();
    JobEvent jobEvent = new JobEvent("", "", JobLifecycleEvent.AGENT_EXCESSIVE_CPU);
    fixture.observerJobEvents(jobEvent);
// An unexpected exception was thrown in user code while executing this test:
//    java.lang.NoClassDefFoundError: com_cenqua_clover/CoverageRecorder
//       at com.intuit.tank.api.enumerated.JobLifecycleEvent.<init>(JobLifecycleEvent.java:43)
//       at com.intuit.tank.api.enumerated.JobLifecycleEvent.<clinit>(JobLifecycleEvent.java:14)
//       at sun.misc.Unsafe.ensureClassInitialized(Native Method)
}
Example 5
Project: classlib6-master  File: Bridge.java View source code
private Unsafe getUnsafe() {
    Field fld = (Field) AccessController.doPrivileged(new PrivilegedAction() {

        public Object run() {
            Field fld = null;
            try {
                Class unsafeClass = sun.misc.Unsafe.class;
                fld = unsafeClass.getDeclaredField("theUnsafe");
                fld.setAccessible(true);
                return fld;
            } catch (NoSuchFieldException exc) {
                Error err = new Error("Could not access Unsafe");
                err.initCause(exc);
                throw err;
            }
        }
    });
    Unsafe unsafe = null;
    try {
        unsafe = (Unsafe) (fld.get(null));
    } catch (Throwable t) {
        Error err = new Error("Could not access Unsafe");
        err.initCause(t);
        throw err;
    }
    return unsafe;
}
Example 6
Project: streamline-master  File: LinkedTransferQueue.java View source code
/**
     * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
     * Replace with a simple call to Unsafe.getUnsafe when integrating
     * into a jdk.
     *
     * @return a sun.misc.Unsafe
     */
static sun.misc.Unsafe getUnsafe() {
    try {
        return sun.misc.Unsafe.getUnsafe();
    } catch (SecurityException se) {
        try {
            return java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {

                public sun.misc.Unsafe run() throws Exception {
                    java.lang.reflect.Field f = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
                    f.setAccessible(true);
                    return (sun.misc.Unsafe) f.get(null);
                }
            });
        } catch (java.security.PrivilegedActionException e) {
            throw new RuntimeException("Could not initialize intrinsics", e.getCause());
        }
    }
}
Example 7
Project: guava-experimental-master  File: Striped64.java View source code
/**
     * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
     * Replace with a simple call to Unsafe.getUnsafe when integrating
     * into a jdk.
     *
     * @return a sun.misc.Unsafe
     */
private static sun.misc.Unsafe getUnsafe() {
    try {
        return sun.misc.Unsafe.getUnsafe();
    } catch (SecurityException se) {
        try {
            return java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {

                public sun.misc.Unsafe run() throws Exception {
                    java.lang.reflect.Field f = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
                    f.setAccessible(true);
                    return (sun.misc.Unsafe) f.get(null);
                }
            });
        } catch (java.security.PrivilegedActionException e) {
            throw new RuntimeException("Could not initialize intrinsics", e.getCause());
        }
    }
}
Example 8
Project: cloudtm-data-platform-master  File: ConcurrentHashMapV8.java View source code
/**
    * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
    * Replace with a simple call to Unsafe.getUnsafe when integrating
    * into a jdk.
    *
    * @return a sun.misc.Unsafe
    */
private static sun.misc.Unsafe getUnsafe() {
    try {
        return sun.misc.Unsafe.getUnsafe();
    } catch (SecurityException se) {
        try {
            return java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {

                @Override
                public sun.misc.Unsafe run() throws Exception {
                    java.lang.reflect.Field f = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
                    f.setAccessible(true);
                    return (sun.misc.Unsafe) f.get(null);
                }
            });
        } catch (java.security.PrivilegedActionException e) {
            throw new RuntimeException("Could not initialize intrinsics", e.getCause());
        }
    }
}
Example 9
Project: flink-master  File: MemoryUtils.java View source code
@SuppressWarnings("restriction")
private static sun.misc.Unsafe getUnsafe() {
    try {
        Field unsafeField = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
        unsafeField.setAccessible(true);
        return (sun.misc.Unsafe) unsafeField.get(null);
    } catch (SecurityException e) {
        throw new RuntimeException("Could not access the sun.misc.Unsafe handle, permission denied by security manager.", e);
    } catch (NoSuchFieldException e) {
        throw new RuntimeException("The static handle field in sun.misc.Unsafe was not found.");
    } catch (IllegalArgumentException e) {
        throw new RuntimeException("Bug: Illegal argument reflection access for static field.", e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException("Access to sun.misc.Unsafe is forbidden by the runtime.", e);
    } catch (Throwable t) {
        throw new RuntimeException("Unclassified error while trying to access the sun.misc.Unsafe handle.", t);
    }
}
Example 10
Project: Chronicle-Values-master  File: FloatingFieldModel.java View source code
@Override
public void generateArrayElementAddAtomic(ArrayFieldModel arrayFieldModel, ValueBuilder valueBuilder, MethodSpec.Builder methodBuilder) {
    arrayFieldModel.checkBounds(methodBuilder);
    methodBuilder.beginControlFlow("while (true)");
    methodBuilder.addStatement("$T $N = " + wrap(valueBuilder, methodBuilder, "$N.$N($N, (long) $T.$N + (index * (long) $T.$N))"), type, oldName(), valueBuilder.unsafe(), getVolatile(), field, Unsafe.class, arrayBase(), Unsafe.class, arrayScale());
    methodBuilder.addStatement("$T $N = $N + addition", type, newName(), oldName());
    methodBuilder.beginControlFlow(format("if ($N.$N($N, (long) $T.$N + (index * (long) $T.$N), %s, %s))", unwrap(methodBuilder, "$N"), unwrap(methodBuilder, "$N")), valueBuilder.unsafe(), compareAndSwap(), field, Unsafe.class, arrayBase(), Unsafe.class, arrayScale(), oldName(), newName());
    methodBuilder.addStatement("return $N", newName());
    methodBuilder.endControlFlow();
    methodBuilder.endControlFlow();
}
Example 11
Project: netty4.0.27Learn-master  File: ForkJoinTask.java View source code
/**
     * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
     * Replace with a simple call to Unsafe.getUnsafe when integrating
     * into a jdk.
     *
     * @return a sun.misc.Unsafe
     */
private static sun.misc.Unsafe getUnsafe() {
    try {
        return sun.misc.Unsafe.getUnsafe();
    } catch (SecurityException tryReflectionInstead) {
    }
    try {
        return java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {

            public sun.misc.Unsafe run() throws Exception {
                Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
                for (java.lang.reflect.Field f : k.getDeclaredFields()) {
                    f.setAccessible(true);
                    Object x = f.get(null);
                    if (k.isInstance(x))
                        return k.cast(x);
                }
                throw new NoSuchFieldError("the Unsafe");
            }
        });
    } catch (java.security.PrivilegedActionException e) {
        throw new RuntimeException("Could not initialize intrinsics", e.getCause());
    }
}
Example 12
Project: metrics-master  File: UnsafeStriped64.java View source code
/**
     * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package. Replace with a simple
     * call to Unsafe.getUnsafe when integrating into a jdk.
     *
     * @return a sun.misc.Unsafe
     */
private static sun.misc.Unsafe getUnsafe() {
    try {
        return sun.misc.Unsafe.getUnsafe();
    } catch (SecurityException ignored) {
    }
    try {
        return java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {

            @Override
            public sun.misc.Unsafe run() throws Exception {
                Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
                for (java.lang.reflect.Field f : k.getDeclaredFields()) {
                    f.setAccessible(true);
                    Object x = f.get(null);
                    if (k.isInstance(x))
                        return k.cast(x);
                }
                throw new NoSuchFieldError("the Unsafe");
            }
        });
    } catch (java.security.PrivilegedActionException e) {
        throw new RuntimeException("Could not initialize intrinsics", e.getCause());
    }
}
Example 13
Project: IKVM.NET-cvs-clone-master  File: Thread.java View source code
private void stop0(Throwable x) {
    if (running) {
        // exceptions from Java.
        if (this == current) {
            sun.misc.Unsafe.getUnsafe().throwException(x);
        } else if (x instanceof ThreadDeath) {
            cli.System.Threading.Thread nativeThread = this.nativeThread;
            if (nativeThread == null) {
                return;
            }
            try {
                if (false)
                    throw new cli.System.Threading.ThreadStateException();
                nativeThread.Abort(x);
            } catch (cli.System.Threading.ThreadStateException _) {
            }
            try {
                if (false)
                    throw new cli.System.Threading.ThreadStateException();
                int suspend = cli.System.Threading.ThreadState.Suspended | cli.System.Threading.ThreadState.SuspendRequested;
                while ((nativeThread.get_ThreadState().Value & suspend) != 0) {
                    nativeThread.Resume();
                }
            } catch (cli.System.Threading.ThreadStateException _) {
            }
        }
    } else {
        stillborn = x;
    }
}
Example 14
Project: guava-master  File: UnsignedBytes.java View source code
/**
       * Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package. Replace with a simple
       * call to Unsafe.getUnsafe when integrating into a jdk.
       *
       * @return a sun.misc.Unsafe
       */
private static sun.misc.Unsafe getUnsafe() {
    try {
        return sun.misc.Unsafe.getUnsafe();
    } catch (SecurityException e) {
    }
    try {
        return java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {

            @Override
            public sun.misc.Unsafe run() throws Exception {
                Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
                for (java.lang.reflect.Field f : k.getDeclaredFields()) {
                    f.setAccessible(true);
                    Object x = f.get(null);
                    if (k.isInstance(x)) {
                        return k.cast(x);
                    }
                }
                throw new NoSuchFieldError("the Unsafe");
            }
        });
    } catch (java.security.PrivilegedActionException e) {
        throw new RuntimeException("Could not initialize intrinsics", e.getCause());
    }
}
Example 15
Project: lucene-solr-master  File: SimpleServer.java View source code
/**
   * currently, this only works/tested on Sun and IBM.
   */
// poached from TestIndexWriterOnJRECrash ... should we factor out to TestUtil?  seems dangerous to give it such "publicity"?
private static void crashJRE() {
    final String vendor = Constants.JAVA_VENDOR;
    final boolean supportsUnsafeNpeDereference = vendor.startsWith("Oracle") || vendor.startsWith("Sun") || vendor.startsWith("Apple");
    try {
        if (supportsUnsafeNpeDereference) {
            try {
                Class<?> clazz = Class.forName("sun.misc.Unsafe");
                java.lang.reflect.Field field = clazz.getDeclaredField("theUnsafe");
                field.setAccessible(true);
                Object o = field.get(null);
                Method m = clazz.getMethod("putAddress", long.class, long.class);
                m.invoke(o, 0L, 0L);
            } catch (Throwable e) {
                System.out.println("Couldn't kill the JVM via Unsafe.");
                e.printStackTrace(System.out);
            }
        }
        // Fallback attempt to Runtime.halt();
        Runtime.getRuntime().halt(-1);
    } catch (Exception e) {
        System.out.println("Couldn't kill the JVM.");
        e.printStackTrace(System.out);
    }
    // We couldn't get the JVM to crash for some reason.
    throw new RuntimeException("JVM refuses to die!");
}
Example 16
Project: SmartAndroidSource-master  File: UnsafeAllocator.java View source code
public static UnsafeAllocator create() {
    // }
    try {
        Class<?> unsafeClass = Class.forName("sun.misc.Unsafe");
        Field f = unsafeClass.getDeclaredField("theUnsafe");
        f.setAccessible(true);
        final Object unsafe = f.get(null);
        final Method allocateInstance = unsafeClass.getMethod("allocateInstance", Class.class);
        return new UnsafeAllocator() {

            @Override
            @SuppressWarnings("unchecked")
            public <T> T newInstance(Class<T> c) throws Exception {
                return (T) allocateInstance.invoke(unsafe, c);
            }
        };
    } catch (Exception ignored) {
    }
    // }
    try {
        final Method newInstance = ObjectInputStream.class.getDeclaredMethod("newInstance", Class.class, Class.class);
        newInstance.setAccessible(true);
        return new UnsafeAllocator() {

            @Override
            @SuppressWarnings("unchecked")
            public <T> T newInstance(Class<T> c) throws Exception {
                return (T) newInstance.invoke(null, c, Object.class);
            }
        };
    } catch (Exception ignored) {
    }
    // }
    try {
        Method getConstructorId = ObjectStreamClass.class.getDeclaredMethod("getConstructorId", Class.class);
        getConstructorId.setAccessible(true);
        final int constructorId = (Integer) getConstructorId.invoke(null, Object.class);
        final Method newInstance = ObjectStreamClass.class.getDeclaredMethod("newInstance", Class.class, int.class);
        newInstance.setAccessible(true);
        return new UnsafeAllocator() {

            @Override
            @SuppressWarnings("unchecked")
            public <T> T newInstance(Class<T> c) throws Exception {
                return (T) newInstance.invoke(null, c, constructorId);
            }
        };
    } catch (Exception ignored) {
    }
    // give up
    return new UnsafeAllocator() {

        @Override
        public <T> T newInstance(Class<T> c) {
            throw new UnsupportedOperationException("Cannot allocate " + c);
        }
    };
}
Example 17
Project: trie4j-master  File: UnsafeBytesSuccinctBitVector.java View source code
@Override
public int select0(int count) {
    if (count > size0)
        return -1;
    if (count <= 3) {
        if (count == 1)
            return node1pos;
        else if (count == 2)
            return node2pos;
        else if (count == 3)
            return node3pos;
        else
            return -1;
    }
    int idx = count / BITS0_COUNT_IN_EACH_INDEX;
    int start = 0;
    int end = 0;
    if (idx < indexCache0.size()) {
        start = indexCache0.get(idx);
        if (count % CACHE_WIDTH == 0)
            return start;
        start /= CACHE_WIDTH;
        if (idx + 1 < indexCache0.size()) {
            end = indexCache0.get(idx + 1) / CACHE_WIDTH + 1;
        } else {
            end = countCache0Size(size);
        }
    } else if (idx > 0) {
        start = indexCache0.get(idx - 1) / CACHE_WIDTH;
        end = Math.min(start + CACHE_WIDTH, countCache0Size(size));
    }
    long m = -1 * Unsafe.ARRAY_INT_INDEX_SCALE + Unsafe.ARRAY_INT_BASE_OFFSET;
    int d = 0;
    long startOffset = start * Unsafe.ARRAY_INT_INDEX_SCALE + Unsafe.ARRAY_INT_BASE_OFFSET;
    long endOffset = end * Unsafe.ARRAY_INT_INDEX_SCALE + Unsafe.ARRAY_INT_BASE_OFFSET;
    if (startOffset != endOffset) {
        do {
            m = ((startOffset + endOffset) / 2) & 0xfffffffffffffffcL;
            d = count - unsafe.getInt(countCache0, m);
            if (d < 0) {
                endOffset = m;
                continue;
            } else if (d > 0) {
                if (startOffset != m)
                    startOffset = m;
                else
                    break;
            } else {
                break;
            }
        } while (endOffset - startOffset >= 4);
        if (d > 0) {
            count = d;
        } else {
            while (m >= Unsafe.ARRAY_INT_BASE_OFFSET && count <= unsafe.getInt(countCache0, m)) {
                m -= Unsafe.ARRAY_INT_INDEX_SCALE;
            }
            if (m >= Unsafe.ARRAY_INT_BASE_OFFSET)
                count -= unsafe.getInt(countCache0, m);
        }
    }
    //		int n = containerBytesCount(size);
    int n = bytes.length;
    for (int i = (((int) (m - Unsafe.ARRAY_INT_BASE_OFFSET) / Unsafe.ARRAY_INT_INDEX_SCALE) + 1) * CACHE_WIDTH / 8; i < n; i++) {
        int bits = bytes[i] & 0xff;
        int c = BITCOUNTS0[bits];
        if (count <= c) {
            return i * 8 + BITPOS0[bits][count - 1];
        }
        count -= c;
    }
    return -1;
}
Example 18
Project: dragome-sdk-master  File: JDKAnalyzer.java View source code
private static void fillGoodBadOverrides() {
    // Problematic:
    // java.security.BasicPermission. Used by many different
    // classes and doing an import on all of java.security.
    // sun.misc.Unsafe: Very low-level functionality.
    GOOD_CLASSES.add("java.security.Permission");
    // Interfaces
    GOOD_CLASSES.add("java.security.Guard");
    // Super-class of a few good classes and not much functionality as it is
    // primarily abstract.
    GOOD_CLASSES.add("java.security.PermissionCollection");
    GOOD_CLASSES.add("java.security.BasicPermission");
    GOOD_CLASSES.add("java.security.PrivilegedAction");
    GOOD_CLASSES.add("java.security.PrivilegedActionException");
    GOOD_CLASSES.add("java.security.PrivilegedExceptionAction");
    // Interfaces from which good classes are created.
    // TODO(Sascha): Maybe do this automatically.
    GOOD_CLASSES.add("sun.reflect.LangReflectAccess");
    GOOD_CLASSES.add("sun.misc.JavaNetAccess");
    GOOD_CLASSES.add("sun.misc.JavaIOAccess");
    GOOD_CLASSES.add("org.xml.sax.EntityResolver");
    GOOD_CLASSES.add("sun.net.spi.nameservice.NameService");
    GOOD_CLASSES.add("org.xml.sax.ErrorHandler");
    GOOD_CLASSES.add("sun.misc.JavaIODeleteOnExitAccess");
    GOOD_CLASSES.add("sun.misc.SignalHandler");
    GOOD_CLASSES.add("sun.misc.JavaLangAccess");
    GOOD_CLASSES.add("sun.misc.JavaUtilJarAccess");
    GOOD_CLASSES.add("sun.misc.JavaIOFileDescriptorAccess");
    GOOD_CLASSES.add("sun.util.LocaleServiceProviderPool$LocalizedObjectGetter");
    GOOD_CLASSES.add("java.nio.channels.Channel");
    GOOD_CLASSES.add("org.apache.harmony.luni.internal.nls.Messages");
    GOOD_CLASSES.add("org.apache.harmony.math.internal.nls.Messages");
    GOOD_CLASSES.add("org.apache.harmony.regex.internal.nls.Messages");
    GOOD_CLASSES.add("org.apache.harmony.archive.internal.nls.Messages");
    BAD_CLASSES.add("java.util.jar.JarVerifier");
    BAD_CLASSES.add("java.lang.management.ManagementFactory");
    BAD_CLASSES.add("java.util.JapaneseImperialCalendar");
    BAD_CLASSES.add("java.lang.ClassLoader");
    BAD_CLASSES.add("java.net.URLClassLoader");
    BAD_CLASSES.add("java.net.URLClassLoader$SubURLClassLoader");
    BAD_CLASSES.add("java.net.FactoryURLClassLoader");
    // This one is a subclass of java.lang.ClassLoader, so it must go as
    // well.
    BAD_CLASSES.add("java.util.ResourceBundle$RBClassLoader");
    // Sub-class of bad class sun.misc.LRUCache.
    BAD_CLASSES.add("java.util.Scanner$1");
    // Sub-class of bad class org.apache.harmony.luni.util.ThreadLocalCache
    BAD_CLASSES.add("java.io.ObjectStreamClass$OSCThreadLocalCache");
    BAD_CLASSES.add("java.io.ObjectStreamClass$OSCThreadLocalCache$1");
    // DEX cannot parse this.
    BAD_CLASSES.add("org.apache.xerces.impl.xpath.regex.ParserForXMLSchema");
}
Example 19
Project: Java-Lang-master  File: ByteBufferReuse.java View source code
private static ByteBufferReuse getReuse() {
    ClassWriter cw = new ClassWriter(0);
    MethodVisitor mv;
    final String reuseImplClassName = "net/openhft/lang/io/ByteBufferReuseImpl";
    cw.visit(V1_6, ACC_PUBLIC + ACC_SUPER, reuseImplClassName, null, "sun/reflect/MagicAccessorImpl", new String[] { "net/openhft/lang/io/ByteBufferReuse" });
    {
        mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
        mv.visitCode();
        mv.visitVarInsn(ALOAD, 0);
        mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
        mv.visitInsn(RETURN);
        mv.visitMaxs(1, 1);
        mv.visitEnd();
    }
    String attachedBufferFieldName = getAttachedBufferFieldName();
    {
        mv = cw.visitMethod(ACC_PUBLIC, "reuse", "(JILjava/lang/Object;Ljava/nio/ByteBuffer;)Ljava/nio/ByteBuffer;", null, null);
        mv.visitCode();
        mv.visitVarInsn(ALOAD, 5);
        String directByteBuffer = "java/nio/DirectByteBuffer";
        mv.visitTypeInsn(INSTANCEOF, directByteBuffer);
        Label l0 = new Label();
        mv.visitJumpInsn(IFEQ, l0);
        mv.visitVarInsn(ALOAD, 5);
        mv.visitTypeInsn(CHECKCAST, directByteBuffer);
        mv.visitVarInsn(ASTORE, 6);
        mv.visitVarInsn(ALOAD, 6);
        mv.visitFieldInsn(GETFIELD, directByteBuffer, attachedBufferFieldName, "Ljava/lang/Object;");
        String settableAtt = "net/openhft/lang/io/SettableAtt";
        mv.visitTypeInsn(INSTANCEOF, settableAtt);
        mv.visitJumpInsn(IFEQ, l0);
        mv.visitVarInsn(ALOAD, 6);
        mv.visitVarInsn(LLOAD, 1);
        mv.visitFieldInsn(PUTFIELD, directByteBuffer, "address", "J");
        mv.visitVarInsn(ALOAD, 6);
        mv.visitInsn(ICONST_M1);
        mv.visitFieldInsn(PUTFIELD, directByteBuffer, "mark", "I");
        mv.visitVarInsn(ALOAD, 6);
        mv.visitInsn(ICONST_0);
        mv.visitFieldInsn(PUTFIELD, directByteBuffer, "position", "I");
        mv.visitVarInsn(ALOAD, 6);
        mv.visitVarInsn(ILOAD, 3);
        mv.visitFieldInsn(PUTFIELD, directByteBuffer, "limit", "I");
        mv.visitVarInsn(ALOAD, 6);
        mv.visitVarInsn(ILOAD, 3);
        mv.visitFieldInsn(PUTFIELD, directByteBuffer, "capacity", "I");
        mv.visitVarInsn(ALOAD, 6);
        mv.visitFieldInsn(GETFIELD, directByteBuffer, attachedBufferFieldName, "Ljava/lang/Object;");
        mv.visitTypeInsn(CHECKCAST, settableAtt);
        mv.visitVarInsn(ALOAD, 4);
        mv.visitFieldInsn(PUTFIELD, settableAtt, "att", "Ljava/lang/Object;");
        mv.visitVarInsn(ALOAD, 6);
        mv.visitInsn(ARETURN);
        mv.visitLabel(l0);
        mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
        mv.visitTypeInsn(NEW, settableAtt);
        mv.visitInsn(DUP);
        mv.visitMethodInsn(INVOKESPECIAL, settableAtt, "<init>", "()V", false);
        mv.visitVarInsn(ASTORE, 6);
        mv.visitVarInsn(ALOAD, 6);
        mv.visitVarInsn(ALOAD, 4);
        mv.visitFieldInsn(PUTFIELD, settableAtt, "att", "Ljava/lang/Object;");
        mv.visitTypeInsn(NEW, directByteBuffer);
        mv.visitInsn(DUP);
        mv.visitVarInsn(LLOAD, 1);
        mv.visitVarInsn(ILOAD, 3);
        mv.visitVarInsn(ALOAD, 6);
        mv.visitMethodInsn(INVOKESPECIAL, directByteBuffer, "<init>", "(JILjava/lang/Object;)V", false);
        mv.visitInsn(ARETURN);
        mv.visitMaxs(6, 7);
        mv.visitEnd();
    }
    cw.visitEnd();
    final byte[] impl = cw.toByteArray();
    final Unsafe unsafe = NativeBytes.UNSAFE;
    Class clazz = AccessController.doPrivileged(new PrivilegedAction<Class>() {

        @Override
        public Class run() {
            ClassLoader cl = MAGIC_CLASS_LOADER;
            return unsafe.defineClass(reuseImplClassName, impl, 0, impl.length, cl, null);
        }
    });
    try {
        return (ByteBufferReuse) clazz.newInstance();
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}
Example 20
Project: JDK-master  File: MethodHandleNatives.java View source code
// this method is also called by test/sun/reflect/CallerSensitiveFinder
// to validate the hand-maintained list
private static boolean isCallerSensitiveMethod(Class<?> defc, String method) {
    switch(method) {
        case "doPrivileged":
        case "doPrivilegedWithCombiner":
            return defc == java.security.AccessController.class;
        case "checkMemberAccess":
            return defc == java.lang.SecurityManager.class;
        case "getUnsafe":
            return defc == sun.misc.Unsafe.class;
        case "lookup":
            return defc == java.lang.invoke.MethodHandles.class;
        case "invoke":
            return defc == java.lang.reflect.Method.class;
        case "get":
        case "getBoolean":
        case "getByte":
        case "getChar":
        case "getShort":
        case "getInt":
        case "getLong":
        case "getFloat":
        case "getDouble":
        case "set":
        case "setBoolean":
        case "setByte":
        case "setChar":
        case "setShort":
        case "setInt":
        case "setLong":
        case "setFloat":
        case "setDouble":
            return defc == java.lang.reflect.Field.class;
        case "newInstance":
            if (defc == java.lang.reflect.Constructor.class)
                return true;
            if (defc == java.lang.Class.class)
                return true;
            break;
        case "getFields":
            return defc == java.lang.Class.class || defc == javax.sql.rowset.serial.SerialJavaObject.class;
        case "forName":
        case "getClassLoader":
        case "getClasses":
        case "getMethods":
        case "getConstructors":
        case "getDeclaredClasses":
        case "getDeclaredFields":
        case "getDeclaredMethods":
        case "getDeclaredConstructors":
        case "getField":
        case "getMethod":
        case "getConstructor":
        case "getDeclaredField":
        case "getDeclaredMethod":
        case "getDeclaredConstructor":
        case "getEnclosingClass":
        case "getEnclosingMethod":
        case "getEnclosingConstructor":
            return defc == java.lang.Class.class;
        case "getConnection":
        case "getDriver":
        case "getDrivers":
        case "deregisterDriver":
            return defc == java.sql.DriverManager.class;
        case "newUpdater":
            if (defc == java.util.concurrent.atomic.AtomicIntegerFieldUpdater.class)
                return true;
            if (defc == java.util.concurrent.atomic.AtomicLongFieldUpdater.class)
                return true;
            if (defc == java.util.concurrent.atomic.AtomicReferenceFieldUpdater.class)
                return true;
            break;
        case "getContextClassLoader":
            return defc == java.lang.Thread.class;
        case "getPackage":
        case "getPackages":
            return defc == java.lang.Package.class;
        case "getParent":
        case "getSystemClassLoader":
            return defc == java.lang.ClassLoader.class;
        case "load":
        case "loadLibrary":
            if (defc == java.lang.Runtime.class)
                return true;
            if (defc == java.lang.System.class)
                return true;
            break;
        case "getCallerClass":
            if (defc == sun.reflect.Reflection.class)
                return true;
            if (defc == java.lang.System.class)
                return true;
            break;
        case "getCallerClassLoader":
            return defc == java.lang.ClassLoader.class;
        case "registerAsParallelCapable":
            return defc == java.lang.ClassLoader.class;
        case "getProxyClass":
        case "newProxyInstance":
            return defc == java.lang.reflect.Proxy.class;
        case "asInterfaceInstance":
            return defc == java.lang.invoke.MethodHandleProxies.class;
        case "getBundle":
        case "clearCache":
            return defc == java.util.ResourceBundle.class;
        case "getType":
            return defc == java.io.ObjectStreamField.class;
        case "forClass":
            return defc == java.io.ObjectStreamClass.class;
        case "getLogger":
            return defc == java.util.logging.Logger.class;
        case "getAnonymousLogger":
            return defc == java.util.logging.Logger.class;
    }
    return false;
}
Example 21
Project: gpu-garbage-collection-master  File: VM.java View source code
/**
   * Complete the task of booting Jikes RVM.
   * Done in a secondary method mainly because this code
   * doesn't have to be uninterruptible and this is the cleanest
   * way to make that distinction.
   */
@Interruptible
private static void finishBooting() {
    // get pthread_id from OS and store into vm_processor field
    //
    sysCall.sysSetupHardwareTrapHandler();
    RVMThread.getCurrentThread().pthread_id = sysCall.sysGetThreadId();
    // Set up buffer locks used by Thread for logging and status dumping.
    //    This can happen at any point before we start running
    //    multi-threaded.
    Services.boot();
    //
    if (verboseBoot >= 1) {
        VM.sysWriteln("Setting up memory manager: bootrecord = ", Magic.objectAsAddress(BootRecord.the_boot_record));
    }
    MemoryManager.boot(BootRecord.the_boot_record);
    //
    if (verboseBoot >= 1)
        VM.sysWriteln("Initializing baseline compiler options to defaults");
    BaselineCompiler.initOptions();
    //
    if (verboseBoot >= 1)
        VM.sysWriteln("Fetching command-line arguments");
    CommandLineArgs.fetchCommandLineArguments();
    //
    if (verboseBoot >= 1)
        VM.sysWriteln("Early stage processing of command line");
    CommandLineArgs.earlyProcessCommandLineArguments();
    // Early initialization of TuningFork tracing engine.
    TraceEngine.engine.earlyStageBooting();
    //
    if (verboseBoot >= 1)
        VM.sysWriteln("Collector processing rest of boot options");
    MemoryManager.postBoot();
    // Initialize class loader.
    //
    String bootstrapClasses = CommandLineArgs.getBootstrapClasses();
    if (verboseBoot >= 1)
        VM.sysWriteln("Initializing bootstrap class loader: ", bootstrapClasses);
    // Wipe out cached application class loader
    RVMClassLoader.boot();
    BootstrapClassLoader.boot(bootstrapClasses);
    //
    if (verboseBoot >= 1)
        VM.sysWriteln("Running various class initializers");
    if (VM.BuildForGnuClasspath) {
        // Need for ThreadLocal
        runClassInitializer("java.util.WeakHashMap");
    }
    runClassInitializer("org.jikesrvm.classloader.Atom$InternedStrings");
    if (VM.BuildForGnuClasspath) {
        runClassInitializer("gnu.classpath.SystemProperties");
        runClassInitializer("java.lang.Throwable$StaticData");
    }
    runClassInitializer("java.lang.Runtime");
    runClassInitializer("java.lang.System");
    runClassInitializer("sun.misc.Unsafe");
    runClassInitializer("java.lang.Character");
    runClassInitializer("org.jikesrvm.classloader.TypeReferenceVector");
    runClassInitializer("org.jikesrvm.classloader.MethodVector");
    runClassInitializer("org.jikesrvm.classloader.FieldVector");
    // java.security.JikesRVMSupport.turnOffChecks();
    if (VM.BuildForGnuClasspath) {
        runClassInitializer("java.lang.ThreadGroup");
    }
    /* We can safely allocate a java.lang.Thread now.  The boot
       thread (running right now, as a Thread) has to become a full-fledged
       Thread, since we're about to encounter a security check:

       EncodingManager checks a system property,
        which means that the permissions checks have to be working,
        which means that VMAccessController will be invoked,
        which means that ThreadLocal.get() will be called,
        which calls Thread.getCurrentThread().

        So the boot Thread needs to be associated with a real Thread for
        Thread.getCurrentThread() to return. */
    VM.safeToAllocateJavaThread = true;
    if (VM.BuildForGnuClasspath) {
        runClassInitializer("java.lang.ThreadLocal");
        runClassInitializer("java.lang.ThreadLocalMap");
    }
    // Possibly fix VMAccessController's contexts and inGetContext fields
    if (VM.BuildForGnuClasspath) {
        runClassInitializer("java.security.VMAccessController");
    }
    if (VM.BuildForHarmony) {
        runClassInitializer("java.security.AccessController");
    }
    if (verboseBoot >= 1)
        VM.sysWriteln("Booting Lock");
    Lock.boot();
    //
    if (verboseBoot >= 1)
        VM.sysWriteln("Booting scheduler");
    RVMThread.boot();
    DynamicLibrary.boot();
    if (verboseBoot >= 1)
        VM.sysWriteln("Setting up boot thread");
    RVMThread.getCurrentThread().setupBootJavaThread();
    // Create JNI Environment for boot thread.
    // After this point the boot thread can invoke native methods.
    org.jikesrvm.jni.JNIEnvironment.boot();
    if (verboseBoot >= 1)
        VM.sysWriteln("Initializing JNI for boot thread");
    RVMThread.getCurrentThread().initializeJNIEnv();
    if (verboseBoot >= 1)
        VM.sysWriteln("JNI initialized for boot thread");
    if (VM.BuildForHarmony) {
        System.loadLibrary("hyluni");
        System.loadLibrary("hythr");
        System.loadLibrary("hyniochar");
    }
    // needed for when we initialize the
    runClassInitializer("java.io.File");
    // system/application class loader.
    runClassInitializer("java.lang.String");
    if (VM.BuildForGnuClasspath) {
        runClassInitializer("gnu.java.security.provider.DefaultPolicy");
    }
    // needed for URLClassLoader
    runClassInitializer("java.net.URL");
    /* Needed for ApplicationClassLoader, which in turn is needed by
       VMClassLoader.getSystemClassLoader()  */
    if (VM.BuildForGnuClasspath) {
        runClassInitializer("java.net.URLClassLoader");
    }
    /* Used if we start up Jikes RVM with the -jar argument; that argument
     * means that we need a working -jar before we can return an
     * Application Class Loader. */
    runClassInitializer("java.net.URLConnection");
    if (VM.BuildForGnuClasspath) {
        runClassInitializer("gnu.java.net.protocol.jar.Connection$JarFileCache");
        runClassInitializer("java.lang.ClassLoader$StaticData");
    }
    runClassInitializer("java.lang.Class$StaticData");
    runClassInitializer("java.nio.charset.Charset");
    if (VM.BuildForGnuClasspath) {
        runClassInitializer("java.nio.charset.CharsetEncoder");
    }
    runClassInitializer("java.nio.charset.CoderResult");
    if (VM.BuildForHarmony) {
        runClassInitializer("org.apache.harmony.niochar.CharsetProviderImpl");
    }
    // Uses System.getProperty
    runClassInitializer("java.io.PrintWriter");
    System.setProperty("line.separator", "\n");
    // Uses System.getProperty
    runClassInitializer("java.io.PrintStream");
    runClassInitializer("java.util.Locale");
    runClassInitializer("java.util.ResourceBundle");
    runClassInitializer("java.util.zip.CRC32");
    if (VM.BuildForHarmony) {
        System.loadLibrary("hyarchive");
    }
    runClassInitializer("java.util.zip.Inflater");
    if (VM.BuildForGnuClasspath) {
        runClassInitializer("java.util.zip.DeflaterHuffman");
        runClassInitializer("java.util.zip.InflaterDynHeader");
        runClassInitializer("java.util.zip.InflaterHuffmanTree");
    }
    // Run class intializers that require JNI
    if (verboseBoot >= 1)
        VM.sysWriteln("Running late class initializers");
    if (VM.BuildForGnuClasspath) {
        System.loadLibrary("javaio");
    }
    runClassInitializer("java.lang.Math");
    runClassInitializer("java.util.TreeMap");
    if (VM.BuildForGnuClasspath) {
        runClassInitializer("gnu.java.nio.VMChannel");
        runClassInitializer("gnu.java.nio.FileChannelImpl");
    }
    runClassInitializer("java.io.FileDescriptor");
    runClassInitializer("java.io.FilePermission");
    runClassInitializer("java.util.jar.JarFile");
    if (VM.BuildForGnuClasspath) {
        runClassInitializer("java.util.zip.ZipFile$PartialInputStream");
    }
    runClassInitializer("java.util.zip.ZipFile");
    if (VM.BuildForHarmony) {
        runClassInitializer("java.util.Hashtable");
        runClassInitializer("java.util.jar.Manifest");
        runClassInitializer("java.util.jar.Attributes$Name");
        runClassInitializer("java.util.BitSet");
        runClassInitializer("java.util.regex.Matcher");
        runClassInitializer("java.util.regex.Pattern");
        runClassInitializer("org.apache.harmony.luni.internal.net.www.protocol.jar.JarURLConnection");
        runClassInitializer("org.apache.harmony.luni.platform.OSMemory");
        runClassInitializer("org.apache.harmony.luni.platform.Platform");
        runClassInitializer("org.apache.harmony.luni.platform.AbstractMemorySpy");
        runClassInitializer("org.apache.harmony.luni.platform.PlatformAddress");
        runClassInitializer("org.apache.harmony.nio.internal.FileChannelImpl");
        runClassInitializer("com.ibm.icu.util.ULocale");
        runClassInitializer("java.io.ObjectStreamClass");
        runClassInitializer("java.io.ObjectStreamClass$OSCThreadLocalCache");
        runClassInitializer("java.io.ObjectInputStream");
        runClassInitializer("java.security.MessageDigest");
    }
    if (VM.BuildForGnuClasspath) {
        runClassInitializer("java.lang.VMDouble");
    }
    runClassInitializer("java.util.PropertyPermission");
    runClassInitializer("org.jikesrvm.classloader.RVMAnnotation");
    runClassInitializer("java.lang.annotation.RetentionPolicy");
    runClassInitializer("java.lang.annotation.ElementType");
    runClassInitializer("java.lang.Thread$State");
    if (VM.BuildForGnuClasspath) {
        runClassInitializer("java.lang.VMClassLoader");
    }
    if (verboseBoot >= 1)
        VM.sysWriteln("initializing standard streams");
    // Initialize java.lang.System.out, java.lang.System.err, java.lang.System.in
    FileSystem.initializeStandardStreams();
    ///////////////////////////////////////////////////////////////
    if (verboseBoot >= 1)
        VM.sysWriteln("VM is now fully booted");
    // Inform interested subsystems that VM is fully booted.
    VM.fullyBooted = true;
    MemoryManager.fullyBootedVM();
    BaselineCompiler.fullyBootedVM();
    TraceEngine.engine.fullyBootedVM();
    runClassInitializer("java.util.logging.Level");
    if (VM.BuildForGnuClasspath) {
        runClassInitializer("gnu.java.nio.charset.EncodingHelper");
        runClassInitializer("java.lang.reflect.Proxy");
        runClassInitializer("java.lang.reflect.Proxy$ProxySignature");
    }
    runClassInitializer("java.util.logging.Logger");
    if (VM.BuildForHarmony) {
        Entrypoints.luni1.setObjectValueUnchecked(null, null);
        Entrypoints.luni2.setObjectValueUnchecked(null, null);
        Entrypoints.luni3.setObjectValueUnchecked(null, null);
        Entrypoints.luni4.setObjectValueUnchecked(null, null);
        Entrypoints.luni5.setObjectValueUnchecked(null, null);
        Entrypoints.luni6.setObjectValueUnchecked(null, null);
        //runClassInitializer("java.lang.String$ConsolePrintStream");
        runClassInitializer("org.apache.harmony.luni.util.Msg");
        runClassInitializer("org.apache.harmony.archive.internal.nls.Messages");
        runClassInitializer("org.apache.harmony.luni.internal.nls.Messages");
        runClassInitializer("org.apache.harmony.nio.internal.nls.Messages");
        runClassInitializer("org.apache.harmony.niochar.internal.nls.Messages");
        runClassInitializer("java.util.logging.LogManager");
    }
    //
    if (verboseBoot >= 1)
        VM.sysWriteln("Initializing runtime compiler");
    RuntimeCompiler.boot();
    // Process remainder of the VM's command line arguments.
    if (verboseBoot >= 1)
        VM.sysWriteln("Late stage processing of command line");
    String[] applicationArguments = CommandLineArgs.lateProcessCommandLineArguments();
    if (VM.verboseClassLoading || verboseBoot >= 1)
        VM.sysWrite("[VM booted]\n");
    if (VM.BuildForAdaptiveSystem) {
        if (verboseBoot >= 1)
            VM.sysWriteln("Initializing adaptive system");
        Controller.boot();
    }
    // The first argument must be a class name.
    if (verboseBoot >= 1)
        VM.sysWriteln("Extracting name of class to execute");
    if (applicationArguments.length == 0) {
        pleaseSpecifyAClass();
    }
    if (applicationArguments.length > 0 && !TypeDescriptorParsing.isJavaClassName(applicationArguments[0])) {
        VM.sysWrite("vm: \"");
        VM.sysWrite(applicationArguments[0]);
        VM.sysWrite("\" is not a legal Java class name.\n");
        pleaseSpecifyAClass();
    }
    if (verboseBoot >= 1)
        VM.sysWriteln("Initializing Application Class Loader");
    RVMClassLoader.getApplicationClassLoader();
    RVMClassLoader.declareApplicationClassLoaderIsReady();
    if (verboseBoot >= 1) {
        VM.sysWriteln("Turning back on security checks.  Letting people see the ApplicationClassLoader.");
    }
    if (VM.BuildForGnuClasspath) {
        runClassInitializer("java.lang.ClassLoader$StaticData");
    }
    // Allow profile information to be read in from a file
    //
    EdgeCounts.boot(EdgeCounterFile);
    if (VM.BuildForAdaptiveSystem) {
        CompilerAdvice.postBoot();
    }
    // enable alignment checking
    if (VM.AlignmentChecking) {
        SysCall.sysCall.sysEnableAlignmentChecking();
    }
    // Schedule "main" thread for execution.
    if (verboseBoot >= 2)
        VM.sysWriteln("Creating main thread");
    // Create main thread.
    if (verboseBoot >= 1)
        VM.sysWriteln("Constructing mainThread");
    mainThread = new MainThread(applicationArguments);
    // Schedule "main" thread for execution.
    if (verboseBoot >= 1)
        VM.sysWriteln("Starting main thread");
    mainThread.start();
    //
    if (VM.TraceThreads)
        RVMThread.trace("VM.boot", "completed - terminating");
    if (verboseBoot >= 2) {
        VM.sysWriteln("Boot sequence completed; finishing boot thread");
    }
    RVMThread.getCurrentThread().terminate();
    if (VM.VerifyAssertions)
        VM._assert(VM.NOT_REACHED);
}
Example 22
Project: openjdk8-jdk-master  File: Basic.java View source code
private static void realMain(String[] args) throws Throwable {
    if (Windows.is())
        System.out.println("This appears to be a Windows system.");
    if (Unix.is())
        System.out.println("This appears to be a Unix system.");
    if (UnicodeOS.is())
        System.out.println("This appears to be a Unicode-based OS.");
    try {
        testIORedirection();
    } catch (Throwable t) {
        unexpected(t);
    }
    //----------------------------------------------------------------
    try {
        ProcessBuilder pb = new ProcessBuilder();
        Map<String, String> environ = pb.environment();
        // New env var
        environ.put("QUUX", "BAR");
        equal(environ.get("QUUX"), "BAR");
        equal(getenvInChild(pb, "QUUX"), "BAR");
        // Modify env var
        environ.put("QUUX", "bear");
        equal(environ.get("QUUX"), "bear");
        equal(getenvInChild(pb, "QUUX"), "bear");
        checkMapSanity(environ);
        // Remove env var
        environ.remove("QUUX");
        equal(environ.get("QUUX"), null);
        equal(getenvInChild(pb, "QUUX"), "null");
        checkMapSanity(environ);
        // Remove non-existent env var
        environ.remove("QUUX");
        equal(environ.get("QUUX"), null);
        equal(getenvInChild(pb, "QUUX"), "null");
        checkMapSanity(environ);
    } catch (Throwable t) {
        unexpected(t);
    }
    //----------------------------------------------------------------
    try {
        ProcessBuilder pb = new ProcessBuilder();
        pb.environment().clear();
        String expected = Windows.is() ? "SystemRoot=" + systemRoot + "," : "";
        if (Windows.is()) {
            pb.environment().put("SystemRoot", systemRoot);
        }
        String result = getenvInChild(pb);
        if (MacOSX.is()) {
            result = removeMacExpectedVars(result);
        }
        equal(result, expected);
    } catch (Throwable t) {
        unexpected(t);
    }
    //----------------------------------------------------------------
    // System.getenv() is read-only.
    //----------------------------------------------------------------
    THROWS(UnsupportedOperationException.class, new Fun() {

        void f() {
            getenv().put("FOO", "BAR");
        }
    }, new Fun() {

        void f() {
            getenv().remove("PATH");
        }
    }, new Fun() {

        void f() {
            getenv().keySet().remove("PATH");
        }
    }, new Fun() {

        void f() {
            getenv().values().remove("someValue");
        }
    });
    try {
        Collection<Map.Entry<String, String>> c = getenv().entrySet();
        if (!c.isEmpty())
            try {
                c.iterator().next().setValue("foo");
                fail("Expected UnsupportedOperationException not thrown");
            }// OK
             catch (UnsupportedOperationException e) {
            }
    } catch (Throwable t) {
        unexpected(t);
    }
    //----------------------------------------------------------------
    try {
        check(System.getenv() == System.getenv());
    } catch (Throwable t) {
        unexpected(t);
    }
    //----------------------------------------------------------------
    // You can't create an env var name containing "=",
    // or an env var name or value containing NUL.
    //----------------------------------------------------------------
    {
        final Map<String, String> m = new ProcessBuilder().environment();
        THROWS(IllegalArgumentException.class, new Fun() {

            void f() {
                m.put("FOO=", "BAR");
            }
        }, new Fun() {

            void f() {
                m.put("FOO", "BAR");
            }
        }, new Fun() {

            void f() {
                m.put("FOO", "BAR");
            }
        });
    }
    //----------------------------------------------------------------
    // Commands must never be null.
    //----------------------------------------------------------------
    THROWS(NullPointerException.class, new Fun() {

        void f() {
            new ProcessBuilder((List<String>) null);
        }
    }, new Fun() {

        void f() {
            new ProcessBuilder().command((List<String>) null);
        }
    });
    //----------------------------------------------------------------
    try {
        List<String> command = new ArrayList<String>();
        ProcessBuilder pb = new ProcessBuilder(command);
        check(pb.command() == command);
        List<String> command2 = new ArrayList<String>(2);
        command2.add("foo");
        command2.add("bar");
        pb.command(command2);
        check(pb.command() == command2);
        pb.command("foo", "bar");
        check(pb.command() != command2 && pb.command().equals(command2));
        pb.command(command2);
        command2.add("baz");
        equal(pb.command().get(2), "baz");
    } catch (Throwable t) {
        unexpected(t);
    }
    //----------------------------------------------------------------
    // Commands must contain at least one element.
    //----------------------------------------------------------------
    THROWS(IndexOutOfBoundsException.class, new Fun() {

        void f() throws IOException {
            new ProcessBuilder().start();
        }
    }, new Fun() {

        void f() throws IOException {
            new ProcessBuilder(new ArrayList<String>()).start();
        }
    }, new Fun() {

        void f() throws IOException {
            Runtime.getRuntime().exec(new String[] {});
        }
    });
    //----------------------------------------------------------------
    // Commands must not contain null elements at start() time.
    //----------------------------------------------------------------
    THROWS(NullPointerException.class, new Fun() {

        void f() throws IOException {
            new ProcessBuilder("foo", null, "bar").start();
        }
    }, new Fun() {

        void f() throws IOException {
            new ProcessBuilder((String) null).start();
        }
    }, new Fun() {

        void f() throws IOException {
            new ProcessBuilder(new String[] { null }).start();
        }
    }, new Fun() {

        void f() throws IOException {
            new ProcessBuilder(new String[] { "foo", null, "bar" }).start();
        }
    });
    //----------------------------------------------------------------
    try {
        new ProcessBuilder().command().add("foo");
        new ProcessBuilder("bar").command().add("foo");
        new ProcessBuilder(new String[] { "1", "2" }).command().add("3");
    } catch (Throwable t) {
        unexpected(t);
    }
    //----------------------------------------------------------------
    try {
        final Map<String, String> env = new ProcessBuilder().environment();
        THROWS(NullPointerException.class, new Fun() {

            void f() {
                env.put("foo", null);
            }
        }, new Fun() {

            void f() {
                env.put(null, "foo");
            }
        }, new Fun() {

            void f() {
                env.remove(null);
            }
        }, new Fun() {

            void f() {
                for (Map.Entry<String, String> e : env.entrySet()) e.setValue(null);
            }
        }, new Fun() {

            void f() throws IOException {
                Runtime.getRuntime().exec(new String[] { "foo" }, new String[] { null });
            }
        });
    } catch (Throwable t) {
        unexpected(t);
    }
    //----------------------------------------------------------------
    try {
        final Map<String, String> env = new ProcessBuilder().environment();
        THROWS(ClassCastException.class, new Fun() {

            void f() {
                env.remove(TRUE);
            }
        }, new Fun() {

            void f() {
                env.keySet().remove(TRUE);
            }
        }, new Fun() {

            void f() {
                env.values().remove(TRUE);
            }
        }, new Fun() {

            void f() {
                env.entrySet().remove(TRUE);
            }
        });
    } catch (Throwable t) {
        unexpected(t);
    }
    //----------------------------------------------------------------
    try {
        List<Map<String, String>> envs = new ArrayList<Map<String, String>>(2);
        envs.add(System.getenv());
        envs.add(new ProcessBuilder().environment());
        for (final Map<String, String> env : envs) {
            //----------------------------------------------------------------
            // Nulls in environment queries are forbidden.
            //----------------------------------------------------------------
            THROWS(NullPointerException.class, new Fun() {

                void f() {
                    getenv(null);
                }
            }, new Fun() {

                void f() {
                    env.get(null);
                }
            }, new Fun() {

                void f() {
                    env.containsKey(null);
                }
            }, new Fun() {

                void f() {
                    env.containsValue(null);
                }
            }, new Fun() {

                void f() {
                    env.keySet().contains(null);
                }
            }, new Fun() {

                void f() {
                    env.values().contains(null);
                }
            });
            //----------------------------------------------------------------
            // Non-String types in environment queries are forbidden.
            //----------------------------------------------------------------
            THROWS(ClassCastException.class, new Fun() {

                void f() {
                    env.get(TRUE);
                }
            }, new Fun() {

                void f() {
                    env.containsKey(TRUE);
                }
            }, new Fun() {

                void f() {
                    env.containsValue(TRUE);
                }
            }, new Fun() {

                void f() {
                    env.keySet().contains(TRUE);
                }
            }, new Fun() {

                void f() {
                    env.values().contains(TRUE);
                }
            });
            //----------------------------------------------------------------
            // Illegal String values in environment queries are (grumble) OK
            //----------------------------------------------------------------
            equal(env.get(""), null);
            check(!env.containsKey(""));
            check(!env.containsValue(""));
            check(!env.keySet().contains(""));
            check(!env.values().contains(""));
        }
    } catch (Throwable t) {
        unexpected(t);
    }
    try {
        final Set<Map.Entry<String, String>> entrySet = new ProcessBuilder().environment().entrySet();
        THROWS(NullPointerException.class, new Fun() {

            void f() {
                entrySet.contains(null);
            }
        });
        THROWS(ClassCastException.class, new Fun() {

            void f() {
                entrySet.contains(TRUE);
            }
        }, new Fun() {

            void f() {
                entrySet.contains(new SimpleImmutableEntry<Boolean, String>(TRUE, ""));
            }
        });
        check(!entrySet.contains(new SimpleImmutableEntry<String, String>("", "")));
    } catch (Throwable t) {
        unexpected(t);
    }
    //----------------------------------------------------------------
    try {
        ProcessBuilder pb = new ProcessBuilder();
        File foo = new File("foo");
        equal(pb.directory(), null);
        equal(pb.directory(foo).directory(), foo);
        equal(pb.directory(null).directory(), null);
    } catch (Throwable t) {
        unexpected(t);
    }
    //----------------------------------------------------------------
    try {
        testEncoding("ASCII", "xyzzy");
        testEncoding("Latin1", "ñá");
        testEncoding("Unicode", "⋱ᇡ");
    } catch (Throwable t) {
        unexpected(t);
    }
    //----------------------------------------------------------------
    // A surprisingly large number of ways to delete an environment var.
    //----------------------------------------------------------------
    testVariableDeleter(new EnvironmentFrobber() {

        public void doIt(Map<String, String> environ) {
            environ.remove("Foo");
        }
    });
    testVariableDeleter(new EnvironmentFrobber() {

        public void doIt(Map<String, String> environ) {
            environ.keySet().remove("Foo");
        }
    });
    testVariableDeleter(new EnvironmentFrobber() {

        public void doIt(Map<String, String> environ) {
            environ.values().remove("BAAR");
        }
    });
    testVariableDeleter(new EnvironmentFrobber() {

        public void doIt(Map<String, String> environ) {
            // Legally fabricate a ProcessEnvironment.StringEntry,
            // even though it's private.
            Map<String, String> environ2 = new ProcessBuilder().environment();
            environ2.clear();
            environ2.put("Foo", "BAAR");
            // Subtlety alert.
            Map.Entry<String, String> e = environ2.entrySet().iterator().next();
            environ.entrySet().remove(e);
        }
    });
    testVariableDeleter(new EnvironmentFrobber() {

        public void doIt(Map<String, String> environ) {
            Map.Entry<String, String> victim = null;
            for (Map.Entry<String, String> e : environ.entrySet()) if (e.getKey().equals("Foo"))
                victim = e;
            if (victim != null)
                environ.entrySet().remove(victim);
        }
    });
    testVariableDeleter(new EnvironmentFrobber() {

        public void doIt(Map<String, String> environ) {
            Iterator<String> it = environ.keySet().iterator();
            while (it.hasNext()) {
                String val = it.next();
                if (val.equals("Foo"))
                    it.remove();
            }
        }
    });
    testVariableDeleter(new EnvironmentFrobber() {

        public void doIt(Map<String, String> environ) {
            Iterator<Map.Entry<String, String>> it = environ.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, String> e = it.next();
                if (e.getKey().equals("Foo"))
                    it.remove();
            }
        }
    });
    testVariableDeleter(new EnvironmentFrobber() {

        public void doIt(Map<String, String> environ) {
            Iterator<String> it = environ.values().iterator();
            while (it.hasNext()) {
                String val = it.next();
                if (val.equals("BAAR"))
                    it.remove();
            }
        }
    });
    //----------------------------------------------------------------
    // A surprisingly small number of ways to add an environment var.
    //----------------------------------------------------------------
    testVariableAdder(new EnvironmentFrobber() {

        public void doIt(Map<String, String> environ) {
            environ.put("Foo", "Bahrein");
        }
    });
    //----------------------------------------------------------------
    // A few ways to modify an environment var.
    //----------------------------------------------------------------
    testVariableModifier(new EnvironmentFrobber() {

        public void doIt(Map<String, String> environ) {
            environ.put("Foo", "NewValue");
        }
    });
    testVariableModifier(new EnvironmentFrobber() {

        public void doIt(Map<String, String> environ) {
            for (Map.Entry<String, String> e : environ.entrySet()) if (e.getKey().equals("Foo"))
                e.setValue("NewValue");
        }
    });
    //----------------------------------------------------------------
    try {
        Map<String, String> environ = new ProcessBuilder().environment();
        int size = environ.size();
        checkSizes(environ, size);
        environ.put("UnLiKeLYeNVIROmtNam", "someVal");
        checkSizes(environ, size + 1);
        // Check for environment independence
        new ProcessBuilder().environment().clear();
        environ.put("UnLiKeLYeNVIROmtNam", "someOtherVal");
        checkSizes(environ, size + 1);
        environ.remove("UnLiKeLYeNVIROmtNam");
        checkSizes(environ, size);
        environ.clear();
        checkSizes(environ, 0);
        environ.clear();
        checkSizes(environ, 0);
        environ = new ProcessBuilder().environment();
        environ.keySet().clear();
        checkSizes(environ, 0);
        environ = new ProcessBuilder().environment();
        environ.entrySet().clear();
        checkSizes(environ, 0);
        environ = new ProcessBuilder().environment();
        environ.values().clear();
        checkSizes(environ, 0);
    } catch (Throwable t) {
        unexpected(t);
    }
    //----------------------------------------------------------------
    // Check that various map invariants hold
    //----------------------------------------------------------------
    checkMapSanity(new ProcessBuilder().environment());
    checkMapSanity(System.getenv());
    checkMapEquality(new ProcessBuilder().environment(), new ProcessBuilder().environment());
    //----------------------------------------------------------------
    try {
        Set<String> env1 = new HashSet<String>(Arrays.asList(nativeEnv((String[]) null).split("\n")));
        ProcessBuilder pb = new ProcessBuilder();
        pb.environment().put("QwErTyUiOp", "AsDfGhJk");
        Set<String> env2 = new HashSet<String>(Arrays.asList(nativeEnv(pb).split("\n")));
        check(env2.size() == env1.size() + 1);
        env1.add("QwErTyUiOp=AsDfGhJk");
        check(env1.equals(env2));
    } catch (Throwable t) {
        unexpected(t);
    }
    //----------------------------------------------------------------
    try {
        String systemRoot = "SystemRoot=" + System.getenv("SystemRoot");
        // '+' < 'A' < 'Z' < '_' < 'a' < 'z' < '~'
        String[] envp = { "FOO=BAR", "BAZ=GORP", "QUUX=", "+=+", "_=_", "~=~", systemRoot };
        String output = nativeEnv(envp);
        String expected = "+=+\nBAZ=GORP\nFOO=BAR\nQUUX=\n" + systemRoot + "\n_=_\n~=~\n";
        // Order is random on Unix, so this test does the sort.
        if (!Windows.is())
            output = sortByLinesWindowsly(output);
        equal(output, expected);
    } catch (Throwable t) {
        unexpected(t);
    }
    //----------------------------------------------------------------
    try {
        if (Windows.is()) {
            String systemRoot = "SystemRoot=" + System.getenv("SystemRoot");
            String[] envp = { "FOO=BAR", "BAZ=GORP", "QUUX=", "+=+", "_=_", "~=~" };
            String output = nativeEnv(envp);
            String expected = "+=+\nBAZ=GORP\nFOO=BAR\nQUUX=\n" + systemRoot + "\n_=_\n~=~\n";
            equal(output, expected);
        }
    } catch (Throwable t) {
        unexpected(t);
    }
    //----------------------------------------------------------------
    try {
        for (Map.Entry<String, String> e : getenv().entrySet()) equal(getenv(e.getKey()), e.getValue());
    } catch (Throwable t) {
        unexpected(t);
    }
    //----------------------------------------------------------------
    try {
        String canonicalUserDir = new File(System.getProperty("user.dir")).getCanonicalPath();
        String[] sdirs = new String[] { ".", "..", "/", "/bin", "C:", "c:", "C:/", "c:\\", "\\", "\\bin", "c:\\windows  ", "c:\\Program Files", "c:\\Program Files\\" };
        for (String sdir : sdirs) {
            File dir = new File(sdir);
            if (!(dir.isDirectory() && dir.exists()))
                continue;
            out.println("Testing directory " + dir);
            //dir = new File(dir.getCanonicalPath());
            ProcessBuilder pb = new ProcessBuilder();
            equal(pb.directory(), null);
            equal(pwdInChild(pb), canonicalUserDir);
            pb.directory(dir);
            equal(pb.directory(), dir);
            equal(pwdInChild(pb), dir.getCanonicalPath());
            pb.directory(null);
            equal(pb.directory(), null);
            equal(pwdInChild(pb), canonicalUserDir);
            pb.directory(dir);
        }
    } catch (Throwable t) {
        unexpected(t);
    }
    //----------------------------------------------------------------
    try {
        if (UnicodeOS.is()) {
            File dir = new File(System.getProperty("test.dir", "."), "ProcessBuilderDir一丂");
            try {
                if (!dir.exists())
                    dir.mkdir();
                out.println("Testing Unicode directory:" + dir);
                ProcessBuilder pb = new ProcessBuilder();
                pb.directory(dir);
                equal(pwdInChild(pb), dir.getCanonicalPath());
            } finally {
                if (dir.exists())
                    dir.delete();
            }
        }
    } catch (Throwable t) {
        unexpected(t);
    }
    //----------------------------------------------------------------
    try {
        List<String> list = new ArrayList<String>(javaChildArgs);
        list.add(1, String.format("-XX:OnOutOfMemoryError=%s -version", javaExe));
        list.add("ArrayOOME");
        ProcessResults r = run(new ProcessBuilder(list));
        check(r.out().contains("java.lang.OutOfMemoryError:"));
        check(r.out().contains(javaExe));
        check(r.err().contains(System.getProperty("java.version")));
        equal(r.exitValue(), 1);
    } catch (Throwable t) {
        unexpected(t);
    }
    //----------------------------------------------------------------
    if (Windows.is())
        try {
            out.println("Running case insensitve variable tests");
            for (String[] namePair : new String[][] { new String[] { "PATH", "PaTh" }, new String[] { "home", "HOME" }, new String[] { "SYSTEMROOT", "SystemRoot" } }) {
                check((getenv(namePair[0]) == null && getenv(namePair[1]) == null) || getenv(namePair[0]).equals(getenv(namePair[1])), "Windows environment variables are not case insensitive");
            }
        } catch (Throwable t) {
            unexpected(t);
        }
    //----------------------------------------------------------------
    if (UnicodeOS.is())
        try {
            ProcessBuilder pb = new ProcessBuilder();
            pb.environment().put("ሴ", "噸");
            pb.environment().remove("PATH");
            equal(getenvInChild1234(pb), "噸");
        } catch (Throwable t) {
            unexpected(t);
        }
    //----------------------------------------------------------------
    try {
        List<String> childArgs = new ArrayList<String>(javaChildArgs);
        childArgs.add("System.getenv()");
        String[] cmdp = childArgs.toArray(new String[childArgs.size()]);
        String[] envp;
        String[] envpWin = { "=C:=\\", "=ExitValue=3", "SystemRoot=" + systemRoot };
        String[] envpOth = { "=ExitValue=3", "=C:=\\" };
        if (Windows.is()) {
            envp = envpWin;
        } else {
            envp = envpOth;
        }
        Process p = Runtime.getRuntime().exec(cmdp, envp);
        String expected = Windows.is() ? "=C:=\\,=ExitValue=3,SystemRoot=" + systemRoot + "," : "=C:=\\,";
        String commandOutput = commandOutput(p);
        if (MacOSX.is()) {
            commandOutput = removeMacExpectedVars(commandOutput);
        }
        equal(commandOutput, expected);
        if (Windows.is()) {
            ProcessBuilder pb = new ProcessBuilder(childArgs);
            pb.environment().clear();
            pb.environment().put("SystemRoot", systemRoot);
            pb.environment().put("=ExitValue", "3");
            pb.environment().put("=C:", "\\");
            equal(commandOutput(pb), expected);
        }
    } catch (Throwable t) {
        unexpected(t);
    }
    //----------------------------------------------------------------
    try {
        String[] cmdp = { "echo" };
        // Yuck!
        String[] envp = { "Hello", "World" };
        Process p = Runtime.getRuntime().exec(cmdp, envp);
        equal(commandOutput(p), "\n");
    } catch (Throwable t) {
        unexpected(t);
    }
    //----------------------------------------------------------------
    try {
        List<String> childArgs = new ArrayList<String>(javaChildArgs);
        childArgs.add("System.getenv()");
        String[] cmdp = childArgs.toArray(new String[childArgs.size()]);
        String[] envpWin = { // Yuck!
        "SystemRoot=" + systemRoot, // Yuck!
        "LC_ALL=C", "FO=BR" };
        String[] envpOth = { // Yuck!
        "LC_ALL=C", "FO=BR" };
        String[] envp;
        if (Windows.is()) {
            envp = envpWin;
        } else {
            envp = envpOth;
        }
        System.out.println("cmdp");
        for (int i = 0; i < cmdp.length; i++) {
            System.out.printf("cmdp %d: %s\n", i, cmdp[i]);
        }
        System.out.println("envp");
        for (int i = 0; i < envp.length; i++) {
            System.out.printf("envp %d: %s\n", i, envp[i]);
        }
        Process p = Runtime.getRuntime().exec(cmdp, envp);
        String commandOutput = commandOutput(p);
        if (MacOSX.is()) {
            commandOutput = removeMacExpectedVars(commandOutput);
        }
        check(commandOutput.equals(Windows.is() ? "LC_ALL=C,SystemRoot=" + systemRoot + "," : "LC_ALL=C,"), "Incorrect handling of envstrings containing NULs");
    } catch (Throwable t) {
        unexpected(t);
    }
    //----------------------------------------------------------------
    try {
        ProcessBuilder pb = new ProcessBuilder();
        equal(pb.redirectErrorStream(), false);
        equal(pb.redirectErrorStream(true), pb);
        equal(pb.redirectErrorStream(), true);
        equal(pb.redirectErrorStream(false), pb);
        equal(pb.redirectErrorStream(), false);
    } catch (Throwable t) {
        unexpected(t);
    }
    try {
        List<String> childArgs = new ArrayList<String>(javaChildArgs);
        childArgs.add("OutErr");
        ProcessBuilder pb = new ProcessBuilder(childArgs);
        {
            ProcessResults r = run(pb);
            equal(r.out(), "outout");
            equal(r.err(), "errerr");
        }
        {
            pb.redirectErrorStream(true);
            ProcessResults r = run(pb);
            equal(r.out(), "outerrouterr");
            equal(r.err(), "");
        }
    } catch (Throwable t) {
        unexpected(t);
    }
    if (Unix.is()) {
        //----------------------------------------------------------------
        try {
            List<String> childArgs = new ArrayList<String>(javaChildArgs);
            childArgs.add("null PATH");
            ProcessBuilder pb = new ProcessBuilder(childArgs);
            pb.environment().remove("PATH");
            ProcessResults r = run(pb);
            equal(r.out(), "");
            equal(r.err(), "");
            equal(r.exitValue(), 0);
        } catch (Throwable t) {
            unexpected(t);
        }
        //----------------------------------------------------------------
        try {
            List<String> childArgs = new ArrayList<String>(javaChildArgs);
            childArgs.add("PATH search algorithm");
            ProcessBuilder pb = new ProcessBuilder(childArgs);
            pb.environment().put("PATH", "dir1:dir2:");
            ProcessResults r = run(pb);
            equal(r.out(), "");
            equal(r.err(), "");
            equal(r.exitValue(), True.exitValue());
        } catch (Throwable t) {
            unexpected(t);
        }
        //----------------------------------------------------------------
        try {
            new File("suBdiR").mkdirs();
            copy("/bin/true", "suBdiR/unliKely");
            final ProcessBuilder pb = new ProcessBuilder(new String[] { "unliKely" });
            pb.environment().put("PATH", "suBdiR");
            THROWS(IOException.class, new Fun() {

                void f() throws Throwable {
                    pb.start();
                }
            });
        } catch (Throwable t) {
            unexpected(t);
        } finally {
            new File("suBdiR/unliKely").delete();
            new File("suBdiR").delete();
        }
    }
    //----------------------------------------------------------------
    try {
        new ProcessBuilder("").start();
        fail("Expected IOException not thrown");
    } catch (IOException e) {
        String m = e.getMessage();
        if (EnglishUnix.is() && !matches(m, "No such file or directory"))
            unexpected(e);
    } catch (Throwable t) {
        unexpected(t);
    }
    //----------------------------------------------------------------
    for (String programName : new String[] { "ð", "ǰ" }) try {
        new ProcessBuilder(programName).start();
        fail("Expected IOException not thrown");
    } catch (IOException e) {
        String m = e.getMessage();
        Pattern p = Pattern.compile(programName);
        if (!matches(m, programName) || (EnglishUnix.is() && !matches(m, "No such file or directory")))
            unexpected(e);
    } catch (Throwable t) {
        unexpected(t);
    }
    //----------------------------------------------------------------
    try {
        new ProcessBuilder("echo").directory(new File("UnLiKeLY")).start();
        fail("Expected IOException not thrown");
    } catch (IOException e) {
        String m = e.getMessage();
        if (!matches(m, "in directory") || (EnglishUnix.is() && !matches(m, "No such file or directory")))
            unexpected(e);
    } catch (Throwable t) {
        unexpected(t);
    }
    //----------------------------------------------------------------
    try {
        List<String> childArgs = new ArrayList<String>(javaChildArgs);
        childArgs.add("print4095");
        final int SIZE = 4095;
        final Process p = new ProcessBuilder(childArgs).start();
        // Might hang!
        print4095(p.getOutputStream(), (byte) '!');
        // Might hang!
        p.waitFor();
        equal(SIZE, p.getInputStream().available());
        equal(SIZE, p.getErrorStream().available());
        THROWS(IOException.class, new Fun() {

            void f() throws IOException {
                p.getOutputStream().write((byte) '!');
                p.getOutputStream().flush();
            }
        });
        final byte[] bytes = new byte[SIZE + 1];
        equal(SIZE, p.getInputStream().read(bytes));
        for (int i = 0; i < SIZE; i++) equal((byte) '!', bytes[i]);
        equal((byte) 0, bytes[SIZE]);
        equal(SIZE, p.getErrorStream().read(bytes));
        for (int i = 0; i < SIZE; i++) equal((byte) 'E', bytes[i]);
        equal((byte) 0, bytes[SIZE]);
        equal(0, p.getInputStream().available());
        equal(0, p.getErrorStream().available());
        equal(-1, p.getErrorStream().read());
        equal(-1, p.getInputStream().read());
        equal(p.exitValue(), 5);
        p.getInputStream().close();
        p.getErrorStream().close();
        try {
            p.getOutputStream().close();
        } catch (IOException flushFailed) {
        }
        InputStream[] streams = { p.getInputStream(), p.getErrorStream() };
        for (final InputStream in : streams) {
            Fun[] ops = { new Fun() {

                void f() throws IOException {
                    in.read();
                }
            }, new Fun() {

                void f() throws IOException {
                    in.read(bytes);
                }
            }, new Fun() {

                void f() throws IOException {
                    in.available();
                }
            } };
            for (Fun op : ops) {
                try {
                    op.f();
                    fail();
                } catch (IOException expected) {
                    check(expected.getMessage().matches("[Ss]tream [Cc]losed"));
                }
            }
        }
    } catch (Throwable t) {
        unexpected(t);
    }
    //----------------------------------------------------------------
    try {
        final int cases = 4;
        for (int i = 0; i < cases; i++) {
            final int action = i;
            List<String> childArgs = new ArrayList<String>(javaChildArgs);
            childArgs.add("sleep");
            final byte[] bytes = new byte[10];
            final Process p = new ProcessBuilder(childArgs).start();
            final CountDownLatch latch = new CountDownLatch(1);
            final InputStream s;
            switch(action & 0x1) {
                case 0:
                    s = p.getInputStream();
                    break;
                case 1:
                    s = p.getErrorStream();
                    break;
                default:
                    throw new Error();
            }
            final Thread thread = new Thread() {

                public void run() {
                    try {
                        int r;
                        latch.countDown();
                        switch(action & 0x2) {
                            case 0:
                                r = s.read();
                                break;
                            case 2:
                                r = s.read(bytes);
                                break;
                            default:
                                throw new Error();
                        }
                        equal(-1, r);
                    } catch (Throwable t) {
                        unexpected(t);
                    }
                }
            };
            thread.start();
            latch.await();
            Thread.sleep(10);
            String os = System.getProperty("os.name");
            if (os.equalsIgnoreCase("Solaris") || os.equalsIgnoreCase("SunOS")) {
                final Object deferred;
                Class<?> c = s.getClass();
                if (c.getName().equals("java.lang.UNIXProcess$DeferredCloseInputStream")) {
                    deferred = s;
                } else {
                    Field deferredField = p.getClass().getDeclaredField("stdout_inner_stream");
                    deferredField.setAccessible(true);
                    deferred = deferredField.get(p);
                }
                Field useCountField = deferred.getClass().getDeclaredField("useCount");
                useCountField.setAccessible(true);
                while (useCountField.getInt(deferred) <= 0) {
                    Thread.yield();
                }
            } else if (s instanceof BufferedInputStream) {
                Field f = Unsafe.class.getDeclaredField("theUnsafe");
                f.setAccessible(true);
                Unsafe unsafe = (Unsafe) f.get(null);
                while (unsafe.tryMonitorEnter(s)) {
                    unsafe.monitorExit(s);
                    Thread.sleep(1);
                }
            }
            p.destroy();
            thread.join();
        }
    } catch (Throwable t) {
        unexpected(t);
    }
    //----------------------------------------------------------------
    try {
        if (Unix.is() && new File("/bin/bash").exists() && new File("/bin/sleep").exists()) {
            final String[] cmd = { "/bin/bash", "-c", "(/bin/sleep 6666)" };
            final ProcessBuilder pb = new ProcessBuilder(cmd);
            final Process p = pb.start();
            final InputStream stdout = p.getInputStream();
            final InputStream stderr = p.getErrorStream();
            final OutputStream stdin = p.getOutputStream();
            final Thread reader = new Thread() {

                public void run() {
                    try {
                        stdout.read();
                    } catch (IOException e) {
                        if (EnglishUnix.is() && !(e.getMessage().matches(".*Bad file.*")))
                            unexpected(e);
                    } catch (Throwable t) {
                        unexpected(t);
                    }
                }
            };
            reader.setDaemon(true);
            reader.start();
            Thread.sleep(100);
            p.destroy();
            // Subprocess is now dead, but file descriptors remain open.
            check(p.waitFor() != 0);
            check(p.exitValue() != 0);
            stdout.close();
            stderr.close();
            stdin.close();
            //----------------------------------------------------------
            if (Boolean.getBoolean("wakeupJeff!")) {
                System.out.println("wakeupJeff!");
                // Initialize signal handler for INTERRUPT_SIGNAL.
                new FileInputStream("/bin/sleep").getChannel().close();
                // Send INTERRUPT_SIGNAL to every thread in this java.
                String[] wakeupJeff = { "/bin/bash", "-c", "/bin/ps --noheaders -Lfp $PPID | " + "/usr/bin/perl -nale 'print $F[3]' | " + // INTERRUPT_SIGNAL == 62 on my machine du jour.
                "/usr/bin/xargs kill -62" };
                new ProcessBuilder(wakeupJeff).start().waitFor();
                // If wakeupJeff worked, reader probably got EBADF.
                reader.join();
            }
        }
    } catch (Throwable t) {
        unexpected(t);
    }
    //----------------------------------------------------------------
    try {
        new File("emptyCommand").delete();
        new FileOutputStream("emptyCommand").close();
        new File("emptyCommand").setExecutable(false);
        new ProcessBuilder("./emptyCommand").start();
        fail("Expected IOException not thrown");
    } catch (IOException e) {
        new File("./emptyCommand").delete();
        String m = e.getMessage();
        if (EnglishUnix.is() && !matches(m, "Permission denied"))
            unexpected(e);
    } catch (Throwable t) {
        unexpected(t);
    }
    new File("emptyCommand").delete();
    //----------------------------------------------------------------
    // Check for correct security permission behavior
    //----------------------------------------------------------------
    final Policy policy = new Policy();
    Policy.setPolicy(policy);
    System.setSecurityManager(new SecurityManager());
    try {
        // No permissions required to CREATE a ProcessBuilder
        policy.setPermissions();
        new ProcessBuilder("env").directory(null).directory();
        new ProcessBuilder("env").directory(new File("dir")).directory();
        new ProcessBuilder("env").command("??").command();
    } catch (Throwable t) {
        unexpected(t);
    }
    THROWS(SecurityException.class, new Fun() {

        void f() throws IOException {
            policy.setPermissions();
            System.getenv("foo");
        }
    }, new Fun() {

        void f() throws IOException {
            policy.setPermissions();
            System.getenv();
        }
    }, new Fun() {

        void f() throws IOException {
            policy.setPermissions();
            new ProcessBuilder("echo").start();
        }
    }, new Fun() {

        void f() throws IOException {
            policy.setPermissions();
            Runtime.getRuntime().exec("echo");
        }
    }, new Fun() {

        void f() throws IOException {
            policy.setPermissions(new RuntimePermission("getenv.bar"));
            System.getenv("foo");
        }
    });
    try {
        policy.setPermissions(new RuntimePermission("getenv.foo"));
        System.getenv("foo");
        policy.setPermissions(new RuntimePermission("getenv.*"));
        System.getenv("foo");
        System.getenv();
        new ProcessBuilder().environment();
    } catch (Throwable t) {
        unexpected(t);
    }
    final Permission execPermission = new FilePermission("<<ALL FILES>>", "execute");
    THROWS(SecurityException.class, new Fun() {

        void f() throws IOException {
            // environment permission by itself insufficient
            policy.setPermissions(new RuntimePermission("getenv.*"));
            ProcessBuilder pb = new ProcessBuilder("env");
            pb.environment().put("foo", "bar");
            pb.start();
        }
    }, new Fun() {

        void f() throws IOException {
            // exec permission by itself insufficient
            policy.setPermissions(execPermission);
            ProcessBuilder pb = new ProcessBuilder("env");
            pb.environment().put("foo", "bar");
            pb.start();
        }
    });
    try {
        // Both permissions? OK.
        policy.setPermissions(new RuntimePermission("getenv.*"), execPermission);
        ProcessBuilder pb = new ProcessBuilder("env");
        pb.environment().put("foo", "bar");
        Process p = pb.start();
        closeStreams(p);
    } catch (// OK
    IOException // OK
    e) {
    } catch (Throwable t) {
        unexpected(t);
    }
    try {
        // Don't need environment permission unless READING environment
        policy.setPermissions(execPermission);
        Runtime.getRuntime().exec("env", new String[] {});
    } catch (// OK
    IOException // OK
    e) {
    } catch (Throwable t) {
        unexpected(t);
    }
    try {
        // Don't need environment permission unless READING environment
        policy.setPermissions(execPermission);
        new ProcessBuilder("env").start();
    } catch (// OK
    IOException // OK
    e) {
    } catch (Throwable t) {
        unexpected(t);
    }
    // Restore "normal" state without a security manager
    policy.setPermissions(new RuntimePermission("setSecurityManager"));
    System.setSecurityManager(null);
    //----------------------------------------------------------------
    try {
        List<String> childArgs = new ArrayList<String>(javaChildArgs);
        childArgs.add("sleep");
        final Process p = new ProcessBuilder(childArgs).start();
        long start = System.nanoTime();
        if (!p.isAlive() || p.waitFor(0, TimeUnit.MILLISECONDS)) {
            fail("Test failed: Process exited prematurely");
        }
        long end = System.nanoTime();
        // give waitFor(timeout) a wide berth (100ms)
        if ((end - start) > 100000000)
            fail("Test failed: waitFor took too long");
        p.destroy();
        p.waitFor();
        if (p.isAlive() || !p.waitFor(0, TimeUnit.MILLISECONDS)) {
            fail("Test failed: Process still alive - please terminate " + p.toString() + " manually");
        }
    } catch (Throwable t) {
        unexpected(t);
    }
    //----------------------------------------------------------------
    try {
        List<String> childArgs = new ArrayList<String>(javaChildArgs);
        childArgs.add("sleep");
        final Process p = new ProcessBuilder(childArgs).start();
        long start = System.nanoTime();
        p.waitFor(1000, TimeUnit.MILLISECONDS);
        long end = System.nanoTime();
        if ((end - start) < 500000000)
            fail("Test failed: waitFor didn't take long enough");
        p.destroy();
        start = System.nanoTime();
        p.waitFor(1000, TimeUnit.MILLISECONDS);
        end = System.nanoTime();
        if ((end - start) > 900000000)
            fail("Test failed: waitFor took too long on a dead process.");
    } catch (Throwable t) {
        unexpected(t);
    }
    //----------------------------------------------------------------
    try {
        List<String> childArgs = new ArrayList<String>(javaChildArgs);
        childArgs.add("sleep");
        final Process p = new ProcessBuilder(childArgs).start();
        final long start = System.nanoTime();
        final CountDownLatch latch = new CountDownLatch(1);
        final Thread thread = new Thread() {

            public void run() {
                try {
                    try {
                        latch.countDown();
                        p.waitFor(10000, TimeUnit.MILLISECONDS);
                    } catch (InterruptedException e) {
                        return;
                    }
                    fail("waitFor() wasn't interrupted");
                } catch (Throwable t) {
                    unexpected(t);
                }
            }
        };
        thread.start();
        latch.await();
        Thread.sleep(1000);
        thread.interrupt();
        p.destroy();
    } catch (Throwable t) {
        unexpected(t);
    }
    //----------------------------------------------------------------
    try {
        List<String> childArgs = new ArrayList<String>(javaChildArgs);
        childArgs.add("sleep");
        final Process proc = new ProcessBuilder(childArgs).start();
        DelegatingProcess p = new DelegatingProcess(proc);
        long start = System.nanoTime();
        p.waitFor(1000, TimeUnit.MILLISECONDS);
        long end = System.nanoTime();
        if ((end - start) < 500000000)
            fail("Test failed: waitFor didn't take long enough");
        p.destroy();
        p.waitFor(1000, TimeUnit.MILLISECONDS);
    } catch (Throwable t) {
        unexpected(t);
    }
}