JesusFreke/smali

how to copy class to new dex using dexlib2

Opened this issue · 4 comments

			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

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);

@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.

@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.

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