Skip to content

Generate .class with MethodParameters

XYHyouKa edited this page Jun 19, 2024 · 2 revisions

In Soot official tutorial and default implementation, BafASMBackend is used to generate .class file.

MethodParameters attribute structure

MethodParameters is an attribute of method (requires Java >= 8). It's generated with -parameters option in javac command.

MethodParameters structure:

Type Name Count
u2 attribute_name_index 1
u4 attribute_length 1
u1 parameters_count 1
parameter parameters parameters_count

parameter structure:

Type Name Count
u2 name_index 1
u2 access_flags 1

Attribure information in Soot

There are 3 additional tags attached to a SootMethod. LocalVariableTableTag and MethodParametersTag can record original attributes information. AggregatedMethodParametersTag is used to generate .class file.

Extend BafASMBackend

BafASMBackend uses ClassWriter(which involves MethodWriter) to generate bytecode. Though Soot ignores MethodParameters, ASM supports the resolving and generating of this attribute. We can call MethodWriter.visitParameter(String name,int access) to put in the parameter information one by one. Finally, ASM will emit this attribute to the bytecode.

In BafASMBackend:

soot.AbstractASMBackend.generateByteCode()
soot.AbstractASMBackend.generateMethods()
soot.AbstractASMBackend.generateAttributes(MethodVisitor mv, SootMethod m)

Implements a class to extends BafASMBackend and override generateAttributes method. Here is an example:

@Override
protected void generateAttributes(MethodVisitor mv, SootMethod m) {
    for (Tag t : m.getTags()) {
        if (t instanceof Attribute) {
            mv.visitAttribute(createASMAttribute((Attribute) t));
        }
        // Emits the bytecode for the MethodParameters attribute
        if (t instanceof AggregatedMethodParametersTag && javaVersion >= Opcodes.V1_8) {
            ((AggregatedMethodParametersTag) t).accept(mv);
        }
    }
}

Or implements like this:

@Override
protected void generateAttributes(MethodVisitor mv, SootMethod m) {
    super.generateAttributes(mv, m);
    // Your implementation
}

Now the new class can be used to generate .class with MethodParameters in the way introduced in Soot Tutorial.

Table of Contents

Clone this wiki locally