Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Inline assembly" for Java byte codes

Tags:

java

bytecode

I'm looking for existing implementations of the following idea: suppose somebody wants to write "inline assembly" byte codes inside a normal Java program (most relevant applications would involve invokedynamic instruction that is not otherwise available in Java). One way to do this would be as follows:

void foo(boolean b) {
    Label l1 = Asm.label();
    Label l2 = Asm.label();

    int i = Asm.no_int();
    Asm._const(0);
    Asm.store(i);
    l1.bind();
    Asm.load(i);
    Asm.push(10);
    Asm.if_cmpge(l2);
    Asm.getstatic("java/lang/System", "out", "Ljava/io/PrintStream");
    Asm.load(i);
    Asm.invokevirtual("java/io/PrintStream", "println", "(I)V");
    Asm.inc(i);
    Asm._goto(l1);
    l2.bind();
    Asm._return();
}

Instructions are encoded as API calls, then we'd need to run a normal java compiler, and then to post-process the byte code and replace the API calls with actual instructions.

P.S. I'm aware of ASMifier of the ASM Framework, it does not solve the problem stated above.

like image 622
Andrey Breslav Avatar asked Aug 04 '13 05:08

Andrey Breslav


1 Answers

ClassLoader has a method, defineClass, that lets you dynamically generate a class by providing the bytecode. Combine this with Javassist or other suggestions from this previous question.

like image 86
jason Avatar answered Sep 19 '22 21:09

jason