Java Code Examples for dalvik.system.DexClassLoader#loadClass()

The following examples show how to use dalvik.system.DexClassLoader#loadClass() . 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: MainActivity.java    From MycroftCore-Android with Apache License 2.0 7 votes vote down vote up
public static void loadExtension(Context context, String apkFile, String packageName) {
    Log.i(TAG, "Trying to load new class from apk.");
    final File dexInternalStoragePath = new File(context.getDir("extensions", Context.MODE_PRIVATE),
            apkFile + ".apk");
    final File optimizedDexOutputPath = context.getDir("outdex", Context.MODE_PRIVATE);
    Log.i(TAG, "dexInternalStoragePath: " + dexInternalStoragePath.getAbsolutePath());
    if (dexInternalStoragePath.exists()) {
        Log.i(TAG, "New apk found! " + apkFile);
        DexClassLoader dexLoader = new DexClassLoader(dexInternalStoragePath.getAbsolutePath(),
                optimizedDexOutputPath.getAbsolutePath(),
                null,
                ClassLoader.getSystemClassLoader().getParent());
        try {
            Class klazz = dexLoader.loadClass("ai.mycroft.extension." + packageName);
            Constructor constructor = klazz.getConstructor(String.class);
            Method method = klazz.getDeclaredMethod("getInfo");
            Object newObject = constructor.newInstance("New object info");
            Log.i(TAG, "New object has class: " + newObject.getClass().getName());
            Log.i(TAG, "Invoking getInfo on new object: " + method.invoke(newObject));
        } catch (Exception e) {
            Log.e(TAG, "Exception:", e);
        }
    } else {
        Log.i(TAG, "Sorry new apk doesn't exist.");
    }
}
 
Example 2
Source File: MainActivity.java    From fooXposed with Apache License 2.0 6 votes vote down vote up
public void decryptText(View view) {
    String name = "Foox_4th_01.apk";
    File file = new File(getFilesDir(), name);
    if (copyAssetFile(name, file)) {
        String dexPath = file.getPath();
        String optimizedDirectory = file.getParent();
        ClassLoader parent = getClass().getClassLoader();
        DexClassLoader classLoader = new DexClassLoader(dexPath, optimizedDirectory, null, parent);
        try {
            Class<?> clazz = classLoader.loadClass("foo.ree.demos.x4th01.Base64Util");
            Method method = clazz.getDeclaredMethod("decrypt", String.class);
            String text = (String) method.invoke(clazz, textView.getText().toString());

            if (!TextUtils.isEmpty(text)) {
                textView.setText(text);
                textView.refreshDrawableState();
                view.setClickable(false);
                Toast.makeText(this, "解密成功", Toast.LENGTH_SHORT).show();
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    Toast.makeText(this, "解密失败", Toast.LENGTH_SHORT).show();
}
 
Example 3
Source File: XulPluginManager.java    From starcor.xul with GNU Lesser General Public License v3.0 6 votes vote down vote up
public boolean init(File path) {
	_path = path;

	try {
		File parentFile = path.getParentFile();
		_classLoader = new DexClassLoader(_path.getAbsolutePath(), parentFile.getAbsolutePath(), null, getClass().getClassLoader());

		_pluginPackage = new ZipFile(_path);
		ZipEntry entry = _pluginPackage.getEntry("plugin.txt");
		BufferedReader reader = new BufferedReader(new InputStreamReader(_pluginPackage.getInputStream(entry)));
		String pluginClassName = reader.readLine();
		reader.close();

		Class<?> pluginClass = _classLoader.loadClass(pluginClassName);
		_plugin = (XulPlugin) pluginClass.newInstance();
		return true;
	} catch (Throwable e) {
		e.printStackTrace();
	}
	return false;
}
 
Example 4
Source File: HotFix.java    From Android-Tech with Apache License 2.0 6 votes vote down vote up
@TargetApi(14)
private static void injectBelowApiLevel14(Context context, String str, String str2)
        throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
    PathClassLoader obj = (PathClassLoader) context.getClassLoader();
    DexClassLoader dexClassLoader =
            new DexClassLoader(str, context.getDir("dex", 0).getAbsolutePath(), str, context.getClassLoader());
    dexClassLoader.loadClass(str2);
    setField(obj, PathClassLoader.class, "mPaths",
            appendArray(getField(obj, PathClassLoader.class, "mPaths"), getField(dexClassLoader, DexClassLoader.class,
                            "mRawDexPath")
            ));
    setField(obj, PathClassLoader.class, "mFiles",
            combineArray(getField(obj, PathClassLoader.class, "mFiles"), getField(dexClassLoader, DexClassLoader.class,
                            "mFiles")
            ));
    setField(obj, PathClassLoader.class, "mZips",
            combineArray(getField(obj, PathClassLoader.class, "mZips"), getField(dexClassLoader, DexClassLoader.class,
                    "mZips")));
    setField(obj, PathClassLoader.class, "mDexs",
            combineArray(getField(obj, PathClassLoader.class, "mDexs"), getField(dexClassLoader, DexClassLoader.class,
                    "mDexs")));
    obj.loadClass(str2);
}
 
Example 5
Source File: HotFix.java    From SDKHoxFix with Apache License 2.0 6 votes vote down vote up
@TargetApi(14)
private static void injectBelowApiLevel14(Context context, String str, String str2)
    throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
    PathClassLoader obj = (PathClassLoader) context.getClassLoader();
    DexClassLoader dexClassLoader =
        new DexClassLoader(str, context.getDir("dex", 0).getAbsolutePath(), str, context.getClassLoader());
    dexClassLoader.loadClass(str2);
    setField(obj, PathClassLoader.class, "mPaths",
        appendArray(getField(obj, PathClassLoader.class, "mPaths"), getField(dexClassLoader, DexClassLoader.class,
                "mRawDexPath")
        ));
    setField(obj, PathClassLoader.class, "mFiles",
        combineArray(getField(obj, PathClassLoader.class, "mFiles"), getField(dexClassLoader, DexClassLoader.class,
                "mFiles")
        ));
    setField(obj, PathClassLoader.class, "mZips",
        combineArray(getField(obj, PathClassLoader.class, "mZips"), getField(dexClassLoader, DexClassLoader.class,
            "mZips")));
    setField(obj, PathClassLoader.class, "mDexs",
        combineArray(getField(obj, PathClassLoader.class, "mDexs"), getField(dexClassLoader, DexClassLoader.class,
            "mDexs")));
    obj.loadClass(str2);
}
 
Example 6
Source File: Task.java    From WeChatMomentStat-Android with GNU General Public License v3.0 6 votes vote down vote up
public void initSnsReader() {
    File outputAPKFile = new File(Config.EXT_DIR + "/wechat.apk");
    if (!outputAPKFile.exists())
        copyAPKFromAssets();

    try {

        Config.initWeChatVersion("6.3.13.64_r4488992");
        DexClassLoader cl = new DexClassLoader(
                outputAPKFile.getAbsolutePath(),
                context.getDir("outdex", 0).getAbsolutePath(),
                null,
                ClassLoader.getSystemClassLoader());

        Class SnsDetailParser = null;
        Class SnsDetail = null;
        Class SnsObject = null;
        SnsDetailParser = cl.loadClass(Config.SNS_XML_GENERATOR_CLASS);
        SnsDetail = cl.loadClass(Config.PROTOCAL_SNS_DETAIL_CLASS);
        SnsObject = cl.loadClass(Config.PROTOCAL_SNS_OBJECT_CLASS);
        snsReader = new SnsReader(SnsDetail, SnsDetailParser, SnsObject);
    } catch (Throwable e) {
        Log.e("wechatmomentstat", "exception", e);
    }
}
 
Example 7
Source File: HotFix.java    From HotFix with MIT License 6 votes vote down vote up
@TargetApi(14)
private static void injectBelowApiLevel14(Context context, String str, String str2)
    throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
    PathClassLoader obj = (PathClassLoader) context.getClassLoader();
    DexClassLoader dexClassLoader =
        new DexClassLoader(str, context.getDir("dex", 0).getAbsolutePath(), str, context.getClassLoader());
    dexClassLoader.loadClass(str2);
    setField(obj, PathClassLoader.class, "mPaths",
        appendArray(getField(obj, PathClassLoader.class, "mPaths"), getField(dexClassLoader, DexClassLoader.class,
                "mRawDexPath")
        ));
    setField(obj, PathClassLoader.class, "mFiles",
        combineArray(getField(obj, PathClassLoader.class, "mFiles"), getField(dexClassLoader, DexClassLoader.class,
                "mFiles")
        ));
    setField(obj, PathClassLoader.class, "mZips",
        combineArray(getField(obj, PathClassLoader.class, "mZips"), getField(dexClassLoader, DexClassLoader.class,
            "mZips")));
    setField(obj, PathClassLoader.class, "mDexs",
        combineArray(getField(obj, PathClassLoader.class, "mDexs"), getField(dexClassLoader, DexClassLoader.class,
            "mDexs")));
    obj.loadClass(str2);
}
 
Example 8
Source File: DexInjector.java    From dalvik_patch with The Unlicense 6 votes vote down vote up
private static synchronized Boolean injectAboveEqualApiLevel14(
        String dexPath, String defaultDexOptPath, String nativeLibPath, String dummyClassName) {
    Log.i(TAG, "--> injectAboveEqualApiLevel14");
    PathClassLoader pathClassLoader = (PathClassLoader) DexInjector.class.getClassLoader();
    DexClassLoader dexClassLoader = new DexClassLoader(dexPath, defaultDexOptPath, nativeLibPath, pathClassLoader);
    try {
        dexClassLoader.loadClass(dummyClassName);
        Object dexElements = combineArray(
                getDexElements(getPathList(pathClassLoader)),
                getDexElements(getPathList(dexClassLoader)));

        Object pathList = getPathList(pathClassLoader);
        setField(pathList, pathList.getClass(), "dexElements", dexElements);
    } catch (Throwable e) {
        e.printStackTrace();
        return false;
    }
    Log.i(TAG, "<-- injectAboveEqualApiLevel14 End.");
    return true;
}
 
Example 9
Source File: DynamicLoader.java    From PhotoMovie with Apache License 2.0 5 votes vote down vote up
public static List<MovieSegment> loadSegmentsFromFile(Context context, String path, String classFullName) {
        List<MovieSegment> segmentList = new ArrayList<MovieSegment>();
        if (TextUtils.isEmpty(path) || TextUtils.isEmpty(classFullName)) {
            return segmentList;
        }
        final File jarFile = new File(path);
        final File dexOutputDir = context.getCacheDir();
//        DexFile.loadDex(jarFile.getAbsolutePath(),dexOutputDir+File.separator+"dexfile",0);
        DexClassLoader mClassLoader = new DexClassLoader(jarFile.getAbsolutePath(), dexOutputDir.getAbsolutePath(), null,
                context.getClassLoader());
        Class libProviderClazz = null;
        try {
            libProviderClazz = mClassLoader.loadClass(classFullName);
            Method[] methods = libProviderClazz.getMethods();
            Method method = null;
            for(int i=0;methods!=null && i<methods.length;i++){
                if("initSegments".equals(methods[i].getName())){
                    method = methods[i];
                    break;
                }
            }
            if(method==null){
                return null;
            }
            return (List<MovieSegment>) method.invoke(null,new Object[0]);
        } catch (Exception exception) {
            // Handle exception gracefully here.
            exception.printStackTrace();
        }
        return segmentList;
    }
 
Example 10
Source File: CustomClassLoader.java    From Evolve with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Class findClass (String name) throws ClassNotFoundException{
    if (!name.contains("dummy")) {
        if (Evolve.debugMode()) System.out.println("THIS RETURNS NULL " + name);
        return null;
    }
    if (dummyToClassMap.containsKey(name)) return dummyToClassMap.get(name);

    try {
        final ClassPool cp = ClassPool.getDefault(context);
        CtClass cls = cp.makeClass(name);
        cls.setSuperclass(cp.get(dummyToSuperMap.get(name)));
        DexFile df = new DexFile();
        cls.writeFile(context.getFilesDir().getAbsolutePath());
        df.addClass(new File(context.getFilesDir(), name.replace('.', File.separatorChar) + ".class"));

        String temppath = File.createTempFile("tempdex",".dex").getAbsolutePath();
        df.writeFile(temppath);
        DexClassLoader classLoader = new DexClassLoader(temppath, context.getFilesDir().getAbsolutePath(), null, getClass().getClassLoader());
        Class c = classLoader.loadClass(name);
        dummyToClassMap.put(name, c);
        return c;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 11
Source File: LoadCode.java    From pivaa with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Method for load and execute class
 * @param classname
 * @return
 */
public String load(String classname) {
    StringBuilder sb = new StringBuilder();

    String path = classname;
    path = path.replace('.', '/');
    path = "assets/" + path + ".jar";


    String[] classnameExploded = classname.split("\\.");
    classname = classnameExploded[classnameExploded.length - 1];

    String resCopy = copyAssetsToFiles(path);
    sb.append(resCopy).append("\n").append("\n");

    String filePath = context.getFilesDir().getPath() + "/test.jar";

    Log.i("htbridge", "Loading class file " + filePath);
    sb.append("Loading class file " + filePath).append("\n").append("\n");


    /**
     * Print all assets
     */
    /*try {
        String[] res = this.context.getAssets().list("com/htbridge/raw");
        for (String s: res) {
            Log.i("htbridge", s);
        }
    } catch(Exception e) {
        e.printStackTrace();
    }*/


    try {
        String dexDir = this.context.getDir("dex", 0).getAbsolutePath();
        ClassLoader parent = getClass().getClassLoader();
        DexClassLoader loader  = new DexClassLoader(filePath, dexDir, null, parent);
        Class c = loader.loadClass(classname);
        Object o = c.newInstance();
        Method m = c.getMethod("run");

        Object res = m.invoke(o);

        Log.i("htbridge", res.toString());
        sb.append("Output from executed code: \"" + res.toString() + "\"").append("\n").append("\n");

        return sb.toString();

    } catch (Exception e) {
        e.printStackTrace();
    }

    sb.append("Error in running").append("\n").append("\n");

    return sb.toString();
}
 
Example 12
Source File: AndroidModLoader.java    From Cubes with MIT License 4 votes vote down vote up
private Class<?> loadDex(FileHandle classFile, String className) throws Exception {
  DexClassLoader classLoader = new DexClassLoader(classFile.file().getAbsolutePath(), androidCompatibility.androidLauncher.getDir("dex", Context.MODE_PRIVATE).getAbsolutePath(), null, AndroidModLoader.class.getClassLoader());
  return classLoader.loadClass(className);
}
 
Example 13
Source File: DexInjector.java    From dalvik_patch with The Unlicense 4 votes vote down vote up
private static synchronized Boolean injectInAliyunOs(
        String dexPath, String defaultDexOptPath, String nativeLibPath, String dummyClassName) {
    Log.i(TAG, "-->injectInAliyunOs");
    PathClassLoader localClassLoader = (PathClassLoader) DexInjector.class.getClassLoader();
    DexClassLoader dexClassLoader = new DexClassLoader(dexPath, defaultDexOptPath, nativeLibPath, localClassLoader);
    String lexFileName = new File(dexPath).getName();
    lexFileName = lexFileName.replaceAll("\\.[a-zA-Z0-9]+", ".lex");
    try {
        dexClassLoader.loadClass(dummyClassName);
        Class<?> classLexClassLoader = Class.forName("dalvik.system.LexClassLoader");
        Constructor<?> constructorLexClassLoader = classLexClassLoader.getConstructor(
                String.class, String.class, String.class, ClassLoader.class);
        Object localLexClassLoader = constructorLexClassLoader.newInstance(
                defaultDexOptPath + File.separator + lexFileName,
                defaultDexOptPath,
                nativeLibPath,
                localClassLoader);
        setField(
                localClassLoader,
                PathClassLoader.class,
                "mPaths",
                appendArray(
                        getField(localClassLoader, PathClassLoader.class, "mPaths"),
                        getField(localLexClassLoader, classLexClassLoader, "mRawDexPath")));
        setField(
                localClassLoader,
                PathClassLoader.class,
                "mFiles",
                combineArray(
                        getField(localClassLoader, PathClassLoader.class, "mFiles"),
                        getField(localLexClassLoader, classLexClassLoader,"mFiles")));
        setField(
                localClassLoader,
                PathClassLoader.class,
                "mZips",
                combineArray(
                        getField(localClassLoader, PathClassLoader.class, "mZips"),
                        getField(localLexClassLoader, classLexClassLoader, "mZips")));
        setField(
                localClassLoader,
                PathClassLoader.class,
                "mLexs",
                combineArray(
                        getField(localClassLoader, PathClassLoader.class, "mLexs"),
                        getField(localLexClassLoader, classLexClassLoader, "mDexs")));

    } catch (Throwable t) {
        t.printStackTrace();
        return false;
    }
    Log.i(TAG, "<--injectInAliyunOs end.");
    return true;
}
 
Example 14
Source File: DexInjector.java    From dalvik_patch with The Unlicense 4 votes vote down vote up
private static synchronized Boolean injectBelowApiLevel14(
        String dexPath, String defaultDexOptPath, String nativeLibPath, String dummyClassName) {
    Log.i(TAG, "--> injectBelowApiLevel14");
    PathClassLoader pathClassLoader = (PathClassLoader) DexInjector.class.getClassLoader();
    DexClassLoader dexClassLoader = new DexClassLoader(dexPath, defaultDexOptPath, nativeLibPath, pathClassLoader);
    try {
        dexClassLoader.loadClass(dummyClassName);
        setField(
                pathClassLoader,
                PathClassLoader.class,
                "mPaths",
                appendArray(
                        getField(pathClassLoader, PathClassLoader.class,"mPaths"),
                        getField(dexClassLoader, DexClassLoader.class,"mRawDexPath")));
        setField(
                pathClassLoader,
                PathClassLoader.class,
                "mFiles",
                combineArray(
                        getField(pathClassLoader, PathClassLoader.class, "mFiles"),
                        getField(dexClassLoader, DexClassLoader.class, "mFiles")));
        setField(
                pathClassLoader,
                PathClassLoader.class,
                "mZips",
                combineArray(
                        getField(pathClassLoader, PathClassLoader.class, "mZips"),
                        getField(dexClassLoader, DexClassLoader.class, "mZips")));
        setField(
                pathClassLoader,
                PathClassLoader.class,
                "mDexs",
                combineArray(
                        getField(pathClassLoader, PathClassLoader.class, "mDexs"),
                        getField(dexClassLoader, DexClassLoader.class, "mDexs")));
    } catch (Throwable e) {
        e.printStackTrace();
        return false;
    }
    Log.i(TAG, "<-- injectBelowApiLevel14");
    return true;
}
 
Example 15
Source File: SystemClassLoaderAdder.java    From buck with Apache License 2.0 4 votes vote down vote up
/**
 * Adds the paths in {@code newClassLoader} to the paths in {@code systemClassLoader}. This works
 * with versions of Android that pre-date {@link BaseDexClassLoader}.
 *
 * @param newClassLoader the class loader with the new paths
 * @param systemClassLoader the system class loader
 */
@SuppressWarnings("PMD.EmptyCatchBlock")
private void addNewClassLoaderToSystemClassLoaderPreBaseDex(
    DexClassLoader newClassLoader, PathClassLoader systemClassLoader)
    throws NoSuchFieldException, IllegalAccessException {

  try {
    // The class loader is lazily initialized. Loading any class forces it to be initialized.
    newClassLoader.loadClass("foo");
  } catch (ClassNotFoundException e) {
    // Expected to fail.
  }

  // Copy value in scalar field newClassLoader.mRawDexPath and array field
  // systemClassLoader.mPaths to a new array that replaces systemClassLoader.mPaths.
  Reflect.setField(
      systemClassLoader,
      PathClassLoader.class,
      "mPaths",
      mergeArrayAndScalar(
          Reflect.getField(systemClassLoader, PathClassLoader.class, "mPaths"),
          Reflect.getField(newClassLoader, DexClassLoader.class, "mRawDexPath")));

  // Copy values in array field newClassLoader.mFiles and array field systemClassLoader.mFiles
  // to a new array that replaces systemClassLoader.mFiles.
  Reflect.setField(
      systemClassLoader,
      PathClassLoader.class,
      "mFiles",
      mergeArrays(
          Reflect.getField(systemClassLoader, PathClassLoader.class, "mFiles"),
          Reflect.getField(newClassLoader, DexClassLoader.class, "mFiles")));

  // Copy values in array field newClassLoader.mZips and array field systemClassLoader.mZips
  // to a new array that replaces systemClassLoader.mZips.
  Reflect.setField(
      systemClassLoader,
      PathClassLoader.class,
      "mZips",
      mergeArrays(
          Reflect.getField(systemClassLoader, PathClassLoader.class, "mZips"),
          Reflect.getField(newClassLoader, DexClassLoader.class, "mZips")));

  // Copy values in array field newClassLoader.mDexs and array field systemClassLoader.mDexs
  // to a new array that replaces systemClassLoader.mDexs.
  Reflect.setField(
      systemClassLoader,
      PathClassLoader.class,
      "mDexs",
      mergeArrays(
          Reflect.getField(systemClassLoader, PathClassLoader.class, "mDexs"),
          Reflect.getField(newClassLoader, DexClassLoader.class, "mDexs")));
}