Java Code Examples for org.jf.dexlib2.iface.DexFile

The following examples show how to use org.jf.dexlib2.iface.DexFile. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: android-classyshark   Source File: RootBuilder.java    License: Apache License 2.0 6 votes vote down vote up
private void fillFromDex(File file, ClassNode rootNode) {
    try {
        DexFile dxFile = DexlibLoader.loadDexFile(file);

        Set<? extends ClassDef> classSet = dxFile.getClasses();
        for (ClassDef o : classSet) {
            int methodCount = 0;
            for (Method method : o.getMethods()) {
                methodCount++;
            }

            String translatedClassName = o.getType().replaceAll("\\/", "\\.").substring(1, o.getType().length() - 1);
            ClassInfo classInfo = new ClassInfo(translatedClassName, methodCount);
            rootNode.add(classInfo);
        }

    } catch (Exception ex) {
        System.err.println("Error parsing Dexfile: " + file.getName() + ": " + ex.getMessage());
        ex.printStackTrace(System.err);
    }
}
 
Example 2
Source Project: PATDroid   Source File: SmaliClassDetailLoader.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Parse an apk file and extract all classes, methods, fields and optionally instructions
 */
public void loadAll(Scope scope) {
    IdentityHashMap<MethodInfo, MethodImplementation> collector = new IdentityHashMap<MethodInfo, MethodImplementation>();
    for (DexFile dexFile: dexFiles) {
        for (final ClassDef classDef : dexFile.getClasses()) {
            ClassInfo ci = Dalvik.findOrCreateClass(scope, classDef.getType());
            ClassDetail detail = translateClassDef(ci, classDef, collector);
            setDetail(ci, detail);
        }
    }
    if (translateInstructions) {
        for (MethodInfo mi: collector.keySet()) {
            final MethodImplementation impl = collector.get(mi);
            // Decode instructions
            if (impl != null) {
                new MethodImplementationTranslator(scope).translate(mi, impl);
            }
        }
    }
}
 
Example 3
Source Project: DexNameNormalizer   Source File: ClassName.java    License: Apache License 2.0 5 votes vote down vote up
private static DexFile getDexFile(List<ClassDef> classes, int API) {

		Collections.sort(classes);

		return new DexFile() {

			@Nonnull
			@Override
			public Set<? extends ClassDef> getClasses() {
				// TODO Auto-generated method stub
				return new AbstractSet<ClassDef>() {

					@Override
					public Iterator<ClassDef> iterator() {
						// TODO Auto-generated method stub
						return classes.iterator();
					}

					@Override
					public int size() {
						// TODO Auto-generated method stub
						return classes.size();
					}

				};
			}

			@Override
			public Opcodes getOpcodes() {
				// TODO Auto-generated method stub
				return Opcodes.forApi(API);
			}
		};
	}
 
Example 4
Source Project: ZjDroid   Source File: ClassPath.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new ClassPath instance that can load classes from the given dex files
 *
 * @param classPath An iterable of DexFile objects. When loading a class, these dex files will be searched in order
 * @param api API level
 */
public ClassPath(@Nonnull Iterable<DexFile> classPath, int api) {
    // add fallbacks for certain special classes that must be present
    Iterable<DexFile> dexFiles = Iterables.concat(classPath, Lists.newArrayList(getBasicClasses()));

    unknownClass = new UnknownClassProto(this);
    loadedClasses.put(unknownClass.getType(), unknownClass);
    this.api = api;

    loadPrimitiveType("Z");
    loadPrimitiveType("B");
    loadPrimitiveType("S");
    loadPrimitiveType("C");
    loadPrimitiveType("I");
    loadPrimitiveType("J");
    loadPrimitiveType("F");
    loadPrimitiveType("D");
    loadPrimitiveType("L");
    //Logger.log("add the classinfo by classpath");
    for (DexFile dexFile: dexFiles) {
        for (ClassDef classDef: dexFile.getClasses()) {
            ClassDef prev = availableClasses.get(classDef.getType());
            if (prev == null) {
                availableClasses.put(classDef.getType(), classDef);
                //Logger.log("add the calldef "+classDef.getType());
            }
        }
    }
    //Logger.log("end the classinfo by classpath");
}
 
Example 5
Source Project: ZjDroid   Source File: ClassPath.java    License: Apache License 2.0 5 votes vote down vote up
private static DexFile getBasicClasses() {
    // fallbacks for some special classes that we assume are present
    return new ImmutableDexFile(ImmutableSet.of(
            new ReflectionClassDef(Class.class),
            new ReflectionClassDef(Cloneable.class),
            new ReflectionClassDef(Object.class),
            new ReflectionClassDef(Serializable.class),
            new ReflectionClassDef(String.class),
            new ReflectionClassDef(Throwable.class)));
}
 
Example 6
Source Project: ZjDroid   Source File: ClassPath.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
public static ClassPath fromClassPath(Iterable<String> classPathDirs, Iterable<String> classPath, DexFile dexFile,
                                      int api) {
    ArrayList<DexFile> dexFiles = Lists.newArrayList();

    for (String classPathEntry: classPath) {
        dexFiles.add(loadClassPathEntry(classPathDirs, classPathEntry, api));
    }
    dexFiles.add(dexFile);
    return new ClassPath(dexFiles, api);
}
 
Example 7
Source Project: atlas   Source File: SmaliDiffUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static Set<String> buildCode(File dexFile, DexDiffInfo info) throws IOException,
        RecognitionException {
    Set<String>classes = new HashSet<>();
    Set<DexBackedClassDef> classDefs = new HashSet<DexBackedClassDef>();
    classDefs.addAll(info.getModifiedClasses());
    classDefs.addAll(info.getAddedClasses());
    DexFileFactory.writeDexFile(dexFile.getAbsolutePath(), new DexFile() {
        @Nonnull
        @Override
        public Set<? extends ClassDef> getClasses() {
            return new AbstractSet<DexBackedClassDef>() {
                @Override
                public Iterator<DexBackedClassDef> iterator() {
                    return classDefs.iterator();
                }

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

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

    for (ClassDef classDef:classDefs){
        classes.add(classDef.getType());
    }
    return classes;
}
 
Example 8
Source Project: zjdroid   Source File: ClassPath.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new ClassPath instance that can load classes from the given dex files
 *
 * @param classPath An iterable of DexFile objects. When loading a class, these dex files will be searched in order
 * @param api API level
 */
public ClassPath(@Nonnull Iterable<DexFile> classPath, int api) {
    // add fallbacks for certain special classes that must be present
    Iterable<DexFile> dexFiles = Iterables.concat(classPath, Lists.newArrayList(getBasicClasses()));

    unknownClass = new UnknownClassProto(this);
    loadedClasses.put(unknownClass.getType(), unknownClass);
    this.api = api;

    loadPrimitiveType("Z");
    loadPrimitiveType("B");
    loadPrimitiveType("S");
    loadPrimitiveType("C");
    loadPrimitiveType("I");
    loadPrimitiveType("J");
    loadPrimitiveType("F");
    loadPrimitiveType("D");
    loadPrimitiveType("L");
    //Logger.log("add the classinfo by classpath");
    for (DexFile dexFile: dexFiles) {
        for (ClassDef classDef: dexFile.getClasses()) {
            ClassDef prev = availableClasses.get(classDef.getType());
            if (prev == null) {
                availableClasses.put(classDef.getType(), classDef);
                //Logger.log("add the calldef "+classDef.getType());
            }
        }
    }
    //Logger.log("end the classinfo by classpath");
}
 
Example 9
Source Project: zjdroid   Source File: ClassPath.java    License: Apache License 2.0 5 votes vote down vote up
private static DexFile getBasicClasses() {
    // fallbacks for some special classes that we assume are present
    return new ImmutableDexFile(ImmutableSet.of(
            new ReflectionClassDef(Class.class),
            new ReflectionClassDef(Cloneable.class),
            new ReflectionClassDef(Object.class),
            new ReflectionClassDef(Serializable.class),
            new ReflectionClassDef(String.class),
            new ReflectionClassDef(Throwable.class)));
}
 
Example 10
Source Project: zjdroid   Source File: ClassPath.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
public static ClassPath fromClassPath(Iterable<String> classPathDirs, Iterable<String> classPath, DexFile dexFile,
                                      int api) {
    ArrayList<DexFile> dexFiles = Lists.newArrayList();

    for (String classPathEntry: classPath) {
        dexFiles.add(loadClassPathEntry(classPathDirs, classPathEntry, api));
    }
    dexFiles.add(dexFile);
    return new ClassPath(dexFiles, api);
}
 
Example 11
@Override
public void deOdex(DexFile parentFile) {
	if (!(parentFile instanceof DexBackedOdexFile))
		throw new RuntimeException("ODEX instruction in non-ODEX file");
	DexBackedOdexFile odexFile = (DexBackedOdexFile) parentFile;
	InlineMethodResolver inlineMethodResolver = InlineMethodResolver.createInlineMethodResolver(
			odexFile.getOdexVersion());
	targetMethod = inlineMethodResolver.resolveExecuteInline(
			new AnalyzedInstruction(instruction, -1, -1));
}
 
Example 12
Source Project: HeyGirl   Source File: ClassPath.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new ClassPath instance that can load classes from the given dex files
 *
 * @param classPath An iterable of DexFile objects. When loading a class, these dex files will be searched in order
 * @param api API level
 */
public ClassPath(@Nonnull Iterable<DexFile> classPath, int api) {
    // add fallbacks for certain special classes that must be present
    Iterable<DexFile> dexFiles = Iterables.concat(classPath, Lists.newArrayList(getBasicClasses()));

    unknownClass = new UnknownClassProto(this);
    loadedClasses.put(unknownClass.getType(), unknownClass);
    this.api = api;

    loadPrimitiveType("Z");
    loadPrimitiveType("B");
    loadPrimitiveType("S");
    loadPrimitiveType("C");
    loadPrimitiveType("I");
    loadPrimitiveType("J");
    loadPrimitiveType("F");
    loadPrimitiveType("D");
    loadPrimitiveType("L");
    //Logger.log("add the classinfo by classpath");
    for (DexFile dexFile: dexFiles) {
        for (ClassDef classDef: dexFile.getClasses()) {
            ClassDef prev = availableClasses.get(classDef.getType());
            if (prev == null) {
                availableClasses.put(classDef.getType(), classDef);
                //Logger.log("add the calldef "+classDef.getType());
            }
        }
    }
    //Logger.log("end the classinfo by classpath");
}
 
Example 13
Source Project: HeyGirl   Source File: ClassPath.java    License: Apache License 2.0 5 votes vote down vote up
private static DexFile getBasicClasses() {
    // fallbacks for some special classes that we assume are present
    return new ImmutableDexFile(ImmutableSet.of(
            new ReflectionClassDef(Class.class),
            new ReflectionClassDef(Cloneable.class),
            new ReflectionClassDef(Object.class),
            new ReflectionClassDef(Serializable.class),
            new ReflectionClassDef(String.class),
            new ReflectionClassDef(Throwable.class)));
}
 
Example 14
Source Project: HeyGirl   Source File: ClassPath.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
public static ClassPath fromClassPath(Iterable<String> classPathDirs, Iterable<String> classPath, DexFile dexFile,
                                      int api) {
    ArrayList<DexFile> dexFiles = Lists.newArrayList();

    for (String classPathEntry: classPath) {
        dexFiles.add(loadClassPathEntry(classPathDirs, classPathEntry, api));
    }
    dexFiles.add(dexFile);
    return new ClassPath(dexFiles, api);
}
 
Example 15
private Set<String> getDexClasses()
{	
		Set<String> dexClasses = new HashSet<String>();
		
		try {
			DexFile dexFile = DexFileFactory.loadDexFile(new File(apk.getAbsolutePath()), targetSdkVersion());
			for (ClassDef classDef: dexFile.getClasses()) 
			{
				String cls = classDef.getType();
				if (cls.contains("$"))
				{
					//do not consider sub-classes
					continue;
				}
				
				cls = cls.replace("/", ".").substring(1, cls.length()-1);
				
				dexClasses.add(cls);
			}
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}
		
		return dexClasses;
 	}
 
Example 16
Source Project: android-classyshark   Source File: DexlibAdapter.java    License: Apache License 2.0 5 votes vote down vote up
public static ClassDef getClassDefByName(String className, DexFile dexFile)
        throws Exception {
    ClassDef result = null;
    String dexName;

    for (ClassDef currentClassDef : dexFile.getClasses()) {
        dexName = currentClassDef.getType();
        if (isMatchFromDex(className, dexName)) {
            result = currentClassDef;
            break;
        }
    }

    return result;
}
 
Example 17
Source Project: android-classyshark   Source File: MetaObjectFactory.java    License: Apache License 2.0 5 votes vote down vote up
private static MetaObject getMetaObjectFromDex(String className, File archiveFile) {
    MetaObject result;
    try {
        DexFile dexFile = DexlibLoader.loadDexFile(archiveFile);
        ClassDef classDef = DexlibAdapter.getClassDefByName(className, dexFile);
        result = new MetaObjectDex(classDef);
    } catch (Exception e) {
        result = new MetaObjectClass(Exception.class);
    }
    return result;
}
 
Example 18
Source Project: android-classyshark   Source File: StressTest.java    License: Apache License 2.0 5 votes vote down vote up
public static void runAllClassesInDex(String jarCanonicalPath) throws Exception {
    DexFile dexFile = DexlibLoader.loadDexFile(new File(jarCanonicalPath));
    Set<? extends ClassDef> allClassesInDex = dexFile.getClasses();

    for (ClassDef currentClass : allClassesInDex) {
        String normType = DexlibAdapter.getClassStringFromDex(currentClass.getType());
        Translator sourceGenerator = TranslatorFactory.createTranslator(
                normType, new File(jarCanonicalPath));
        sourceGenerator.apply();
        System.out.println(sourceGenerator.toString());
    }
}
 
Example 19
Source Project: android-classyshark   Source File: DexReader.java    License: Apache License 2.0 5 votes vote down vote up
public static List<String> readClassNamesFromDex(File binaryArchiveFile) throws Exception {
    DexFile dexFile = DexlibLoader.loadDexFile(binaryArchiveFile);
    List<String> result = new ArrayList<>();

    for (ClassDef classDef : dexFile.getClasses()) {
        result.add(classDef.getType().replaceAll("/", ".").
                substring(1, classDef.getType().length() - 1));
    }

    Collections.sort(result);
    return result;
}
 
Example 20
Source Project: PATDroid   Source File: SmaliClassDetailLoader.java    License: Apache License 2.0 5 votes vote down vote up
public static SmaliClassDetailLoader fromFramework(File frameworkClassesFolder, int apiLevel) {
    File f = new File(frameworkClassesFolder, "android-" + apiLevel + ".dex");
    if (!f.exists())
        throw new RuntimeException("framework file not available");
    DexFile dex;
    try {
        dex = DexFileFactory.loadDexFile(f, apiLevel);
    } catch (IOException e) {
        throw new RuntimeException("failed to load framework classes");
    }
    return new SmaliClassDetailLoader(new DexFile[] {dex}, false, true);
}
 
Example 21
Source Project: ZjDroid   Source File: ClassPath.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new ClassPath instance that can load classes from the given dex files
 *
 * @param classPath An iterable of DexFile objects. When loading a class, these dex files will be searched in order
 * @param api API level
 */
public ClassPath(@Nonnull Iterable<DexFile> classPath, int api) {
    // add fallbacks for certain special classes that must be present
    Iterable<DexFile> dexFiles = Iterables.concat(classPath, Lists.newArrayList(getBasicClasses()));

    unknownClass = new UnknownClassProto(this);
    loadedClasses.put(unknownClass.getType(), unknownClass);
    this.api = api;

    loadPrimitiveType("Z");
    loadPrimitiveType("B");
    loadPrimitiveType("S");
    loadPrimitiveType("C");
    loadPrimitiveType("I");
    loadPrimitiveType("J");
    loadPrimitiveType("F");
    loadPrimitiveType("D");
    loadPrimitiveType("L");
    //Logger.log("add the classinfo by classpath");
    for (DexFile dexFile: dexFiles) {
        for (ClassDef classDef: dexFile.getClasses()) {
            ClassDef prev = availableClasses.get(classDef.getType());
            if (prev == null) {
                availableClasses.put(classDef.getType(), classDef);
                //Logger.log("add the calldef "+classDef.getType());
            }
        }
    }
    //Logger.log("end the classinfo by classpath");
}
 
Example 22
Source Project: ZjDroid   Source File: ClassPath.java    License: Apache License 2.0 5 votes vote down vote up
private static DexFile getBasicClasses() {
    // fallbacks for some special classes that we assume are present
    return new ImmutableDexFile(ImmutableSet.of(
            new ReflectionClassDef(Class.class),
            new ReflectionClassDef(Cloneable.class),
            new ReflectionClassDef(Object.class),
            new ReflectionClassDef(Serializable.class),
            new ReflectionClassDef(String.class),
            new ReflectionClassDef(Throwable.class)));
}
 
Example 23
Source Project: ZjDroid   Source File: ClassPath.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
public static ClassPath fromClassPath(Iterable<String> classPathDirs, Iterable<String> classPath, DexFile dexFile,
                                      int api) {
    ArrayList<DexFile> dexFiles = Lists.newArrayList();

    for (String classPathEntry: classPath) {
        dexFiles.add(loadClassPathEntry(classPathDirs, classPathEntry, api));
    }
    dexFiles.add(dexFile);
    return new ClassPath(dexFiles, api);
}
 
Example 24
Source Project: ZjDroid   Source File: ImmutableDexFile.java    License: Apache License 2.0 4 votes vote down vote up
public static ImmutableDexFile of(DexFile dexFile) {
    if (dexFile instanceof ImmutableDexFile) {
        return (ImmutableDexFile)dexFile;
    }
    return new ImmutableDexFile(dexFile.getClasses());
}
 
Example 25
Source Project: ZjDroid   Source File: DexFileFactory.java    License: Apache License 2.0 4 votes vote down vote up
public static void writeDexFile(String path, DexFile dexFile) throws IOException {
    DexPool.writeTo(path, dexFile);
}
 
Example 26
Source Project: atlas   Source File: DexReader.java    License: Apache License 2.0 4 votes vote down vote up
public DexReader(File file) throws IOException {
    if (file.exists()){
        org.jf.dexlib2.iface.DexFile dexFile = DexFileFactory.loadDexFile(file,Opcodes.getDefault());
        this.classDefs = dexFile.getClasses();
    }
}
 
Example 27
Source Project: atlas   Source File: DexReader.java    License: Apache License 2.0 4 votes vote down vote up
public DexReader(List<File>files) throws IOException {
    for (File file:files){
        DexFile dexFile =DexFileFactory.loadDexFile(file, Opcodes.getDefault());
        classDefs.addAll(dexFile.getClasses());
    }
}
 
Example 28
Source Project: atlas   Source File: DexObfuscatedTool.java    License: Apache License 2.0 4 votes vote down vote up
public void obfuscateDex(File inputFile, File outPutFile) throws IOException {
    if (mappingFile == null || !mappingFile.exists()) {
        throw new IOException("mapping file is not exits!");

    }
    if (inputFile == null || !inputFile.exists()) {
        throw new IOException("input dexFile is not exits!");
    }
    MappingReader mappingReader = null;
    MappingProcessor mappingProcessor = null;
    mappingReader = new MappingReader(mappingFile);
    mappingProcessor = new MappingProcessorImpl(map);
    mappingReader.pump(mappingProcessor);
    mappingProcessor.updateMethod();
    mappingProcessor.updateFieldType();
    InsTructionsReIClassDef insTructionsReDef = new InsTructionsReIClassDef(new MappingClassProcessor(mappingProcessor));
    DexFile dFile = DexFileFactory.loadDexFile(inputFile.getAbsolutePath(), Opcodes.getDefault());
    Set<ClassDef> classes = new HashSet<ClassDef>();
    classes.addAll(dFile.getClasses());
    final Set<ClassDef> obfuscateClasses = new HashSet<ClassDef>();
    for (ClassDef classDef : classes) {
        obfuscateClasses.add(insTructionsReDef.reClassDef(classDef));
    }
    DexFileFactory.writeDexFile(outPutFile.getAbsolutePath(), new DexFile() {
        @Nonnull
        @Override
        public Set<? extends ClassDef> getClasses() {
            return new AbstractSet<ClassDef>() {
                @Nonnull
                @Override
                public Iterator<ClassDef> iterator() {
                    return obfuscateClasses.iterator();
                }

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

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


}
 
Example 29
Source Project: atlas   Source File: PatchMethodTool.java    License: Apache License 2.0 4 votes vote down vote up
public static void modifyMethod(String srcDexFile, String outDexFile, boolean isAndFix) throws IOException {

        DexFile dexFile = DexFileFactory.loadDexFile(srcDexFile, Opcodes.getDefault());

        final Set<ClassDef> classes = Sets.newConcurrentHashSet();

        for (ClassDef classDef : dexFile.getClasses()) {
            Set<Method> methods = Sets.newConcurrentHashSet();
            boolean modifiedMethod = false;
            for (Method method : classDef.getMethods()) {
                    MethodImplementation implementation = method.getImplementation();
                    if (implementation != null&&(methodNeedsModification(classDef, method, isAndFix))) {
                        modifiedMethod = true;
                        methods.add(new ImmutableMethod(
                                method.getDefiningClass(),
                                method.getName(),
                                method.getParameters(),
                                method.getReturnType(),
                                method.getAccessFlags(),
                                method.getAnnotations(),
                                isAndFix ?
                                        modifyMethodAndFix(implementation, method) : modifyMethodTpatch(implementation, method)));
                    } else {
                        methods.add(method);
                    }
                }
            if (!modifiedMethod) {
                classes.add(classDef);
            } else {
                classes.add(new ImmutableClassDef(
                        classDef.getType(),
                        classDef.getAccessFlags(),
                        classDef.getSuperclass(),
                        classDef.getInterfaces(),
                        classDef.getSourceFile(),
                        classDef.getAnnotations(),
                        classDef.getFields(),
                        methods));
            }

        }

        DexFileFactory.writeDexFile(outDexFile, 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.getDefault();
            }
        });
    }
 
Example 30
Source Project: zjdroid   Source File: ImmutableDexFile.java    License: Apache License 2.0 4 votes vote down vote up
public static ImmutableDexFile of(DexFile dexFile) {
    if (dexFile instanceof ImmutableDexFile) {
        return (ImmutableDexFile)dexFile;
    }
    return new ImmutableDexFile(dexFile.getClasses());
}