JesusFreke/smali

How to create a new method using dexlib2

Opened this issue · 2 comments

Hi

Sorry if I am asking this question in the wrong place. I know we can use Rewriter to modify an existing method. How can we create a new method to add to the dex file? Can anyone give a simple example?

Something like that should work. You create a new method implementation and fill it up with instructions. Look up the API for the concrete parameter descriptions.

            int paramIndex = 1;
            MutableMethodImplementation implementation = new MutableMethodImplementation(2 + paramCount);

            implementation.addInstruction(new BuilderInstruction35c(Opcode.INVOKE_SUPER, 1 + paramCount,
                    paramIndex++, paramIndex++, paramIndex++, paramIndex++, paramIndex++,
                    new ImmutableMethodReference(superClass, methodName, params, returnType)));

            implementation.addInstruction(new BuilderInstruction10x(Opcode.RETURN_VOID));

 

       List<MethodParameter> methodParams = params.stream().map(p ->
                new ImmutableMethodParameter(p, null,
                        // use three random letters as param names
                        RandomStringUtils.random(3, true, false).toLowerCase()))
                .collect(Collectors.toList());

        return new ImmutableMethod(
                classDef.toString(),
                methodName,
                methodParams,
                returnType,
                4,
                null,
                null,
                implementation);

Thanks, we will take a look at that.