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 Project: Stark   Author: ximsfei   File: Stark.java    License: 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 #2
Source Project: fooXposed   Author: fooree   File: MainActivity.java    License: 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 Project: JPPF   Author: jppf-grid   File: AndroidClassLoader.java    License: 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 #4
Source Project: Neptune   Author: iqiyi   File: ClassLoaderInjectHelper.java    License: 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 #5
Source Project: YAHFA   Author: PAGalaxyLab   File: MainApp.java    License: 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 #6
Source Project: starcor.xul   Author: starcor-company   File: XulPluginManager.java    License: 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 #7
Source Project: SDKHoxFix   Author: bihe0832   File: HotFix.java    License: 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 #8
Source Project: MycroftCore-Android   Author: MycroftAI   File: MainActivity.java    License: Apache License 2.0 6 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 #9
Source Project: ZeusPlugin   Author: iReaderAndroid   File: PluginManager.java    License: 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 #10
Source Project: zone-sdk   Author: luhaoaimama1   File: DexUtils.java    License: 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 #11
Source Project: WeChatMomentStat-Android   Author: Chion82   File: Task.java    License: 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 #12
Source Project: ACDD   Author: woyaowenzi   File: OpenAtlasHacks.java    License: 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 Project: ACDD   Author: woyaowenzi   File: OpenAtlasHacks.java    License: 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 #14
Source Project: appcan-android   Author: AppCanOpenSource   File: EUtil.java    License: 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 #15
Source Project: Android-Plugin-Framework   Author: limpoxe   File: RealPluginClassLoader.java    License: 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 #16
Source Project: HotFix   Author: dodola   File: HotFix.java    License: 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 #17
Source Project: titan-hotfix   Author: baidu   File: PatchManagerService.java    License: 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 #18
Source Project: PhotoMovie   Author: yellowcath   File: DynamicLoader.java    License: 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 #19
Source Project: fooXposed   Author: fooree   File: DexHook.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void handleLoadPackage(final LoadPackageParam lp) throws Throwable {
    if (Build.VERSION.SDK_INT < 19 || Build.VERSION.SDK_INT > 25) {
        return;
    }

    shares.reload();
    String pkg = shares.getString(Constants.SELECT_APPLICATION, null);
    if (lp.packageName.equals(pkg)) {
        Log.i(TAG, "Loading " + lp.packageName);

        final ClassLoader systemLoader = ClassLoader.getSystemClassLoader();
        final ClassLoader bootLoader = DexClassLoader.class.getClassLoader();

        findAndHookMethod(ClassLoader.class, "loadClass", String.class, new XC_MethodHook() {
            @Override
            protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                ClassLoader loader = (ClassLoader) param.thisObject;
                if (param.hasThrowable()
                        || loader == bootLoader
                        || loader == systemLoader
                        || loader.getParent() == systemLoader) {
                    return;
                }

                Class<?> clazz = (Class<?>) param.getResult();
                Object dex = XposedHelpers.callMethod(clazz, "getDex");
                byte[] data = (byte[]) XposedHelpers.callMethod(dex, "getBytes");

                File file = new File(DUMP_PATH, data.length + ".dex");
                if (!file.exists() && file.createNewFile()) {
                    file.setReadable(true, false);
                    IO.write(data, file);
                }
            }
        });
    }
}
 
Example #20
Source Project: Neptune   Author: iqiyi   File: ClassLoaderInjectHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 阿里云系统注入jar
 *
 * @param context application object
 * @param dexPath lib path
 * @return inject result
 */
private static InjectResult injectInAliyunOs(Context context, String dexPath, String soPath) {
    InjectResult result = null;
    PathClassLoader localClassLoader = (PathClassLoader) context.getClassLoader();
    File optDir = PluginInstaller.getPluginInjectRootPath(context);
    FileUtils.checkOtaFileValid(optDir, new File(dexPath));
    new DexClassLoader(dexPath, optDir.getAbsolutePath(), soPath, localClassLoader);
    String lexFileName = new File(dexPath).getName();
    lexFileName = lexFileName.replaceAll("\\.[a-zA-Z0-9]+", ".lex");
    try {
        Class<?> classLexClassLoader = Class.forName("dalvik.system.LexClassLoader");
        Constructor<?> constructorLexClassLoader = classLexClassLoader.getConstructor(String.class, String.class, String.class,
                ClassLoader.class);
        Object localLexClassLoader = constructorLexClassLoader.newInstance(
                optDir.getAbsolutePath() + File.separator + lexFileName, optDir.getAbsolutePath(),
                soPath, 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")));

        result = makeInjectResult(true, null);
    } catch (Exception e) {
        result = makeInjectResult(false, e);
        e.printStackTrace();
    }

    return result;
}
 
Example #21
Source Project: Neptune   Author: iqiyi   File: ClassLoaderInjectHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * api < 14时,注入jar
 *
 * @param context application
 * @param dexPath lib path
 * @return inject result
 */
private static InjectResult injectBelowApiLevel14(Context context, String dexPath, String someClass, String soPath) {
    InjectResult result = null;
    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);

    result = injectBelowApiLevel14(pathClassLoader, dexClassLoader, someClass);

    return result;
}
 
Example #22
Source Project: Neptune   Author: iqiyi   File: ClassLoaderInjectHelper.java    License: Apache License 2.0 5 votes vote down vote up
private static InjectResult ejectAboveEqualApiLevel14(ClassLoader parentClassLoader, ClassLoader childClassLoader) {
    PathClassLoader pathClassLoader = (PathClassLoader) parentClassLoader;
    DexClassLoader dexClassLoader = (DexClassLoader) childClassLoader;
    InjectResult result = null;
    try {
        // 注入 dex
        Object dexElements = removeArrayElements(getDexElements(getPathList(pathClassLoader)),
                getDexElements(getPathList(dexClassLoader)));

        Object pathList = getPathList(pathClassLoader);

        setField(pathList, pathList.getClass(), "dexElements", dexElements);

        // 注入 native lib so 目录,需要parent class loader
        // 遍历此目录能够找到。因为注入了以后,不处理这个目录找不到。
        Object dexNativeLibraryDirs = removeArrayElements(getNativeLibraryDirectories(getPathList(pathClassLoader)),
                getNativeLibraryDirectories(getPathList(dexClassLoader)));

        setField(pathList, pathList.getClass(), "nativeLibraryDirectories", dexNativeLibraryDirs);

        result = makeInjectResult(true, null);
    } catch (Exception e) {
        result = makeInjectResult(false, e);
        e.printStackTrace();
    }

    return result;
}
 
Example #23
Source Project: Neptune   Author: iqiyi   File: PluginLoadedApk.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 创建插件新的ClassLoader,不使用注入Host ClassLoader方案
 */
private boolean createNewClassLoader() {

    PluginDebugLog.runtimeLog(TAG, "createNewClassLoader");
    File optDir = getDataDir(mHostContext, mPluginPackageName);
    mParent = mPluginPackageInfo.isIndividualMode() ? mHostClassLoader.getParent() : mHostClassLoader;
    if (optDir != null && isOptDirAccessible(optDir)) {
        DexClassLoader classLoader = sAllPluginClassLoader.get(mPluginPackageName);
        if (classLoader == null) {
            FileUtils.checkOtaFileValid(optDir, new File(mPluginPath));  //检测oat文件是否损坏
            mPluginClassLoader = new PluginClassLoader(mPluginPackageInfo, mPluginPath,
                    optDir.getAbsolutePath(), mPluginPackageInfo.getNativeLibraryDir(), mParent);
            PluginDebugLog.runtimeLog(TAG, "createNewClassLoader success for plugin " + mPluginPackageName);
            sAllPluginClassLoader.put(mPluginPackageName, mPluginClassLoader);
        } else {
            PluginDebugLog.runtimeLog(TAG, "classloader find in cache, createNewClassLoader success for plugin " + mPluginPackageName);
            mPluginClassLoader = classLoader;
        }

        return handleNewDependencies();
    } else if (optDir != null) {
        PluginDebugLog.runtimeLog(TAG,
                "createNewClassLoader failed as " + optDir.getAbsolutePath() + " exist: "
                        + optDir.exists() + " can read: " + optDir.canRead()
                        + " can write: " + optDir.canWrite());
    }
    return false;
}
 
Example #24
Source Project: Neptune   Author: iqiyi   File: DexOptimizer.java    License: Apache License 2.0 5 votes vote down vote up
public boolean run() {
    try {
        if (!isLegalFile(dexFile)) {
            if (callback != null) {
                callback.onFailed(dexFile, optimizedDir,
                        new IOException("dex file " + dexFile.getAbsolutePath() + " is not exist!"));
                return false;
            }
        }
        if (callback != null) {
            callback.onStart(dexFile, optimizedDir);
        }
        String optimizedPath = optimizedPathFor(this.dexFile, this.optimizedDir, targetISA);
        if (useInterpretMode) {
            interpretDex2Oat(dexFile.getAbsolutePath(), optimizedPath);
        } else {
            new DexClassLoader(dexFile.getAbsolutePath(), this.optimizedDir.getAbsolutePath(), null, this.getClass().getClassLoader());
        }
        if (callback != null) {
            callback.onSuccess(dexFile, optimizedDir, new File(optimizedPath));
        }
    } catch (final Throwable e) {
        Log.e(TAG, "Failed to optimize dex: " + dexFile.getAbsolutePath(), e);
        if (callback != null) {
            callback.onFailed(dexFile, optimizedDir, e);
            return false;
        }
    }
    return true;
}
 
Example #25
Source Project: letv   Author: JackChan1999   File: HotFix.java    License: Apache License 2.0 5 votes vote down vote up
@TargetApi(14)
private static void injectBelowApiLevel14(Context context, String str) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
    PathClassLoader obj = (PathClassLoader) context.getClassLoader();
    DexClassLoader dexClassLoader = new DexClassLoader(str, context.getDir(Constant.JAR_IN_FOLDER_NAME, 0).getAbsolutePath(), str, context.getClassLoader());
    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")));
}
 
Example #26
Source Project: VirtualAPK   Author: didi   File: LoadedPlugin.java    License: Apache License 2.0 5 votes vote down vote up
protected ClassLoader createClassLoader(Context context, File apk, File libsDir, ClassLoader parent) throws Exception {
    File dexOutputDir = getDir(context, Constants.OPTIMIZE_DIR);
    String dexOutputPath = dexOutputDir.getAbsolutePath();
    DexClassLoader loader = new DexClassLoader(apk.getAbsolutePath(), dexOutputPath, libsDir.getAbsolutePath(), parent);

    if (Constants.COMBINE_CLASSLOADER) {
        DexUtil.insertDex(loader, parent, libsDir);
    }

    return loader;
}
 
Example #27
Source Project: VirtualAPK   Author: didi   File: DexUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static void insertDex(DexClassLoader dexClassLoader, ClassLoader baseClassLoader, File nativeLibsDir) throws Exception {
    Object baseDexElements = getDexElements(getPathList(baseClassLoader));
    Object newDexElements = getDexElements(getPathList(dexClassLoader));
    Object allDexElements = combineArray(baseDexElements, newDexElements);
    Object pathList = getPathList(baseClassLoader);
    Reflector.with(pathList).field("dexElements").set(allDexElements);

    insertNativeLibrary(dexClassLoader, baseClassLoader, nativeLibsDir);
}
 
Example #28
Source Project: appinventor-extensions   Author: mit-cml   File: ReplForm.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This is a nasty hack. For loading external component's dex file so that they can be accessible for
 * kawa to load it, when required. This assumes classloader checks class via delegation through the parent
 * classloaders. For multiple dex files, we just cascade the classloaders in the hierarchy
 */
public void loadComponents(List<String> extensionNames) {
  Set<String> extensions = new HashSet<String>(extensionNames);
  // Store the loaded dex files in the private storage of the App for stable optimization
  File dexOutput = activeForm.$context().getDir("componentDexs", Context.MODE_PRIVATE);
  File componentFolder = new File(REPL_COMP_DIR );
  if (!checkComponentDir()) {
    Log.d(LOG_TAG, "Unable to create components directory");
    dispatchErrorOccurredEventDialog(this, "loadComponents", ErrorMessages.ERROR_EXTENSION_ERROR,
        1, "App Inventor", "Unable to create component directory.");
    return;
  }
  // Current Thread Class Loader
  ClassLoader parentClassLoader = ReplForm.class.getClassLoader();
  StringBuilder sb = new StringBuilder();
  loadedExternalDexs.clear();
  for (File compFolder : componentFolder.listFiles()) {
    if (compFolder.isDirectory()) {
      if (!extensions.contains(compFolder.getName())) continue;  // Skip extensions on the phone but not required by the project
      File component = new File(compFolder.getPath() + File.separator + "classes.jar");
      File loadComponent = new File(compFolder.getPath() + File.separator + compFolder.getName() + ".jar");
      component.renameTo(loadComponent);
      if (loadComponent.exists() && !loadedExternalDexs.contains(loadComponent.getName())) {
        Log.d(LOG_TAG, "Loading component dex " + loadComponent.getAbsolutePath());
        loadedExternalDexs.add(loadComponent.getName());
        sb.append(File.pathSeparatorChar);
        sb.append(loadComponent.getAbsolutePath());
      }
    }
  }
  DexClassLoader dexCloader = new DexClassLoader(sb.substring(1), dexOutput.getAbsolutePath(),
      null, parentClassLoader);
  Thread.currentThread().setContextClassLoader(dexCloader);
  Log.d(LOG_TAG, Thread.currentThread().toString());
  Log.d(LOG_TAG, Looper.getMainLooper().getThread().toString());
  Looper.getMainLooper().getThread().setContextClassLoader(dexCloader);
}
 
Example #29
Source Project: MiPushFramework   Author: MiPushFramework   File: C0033d.java    License: GNU General Public License v3.0 5 votes vote down vote up
static boolean load(String str, String str2, String str3, ClassLoader classLoader, Context context) {
    if (str == null && (str3 == null || context == null)) {
        return false;
    }
    try {
        String str4;
        Object a = C0033d.m46a(classLoader);
        if (str != null) {
            str4 = str;
        } else if (VERSION.SDK_INT < 23) {
            C0033d.m52b(a, str3);
            return true;
        } else {
            str2 = null;
            str4 = context.getApplicationInfo().sourceDir;
        }
        Object a2 = C0033d.m46a(str2 == null ? new PathClassLoader(str4, str3, classLoader.getParent()) : new DexClassLoader(str4, str2, str3, classLoader.getParent()));
        if (str != null) {
            C0033d.m49a(a, a2);
        }
        if (str3 != null) {
            C0033d.m50a(a, a2, str3);
        }
        return true;
    } catch (IllegalArgumentException e) {
        return false;
    } catch (IllegalAccessException e2) {
        return false;
    } catch (ClassNotFoundException e3) {
        return false;
    } catch (NoSuchFieldException e4) {
        return false;
    }
}
 
Example #30
Source Project: HotFixDemo   Author: GitLqr   File: FixDexUtils.java    License: MIT License 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();
    }
}