麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁 > 學院 > 開發設計 > 正文

插件化開發---DroidPlugin對Servie的管理

2019-11-09 17:25:00
字體:
來源:轉載
供稿:網友

Service分為兩種形式:以startService啟動的服務和用bindService綁定的服務;由于這兩個過程大體相似,這里以稍復雜的bindService為例分析Service組件的工作原理。

綁定Service的過程是通過Context類的bindService完成的,這個方法需要三個參數:第一個參數代表想要綁定的Service的Intent,第二個參數是一個ServiceConnetion,我們可以通過這個對象接收到Service綁定成功或者失敗的回調;第三個參數則是綁定時候的一些FLAG

Context的具體實現在ContextImpl類,ContextImpl中的bindService方法直接調用了bindServiceCommon方法,此方法源碼如下:

/** @hide */ @Override public boolean bindServiceAsUser(Intent service, ServiceConnection conn, int flags, UserHandle user) { return bindServiceCommon(service, conn, flags, user); } PRivate boolean bindServiceCommon(Intent service, ServiceConnection conn, int flags, UserHandle user) { IServiceConnection sd; if (conn == null) { throw new IllegalArgumentException("connection is null"); } if (mPackageInfo != null) { sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), mMainThread.getHandler(), flags); } else { throw new RuntimeException("Not supported in system context"); } validateServiceIntent(service); try { IBinder token = getActivityToken(); if (token == null && (flags&BIND_AUTO_CREATE) == 0 && mPackageInfo != null && mPackageInfo.getapplicationInfo().targetSdkVersion < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) { flags |= BIND_WAIVE_PRIORITY; } service.prepareToLeaveProcess(); int res = ActivityManagerNative.getDefault().bindService( mMainThread.getApplicationThread(), getActivityToken(), service, service.resolveTypeIfNeeded(getContentResolver()), sd, flags, user.getIdentifier()); if (res < 0) { throw new SecurityException( "Not allowed to bind to service " + service); } return res != 0; } catch (RemoteException e) { return false; } }

大致觀察就能發現這個方法最終通過ActivityManagerNative借助AMS進而完成Service的綁定過程,在跟蹤AMS的bindService源碼之前,我們關注一下這個方法開始處創建的sd變量。這個變量的類型是IServiceConnection,如果讀者還有印象,我們在 廣播的管理 一文中也遇到過類似的處理方式——IIntentReceiver;所以,這個IServiceConnection與IApplicationThread以及IIntentReceiver相同,都是ActivityThread給AMS提供的用來與之進行通信的Binder對象;這個接口的實現類為LoadedApk.ServiceDispatcher。

bindService這個方法相當簡單,只是做了一些參數校檢之后直接調用了ActivityServices類的bindServiceLocked方法:

int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service, String resolvedType, IServiceConnection connection, int flags, String callingPackage, int userId) throws TransactionTooLargeException { final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller); // 參數校檢,略 ServiceLookupResult res = retrieveServiceLocked(service, resolvedType, callingPackage, Binder.getCallingPid(), Binder.getCallingUid(), userId, true, callerFg); // 結果校檢, 略 ServiceRecord s = res.record; final long origId = Binder.clearCallingIdentity(); try { // ... 不關心, 略 mAm.startAssociationLocked(callerApp.uid, callerApp.processName, s.appInfo.uid, s.name, s.processName); AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp); ConnectionRecord c = new ConnectionRecord(b, activity, connection, flags, clientLabel, clientIntent); IBinder binder = connection.asBinder(); ArrayList<ConnectionRecord> clist = s.connections.get(binder); // 對connection進行處理, 方便存取,略 clist.add(c); if ((flags&Context.BIND_AUTO_CREATE) != 0) { s.lastActivity = SystemClock.uptimeMillis(); if (bringUpServiceLocked(s, service.getFlags(), callerFg, false) != null) { return 0; } } // 與BIND_AUTO_CREATE不同的啟動FLAG,原理與后續相同,略 } finally { Binder.restoreCallingIdentity(origId); } return 1;}

這個方法比較長,我這里省去了很多無關代碼,只列出關鍵邏輯;首先它通過retrieveServiceLocked方法獲取到了intent匹配到的需要bind到的Service組件res;然后把ActivityThread傳遞過來的IServiceConnection使用ConnectionRecord進行了包裝,方便接下來使用;最后如果啟動的FLAG為BIND_AUTO_CREATE,那么調用bringUpServiceLocked開始創建Service,

在bringUpServiceLocked方法中進行判斷,如果Service所在的進程已經啟動,那么直接調用realStartServiceLocked方法來真正啟動Service組件;如果Service所在的進程還沒有啟動,那么先在AMS中記下這個要啟動的Service組件,然后通過startProcessLocked啟動新的進程。

我們先看Service進程已經啟動的情況,也即realStartServiceLocked分支:

private final void realStartServiceLocked(ServiceRecord r, ProcessRecord app, boolean execInFg) throws RemoteException { // 略。。 boolean created = false; try { synchronized (r.stats.getBatteryStats()) { r.stats.startLaunchedLocked(); } mAm.ensurePackageDexOpt(r.serviceInfo.packageName); app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE); app.thread.scheduleCreateService(r, r.serviceInfo, mAm.compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo), app.repProcState); r.postNotification(); created = true; } catch (DeadObjectException e) { mAm.appDiedLocked(app); throw e; } finally { // 略。。 } requestServiceBindingsLocked(r, execInFg); // 不關心,略。。}

這個方法首先調用了app.thread的scheduleCreateService方法,我們知道,這是一個IApplicationThread對象,它是App所在進程提供給AMS的用來與App進程進行通信的Binder對象,這個Binder的Server端在ActivityThread的ApplicationThread類,因此,我們跟蹤ActivityThread類,這個方法的實現如下:

public final void scheduleCreateService(IBinder token, ServiceInfo info, CompatibilityInfo compatInfo, int processState) { updateProcessState(processState, false); CreateServiceData s = new CreateServiceData(); s.token = token; s.info = info; s.compatInfo = compatInfo; sendMessage(H.CREATE_SERVICE, s);}

它不過是轉發了一個消息給ActivityThread的H這個Handler,H類收到這個消息之后,直接調用了ActivityThread類的handleCreateService方法,如下:

private void handleCreateService(CreateServiceData data) { unscheduleGcIdler(); LoadedApk packageInfo = getPackageInfoNoCheck( data.info.applicationInfo, data.compatInfo); Service service = null; try { java.lang.ClassLoader cl = packageInfo.getClassLoader(); service = (Service) cl.loadClass(data.info.name).newInstance(); } catch (Exception e) { } try { ContextImpl context = ContextImpl.createAppContext(this, packageInfo); context.setOuterContext(service); Application app = packageInfo.makeApplication(false, mInstrumentation); service.attach(context, this, data.info.name, data.token, app, ActivityManagerNative.getDefault()); service.onCreate(); mServices.put(data.token, service); try { ActivityManagerNative.getDefault().serviceDoneExecuting( data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0); } catch (RemoteException e) { // nothing to do. } } catch (Exception e) { }}

看到這段代碼,是不是似曾相識?!沒錯,這里與Activity組件的創建過程如出一轍!所以這里就不贅述了,可以參閱 Activity生命周期管理。

需要注意的是,這里Service類的創建過程與Activity是略微有點不同的,雖然都是通過ClassLoader通過反射創建,但是Activity卻把創建過程委托給了Instrumentation類,而Service則是直接進行。 OK,現在ActivityThread里面的handleCreateService方法成功創建出了Service對象,并且調用了它的onCreate方法;到這里我們的Service已經啟動成功。scheduleCreateService這個Binder調用過程結束,代碼又回到了AMS進程的realStartServiceLocked方法

app.thread.scheduleCreateService(r, r.serviceInfo, mAm.compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo), app.repProcState);............ requestServiceBindingsLocked(r, execInFg);

這個方法在完成scheduleCreateService這個binder調用之后,執行了一個requestServiceBindingsLocked方法;看方法名好像于「綁定服務」有關,它簡單地執行了一個遍歷然后調用了另外一個方法:

private final boolean requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i, boolean execInFg, boolean rebind) throws TransactionTooLargeException { if (r.app == null || r.app.thread == null) { return false; } if ((!i.requested || rebind) && i.apps.size() > 0) { try { bumpServiceExecutingLocked(r, execInFg, "bind"); r.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE); r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind, r.app.repProcState); // 不關心,略。。 } return true;}

可以看到,這里又通過IApplicationThread這個Binder進行了一次ipC調用,我們跟蹤ActivityThread類里面的ApplicationThread的scheduleBindService方法,發現這個方法不過通過Handler轉發了一次消息,真正的處理代碼在handleBindService里面:

rivate void handleBindService(BindServiceData data) { Service s = mServices.get(data.token); if (s != null) { try { data.intent.setExtrasClassLoader(s.getClassLoader()); data.intent.prepareToEnterProcess(); try { if (!data.rebind) { IBinder binder = s.onBind(data.intent); ActivityManagerNative.getDefault().publishService( data.token, data.intent, binder); } else { s.onRebind(data.intent); ActivityManagerNative.getDefault().serviceDoneExecuting( data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0); } ensureJitEnabled(); } catch (RemoteException ex) { } } catch (Exception e) { } }}

我們要Bind的Service終于在這里完成了綁定!綁定之后又通過ActivityManagerNative這個Binder進行一次IPC調用,我們查看AMS的publishService方法,這個方法簡單第調用了publishServiceLocked方法,源碼如下:

void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) { final long origId = Binder.clearCallingIdentity(); try { if (r != null) { Intent.FilterComparison filter = new Intent.FilterComparison(intent); IntentBindRecord b = r.bindings.get(filter); if (b != null && !b.received) { b.binder = service; b.requested = true; b.received = true; for (int conni=r.connections.size()-1; conni>=0; conni--) { ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni); for (int i=0; i<clist.size(); i++) { ConnectionRecord c = clist.get(i); if (!filter.equals(c.binding.intent.intent)) { continue; } try { c.conn.connected(r.name, service); } catch (Exception e) { } } } } serviceDoneExecutingLocked(r, mDestroyingServices.contains(r), false); } } finally { Binder.restoreCallingIdentity(origId); }}

還記得我們之前提到的那個IServiceConnection嗎?在bindServiceLocked方法里面,我們把這個IServiceConnection放到了一個ConnectionRecord的List中存放在ServiceRecord里面,這里所做的就是取出已經被Bind的這個Service對應的IServiceConnection對象,然后調用它的connected方法;我們說過,這個IServiceConnection也是一個Binder對象,它的Server端在LoadedApk.ServiceDispatcher里面。

最后提一點,以上我們分析了Service所在進程已經存在的情況,如果Service所在進程不存在,那么會調用startProcessLocked方法創建一個新的進程,并把需要啟動的Service放在一個隊列里面;創建進程的過程通過Zygote fork出來,進程創建成功之后會調用ActivityThread的main方法,在這個main方法里面間接調用到了AMS的attachApplication方法,在AMS的attachApplication里面會檢查剛剛那個待啟動Service隊列里面的內容,并執行Service的啟動操作;之后的啟動過程與進程已經存在的情況下相同;可以自行分析。

Service的插件化思路 可以注冊一個真正的Service組件ProxyService,讓這個ProxyService承載一個真正的Service組件所具備的能力(進程優先級等);當啟動插件的服務比如PluginService的時候,我們統一啟動這個ProxyService,當這個ProxyService運行起來之后,再在它的onStartCommand等方法里面進行分發,執行PluginService的onStartCommond等對應的方法;我們把這種方案形象地稱為「代理分發技術」

注冊代理Service 我們需要一個貨真價實的Service組件來承載進程優先級等功能,因此需要在AndroidManifest.xml中聲明一個或者多個(用以支持多進程)這樣的Sevice:

<service android:name="com.weishu.upf.service_management.app.ProxyService" android:process="plugin01"/>

加載Service 我們可以在ProxyService里面把任務轉發給真正要啟動的插件Service組件,要完成這個過程肯定需要創建一個對應的插件Service對象,比如PluginService;但是通常情況下插件存在與單獨的文件之中,正常的方式是無法創建這個PluginService對象的,宿主程序默認的ClassLoader無法加載插件中對應的這個類;所以,要創建這個對應的PluginService對象,必須先完成插件的加載過程,讓這個插件中的所有類都可以被正常訪問;

public static void patchClassLoader(ClassLoader cl, File apkFile, File optDexFile) throws IllegalaccessException, NoSuchMethodException, IOException, InvocationTargetException, InstantiationException, NoSuchFieldException { // 獲取 BaseDexClassLoader : pathList Field pathListField = DexClassLoader.class.getSuperclass().getDeclaredField("pathList"); pathListField.setAccessible(true); Object pathListObj = pathListField.get(cl); // 獲取 PathList: Element[] dexElements Field dexElementArray = pathListObj.getClass().getDeclaredField("dexElements"); dexElementArray.setAccessible(true); Object[] dexElements = (Object[]) dexElementArray.get(pathListObj); // Element 類型 Class<?> elementClass = dexElements.getClass().getComponentType(); // 創建一個數組, 用來替換原始的數組 Object[] newElements = (Object[]) Array.newInstance(elementClass, dexElements.length + 1); // 構造插件Element(File file, boolean isDirectory, File zip, DexFile dexFile) 這個構造函數 Constructor<?> constructor = elementClass.getConstructor(File.class, boolean.class, File.class, DexFile.class); Object o = constructor.newInstance(apkFile, false, apkFile, DexFile.loadDex(apkFile.getCanonicalPath(), optDexFile.getAbsolutePath(), 0)); Object[] toAddElementArray = new Object[] { o }; // 把原始的elements復制進去 System.arraycopy(dexElements, 0, newElements, 0, dexElements.length); // 插件的那個element復制進去 System.arraycopy(toAddElementArray, 0, newElements, dexElements.length, toAddElementArray.length); // 替換 dexElementArray.set(pathListObj, newElements);} /** * 解析Apk文件中的 <service>, 并存儲起來 * 主要是調用PackageParser類的generateServiceInfo方法 * @param apkFile 插件對應的apk文件 * @throws Exception 解析出錯或者反射調用出錯, 均會拋出異常 */ public void preLoadServices(File apkFile) throws Exception { Class<?> packageParserClass = Class.forName("android.content.pm.PackageParser"); Method parsePackageMethod = packageParserClass.getDeclaredMethod("parsePackage", File.class, int.class); Object packageParser = packageParserClass.newInstance(); // 首先調用parsePackage獲取到apk對象對應的Package對象 Object packageObj = parsePackageMethod.invoke(packageParser, apkFile, PackageManager.GET_SERVICES); // 讀取Package對象里面的services字段 // 接下來要做的就是根據這個List<Service> 獲取到Service對應的ServiceInfo Field servicesField = packageObj.getClass().getDeclaredField("services"); List services = (List) servicesField.get(packageObj); // 調用generateServiceInfo 方法, 把PackageParser.Service轉換成ServiceInfo Class<?> packageParser$ServiceClass = Class.forName("android.content.pm.PackageParser$Service"); Class<?> packageUserStateClass = Class.forName("android.content.pm.PackageUserState"); Class<?> userHandler = Class.forName("android.os.UserHandle"); Method getCallingUserIdMethod = userHandler.getDeclaredMethod("getCallingUserId"); int userId = (Integer) getCallingUserIdMethod.invoke(null); Object defaultUserState = packageUserStateClass.newInstance(); // 需要調用 android.content.pm.PackageParser#generateActivityInfo(android.content.pm.ActivityInfo, int, android.content.pm.PackageUserState, int) Method generateReceiverInfo = packageParserClass.getDeclaredMethod("generateServiceInfo", packageParser$ServiceClass, int.class, packageUserStateClass, int.class); // 解析出intent對應的Service組件 for (Object service : services) { ServiceInfo info = (ServiceInfo) generateReceiverInfo.invoke(packageParser, service, 0, defaultUserState, userId); mServiceInfoMap.put(new ComponentName(info.packageName, info.name), info); } }

攔截startService等調用過程 要手動控制Service組件的生命周期,需要攔截startService,stopService等調用,并且把啟動插件Service全部重定向為啟動ProxyService(保留原始插件Service信息);這個攔截過程需要Hook ActvityManagerNative,我們對這種技術應該是輕車熟路了

public static void hookActivityManagerNative() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, NoSuchFieldException { Class<?> activityManagerNativeClass = Class.forName("android.app.ActivityManagerNative"); Field gDefaultField = activityManagerNativeClass.getDeclaredField("gDefault"); gDefaultField.setAccessible(true); Object gDefault = gDefaultField.get(null); // gDefault是一個 android.util.Singleton對象; 我們取出這個單例里面的字段 Class<?> singleton = Class.forName("android.util.Singleton"); Field mInstanceField = singleton.getDeclaredField("mInstance"); mInstanceField.setAccessible(true); // ActivityManagerNative 的gDefault對象里面原始的 IActivityManager對象 Object rawIActivityManager = mInstanceField.get(gDefault); // 創建一個這個對象的代理對象, 然后替換這個字段, 讓我們的代理對象幫忙干活 Class<?> iActivityManagerInterface = Class.forName("android.app.IActivityManager"); Object proxy = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[] { iActivityManagerInterface }, new IActivityManagerHandler(rawIActivityManager)); mInstanceField.set(gDefault, proxy);}

我們在收到startService,stopService之后可以進行具體的操作,對于startService來說,就是直接替換啟動的插件Service為ProxyService等待后續處理,

if ("startService".equals(method.getName())) { // API 23: // public ComponentName startService(IApplicationThread caller, Intent service, // String resolvedType, int userId) throws RemoteException // 找到參數里面的第一個Intent 對象 Pair<Integer, Intent> integerIntentPair = foundFirstIntentOfArgs(args); Intent newIntent = new Intent(); // 代理Service的包名, 也就是我們自己的包名 String stubPackage = UPFApplication.getContext().getPackageName(); // 這里我們把啟動的Service替換為ProxyService, 讓ProxyService接收生命周期回調 ComponentName componentName = new ComponentName(stubPackage, ProxyService.class.getName()); newIntent.setComponent(componentName); // 把我們原始要啟動的TargetService先存起來 newIntent.putExtra(AMSHookHelper.EXTRA_TARGET_INTENT, integerIntentPair.second); // 替換掉Intent, 達到欺騙AMS的目的 args[integerIntentPair.first] = newIntent; Log.v(TAG, "hook method startService success"); return method.invoke(mBase, args);}

分發Service Hook ActivityManagerNative之后,所有的插件Service的啟動都被重定向了到了我們注冊的ProxyService,這樣可以保證我們的插件Service有一個真正的Service組件作為宿主;但是要執行特定插件Service的任務,我們必須把這個任務分發到真正要啟動的Service上去;以onStart為例,在啟動ProxyService之后,會收到ProxyService的onStart回調,我們可以在這個方法里面把具體的任務交給原始要啟動的插件Service組件:

@Override public void onStart(Intent intent, int startId) { Log.d(TAG, "onStart() called with " + "intent = [" + intent + "], startId = [" + startId + "]"); // 分發Service ServiceManager.getInstance().onStart(intent, startId); super.onStart(intent, startId); }

匹配過程 上文中我們把啟動插件Service重定向為啟動ProxyService,現在ProxyService已經啟動,因此必須把控制權交回原始的PluginService;在加載插件的時候,我們存儲了插件中所有的Service組件的信息,因此,只需要根據Intent里面的Component信息就可以取出對應的PluginService。

private ServiceInfo selectPluginService(Intent pluginIntent) { for (ComponentName componentName : mServiceInfoMap.keySet()) { if (componentName.equals(pluginIntent.getComponent())) { return mServiceInfoMap.get(componentName); } } return null;}

創建以及分發 可以看到,系統也是通過反射創建出了對應的Service對象,然后也創建了對應的Context,并給Service注入了活力。如果我們模擬系統創建Context這個過程,勢必需要進行一系列反射調用,那么我們何不直接反射handleCreateService方法呢?

現在我們已經創建出了對應的PluginService,并且擁有至關重要的Context對象;接下來就可以把消息分發給原始的PluginService組件了,這個分發的過程很簡單,直接執行消息對應的回調(onStart, onDestroy等)即可;因此,完整的startService分發過程如下:

public void onStart(Intent proxyIntent, int startId) { Intent targetIntent = proxyIntent.getParcelableExtra(AMSHookHelper.EXTRA_TARGET_INTENT); ServiceInfo serviceInfo = selectPluginService(targetIntent); if (serviceInfo == null) { Log.w(TAG, "can not found service : " + targetIntent.getComponent()); return; } try { if (!mServiceMap.containsKey(serviceInfo.name)) { // service還不存在, 先創建 proxyCreateService(serviceInfo); } Service service = mServiceMap.get(serviceInfo.name); service.onStart(targetIntent, startId); } catch (Exception e) { e.printStackTrace(); }}

、、、、、、、、、、、、、、、、、、、、、代碼區、、、、、、、、、、、、、、、、、、、、、、、 這里寫圖片描述

配置文件

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.weishu.upf.service_management.app"> <application android:allowBackup="true" android:name="com.weishu.upf.service_management.app.UPFApplication" android:label="@string/app_name" android:icon="@mipmap/ic_launcher"> <activity android:name="com.weishu.upf.service_management.app.MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> <service android:name="com.weishu.upf.service_management.app.ProxyService" android:process="plugin01"/> </application></manifest>

UPFApplication

package com.weishu.upf.service_management.app;import java.io.File;import android.app.Application;import android.content.Context;import com.weishu.upf.service_management.app.hook.AMSHookHelper;import com.weishu.upf.service_management.app.hook.BaseDexClassLoaderHookHelper;/** * 這個類只是為了方便獲取全局Context的. */public class UPFApplication extends Application { private static Context sContext; @Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); sContext = base; try { // 攔截startService, stopService等操作 AMSHookHelper.hookActivityManagerNative(); Utils.extractAssets(base, "test.jar"); File apkFile = getFileStreamPath("test.jar"); File odexFile = getFileStreamPath("test.odex"); // Hook ClassLoader, 讓插件中的類能夠被成功加載 BaseDexClassLoaderHookHelper.patchClassLoader(getClassLoader(), apkFile, odexFile); // 解析插件中的Service組件 ServiceManager.getInstance().preLoadServices(apkFile); } catch (Exception e) { throw new RuntimeException("hook failed"); } } public static Context getContext() { return sContext; }}

AMSHookHelper.hookActivityManagerNative(); AMSHookHelper

package com.weishu.upf.service_management.app.hook;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Proxy;public class AMSHookHelper { public static final String EXTRA_TARGET_INTENT = "extra_target_intent"; /** * Hook AMS * <p/> * 主要完成的操作是 "把真正要啟動的Activity臨時替換為在AndroidManifest.xml中聲明的替身Activity" * <p/> * 進而騙過AMS * * @throws ClassNotFoundException * @throws NoSuchMethodException * @throws InvocationTargetException * @throws IllegalAccessException * @throws NoSuchFieldException */ public static void hookActivityManagerNative() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, NoSuchFieldException { // 17package android.util; // 18 // 19/** // 20 * Singleton helper class for lazily initialization. // 21 * // 22 * Modeled after frameworks/base/include/utils/Singleton.h // 23 * // 24 * @hide // 25 */ // 26public abstract class Singleton<T> { // 27 private T mInstance; // 28 // 29 protected abstract T create(); // 30 // 31 public final T get() { // 32 synchronized (this) { // 33 if (mInstance == null) { // 34 mInstance = create(); // 35 } // 36 return mInstance; // 37 } // 38 } // 39} // 40 Class<?> activityManagerNativeClass = Class.forName("android.app.ActivityManagerNative"); Field gDefaultField = activityManagerNativeClass.getDeclaredField("gDefault"); gDefaultField.setAccessible(true); Object gDefault = gDefaultField.get(null); // gDefault是一個 android.util.Singleton對象; 我們取出這個單例里面的字段 Class<?> singleton = Class.forName("android.util.Singleton"); Field mInstanceField = singleton.getDeclaredField("mInstance"); mInstanceField.setAccessible(true); // ActivityManagerNative 的gDefault對象里面原始的 IActivityManager對象 Object rawIActivityManager = mInstanceField.get(gDefault); // 創建一個這個對象的代理對象, 然后替換這個字段, 讓我們的代理對象幫忙干活 Class<?> iActivityManagerInterface = Class.forName("android.app.IActivityManager"); Object proxy = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[] { iActivityManagerInterface }, new IActivityManagerHandler(rawIActivityManager)); mInstanceField.set(gDefault, proxy); }}

IActivityManagerHandler

package com.weishu.upf.service_management.app.hook;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import android.content.ComponentName;import android.content.Intent;import android.text.TextUtils;import android.util.Log;import android.util.Pair;import com.weishu.upf.service_management.app.ProxyService;import com.weishu.upf.service_management.app.ServiceManager;import com.weishu.upf.service_management.app.UPFApplication;/** * @author weishu * @dete 16/1/7. *//* package */ class IActivityManagerHandler implements InvocationHandler { private static final String TAG = "IActivityManagerHandler"; Object mBase; public IActivityManagerHandler(Object base) { mBase = base; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if ("startService".equals(method.getName())) { // 只攔截這個方法 // API 23: // public ComponentName startService(IApplicationThread caller, Intent service, // String resolvedType, int userId) throws RemoteException // 找到參數里面的第一個Intent 對象 Pair<Integer, Intent> integerIntentPair = foundFirstIntentOfArgs(args); Intent newIntent = new Intent(); // 代理Service的包名, 也就是我們自己的包名 String stubPackage = UPFApplication.getContext().getPackageName(); // 這里我們把啟動的Service替換為ProxyService, 讓ProxyService接收生命周期回調 ComponentName componentName = new ComponentName(stubPackage, ProxyService.class.getName()); newIntent.setComponent(componentName); // 把我們原始要啟動的TargetService先存起來 newIntent.putExtra(AMSHookHelper.EXTRA_TARGET_INTENT, integerIntentPair.second); // 替換掉Intent, 達到欺騙AMS的目的 args[integerIntentPair.first] = newIntent; Log.v(TAG, "hook method startService success"); return method.invoke(mBase, args); } // public int stopService(IApplicationThread caller, Intent service, // String resolvedType, int userId) throws RemoteException if ("stopService".equals(method.getName())) { Intent raw = foundFirstIntentOfArgs(args).second; if (!TextUtils.equals(UPFApplication.getContext().getPackageName(), raw.getComponent().getPackageName())) { // 插件的intent才做hook Log.v(TAG, "hook method stopService success"); return ServiceManager.getInstance().stopService(raw); } } return method.invoke(mBase, args); } private Pair<Integer, Intent> foundFirstIntentOfArgs(Object... args) { int index = 0; for (int i = 0; i < args.length; i++) { if (args[i] instanceof Intent) { index = i; break; } } return Pair.create(index, (Intent) args[index]); }}

Utils.extractAssets(base, “test.jar”); Utils

package com.weishu.upf.service_management.app;import java.io.Closeable;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import android.content.Context;import android.content.res.AssetManager;/** * @author weishu * @date 16/3/29 */public class Utils { /** * 把Assets里面得文件復制到 /data/data/files 目錄下 * * @param context * @param sourceName */ public static void extractAssets(Context context, String sourceName) { AssetManager am = context.getAssets(); InputStream is = null; FileOutputStream fos = null; try { is = am.open(sourceName); File extractFile = context.getFileStreamPath(sourceName); fos = new FileOutputStream(extractFile); byte[] buffer = new byte[1024]; int count = 0; while ((count = is.read(buffer)) > 0) { fos.write(buffer, 0, count); } fos.flush(); } catch (IOException e) { e.printStackTrace(); } finally { closeSilently(is); closeSilently(fos); } } // -------------------------------------------------------------------------- private static void closeSilently(Closeable closeable) { if (closeable == null) { return; } try { closeable.close(); } catch (Throwable e) { // ignore } } private static File sBaseDir;}

BaseDexClassLoaderHookHelper.patchClassLoader(getClassLoader(), apkFile, odexFile); BaseDexClassLoaderHookHelper

package com.weishu.upf.service_management.app.hook;import java.io.File;import java.io.IOException;import java.lang.reflect.Array;import java.lang.reflect.Constructor;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import dalvik.system.DexClassLoader;import dalvik.system.DexFile;/** * 由于應用程序使用的ClassLoader為PathClassLoader * 最終繼承自 BaseDexClassLoader * 查看源碼得知,這個BaseDexClassLoader加載代碼根據一個叫做 * dexElements的數組進行, 因此我們把包含代碼的dex文件插入這個數組 * 系統的classLoader就能幫助我們找到這個類 * * 這個類用來進行對于BaseDexClassLoader的Hook * 類名太長, 不要吐槽. * @author weishu * @date 16/3/28 */public final class BaseDexClassLoaderHookHelper { public static void patchClassLoader(ClassLoader cl, File apkFile, File optDexFile) throws IllegalAccessException, NoSuchMethodException, IOException, InvocationTargetException, InstantiationException, NoSuchFieldException { // 獲取 BaseDexClassLoader : pathList Field pathListField = DexClassLoader.class.getSuperclass().getDeclaredField("pathList"); pathListField.setAccessible(true); Object pathListObj = pathListField.get(cl); // 獲取 PathList: Element[] dexElements Field dexElementArray = pathListObj.getClass().getDeclaredField("dexElements"); dexElementArray.setAccessible(true); Object[] dexElements = (Object[]) dexElementArray.get(pathListObj); // Element 類型 Class<?> elementClass = dexElements.getClass().getComponentType(); // 創建一個數組, 用來替換原始的數組 Object[] newElements = (Object[]) Array.newInstance(elementClass, dexElements.length + 1); // 構造插件Element(File file, boolean isDirectory, File zip, DexFile dexFile) 這個構造函數 Constructor<?> constructor = elementClass.getConstructor(File.class, boolean.class, File.class, DexFile.class); Object o = constructor.newInstance(apkFile, false, apkFile, DexFile.loadDex(apkFile.getCanonicalPath(), optDexFile.getAbsolutePath(), 0)); Object[] toAddElementArray = new Object[] { o }; // 把原始的elements復制進去 System.arraycopy(dexElements, 0, newElements, 0, dexElements.length); // 插件的那個element復制進去 System.arraycopy(toAddElementArray, 0, newElements, dexElements.length, toAddElementArray.length); // 替換 dexElementArray.set(pathListObj, newElements); }}

MainActivity

package com.weishu.upf.service_management.app;import android.app.Activity;import android.content.ComponentName;import android.content.Intent;import android.os.Bundle;import android.view.View;/** * @author weishu * @date 16/5/9 */public class MainActivity extends Activity implements View.OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); findViewById(R.id.startService1).setOnClickListener(this); findViewById(R.id.startService2).setOnClickListener(this); findViewById(R.id.stopService1).setOnClickListener(this); findViewById(R.id.stopService2).setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.startService1: startService(new Intent().setComponent( new ComponentName("com.weishu.upf.demo.app2", "com.weishu.upf.demo.app2.TargetService1"))); break; case R.id.startService2: startService(new Intent().setComponent( new ComponentName("com.weishu.upf.demo.app2", "com.weishu.upf.demo.app2.TargetService2"))); break; case R.id.stopService1: stopService(new Intent().setComponent( new ComponentName("com.weishu.upf.demo.app2", "com.weishu.upf.demo.app2.TargetService1"))); break; case R.id.stopService2: stopService(new Intent().setComponent( new ComponentName("com.weishu.upf.demo.app2", "com.weishu.upf.demo.app2.TargetService2"))); break; } }}

ProxyService

package com.weishu.upf.service_management.app;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.util.Log;/** * @author weishu * @date 16/5/10 */public class ProxyService extends Service { private static final String TAG = "ProxyService"; @Override public void onCreate() { Log.d(TAG, "onCreate() called"); super.onCreate(); } @Override public void onStart(Intent intent, int startId) { Log.d(TAG, "onStart() called with " + "intent = [" + intent + "], startId = [" + startId + "]"); // 分發Service ServiceManager.getInstance().onStart(intent, startId); super.onStart(intent, startId); } @Override public IBinder onBind(Intent intent) { // TODO: 16/5/11 bindService實現 return null; } @Override public void onDestroy() { Log.d(TAG, "onDestroy() called"); super.onDestroy(); }}

ServiceManager

package com.weishu.upf.service_management.app;import java.io.File;import java.lang.reflect.Constructor;import java.lang.reflect.Field;import java.lang.reflect.Method;import java.util.HashMap;import java.util.List;import java.util.Map;import android.app.Service;import android.content.ComponentName;import android.content.Context;import android.content.Intent;import android.content.pm.PackageManager;import android.content.pm.ServiceInfo;import android.os.Binder;import android.os.IBinder;import android.util.Log;import com.weishu.upf.service_management.app.hook.AMSHookHelper;/** * @author weishu * @date 16/5/10 */public final class ServiceManager { private static final String TAG = "ServiceManager"; private static volatile ServiceManager sInstance; private Map<String, Service> mServiceMap = new HashMap<String, Service>(); // 存儲插件的Service信息 private Map<ComponentName, ServiceInfo> mServiceInfoMap = new HashMap<ComponentName, ServiceInfo>(); public synchronized static ServiceManager getInstance() { if (sInstance == null) { sInstance = new ServiceManager(); } return sInstance; } /** * 啟動某個插件Service; 如果Service還沒有啟動, 那么會創建新的插件Service * @param proxyIntent * @param startId */ public void onStart(Intent proxyIntent, int startId) { Intent targetIntent = proxyIntent.getParcelableExtra(AMSHookHelper.EXTRA_TARGET_INTENT); ServiceInfo serviceInfo = selectPluginService(targetIntent); if (serviceInfo == null) { Log.w(TAG, "can not found service : " + targetIntent.getComponent()); return; } try { if (!mServiceMap.containsKey(serviceInfo.name)) { // service還不存在, 先創建 proxyCreateService(serviceInfo); } Service service = mServiceMap.get(serviceInfo.name); service.onStart(targetIntent, startId); } catch (Exception e) { e.printStackTrace(); } } /** * 停止某個插件Service, 當全部的插件Service都停止之后, ProxyService也會停止 * @param targetIntent * @return */ public int stopService(Intent targetIntent) { ServiceInfo serviceInfo = selectPluginService(targetIntent); if (serviceInfo == null) { Log.w(TAG, "can not found service: " + targetIntent.getComponent()); return 0; } Service service = mServiceMap.get(serviceInfo.name); if (service == null) { Log.w(TAG, "can not runnning, are you stopped it multi-times?"); return 0; } service.onDestroy(); mServiceMap.remove(serviceInfo.name); if (mServiceMap.isEmpty()) { // 沒有Service了, 這個沒有必要存在了 Log.d(TAG, "service all stopped, stop proxy"); Context appContext = UPFApplication.getContext(); appContext.stopService(new Intent().setComponent(new ComponentName(appContext.getPackageName(), ProxyService.class.getName()))); } return 1; } /** * 選擇匹配的ServiceInfo * @param pluginIntent 插件的Intent * @return */ private ServiceInfo selectPluginService(Intent pluginIntent) { for (ComponentName componentName : mServiceInfoMap.keySet()) { if (componentName.equals(pluginIntent.getComponent())) { return mServiceInfoMap.get(componentName); } } return null; } /** * 通過ActivityThread的handleCreateService方法創建出Service對象 * @param serviceInfo 插件的ServiceInfo * @throws Exception */ private void proxyCreateService(ServiceInfo serviceInfo) throws Exception { IBinder token = new Binder(); // 創建CreateServiceData對象, 用來傳遞給ActivityThread的handleCreateService 當作參數 Class<?> createServiceDataClass = Class.forName("android.app.ActivityThread$CreateServiceData"); Constructor<?> constructor = createServiceDataClass.getDeclaredConstructor(); constructor.setAccessible(true); Object createServiceData = constructor.newInstance(); // 寫入我們創建的createServiceData的token字段, ActivityThread的handleCreateService用這個作為key存儲Service Field tokenField = createServiceDataClass.getDeclaredField("token"); tokenField.setAccessible(true); tokenField.set(createServiceData, token); // 寫入info對象 // 這個修改是為了loadClass的時候, LoadedApk會是主程序的ClassLoader, 我們選擇Hook BaseDexClassLoader的方式加載插件 serviceInfo.applicationInfo.packageName = UPFApplication.getContext().getPackageName(); Field infoField = createServiceDataClass.getDeclaredField("info"); infoField.setAccessible(true); infoField.set(createServiceData, serviceInfo); // 寫入compatInfo字段 // 獲取默認的compatibility配置 Class<?> compatibilityClass = Class.forName("android.content.res.CompatibilityInfo"); Field defaultCompatibilityField = compatibilityClass.getDeclaredField("DEFAULT_COMPATIBILITY_INFO"); Object defaultCompatibility = defaultCompatibilityField.get(null); Field compatInfoField = createServiceDataClass.getDeclaredField("compatInfo"); compatInfoField.setAccessible(true); compatInfoField.set(createServiceData, defaultCompatibility); Class<?> activityThreadClass = Class.forName("android.app.ActivityThread"); Method currentActivityThreadMethod = activityThreadClass.getDeclaredMethod("currentActivityThread"); Object currentActivityThread = currentActivityThreadMethod.invoke(null); // private void handleCreateService(CreateServiceData data) { Method handleCreateServiceMethod = activityThreadClass.getDeclaredMethod("handleCreateService", createServiceDataClass); handleCreateServiceMethod.setAccessible(true); handleCreateServiceMethod.invoke(currentActivityThread, createServiceData); // handleCreateService創建出來的Service對象并沒有返回, 而是存儲在ActivityThread的mServices字段里面, 這里我們手動把它取出來 Field mServicesField = activityThreadClass.getDeclaredField("mServices"); mServicesField.setAccessible(true); Map mServices = (Map) mServicesField.get(currentActivityThread); Service service = (Service) mServices.get(token); // 獲取到之后, 移除這個service, 我們只是借花獻佛 mServices.remove(token); // 將此Service存儲起來 mServiceMap.put(serviceInfo.name, service); } /** * 解析Apk文件中的 <service>, 并存儲起來 * 主要是調用PackageParser類的generateServiceInfo方法 * @param apkFile 插件對應的apk文件 * @throws Exception 解析出錯或者反射調用出錯, 均會拋出異常 */ public void preLoadServices(File apkFile) throws Exception { Class<?> packageParserClass = Class.forName("android.content.pm.PackageParser"); Method parsePackageMethod = packageParserClass.getDeclaredMethod("parsePackage", File.class, int.class); Object packageParser = packageParserClass.newInstance(); // 首先調用parsePackage獲取到apk對象對應的Package對象 Object packageObj = parsePackageMethod.invoke(packageParser, apkFile, PackageManager.GET_SERVICES); // 讀取Package對象里面的services字段 // 接下來要做的就是根據這個List<Service> 獲取到Service對應的ServiceInfo Field servicesField = packageObj.getClass().getDeclaredField("services"); List services = (List) servicesField.get(packageObj); // 調用generateServiceInfo 方法, 把PackageParser.Service轉換成ServiceInfo Class<?> packageParser$ServiceClass = Class.forName("android.content.pm.PackageParser$Service"); Class<?> packageUserStateClass = Class.forName("android.content.pm.PackageUserState"); Class<?> userHandler = Class.forName("android.os.UserHandle"); Method getCallingUserIdMethod = userHandler.getDeclaredMethod("getCallingUserId"); int userId = (Integer) getCallingUserIdMethod.invoke(null); Object defaultUserState = packageUserStateClass.newInstance(); // 需要調用 android.content.pm.PackageParser#generateActivityInfo(android.content.pm.ActivityInfo, int, android.content.pm.PackageUserState, int) Method generateReceiverInfo = packageParserClass.getDeclaredMethod("generateServiceInfo", packageParser$ServiceClass, int.class, packageUserStateClass, int.class); // 解析出intent對應的Service組件 for (Object service : services) { ServiceInfo info = (ServiceInfo) generateReceiverInfo.invoke(packageParser, service, 0, defaultUserState, userId); mServiceInfoMap.put(new ComponentName(info.packageName, info.name), info); } }}
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 国产精品久久久久久久成人午夜 | 成人免费观看在线视频 | 成人免费在线播放 | 日本在线一区二区 | 日本中文字幕久久 | 操操插插| 中文字幕在线观看www | 国产成人在线网站 | 热99在线视频 | 久久精品视频一区二区三区 | av免费在线观| 萌白酱福利视频在线网站 | 姑娘第5集高清在线观看 | 黄色网址进入 | 蜜桃视频日韩 | 免费一及片 | 天天草天天操 | 911精品影院在线观看 | 日本免费aaa观看 | 国产成人免费精品 | 成人短视频在线播放 | 毛片在线免费观看完整版 | 超碰在线97国产 | 亚洲网站免费看 | 草莓福利视频在线观看 | 久久久久久久久久久久网站 | 日本网站一区 | 天天干天天透 | 国产成人高清成人av片在线看 | 亚洲免费视频一区二区 | 精品一区二区久久久久 | 国产精品久久久久久婷婷天堂 | 美国黄色小视频 | 亚洲成人精品久久久 | 国产欧美在线一区二区三区 | 性大片免费看 | 欧美另类69xxxxx 视频 | 国产亚洲精品美女久久久 | 国产乱一区二区三区视频 | 国产亚洲精品视频中文字幕 | 爱看久久 |