JesusFreke / smali

smali/baksmali
6.26k stars 1.07k forks source link

how to copy class to new dex using dexlib2 #877

Open yujack008 opened 10 months ago

yujack008 commented 10 months ago
            Set<? extends DexBackedClassDef> defs = dexBackedDexFile.getClasses();

            for (DexBackedClassDef def : defs) {
                dexBuilder.internClassDef(def.getType(), def.getAccessFlags(),
                        def.getSuperclass(), def.getInterfaces(), def.getSourceFile(),
                        def.getAnnotations(), def.getFields(),def.getMethods());
            }

def.getFields() and def.getMethods() ERROR

auermich93 commented 10 months ago

I use the following code for plain dexlib2 to write the classes to a new dex file:

    public static void writeToDexFile(String filePath, List<ClassDef> classes, int opCode) throws IOException {

        DexFileFactory.writeDexFile(filePath, new DexFile() {
            @Nonnull
            @Override
            public Set<? extends ClassDef> getClasses() {
                return new AbstractSet<ClassDef>() {
                    @Nonnull
                    @Override
                    public Iterator<ClassDef> iterator() {
                        return classes.iterator();
                    }

                    @Override
                    public int size() {
                        return classes.size();
                    }
                };
            }

            @Nonnull
            @Override
            public Opcodes getOpcodes() {
                return Opcodes.forApi(opCode);
            }
        });
    }

And the following code to create/modify an existing class:

        List<Method> instrumentedMethods = Lists.newArrayList(classDef.getMethods()).parallelStream()
                .map(method -> instrumentMethod(dexFile, classDef, method))
                .collect(Collectors.toList());

        return new ImmutableClassDef(
                classDef.getType(),
                classDef.getAccessFlags(),
                classDef.getSuperclass(),
                classDef.getInterfaces(),
                classDef.getSourceFile(),
                classDef.getAnnotations(),
                classDef.getFields(),
                instrumentedMethods);
yujack008 commented 9 months ago

@auermich93 thinks. then, how to get a class all import class. i want to write a class and all depends import class to a dex file.

auermich93 commented 9 months ago

@yujack008 There are no explicit imports like in a .java file. You have to iterate over all fields and instructions and collect this information on your own.

xudabeauty commented 8 months ago

i want to move the useless classes to a new dex ,how to?