AndFix原理浅析(二)之补丁合并原理

2017/05/19 热修复技术

  上一遍写了AndFix原理浅析(一)之补丁生成原理,本篇来分析补丁过程原理。如果还没有了解如何使用AndFix可以看之前的文章AndFix 实战以及遇到的坑。回顾之前文章,AndFix使用上主要是如下代码:

        //1)初始化PatchManager
        mPatchManager = new PatchManager(this);
        mPatchManager.init(AppInfoUtils.getVersionCode(this));
        //2)load patch
        mPatchManager.loadPatch();
        try {
        // .apatch file path ,这里一定要注意每台手机sd卡路径不同
        String patchFileString = "sdcard" + Environment.getExternalStorageDirectory()
                .getAbsolutePath() + APATCH_PATH;
        //3)添加patch
        mPatchManager.addPatch(patchFileString);
        Log.d(TAG, "apatch:" + patchFileString + " added.");
    } catch (IOException e) {
        Log.e(TAG, "", e);
    }
JAVA源码分析

  首先到github上把AndFix源码clone下来。按照顺序先来看com.alipay.euler.andfix.patch包下PatchManager.init()

public void init(String appVersion) {
		if (!mPatchDir.exists() && !mPatchDir.mkdirs()) {// make directory fail
			Log.e(TAG, "patch dir create error.");
			return;
		} else if (!mPatchDir.isDirectory()) {// not directory
			mPatchDir.delete();
			return;
		}
		SharedPreferences sp = mContext.getSharedPreferences(SP_NAME,
				Context.MODE_PRIVATE);
		String ver = sp.getString(SP_VERSION, null);
                //获取之前存储的版本号与当前版本号对比、如果不同清除patch,并存储当前版本号
		if (ver == null || !ver.equalsIgnoreCase(appVersion)) {
			cleanPatch();
			sp.edit().putString(SP_VERSION, appVersion).commit();
		} else {
                        //如果相同初始化patchs
			initPatchs();
		}
	}

  看初始化patchs方法PatchManager.initPatchs()

	private void initPatchs() {
        // 缓存目录data/data/package/file/apatch/会缓存补丁文件
		// 即使原目录被删除也可以打补丁
		File[] files = mPatchDir.listFiles();
		for (File file : files) {
			addPatch(file);
		}
	}

  这里可以看下mPatchDir 变量的定义 mPatchDir = new File(mContext.getFilesDir(), DIR);   是沙盒中data/data/package/file/apatch/ 目录下的文件夹目录。这一步逻辑我们可以试想肯定有patch文件会存入此目录下。 每次程序初始化加载patch文件都会从沙盒的缓存目录下读取, 而不用担心patch文件被删除。

  继续来看PatchManager.addPatch()

private Patch addPatch(File file) {
		Patch patch = null;
		if (file.getName().endsWith(SUFFIX)) {
			try {
				patch = new Patch(file);
				mPatchs.add(patch);
			} catch (IOException e) {
				Log.e(TAG, "addPatch", e);
			}
		}
		return patch;
	}

  这里逻辑比较简单,检测只要文件后缀为.apatch就加入到mPatchs数组中。至此PatchManager.initPatchs()走完了。往下走来看PatchManager.loadPatch()

public void loadPatch() {
		mLoaders.put("*", mContext.getClassLoader());// wildcard
		Set<String> patchNames;
		List<String> classes;
		for (Patch patch : mPatchs) {
			patchNames = patch.getPatchNames();
			for (String patchName : patchNames) {
				classes = patch.getClasses(patchName);
				mAndFixManager.fix(patch.getFile(), mContext.getClassLoader(),
						classes);
			}
		}
	}

  这个函数对所有的patchs进行了遍历,并取出每个patch内的class数组,然后传入AndFixManager.fix()

public synchronized void fix(File file, ClassLoader classLoader,
			List<String> classes) {
		 ......省略安全性检测相关代码
            //读取dex文件
			final DexFile dexFile = DexFile.loadDex(file.getAbsolutePath(),
					optfile.getAbsolutePath(), Context.MODE_PRIVATE);

			if (saveFingerprint) {
				mSecurityChecker.saveOptSig(optfile);
			}
            //初始化类加载器
			ClassLoader patchClassLoader = new ClassLoader(classLoader) {
				@Override
				protected Class<?> findClass(String className)
						throws ClassNotFoundException {
					Class<?> clazz = dexFile.loadClass(className, this);
					if (clazz == null
							&& className.startsWith("com.alipay.euler.andfix")) {
						return Class.forName(className);// annotation’s class
														// not found
					}
					if (clazz == null) {
						throw new ClassNotFoundException(className);
					}
					return clazz;
				}
			};
			Enumeration<String> entrys = dexFile.entries();
			Class<?> clazz = null;
            //遍历dex中条目(类名称)
			while (entrys.hasMoreElements()) {
				String entry = entrys.nextElement();
				if (classes != null && !classes.contains(entry)) {
					continue;// skip, not need fix
				}
                //load 需要fix的Class
				clazz = dexFile.loadClass(entry, patchClassLoader);
				if (clazz != null) {
                    //fix class
					fixClass(clazz, classLoader);
				}
			}
		} catch (IOException e) {
			Log.e(TAG, "pacth", e);
		}
	}

   前面都是安全性检测代码略过, 后面检测出需要fix的Class然后执行到AndFixManager.fixClass()

private void fixClass(Class<?> clazz, ClassLoader classLoader) {
		Method[] methods = clazz.getDeclaredMethods();
		MethodReplace methodReplace;
		String clz;
		String meth;
		for (Method method : methods) {
           //获取到MethodReplace注解(需要被替换的方法)
			methodReplace = method.getAnnotation(MethodReplace.class);
			if (methodReplace == null)
				continue;
           //注解的类
			clz = methodReplace.clazz();
           //需要被替换的方法
			meth = methodReplace.method();
			if (!isEmpty(clz) && !isEmpty(meth)) {
            //替换方法
				replaceMethod(classLoader, clz, meth, method);
			}
		}
	}

继续看 replaceMethod方法

private void replaceMethod(ClassLoader classLoader, String clz,
			String meth, Method method) {
		try {
			String key = clz + "@" + classLoader.toString();
			Class<?> clazz = mFixedClass.get(key);
			if (clazz == null) {// class not load
                //load 需要修复的class 
				Class<?> clzz = classLoader.loadClass(clz);
				// 初始化并且更改class 访问权限public
				clazz = AndFix.initTargetClass(clzz);
			}
			if (clazz != null) {// initialize class OK
                //放入缓存map
				mFixedClass.put(key, clazz);
               //获取原method
				Method src = clazz.getDeclaredMethod(meth,
						method.getParameterTypes());
              //进行替换操作
				AndFix.addReplaceMethod(src, method);
			}
		} catch (Exception e) {
			Log.e(TAG, "replaceMethod", e);
		}
	}

继续看AndFix.addReplaceMethod()

	public static void addReplaceMethod(Method src, Method dest) {
		try {
            //替换方法为native方法
			replaceMethod(src, dest);
            //修改类成员变量访问权限为public
			initFields(dest.getDeclaringClass());
		} catch (Throwable e) {
			Log.e(TAG, "addReplaceMethod", e);
		}
	}

private static native void replaceMethod(Method dest, Method src); replaceMethod的定义可知它为 native方法

Native层分析

NatIve源码在jni目录下 如图: 9A5C27B4-6085-4222-86B9-F68B9C3B76DC.png 来看andfix.cpp

static void replaceMethod(JNIEnv* env, jclass clazz, jobject src,
		jobject dest) {
	if (isArt) {
		art_replaceMethod(env, src, dest);
	} else {
		dalvik_replaceMethod(env, src, dest);
	}
}

根据不同的模式 art or dalvik 调用不同的方法。这里我们只看dalvik ,art 与dalvik原理都差不多。 打开dalvik文件夹下dalvik_method_replace.cpp 来看dalvik_replaceMethod ()

extern void __attribute__ ((visibility ("hidden"))) dalvik_replaceMethod(
		JNIEnv* env, jobject src, jobject dest) {
	jobject clazz = env->CallObjectMethod(dest, jClassMethod);
	ClassObject* clz = (ClassObject*) dvmDecodeIndirectRef_fnPtr(
			dvmThreadSelf_fnPtr(), clazz);
	clz->status = CLASS_INITIALIZED;
    //旧的方法(需要被替换的方法)
	Method* meth = (Method*) env->FromReflectedMethod(src);
    //新的方法
	Method* target = (Method*) env->FromReflectedMethod(dest);
	LOGD("dalvikMethod: %s", meth->name);

//	meth->clazz = target->clazz;
    //旧的方法访问权限设置为public
	meth->accessFlags |= ACC_PUBLIC;
	meth->methodIndex = target->methodIndex;
	meth->jniArgInfo = target->jniArgInfo;
	meth->registersSize = target->registersSize;
	meth->outsSize = target->outsSize;
	meth->insSize = target->insSize;
	meth->prototype = target->prototype;
    //替换方法信息
	meth->insns = target->insns;
    //旧的方法设置为native
	meth->nativeFunc = target->nativeFunc;
}
总结

AndFix热补丁原理就是在native动态替换方法java层的代码,通过native层hook java层的代码。

Search

    Table of Contents