Skip to content

Instantly share code, notes, and snippets.

@oleavr
Created January 27, 2019 20:18
Show Gist options
  • Save oleavr/f86f01aa2d7854ce22d2b1cf795cbe69 to your computer and use it in GitHub Desktop.
Save oleavr/f86f01aa2d7854ce22d2b1cf795cbe69 to your computer and use it in GitHub Desktop.

Revisions

  1. oleavr created this gist Jan 27, 2019.
    33 changes: 33 additions & 0 deletions jit-example.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,33 @@
    'use strict';

    const slowCallback = new NativeCallback(value => {
    console.log('slowCallback hit');
    return 43;
    }, 'int', ['int']);

    const fastCallback = Memory.alloc(Process.pageSize);
    Memory.patchCode(fastCallback, 128, code => {
    const cw = new X86Writer(code, { pc: fastCallback });
    cw.putCmpRegI32('edi', 10);
    cw.putJccShortLabel('je', 'match', 'unlikely');

    cw.putLabel('nomatch');
    cw.putMovRegU64('rax', 42);
    cw.putJmpShortLabel('done');

    cw.putLabel('match');
    cw.putSubRegImm('rsp', 8);
    cw.putCallAddressWithAlignedArguments(slowCallback, ['edi']);
    cw.putAddRegImm('rsp', 8);

    cw.putLabel('done');
    cw.putRet();

    cw.flush();
    });

    const cb = new NativeFunction(fastCallback, 'int', ['int']);
    for (let i = 0; i !== 100; i++) {
    const result = cb(i)
    console.log(`${i} => ${result}`);
    }