編輯:關於Android編程
AndFix的原理就是通過c++指針進行方法的替換,把有bug的方法替換成補丁文件中的方法。
vczmu7tidWe3vbeoo6zS0bTvtb3Q3ri0YnVntcTEv7XEoaM8L3A+DQo8cD7KudPDQW5kRml40N64tMjI0N64tLXE1fvM5cH3s8yjujwvcD4NCjxwPjxpbWcgYWx0PQ=="這裡寫圖片描述" src="/uploadfile/Collfiles/20160602/20160602090922236.png" title="\" />
方法替換過程:
解析源碼從使用的方法一一解析。
PatchManager mPatchManager = new PatchManager();
直接實例化了一個PatchManger實例對象,接下看PatchManager類源碼:
public PatchManager(Context context) {
mContext = context;
mAndFixManager = new AndFixManager(mContext);//初始化AndFixManager
mPatchDir = new File(mContext.getFilesDir(), DIR);//初始化存放patch補丁文件的文件夾
mPatchs = new ConcurrentSkipListSet();//初始化存在Patch類的集合,此類適合大並發
mLoaders = new ConcurrentHashMap();//初始化存放類對應的類加載器集合
}
後看AndFixManager的初始化:
public AndFixManager(Context context) {
mContext = context;
mSupport = Compat.isSupport();//判斷Android機型是否適支持AndFix
if (mSupport) {
mSecurityChecker = new SecurityChecker(mContext);//初始化簽名判斷類
mOptDir = new File(mContext.getFilesDir(), DIR);//初始化patch文件存放的文件夾
if (!mOptDir.exists() && !mOptDir.mkdirs()) {// make directory fail
mSupport = false;
Log.e(TAG, "opt dir create error.");
} else if (!mOptDir.isDirectory()) {// not directory
mOptDir.delete();//如果不是文件目錄就刪除
mSupport = false;
}
}
}
public static synchronized boolean isSupport() {//此處加了同步鎖機制
if (isChecked)
return isSupport;
isChecked = true;
// not support alibaba's YunOs
boolean isYunOs = isYunOS();//判斷系統是否是YunOs系統,YunOs系統是阿裡巴巴的系統
boolean setup =AndFix.setup();//判斷是Dalvik還是Art虛擬機,來注冊Native方法
boolean isSupportSDKVersion = isSupportSDKVersion();//根據sdk版本判斷是否支持
if (!isYunOs && setup && isSupportSDKVersion) {//根據上面三個boolean值判斷是否支持
isSupport = true;
}
if (inBlackList()) {
isSupport = false;
}
return isSupport;
}
private static boolean isSupportSDKVersion() {
if (android.os.Build.VERSION.SDK_INT >= 8
&& android.os.Build.VERSION.SDK_INT <= 23) {
return true;
}
return false;
}
public static boolean setup() {
try {
final String vmVersion = System.getProperty("java.vm.version");
boolean isArt = vmVersion != null && vmVersion.startsWith("2");
int apilevel = Build.VERSION.SDK_INT;
return setup(isArt, apilevel);
} catch (Exception e) {
Log.e(TAG, "setup", e);
return false;
}
}
//簽名機制的初始化過程
public SecurityChecker(Context context) {
mContext = context;
init(mContext);
}
//主要是獲取當前應用的簽名及其他信息,為了判斷與patch文件的簽名是否一致
private void init(Context context) {
try {
PackageManager pm = context.getPackageManager();
String packageName = context.getPackageName();
PackageInfo packageInfo = pm.getPackageInfo(packageName,
PackageManager.GET_SIGNATURES);
CertificateFactory certFactory = CertificateFactory
.getInstance("X.509");
ByteArrayInputStream stream = new ByteArrayInputStream(
packageInfo.signatures[0].toByteArray());
X509Certificate cert = (X509Certificate) certFactory
.generateCertificate(stream);
mDebuggable = cert.getSubjectX500Principal().equals(DEBUG_DN);
mPublicKey = cert.getPublicKey();
} catch (NameNotFoundException e) {
Log.e(TAG, "init", e);
} catch (CertificateException e) {
Log.e(TAG, "init", e);
}
}
接下,看一下版本的初始化:
mPatchManager.init("version")
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);//存儲關於patch文件的信息
//根據你傳入的版本號和之前的對比,做不同的處理
String ver = sp.getString(SP_VERSION, null);
if (ver == null || !ver.equalsIgnoreCase(appVersion)) {
cleanPatch();//刪除本地patch文件
sp.edit().putString(SP_VERSION, appVersion).commit();//並把傳入的版本號保存
} else {
initPatchs();//初始化patch列表,把本地的patch文件加載到內存
}
}
private void cleanPatch() {
File[] files = mPatchDir.listFiles();
for (File file : files) {
mAndFixManager.removeOptFile(file);//刪除所有的本地緩存patch文件
if (!FileUtil.deleteFile(file)) {
Log.e(TAG, file.getName() + " delete error.");
}
}
}
private void initPatchs() {
File[] files = mPatchDir.listFiles();
for (File file : files) {
addPatch(file);//加載Patch文件
}
}
private Patch addPatch(File file) {
Patch patch = null;
if (file.getName().endsWith(SUFFIX)) {
try {
patch = new Patch(file);//實例化Patch對象
mPatchs.add(patch);//把patch實例存儲到內存的集合中,在PatchManager實例化集合
} catch (IOException e) {
Log.e(TAG, "addPatch", e);
}
}
return patch;
}
Patch文件的加載
public Patch(File file) throws IOException {
mFile = file;
init();
}
@SuppressWarnings("deprecation")
private void init() throws IOException {
JarFile jarFile = null;
InputStream inputStream = null;
try {
jarFile = new JarFile(mFile);//使用JarFile讀取Patch文件
JarEntry entry = jarFile.getJarEntry(ENTRY_NAME);//獲取META-INF/PATCH.MF文件
inputStream = jarFile.getInputStream(entry);
Manifest manifest = new Manifest(inputStream);
Attributes main = manifest.getMainAttributes();
mName = main.getValue(PATCH_NAME);//獲取PATCH.MF屬性Patch-Name
mTime = new Date(main.getValue(CREATED_TIME));//獲取PATCH.MF屬性Created-Time
mClassesMap = new HashMap>();
Attributes.Name attrName;
String name;
List strings;
for (Iterator it = main.keySet().iterator(); it.hasNext();) {
attrName = (Attributes.Name) it.next();
name = attrName.toString();
//判斷name的後綴是否是-Classes,並把name對應的值加入到集合中,對應的值就是class類名的列表
if (name.endsWith(CLASSES)) {
strings = Arrays.asList(main.getValue(attrName).split(","));
if (name.equalsIgnoreCase(PATCH_CLASSES)) {
mClassesMap.put(mName, strings);
} else {
mClassesMap.put(
name.trim().substring(0, name.length() - 8),// remove
// "-Classes"
strings);
}
}
}
} finally {
if (jarFile != null) {
jarFile.close();
}
if (inputStream != null) {
inputStream.close();
}
}
}
public synchronized void fix(File file, ClassLoader classLoader,
List classes) {
if (!mSupport) {
return;
}
//判斷patch文件的簽名
if (!mSecurityChecker.verifyApk(file)) {// security check fail
return;
}
try {
File optfile = new File(mOptDir, file.getName());
boolean saveFingerprint = true;
if (optfile.exists()) {
// need to verify fingerprint when the optimize file exist,
// prevent someone attack on jailbreak device with
// Vulnerability-Parasyte.
// btw:exaggerated android Vulnerability-Parasyte
// http://secauo.com/Exaggerated-Android-Vulnerability-Parasyte.html
if (mSecurityChecker.verifyOpt(optfile)) {
saveFingerprint = false;
} else if (!optfile.delete()) {
return;
}
}
//加載patch文件中的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 {//重寫ClasLoader的findClass方法
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 entrys = dexFile.entries();
Class clazz = null;
while (entrys.hasMoreElements()) {
String entry = entrys.nextElement();
if (classes != null && !classes.contains(entry)) {
continue;// skip, not need fix
}
clazz = dexFile.loadClass(entry, patchClassLoader);//獲取有bug的類文件
if (clazz != null) {
fixClass(clazz, classLoader);// next code
}
}
} catch (IOException e) {
Log.e(TAG, "pacth", e);
}
}
private void fixClass(Class clazz, ClassLoader classLoader) {
Method[] methods = clazz.getDeclaredMethods();
MethodReplace methodReplace;
String clz;
String meth;
for (Method method : methods) {
//獲取此方法的注解,因為有bug的方法在生成的patch的類中的方法都是有注解的,下面會給圖進行展示
methodReplace = method.getAnnotation(MethodReplace.class);
if (methodReplace == null)
continue;
clz = methodReplace.clazz();//獲取注解中clazz的值
meth = methodReplace.method();//獲取注解中method的值
if (!isEmpty(clz) && !isEmpty(meth)) {
replaceMethod(classLoader, clz, meth, method);//next code
}
}
}
private void replaceMethod(ClassLoader classLoader, String clz,
String meth, Method method) {
try {
String key = clz + "@" + classLoader.toString();
Class clazz = mFixedClass.get(key);//判斷此類是否被fix
if (clazz == null) {// class not load
Class clzz = classLoader.loadClass(clz);
// initialize target class
clazz = AndFix.initTargetClass(clzz);//初始化class
}
if (clazz != null) {// initialize class OK
mFixedClass.put(key, clazz);
Method src = clazz.getDeclaredMethod(meth,
method.getParameterTypes());//根據反射獲取到有bug的類的方法(有bug的apk)
AndFix.addReplaceMethod(src, method);//src是有bug的方法,method是補丁方法
}
} catch (Exception e) {
Log.e(TAG, "replaceMethod", e);
}
}
public static void addReplaceMethod(Method src, Method dest) {
try {
replaceMethod(src, dest);//調用了native方法,next code
initFields(dest.getDeclaringClass());
} catch (Throwable e) {
Log.e(TAG, "addReplaceMethod", e);
}
}
private static native void replaceMethod(Method dest, Method src);
由於Android4.4後才用的Art虛擬機,之前的系統都是Dalvik虛擬機,因此Natice層寫了2個方法,對不同的系統做不同的處理方式。
extern void dalvik_replaceMethod(JNIEnv* env, jobject src, jobject dest);//Dalvik
extern void art_replaceMethod(JNIEnv* env, jobject src, jobject dest);//Art
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->jniArgInfo = 0x80000000;
meth->accessFlags |= ACC_NATIVE;//把Method的屬性設置成Native方法
int argsSize = dvmComputeMethodArgsSize_fnPtr(meth);
if (!dvmIsStaticMethod(meth))
argsSize++;
meth->registersSize = meth->insSize = argsSize;
meth->insns = (void*) target;
meth->nativeFunc = dalvik_dispatcher;//把方法的實現替換成native方法
}
//不同的art系統版本不同處理也不同
extern void __attribute__ ((visibility ("hidden"))) art_replaceMethod(
JNIEnv* env, jobject src, jobject dest) {
if (apilevel > 22) {
replace_6_0(env, src, dest);
} else if (apilevel > 21) {
replace_5_1(env, src, dest);
} else {
replace_5_0(env, src, dest);
}
}
//以5.0為例:
void replace_5_0(JNIEnv* env, jobject src, jobject dest) {
art::mirror::ArtMethod* smeth =
(art::mirror::ArtMethod*) env->FromReflectedMethod(src);
art::mirror::ArtMethod* dmeth =
(art::mirror::ArtMethod*) env->FromReflectedMethod(dest);
dmeth->declaring_class_->class_loader_ =
smeth->declaring_class_->class_loader_; //for plugin classloader
dmeth->declaring_class_->clinit_thread_id_ =
smeth->declaring_class_->clinit_thread_id_;
dmeth->declaring_class_->status_ = (void *)((int)smeth->declaring_class_->status_-1);
//把一些參數的指針給補丁方法
smeth->declaring_class_ = dmeth->declaring_class_;
smeth->access_flags_ = dmeth->access_flags_;
smeth->frame_size_in_bytes_ = dmeth->frame_size_in_bytes_;
smeth->dex_cache_initialized_static_storage_ =
dmeth->dex_cache_initialized_static_storage_;
smeth->dex_cache_resolved_types_ = dmeth->dex_cache_resolved_types_;
smeth->dex_cache_resolved_methods_ = dmeth->dex_cache_resolved_methods_;
smeth->vmap_table_ = dmeth->vmap_table_;
smeth->core_spill_mask_ = dmeth->core_spill_mask_;
smeth->fp_spill_mask_ = dmeth->fp_spill_mask_;
smeth->mapping_table_ = dmeth->mapping_table_;
smeth->code_item_offset_ = dmeth->code_item_offset_;
smeth->entry_point_from_compiled_code_ =
dmeth->entry_point_from_compiled_code_;
smeth->entry_point_from_interpreter_ = dmeth->entry_point_from_interpreter_;
smeth->native_method_ = dmeth->native_method_;//把補丁方法替換掉
smeth->method_index_ = dmeth->method_index_;
smeth->method_dex_index_ = dmeth->method_dex_index_;
LOGD("replace_5_0: %d , %d", smeth->entry_point_from_compiled_code_,
dmeth->entry_point_from_compiled_code_);
}
mPatchManager.addPatch(path)
源碼:
public void addPatch(String path) throws IOException {
File src = new File(path);
File dest = new File(mPatchDir, src.getName());
if (!src.exists()) {
throw new FileNotFoundException(path);
}
if (dest.exists()) {
Log.d(TAG, "patch [" + path + "] has be loaded.");
return;
}
FileUtil.copyFile(src, dest);// copy to patch's directory
Patch patch = addPatch(dest);//同loadPatch中的addPatch一樣的操作
if (patch != null) {
loadPatch(patch);//加載pach,同上loadPatch
}
}
mPatchManager.removeAllPatch();
源碼:
public void removeAllPatch() {
cleanPatch();//刪除本地緩存的patch文件列表
SharedPreferences sp = mContext.getSharedPreferences(SP_NAME,
Context.MODE_PRIVATE);
sp.edit().clear().commit();//把關於patch的數據進行清空
}
到此源代碼就解析結束。
patch文件中.dex文件反編譯後,看到源碼效果如下:
紅框標注的部分,就是補丁方法。方法的注解部分寫了clazz和method的值,對應著apk包中的類名和方法名稱。
首先看一張國內Top500 Android應用中它們用到的第三方推送以及所占數量:現在總結下Android平台下幾種推送方案的基本情況以及優缺點:一、使用GCM(Goog
背景Vulkan為Khronos Group推出的下一代跨平台圖形開發接口,用於替代歷史悠久的OpenGL。Android從7.0(Nougat)開始加入了對其的支持。V
Notification是顯示在手機狀態欄的通知,Notification通知是具有全局性的通知,一般通過NotificationManager來進行管理.一般運用Not
大家在平時使用 Android 手機的時候,都會發現有些應用(例如 qq,微信,淘寶)為自己創建了賬號系統,並且能夠在設置頁面看到他,可是當自