user466540
user466540

Reputation: 81

ByteBuddy - how to add local variable

I need to add local variable to the generated body of the intercepted method.

I have tried (in order to generate an int variable):

List<StackManipulation> statements = new ArrayList();

statements.add(IntegerConstant.forValue(false));
statements.add(MethodVariableAccess.INTEGER.storeAt(3));

...

StackManipulation logic = new StackManipulation.Compound(statements.toArray(new StackManipulation[0]));

StackManipulation.Size size = new StackManipulation.Compound(logic).apply(methodVisitor, context);

return new ByteCodeAppender.Size(size.getMaximalSize(), methodDescription.getStackSize());

but this gives me

java.lang.VerifyError: Local variable table overflow.

Of course, local variable table should already has this variable.

To get around this I am now creating extra method parameters to act as local variables, which of course is not convenient.

So, how could I modify the local variable table using ByteBuddy?

Upvotes: 2

Views: 547

Answers (1)

Rafael Winterhalter
Rafael Winterhalter

Reputation: 44067

You have to specify the correct size for the local variable array. If you require an additional slot, you have to indicate the correct size for the appender:

new ByteCodeAppender.Size(
  size.getMaximalSize(), 
  methodDescription.getStackSize() + 1
);

In the above example, it seems as if you only reserve place for the values of the instrumented method.

Upvotes: 3

Related Questions