org.jf.dexlib2.DexFileFactory Java Examples

The following examples show how to use org.jf.dexlib2.DexFileFactory. 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 File: ApkSmaliDecoder.java    From apk-dependency-graph with Apache License 2.0 6 votes vote down vote up
private DexBackedDexFile loadDexFile(
        File apkFile, String dexFilePath, int apiVersion)
        throws IOException {
    DexBackedDexFile dexFile = DexFileFactory.loadDexEntry(
        apkFile, dexFilePath, true, Opcodes.forApi(apiVersion));

    if (dexFile == null || dexFile.isOdexFile()) {
        throw new IOException(WARNING_DISASSEMBLING_ODEX_FILE);
    }

    return dexFile;
}
 
Example #2
Source File: DexDiffer.java    From atlas with Apache License 2.0 6 votes vote down vote up
/**
 * scan base Dex,get base Dex info
 */
private void scanBaseDexFile() throws IOException {
    for (File baseDexFile : baseDexFiles) {
        String s = baseDexFile.getName().substring(7);
        String dexNum = s.startsWith(".")? "0":s.substring(0,s.indexOf("."));
        DexBackedDexFile baseBackedDexFile = DexFileFactory.loadDexFile(baseDexFile, Opcodes.getDefault());
        final Set<? extends DexBackedClassDef> baseClassDefs = baseBackedDexFile.getClasses();
        baseClassDefs.forEach(new Consumer<DexBackedClassDef>() {
            @Override
            public void accept(DexBackedClassDef dexBackedClassDef) {
                if (dexBackedClassDef.getType().equals("Lcom/ali/mobisecenhance/ReflectMap;")){
                    noPatchDexNum = dexNum;
                }
            }
        });
        dexDiffInfo.setOldClasses(dexNum,baseClassDefs);
        for (DexBackedClassDef baseClassDef : baseClassDefs) {
            String className = getDalvikClassName(baseClassDef.getType());
            baseClassDefMap.put(className, baseClassDef);
        }
    }
}
 
Example #3
Source File: SmaliDiffUtils.java    From atlas with Apache License 2.0 6 votes vote down vote up
public static Set<DexBackedClassDef> scanClasses(File smaliDir, List<File> newFiles) throws PatchException {

        Set<DexBackedClassDef> classes = Sets.newHashSet();
        try {
            for (File newFile : newFiles) {
                DexBackedDexFile newDexFile = DexFileFactory.loadDexFile(newFile, Opcodes.getDefault());
                Set<? extends DexBackedClassDef> dexClasses = newDexFile.getClasses();
                classes.addAll(dexClasses);
            }

            final ClassFileNameHandler outFileNameHandler = new ClassFileNameHandler(smaliDir, ".smali");
            final ClassFileNameHandler inFileNameHandler = new ClassFileNameHandler(smaliDir, ".smali");

            for (DexBackedClassDef classDef : classes) {
                String className = classDef.getType();
                ApkPatch.currentClassType = null;
                AfBakSmali.disassembleClass(classDef, outFileNameHandler, getBuildOption(classes, 19), true, true);
                File smaliFile = inFileNameHandler.getUniqueFilenameForClass(className);
            }
        } catch (Exception e) {
            throw new PatchException(e);
        }
        return classes;
    }
 
Example #4
Source File: SmaliUtils.java    From Box with Apache License 2.0 5 votes vote down vote up
@NotNull
public static String getSmaliCode(DexNode dex, int clsDefOffset) {
	try {
		Path path = dex.getDexFile().getPath();
		DexBackedDexFile dexFile = DexFileFactory.loadDexFile(path.toFile(), null);
		DexBackedClassDef dexBackedClassDef = new DexBackedClassDef(dexFile, clsDefOffset);
		return getSmaliCode(dexBackedClassDef);
	} catch (Exception e) {
		LOG.error("Error generating smali", e);
		return "Error generating smali code: " + e.getMessage()
				+ '\n' + Utils.getStackTrace(e);
	}
}
 
Example #5
Source File: SmaliClassDetailLoader.java    From PATDroid with 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 #6
Source File: ProcessManifest.java    From DroidRA with GNU Lesser General Public License v2.1 5 votes vote down vote up
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 #7
Source File: DexClassProvider.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Return names of classes in dex/apk file.
 *
 * @param file
 *            file to dex/apk file. Can be the path of a zip file.
 *
 * @return set of class names
 */
public static Set<String> classesOfDex(File file) throws IOException {
	Set<String> classes = new HashSet<String>();
	// TODO (SA): Go for API 1 because DexlibWrapper does so, but needs more attention
	DexBackedDexFile d = DexFileFactory.loadDexFile(file, 1, false);
	for (ClassDef c : d.getClasses()) {
		String name = Util.dottedClassName(c.getType());
		classes.add(name);
	}
	return classes;
}
 
Example #8
Source File: DexlibWrapper.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
public void initialize() {

        try {
            int api = 1; // TODO:
            this.dexFile = DexFileFactory.loadDexFile(inputDexFile, api, false);
        } catch (Exception e) {
            throw new RuntimeException(e.toString());
        }

        if (dexFile instanceof DexBackedDexFile) {
            DexBackedDexFile dbdf = (DexBackedDexFile)dexFile;
            for (int i = 0; i < dbdf.getTypeCount(); i++) {
            	String t = dbdf.getType(i);

            	Type st = DexType.toSoot(t);
            	if (st instanceof ArrayType) {
            		st = ((ArrayType) st).baseType;
            	}
            	Debug.printDbg("Type: ", t ," soot type:", st);
            	String sootTypeName = st.toString();
            	if (!Scene.v().containsClass(sootTypeName)) {
            		if (st instanceof PrimType || st instanceof VoidType || systemAnnotationNames.contains(sootTypeName)) {
            			// dex files contain references to the Type IDs of void / primitive types - we obviously do not want them to be resolved
            			/*
            			 * dex files contain references to the Type IDs of the system annotations.
            			 * They are only visible to the Dalvik VM (for reflection, see vm/reflect/Annotations.cpp), and not to
            			 * the user - so we do not want them to be resolved.
            			 */
            			continue;
            		}
            		SootResolver.v().makeClassRef(sootTypeName);
            	}
            	SootResolver.v().resolveClass(sootTypeName, SootClass.SIGNATURES);
            }
        } else {
            System.out.println("Warning: DexFile not instance of DexBackedDexFile! Not resolving types!");
            System.out.println("type: "+ dexFile.getClass());
        }
    }
 
Example #9
Source File: PatchUtils.java    From atlas with Apache License 2.0 5 votes vote down vote up
private static Map<String, ClassDef> getBundleClassDef(File file) throws IOException {
    HashMap<String, ClassDef> classDefMap = new HashMap<String, ClassDef>();
    File[] dexFiles = getDexFiles(file);
    HashSet<ClassDef> classDefs = new HashSet<ClassDef>();
    for (File dexFile : dexFiles) {
        classDefs.addAll(DexFileFactory.loadDexFile(dexFile, Opcodes.getDefault()).getClasses());
    }
    for (ClassDef classDef : classDefs) {
        classDefMap.put(classDef.getType(), classDef);
    }

    return classDefMap;
}
 
Example #10
Source File: PatchFieldTool.java    From atlas with Apache License 2.0 5 votes vote down vote up
public static void addField(String inFile, String outFile, DexBackedClassDef dexBackedClassDef, ImmutableField immutableField) throws IOException {

        DexFile dexFile = readDexFile(inFile);
        for (ClassDef classDef : dexFile.getClasses()) {
            if (dexBackedClassDef != null && dexBackedClassDef.getType().equals(classDef.getType())) {
                dexFile = addField(dexFile, classDef.getType(), immutableField);
            } else if (dexBackedClassDef == null) {
                dexFile = addField(dexFile, classDef.getType(), immutableField);

            }
        }
        reDexFile(dexFile);

        DexFileFactory.writeDexFile(outFile, 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 #11
Source File: SmaliDiffUtils.java    From atlas with 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 #12
Source File: D8DexMergerTest.java    From bundletool with Apache License 2.0 5 votes vote down vote up
private static ImmutableSet<String> listClassesInDexFiles(Collection<Path> dexPaths)
    throws Exception {
  ImmutableSet.Builder<String> classes = ImmutableSet.builder();
  for (Path dexPath : dexPaths) {
    DexBackedDexFile dexFile = DexFileFactory.loadDexFile(dexPath.toFile(), Opcodes.getDefault());
    for (DexBackedClassDef clazz : dexFile.getClasses()) {
      classes.add(clazz.getType());
    }
  }
  return classes.build();
}
 
Example #13
Source File: SmaliDecoder.java    From ratel with Apache License 2.0 5 votes vote down vote up
private void decode() throws AndrolibException {
    try {
        final BaksmaliOptions options = new BaksmaliOptions();

        // options
        options.deodex = false;
        options.implicitReferences = false;
        options.parameterRegisters = true;
        options.localsDirective = true;
        options.sequentialLabels = true;
        options.debugInfo = mBakDeb;
        options.codeOffsets = false;
        options.accessorComments = false;
        options.registerInfo = 0;
        options.inlineResolver = null;

        // set jobs automatically
        int jobs = Runtime.getRuntime().availableProcessors();
        if (jobs > 6) {
            jobs = 6;
        }

        // create the dex
        DexBackedDexFile dexFile = DexFileFactory.loadDexEntry(mApkFile, mDexFile, true, Opcodes.forApi(mApi));

        if (dexFile.isOdexFile()) {
            throw new AndrolibException("Warning: You are disassembling an odex file without deodexing it.");
        }

        if (dexFile instanceof DexBackedOdexFile) {
            options.inlineResolver =
                    InlineMethodResolver.createInlineMethodResolver(((DexBackedOdexFile)dexFile).getOdexVersion());
        }

        Baksmali.disassembleDexFile(dexFile, mOutDir, jobs, options);
    } catch (IOException ex) {
        throw new AndrolibException(ex);
    }
}
 
Example #14
Source File: SmaliUtils.java    From Box with Apache License 2.0 5 votes vote down vote up
@NotNull
public static String getSmaliCode(DexNode dex, int clsDefOffset) {
	try {
		Path path = dex.getDexFile().getPath();
		DexBackedDexFile dexFile = DexFileFactory.loadDexFile(path.toFile(), null);
		DexBackedClassDef dexBackedClassDef = new DexBackedClassDef(dexFile, clsDefOffset);
		return getSmaliCode(dexBackedClassDef);
	} catch (Exception e) {
		LOG.error("Error generating smali", e);
		return "Error generating smali code: " + e.getMessage()
				+ '\n' + Utils.getStackTrace(e);
	}
}
 
Example #15
Source File: PatchMethodTool.java    From atlas with 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 #16
Source File: DexObfuscatedTool.java    From atlas with 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 #17
Source File: PatchFieldTool.java    From atlas with Apache License 2.0 4 votes vote down vote up
private static DexFile readDexFile(String fileName) throws IOException {
    File srcFile = new File(fileName);
    return DexFileFactory.loadDexFile(srcFile, Opcodes.getDefault());
}
 
Example #18
Source File: DexReader.java    From atlas with 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 #19
Source File: ApkToolPlus.java    From ApkToolPlus with Apache License 2.0 4 votes vote down vote up
/**
 * .dex转换为smali
 *
 * @param dexFile       dex/apk文件
 * @param outDir        smali文件输出目录
 * @return  是否转换成功
 */
public static boolean dex2smali(File dexFile, File outDir){

    if (dexFile == null || !dexFile.exists()){
        LogUtils.w( "dex2smali dexFile is null or not exists : " + dexFile.getPath());
        return false;
    }

    // dex文件的处理
    BaksmaliOptions options = new BaksmaliOptions();

    // options
    options.deodex = false;
    options.implicitReferences = false;
    options.parameterRegisters = true;
    options.localsDirective = true;
    options.sequentialLabels = true;
    options.debugInfo = true;
    options.codeOffsets = false;
    options.accessorComments = false;
    options.registerInfo = 0;
    options.inlineResolver = null;

    // set jobs automatically
    int jobs = Runtime.getRuntime().availableProcessors();
    if (jobs > 6) {
        jobs = 6;
    }

    try {
        //brut/androlib/ApkDecoder.mApi default value is 15
        // create the dex
        DexBackedDexFile dexBackedDexFile = DexFileFactory.loadDexFile(dexFile, Opcodes.forApi(15));

        if (dexBackedDexFile.isOdexFile()) {
            LogUtils.w("Warning: You are disassembling an odex file without deodexing it.");
        }

        if (dexBackedDexFile instanceof DexBackedOdexFile) {
            options.inlineResolver =
                    InlineMethodResolver.createInlineMethodResolver(((DexBackedOdexFile)dexBackedDexFile).getOdexVersion());
        }

        Baksmali.disassembleDexFile(dexBackedDexFile, outDir, jobs, options);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return false;
}
 
Example #20
Source File: DexReader.java    From atlas with 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 #21
Source File: DexlibLoader.java    From android-classyshark with Apache License 2.0 4 votes vote down vote up
public static DexFile loadDexFile(File binaryArchiveFile) throws Exception {
    DexBackedDexFile newDexFile = DexFileFactory.loadDexFile(binaryArchiveFile,
            Opcodes.forApi(19));

    return newDexFile;
}