dalvik.system.DexClassLoader Java Examples

The following examples show how to use dalvik.system.DexClassLoader. 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: 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 #3
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 #4
Source File: RealPluginClassLoader.java    From Android-Plugin-Framework with MIT License 6 votes vote down vote up
public RealPluginClassLoader(String pluginPackageName, String dexPath, String[] dependencies,
							 String optimizedDirectory, String libraryPath,
							 List<String> multiDexList, boolean isStandalone) {
	super(dexPath, optimizedDirectory, libraryPath, isStandalone ? ClassLoader.getSystemClassLoader().getParent() : RealPluginClassLoader.class.getClassLoader());
	this.dependencies = dependencies;
	this.pluginPackageName = pluginPackageName;
	this.isStandalone = isStandalone;
	if (multiDexList != null) {
		if (multiDexClassLoaderList == null) {
			multiDexClassLoaderList = new ArrayList<DexClassLoader>(multiDexList.size());
			for(String path: multiDexList) {
				multiDexClassLoaderList.add(new DexClassLoader(path, optimizedDirectory, libraryPath, getParent()));
			}
		}
	}
}
 
Example #5
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 #6
Source File: AndroidClassLoader.java    From JPPF with Apache License 2.0 6 votes vote down vote up
/**
 * Create a {@link DexClassLoader} based on the specified classpath.
 * @param parent  the parent class loader.
 * @param classpath contains the locations of jar files with dex files. In principle these should only be memory locations.
 * @return a new {@link DexClassLoader} instance.
 */
private static DexClassLoader createDexClassLoader(final ClassLoader parent, ClassPath classpath) {
  Log.v(LOG_TAG, String.format("in createDexClassLoader(classpath=%s)", classpath));
  StringBuilder pathBuilder = new StringBuilder();
  int count = 0;
  File inDir = AndroidHelper.getActivity().getDir(DEX_IN_DIR, Context.MODE_PRIVATE);
  FileUtils.deletePath(inDir, true);
  File outDir = AndroidHelper.getActivity().getDir(DEX_OUT_DIR, Context.MODE_PRIVATE);
  FileUtils.deletePath(outDir, true);
  if (classpath != null) {
    for (ClassPathElement element: classpath) {
      Log.v(LOG_TAG, "in createDexClassLoader() : processing cp element '" + element.getName() + "'");
      File file = createDexFile(element, inDir);
      if (count > 0) pathBuilder.append(File.pathSeparator);
      pathBuilder.append(file.getAbsolutePath());
      count++;
    }
  }
  return new DexClassLoader(pathBuilder.toString(), outDir.getAbsolutePath(), null, parent);
}
 
Example #7
Source File: ClassLoaderInjectHelper.java    From Neptune with Apache License 2.0 6 votes vote down vote up
/**
 * api >= 14时,注入jar
 *
 * @param context application object
 * @param dexPath lib path
 * @return inject object
 */
private static InjectResult injectAboveEqualApiLevel14(Context context, String dexPath, String soPath) {
    PathClassLoader pathClassLoader = (PathClassLoader) context.getClassLoader();
    File optDir = PluginInstaller.getPluginInjectRootPath(context);
    FileUtils.checkOtaFileValid(optDir, new File(dexPath));
    DexClassLoader dexClassLoader = new DexClassLoader(dexPath, optDir.getAbsolutePath(), soPath,
            pathClassLoader);
    InjectResult result = null;

    // If version > 22 LOLLIPOP_MR1
    if (Build.VERSION.SDK_INT > 22) {
        result = injectAboveApiLevel22(pathClassLoader, dexClassLoader);
    } else {
        result = injectAboveEqualApiLevel14(pathClassLoader, dexClassLoader);
    }

    return result;
}
 
Example #8
Source File: EUtil.java    From appcan-android with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static DexClassLoader loadDex(Context ctx, String dexAssertPath) {
    int index = dexAssertPath.lastIndexOf('/');
    if (index < 0) {
        return null;
    }
    String dexName = dexAssertPath.substring(index);
    String dexPath = ctx.getDir("dex", Context.MODE_PRIVATE).getAbsolutePath() + dexName;
    File f = new File(dexPath);
    if (!f.exists()) {
        boolean ok = copyDex(ctx, dexAssertPath, dexPath);
        if (!ok) {
            return null;
        }
    }
    String dexOutputDir = ctx.getDir("outdex", Context.MODE_PRIVATE).getAbsolutePath();
    DexClassLoader cl = new DexClassLoader(dexPath, dexOutputDir, null, ctx.getClassLoader());
    return cl;
}
 
Example #9
Source File: OpenAtlasHacks.java    From ACDD with MIT License 6 votes vote down vote up
/***
 * hack all defined methods
 **/
private static void allMethods() throws HackAssertionException {
    ActivityThread_currentActivityThread = ActivityThread.method(
            "currentActivityThread");
    AssetManager_addAssetPath = AssetManager.method("addAssetPath",
            String.class);
    Application_attach = Application.method("attach", Context.class);
    ClassLoader_findLibrary = ClassLoader.method("findLibrary",
            String.class);
    if (LexFile != null && LexFile.getmClass() != null) {
        LexFile_loadLex = LexFile.method("loadLex", String.class,
                Integer.TYPE);
        LexFile_loadClass = LexFile.method("loadClass", String.class,
                ClassLoader.class);
        LexFile_close = LexFile.method("close");
        DexClassLoader_findClass = DexClassLoader.method("findClass",
                String.class);
    }
}
 
Example #10
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 #11
Source File: DexUtils.java    From zone-sdk with MIT License 6 votes vote down vote up
public static DexClassLoader getDex(Context apps) {
	ApplicationInfo info = apps.getApplicationInfo();
	String dexPath=info.sourceDir;
	String dexOutputDir=info.dataDir;
	String libPath=info.nativeLibraryDir;
	DexClassLoader dl= new DexClassLoader(dexPath, dexOutputDir, 
			libPath, apps.getClass().getClassLoader());
	try {
		Enumeration<URL> gaga = dl.getResources("com.example.mylib_test");
		System.out.println(1);
	} catch (IOException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	}
	try {
		DexFile df = new DexFile(dexOutputDir);
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
	return dl;
}
 
Example #12
Source File: OpenAtlasHacks.java    From ACDD with MIT License 6 votes vote down vote up
/**
 * hack all defined classes
 ***/
private static void allClasses() throws HackAssertionException {
    if (VERSION.SDK_INT <= 8) {
        LoadedApk = Hack.into("android.app.ActivityThread$PackageInfo");
    } else {
        LoadedApk = Hack.into("android.app.LoadedApk");
    }
    ActivityThread = Hack.into("android.app.ActivityThread");
    Resources = Hack.into(Resources.class);
    Application = Hack.into(Application.class);
    AssetManager = Hack.into(AssetManager.class);
    IPackageManager = Hack.into("android.content.pm.IPackageManager");
    Service = Hack.into(Service.class);
    ContextImpl = Hack.into("android.app.ContextImpl");
    ContextThemeWrapper = Hack.into(ContextThemeWrapper.class);
    ContextWrapper = Hack.into("android.content.ContextWrapper");
    sIsIgnoreFailure = true;
    ClassLoader = Hack.into(ClassLoader.class);
    DexClassLoader = Hack.into(DexClassLoader.class);
    LexFile = Hack.into("dalvik.system.LexFile");
    sIsIgnoreFailure = false;
}
 
Example #13
Source File: PluginManager.java    From ZeusPlugin with MIT License 6 votes vote down vote up
/**
 * 安装初始的内置插件
 */
private static void installInitPlugins() {
    HashMap<String, PluginManifest> installedList = getInstalledPlugin();
    HashMap<String, Integer> defaultList = getDefaultPlugin();
    for (String key : defaultList.keySet()) {
        int installVersion = -1;
        int defaultVersion = defaultList.get(key);

        if (installedList.containsKey(key)) {
            installVersion = installedList.get(key).getVersion();
        }

        ZeusPlugin plugin = getPlugin(key);
        if (defaultVersion > installVersion) {
            boolean ret = plugin.installAssetPlugin();
            //提前将dex文件优化为odex或者opt文件
            if (ret) {
                try {
                    new DexClassLoader(PluginUtil.getAPKPath(key), PluginUtil.getDexCacheParentDirectPath(key), null, mBaseClassLoader.getParent());
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
 
Example #14
Source File: MainApp.java    From YAHFA with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void attachBaseContext(Context base) {
    super.attachBaseContext(base);

    try {
    /*
    Build and put the demoPlugin apk in sdcard before running the demoApp
     */
        ClassLoader classLoader = getClassLoader();

        DexClassLoader dexClassLoader = new DexClassLoader(
                new File(Environment.getExternalStorageDirectory(), "demoPlugin-debug.apk").getAbsolutePath(),
                getCodeCacheDir().getAbsolutePath(), null, classLoader);
        HookMain.doHookDefault(dexClassLoader, classLoader);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #15
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 #16
Source File: Stark.java    From Stark with Apache License 2.0 6 votes vote down vote up
/**
 * If the patch file exists. The load method will loads the patch.
 *
 * @param context
 */
public void load(Context context) {
    mAppContext = context.getApplicationContext() != null ? context.getApplicationContext() : context;
    File patch = getPatchFile(context);
    if (!patch.exists()) {
        return;
    }
    if (!checkPatchValid(patch)) {
        patch.delete();
        return;
    }
    DexClassLoader dexClassLoader = new DexClassLoader(patch.getAbsolutePath(),
            context.getCacheDir().getPath(), context.getCacheDir().getPath(),
            getClass().getClassLoader());
    try {
        Class<?> aClass = Class.forName("com.ximsfei.stark.core.runtime.StarkPatchLoaderImpl",
                true, dexClassLoader);
        PatchLoader patchLoader = (PatchLoader) aClass.newInstance();
        mPatchLoaded = patchLoader.load();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #17
Source File: HotFix.java    From HotFix with MIT License 5 votes vote down vote up
private static void injectAboveEqualApiLevel14(Context context, String str, String str2)
    throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
    PathClassLoader pathClassLoader = (PathClassLoader) context.getClassLoader();
    Object a = combineArray(getDexElements(getPathList(pathClassLoader)),
        getDexElements(getPathList(
            new DexClassLoader(str, context.getDir("dex", 0).getAbsolutePath(), str, context.getClassLoader()))));
    Object a2 = getPathList(pathClassLoader);
    setField(a2, a2.getClass(), "dexElements", a);
    pathClassLoader.loadClass(str2);
}
 
Example #18
Source File: TGResourceLoaderImpl.java    From tuxguitar with GNU Lesser General Public License v2.1 5 votes vote down vote up
public ClassLoader createClassLoader() throws TGResourceException {
	Context context = this.activity.getApplicationContext();
	
	String optimizedDirectory = context.getDir("dex", Context.MODE_PRIVATE).getAbsolutePath();
	
	List<String> fileNames = this.unpackPlugins(optimizedDirectory);
	if(!fileNames.isEmpty()) {
		return new DexClassLoader(this.createPath(fileNames), optimizedDirectory, this.createLibraryPath(), context.getClassLoader());
	}
	return context.getClassLoader();
}
 
Example #19
Source File: XmPluginPackage.java    From NewXmPluginSDK with Apache License 2.0 5 votes vote down vote up
public XmPluginPackage(String packageName, String path,
        DexClassLoader loader, AssetManager assetManager,
        Resources resources, PackageInfo packageInfo, String model,
        IXmPluginMessageReceiver xmPluginMessageReceiver) {
    this.packageName = packageName;
    this.packagePath = path;
    this.classLoader = loader;
    this.assetManager = assetManager;
    this.resources = resources;
    this.packageInfo = packageInfo;

    this.model = model;
    this.xmPluginMessageReceiver = xmPluginMessageReceiver;
}
 
Example #20
Source File: AtlasHacks.java    From AtlasForAndroid with MIT License 5 votes vote down vote up
public static void allMethods() throws HackAssertionException {
    ActivityThread_currentActivityThread = ActivityThread.method("currentActivityThread", new Class[0]);
    AssetManager_addAssetPath = AssetManager.method("addAssetPath", String.class);
    Application_attach = Application.method("attach", Context.class);
    ClassLoader_findLibrary = ClassLoader.method("findLibrary", String.class);
    if (LexFile != null && LexFile.getmClass() != null) {
        LexFile_loadLex = LexFile.method("loadLex", String.class, Integer.TYPE);
        LexFile_loadClass = LexFile.method("loadClass", String.class, ClassLoader.class);
        LexFile_close = LexFile.method("close", new Class[0]);
        DexClassLoader_findClass = DexClassLoader.method("findClass", String.class);
    }
}
 
Example #21
Source File: PluginLoader.java    From PluginLoader with Apache License 2.0 5 votes vote down vote up
public static Context getNewPluginContext(Context pluginContext) {
	if (pluginContext != null) {
		pluginContext = PluginCreator.createPluginApplicationContext(((PluginContextTheme) pluginContext).getPluginDescriptor(),
				mApplication, pluginContext.getResources(),
				(DexClassLoader) pluginContext.getClassLoader());
		pluginContext.setTheme(mApplication.getApplicationContext().getApplicationInfo().theme);
	}
	return pluginContext;
}
 
Example #22
Source File: PluginLoader.java    From PluginLoader with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
public static Class loadPluginClassByName(String clazzName) {

	PluginDescriptor pluginDescriptor = getPluginDescriptorByClassName(clazzName);

	if (pluginDescriptor != null) {

		ensurePluginInited(pluginDescriptor);

		DexClassLoader pluginClassLoader = pluginDescriptor.getPluginClassLoader();

		try {
			Class pluginClazz = ((ClassLoader) pluginClassLoader).loadClass(clazzName);
			PaLog.d("loadPluginClass Success for clazzName ", clazzName);
			return pluginClazz;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (java.lang.IllegalAccessError illegalAccessError) {
			illegalAccessError.printStackTrace();
			throw new IllegalAccessError("出现这个异常最大的可能是插件dex和" +
					"宿主dex包含了相同的class导致冲突, " +
					"请检查插件的编译脚本,确保排除了所有公共依赖库的jar");
		}

	}

	PaLog.e("loadPluginClass Fail for clazzName ", clazzName);

	return null;

}
 
Example #23
Source File: PluginLoader.java    From PluginLoader with Apache License 2.0 5 votes vote down vote up
/**
 * 根据插件中的classId加载一个插件中的class
 *
 * @param clazzId
 * @return
 */
@SuppressWarnings("rawtypes")
public static Class loadPluginFragmentClassById(String clazzId) {

	PluginDescriptor pluginDescriptor = getPluginDescriptorByFragmenetId(clazzId);

	if (pluginDescriptor != null) {

		ensurePluginInited(pluginDescriptor);

		DexClassLoader pluginClassLoader = pluginDescriptor.getPluginClassLoader();

		String clazzName = pluginDescriptor.getPluginClassNameById(clazzId);
		if (clazzName != null) {
			try {
				Class pluginClazz = ((ClassLoader) pluginClassLoader).loadClass(clazzName);
				PaLog.d("loadPluginClass for clazzId", clazzId, "clazzName", clazzName, "success");
				return pluginClazz;
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
	}

	PaLog.e("loadPluginClass for clazzId", clazzId, "fail");

	return null;

}
 
Example #24
Source File: PatchManagerService.java    From titan-hotfix with Apache License 2.0 5 votes vote down vote up
/**
 * do dex opt
 * @param installInfo
 * @return
 */
private boolean dexOpt(PatchInstallInfo installInfo, JSONObject logJson) {
    File dexOptDir = installInfo.getDexOptDir();
    dexOptDir.mkdirs();
    try {
        DexClassLoader dexClassLoader = new DelegateClassLoader(
                installInfo.getDexPath(),
                dexOptDir.getAbsolutePath(),
                null,
                Object.class.getClassLoader(),
                installInfo.getClass().getClassLoader());
        // 只在kitkat及以下版本校验opt 文件
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
            installInfo.saveOptFileDigests(dexOptDir);
        }
        return true;
    } catch (Throwable t) {
        if (logJson != null) {
            try {
                logJson.put("dexopt_ex", Log.getStackTraceString(t));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
    return false;
}
 
Example #25
Source File: PluginUtils.java    From NGA-CLIENT-VER-OPEN-SOURCE with GNU General Public License v2.0 5 votes vote down vote up
public static ClassLoader createClassLoader(String name) {
    Context context = ApplicationContextHolder.getContext();
    File extractFile = context.getFileStreamPath(name);
    String dexPath = extractFile.getPath();
    String libPath = PluginUtils.unzipLibraryFile(dexPath, extractFile.getParent());
    File fileRelease = context.getDir("dex", Context.MODE_PRIVATE);
    return new DexClassLoader(dexPath, fileRelease.getAbsolutePath(), libPath, context.getClassLoader());
}
 
Example #26
Source File: HotFix.java    From SDKHoxFix with Apache License 2.0 5 votes vote down vote up
private static void injectAboveEqualApiLevel14(Context context, String str, String str2)
    throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
    PathClassLoader pathClassLoader = (PathClassLoader) context.getClassLoader();
    Object a = combineArray(getDexElements(getPathList(pathClassLoader)),
        getDexElements(getPathList(
            new DexClassLoader(str, context.getDir("dex", 0).getAbsolutePath(), str, context.getClassLoader()))));
    Object a2 = getPathList(pathClassLoader);
    setField(a2, a2.getClass(), "dexElements", a);
    pathClassLoader.loadClass(str2);
}
 
Example #27
Source File: FixDexUtils.java    From My-MVP with Apache License 2.0 5 votes vote down vote up
private static void doDexInject(Context appContext, HashSet<File> loadedDex) {
    String optimizeDir = appContext.getFilesDir().getAbsolutePath() + File.separator + OPTIMIZE_DEX_DIR;// data/data/包名/files/optimize_dex(这个必须是自己程序下的目录)
    File fopt = new File(optimizeDir);
    if (!fopt.exists()) {
        fopt.mkdirs();
    }
    try {
        // 1.加载应用程序的dex
        PathClassLoader pathLoader = (PathClassLoader) appContext.getClassLoader();
        for (File dex : loadedDex) {
            // 2.加载指定的修复的dex文件
            DexClassLoader dexLoader = new DexClassLoader(
                    dex.getAbsolutePath(),// 修复好的dex(补丁)所在目录
                    fopt.getAbsolutePath(),// 存放dex的解压目录(用于jar、zip、apk格式的补丁)
                    null,// 加载dex时需要的库
                    pathLoader// 父类加载器
            );
            // 3.合并
            Object dexPathList = getPathList(dexLoader);
            Object pathPathList = getPathList(pathLoader);
            Object leftDexElements = getDexElements(dexPathList);
            Object rightDexElements = getDexElements(pathPathList);
            // 合并完成
            Object dexElements = combineArray(leftDexElements, rightDexElements);
            // 重写给PathList里面的Element[] dexElements;赋值
            Object pathList = getPathList(pathLoader);
            setField(pathList, pathList.getClass(), "dexElements", dexElements);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #28
Source File: Anole.java    From AnoleFix with MIT License 5 votes vote down vote up
public static void applyPatch(Context context, String dexFile) {
    try {
        ClassLoader classLoader = context.getClass().getClassLoader();

        String nativeLibraryPath;
        try {
            nativeLibraryPath = (String) classLoader.getClass().getMethod("getLdLibraryPath")
                    .invoke(classLoader);
        } catch (Throwable t) {
            nativeLibraryPath = getNativeLibraryFolder(context).getPath();
        }
        DexClassLoader dexClassLoader = new DexClassLoader(dexFile,
                context.getCacheDir().getPath(), nativeLibraryPath,
                context.getClass().getClassLoader());

        // we should transform this process with an interface/impl
        Class<?> aClass = Class.forName(
                "dodola.anole.runtime.AppPatchesLoaderImpl", true, dexClassLoader);
        try {

            PatchesLoader loader = (PatchesLoader) aClass.newInstance();
            String[] getPatchedClasses = (String[]) aClass
                    .getDeclaredMethod("getPatchedClasses").invoke(loader);
            Log.v(LOG_TAG, "Got the list of classes ");
            for (String getPatchedClass : getPatchedClasses) {
                Log.v(LOG_TAG, "class " + getPatchedClass);
            }
            if (!loader.load()) {
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}
 
Example #29
Source File: HotFix.java    From Android-Tech with Apache License 2.0 5 votes vote down vote up
private static void injectAboveEqualApiLevel14(Context context, String str, String str2)
        throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
    PathClassLoader pathClassLoader = (PathClassLoader) context.getClassLoader();
    Object a = combineArray(getDexElements(getPathList(pathClassLoader)),
            getDexElements(getPathList(
                    new DexClassLoader(str, context.getDir("dex", 0).getAbsolutePath(), str, context.getClassLoader()))));
    Object a2 = getPathList(pathClassLoader);
    setField(a2, a2.getClass(), "dexElements", a);
    pathClassLoader.loadClass(str2);
}
 
Example #30
Source File: PluginLoader.java    From PluginLoader with Apache License 2.0 5 votes vote down vote up
/**
 * 构造插件信息
 *
 * @param
 */
static void ensurePluginInited(PluginDescriptor pluginDescriptor) {
	if (pluginDescriptor != null) {
		DexClassLoader pluginClassLoader = pluginDescriptor.getPluginClassLoader();
		if (pluginClassLoader == null) {
			PaLog.d("正在初始化插件Resources, DexClassLoader, Context, Application ");

			PaLog.d("是否为独立插件", pluginDescriptor.isStandalone());

			Resources pluginRes = PluginCreator.createPluginResource(mApplication, pluginDescriptor.getInstalledPath(),
					pluginDescriptor.isStandalone());

			pluginClassLoader = PluginCreator.createPluginClassLoader(pluginDescriptor.getInstalledPath(),
					pluginDescriptor.isStandalone());
			Context pluginContext = PluginCreator
					.createPluginContext(pluginDescriptor, mApplication, pluginRes, pluginClassLoader);

			pluginContext.setTheme(mApplication.getApplicationContext().getApplicationInfo().theme);
			pluginDescriptor.setPluginContext(pluginContext);
			pluginDescriptor.setPluginClassLoader(pluginClassLoader);

			//使用了openAtlasExtention之后就不需要Public.xml文件了
			//checkPluginPublicXml(pluginDescriptor, pluginRes);

			callPluginApplicationOnCreate(pluginDescriptor);

			PaLog.d("初始化插件" + pluginDescriptor.getPackageName() + "完成");
		}
	}
}