# Thursday, 30 May 2013
« The End of ACC_SUPER | Main | Type Confusion PoC for CVE-2013-3131 (MS... »
Overriding a Final Finalize

Compile the following code:

class Base {
  protected final void finalize() {
    System.out.println("Base.finalize");
  }
}

class Derived extends Base {
  private void fin_lize() {
    System.out.println("Derived.finalize");
  }

  public static void main(String[] args) {
    new Derived();
    System.gc();
    System.runFinalization();
  }
}

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, 30 May 2013 16:11:44 (W. Europe Daylight Time, UTC+02:00)  #    Comments [14]