溫馨提示:閱讀本文需要20-30分鐘(一大波程式碼) 關注公眾號:顧林海
今天,我們來解決一個問題:
Activity外掛化原理第二種方案:Hook IActivityManager
人生一切難題,知識給你答案。
第一種方案Hook Instrumentation已經順利完成,接下來我們看第二個方案,還是看這段程式碼:
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
@Nullable Bundle options) {
if (mParent == null) {
//Activity啟動
options = transferSpringboardActivityOptions(options);
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode, options);
if (ar != null) {
mMainThread.sendActivityResult(
mToken, mEmbeddedID, requestCode, ar.getResultCode(),
ar.getResultData());
}
if (requestCode >= 0) {
mStartedActivity = true;
}
cancelInputsAndStartExitTransition(options);
windows.
} else {
if (options != null) {
mParent.startActivityFromChild(this, intent, requestCode, options);
} else {
mParent.startActivityFromChild(this, intent, requestCode);
}
}
}
複製程式碼
通過mInstrumentation的execStartActivity方法啟動Activity,在execStartActivity方法中會獲取AMS的代理,Android 7.0通過ActivityManagerNative的getDefault方法獲取一個ActivityManagerProxy,這個ActivityManagerProxy內部封裝了IBinder型別的ActivityManagerService的代理類,這樣在應用程式程式中就可以通過這個ActivityManagerProxy與SystemServer程式的ActivityManagerService進行通訊,而在Android 8.0去除了ActivityManagerProxy這個代理類,由IActivityManager代替,這裡的IActivityManager.aidl通過AIDL工具自動生成IActivityManager.java。
Android 7.0-Activity啟動
ActivityManager是一個和AMS相關聯的類,它主要對執行中的Activity進行管理,ActivityManager中相關管理方法最終會通過ActivityManagerNative的getDefault方法來得到ActivityManagerProxy,再呼叫ActivityManagerProxy的相關管理方法,ActivityManagerProxy就是AMS的代理類,通過這個代理類就可以和AMS進行通訊。
Android7.0的Activity啟動過程會呼叫Instrumentation的execStartActivity方法,程式碼如下:
public ActivityResult execStartActivity(
...
try {
...
int result = ActivityManagerNative.getDefault()
.startActivity(whoThread, who.getBasePackageName(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target, requestCode, 0, null, options);
checkStartActivityResult(result, intent);
} catch (RemoteException e) {
throw new RuntimeException("Failure from system", e);
}
return null;
}
複製程式碼
在execStartActivity方法中會呼叫ActivityManagerNative的getDefault方法來獲取ActivityManagerProxy,ActivityManagerProxy又是AMS的代理類,這樣的話就可以通過ActivityManagerProxy向AMS傳送startActivity的請求。
ActivityManagerNative的getDefault方法的程式碼如下:
private static final Singleton<IActivityManager> gDefault = new Singleton<IActivityManager>() {
protected IActivityManager create() {
IBinder b = ServiceManager.getService("activity");
...
IActivityManager am = asInterface(b);
...
return am;
}
};
static public IActivityManager getDefault() {
return gDefault.get();
}
複製程式碼
在getDefault方法中呼叫了gDefault的get方法,gDefault是一個單例類。通過ServiceManager的getService方法獲取一個IBinder型別的AMS的引用,再將它通過asInterface方法轉換成ActivityManagerProxy型別的物件。
asInterface方法:
static public IActivityManager asInterface(IBinder obj) {
if (obj == null) {
return null;
}
//檢查本地程式是否有IActivityManager介面的實現
IActivityManager in =
(IActivityManager)obj.queryLocalInterface(descriptor);
if (in != null) {
return in;
}
//本地程式沒有IActivityManager介面的實現,將IBinder型別的AMS引用封裝成AMP
return new ActivityManagerProxy(obj);
}
複製程式碼
在asInterface方法中分兩種情況,首先會檢查本地程式是否有IActivityManager介面的實現,如果有就直接返回;如果沒有,就將IBinder型別的AMS引用封裝成ActivityManagerProxy。
public abstract class ActivityManagerNative extends Binder implements IActivityManager{
...
class ActivityManagerProxy implements IActivityManager{
public ActivityManagerProxy(IBinder remote){
mRemote = remote;
}
...
}
...
}
複製程式碼
ActivityManagerProxy是ActivityManagerNative的內部類,在ActivityManagerProxy的構造方法中將AMS的引用賦值給變數mRemote,這樣在ActivityManagerProxy中就可以使用AMS了。
繼續回到Instrumentation的execStartActivity方法,程式碼如下:
public ActivityResult execStartActivity(
...
try {
...
int result = ActivityManagerNative.getDefault()
.startActivity(whoThread, who.getBasePackageName(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target, requestCode, 0, null, options);
checkStartActivityResult(result, intent);
} catch (RemoteException e) {
throw new RuntimeException("Failure from system", e);
}
return null;
}
複製程式碼
通過ActivityManagerNative的getDefault方法獲取AMS的代理類ActivityManagerProxy,再呼叫ActivityManagerProxy的startActivity方法。
ActivityManagerProxy的startActivity方法:
public int startActivity(IApplicationThread caller, String callingPackage, Intent intent,
String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle options) throws RemoteException {
...
//向AMS傳送START_ACTIVITY_TRANSACTION型別的程式間通訊請求
mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0);
reply.readException();
int result = reply.readInt();
reply.recycle();
data.recycle();
return result;
}
複製程式碼
在ActivityManagerProxy的startActivity方法中,通過mRemote,也就是AMS的引用,向服務端的AMS傳送一個START_ACTIVITY_TRANSACTION型別的程式間通訊請求,服務端AMS就會從Binder執行緒池中讀取客戶端發來的資料,最終會呼叫ActivityManagerNative的onTransact方法。
@Override
public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
throws RemoteException {
switch (code) {
case START_ACTIVITY_TRANSACTION:{
...
int result = startActivity(app, callingPackage, intent, resolvedType,
...
return true;
}
...
}
return super.onTransact(code, data, reply, flags);
}
複製程式碼
同時ActivityManagerService繼承自ActivityManagerNative,因此onTransact方法的switch語句的START_ACTIVITY_TRANSACTION分支會呼叫AMS的startActivity。
public final class ActivityManagerService extends ActivityManagerNative implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
@Override public final int startActivity(IApplicationThread caller, String callingPackage,
Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
resultWho, requestCode, startFlags, profilerInfo, bOptions,
UserHandle.getCallingUserId());
}
}
複製程式碼
Android 8.0-Activity啟動
Android8.0和7.0的Activity啟動過程都會呼叫Instrumentation的execStartActivity方法,程式碼如下:
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, String target,
Intent intent, int requestCode, Bundle options) {
...
try {
...
int result = ActivityManager.getService()
.startActivity(whoThread, who.getBasePackageName(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target, requestCode, 0, null, options);
checkStartActivityResult(result, intent);
} catch (RemoteException e) {
throw new RuntimeException("Failure from system", e);
}
return null;
}
複製程式碼
在execStartActivity方法中通過ActivityManager的getService獲取IActivityManager物件,並通過IActivityManager物件的startActivity方法通知AMS啟動Activity。
public static IActivityManager getService() {
return IActivityManagerSingleton.get();
}
private static final Singleton<IActivityManager> IActivityManagerSingleton =
new Singleton<IActivityManager>() {
@Override
protected IActivityManager create() {
final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
final IActivityManager am = IActivityManager.Stub.asInterface(b);
return am;
}
};
複製程式碼
IActivityManagerSingleto是一個單例類,在它的create方法中獲取iBinder型別的AMS引用,接著通過AIDL,將AMS應用轉換成IActivityManager型別的物件。相比於Android 7.0來說,這裡去掉了ActivityManagerProxy這個代理類,由IActivityManager代替,這裡的IActivityManager.aidl通過AIDL工具自動生成IActivityManager.java。
通過Android 7.0和Android 8.0的Activity啟動流程可以得出Activity外掛化的另一種方案:Hook IActivityManager,通過動態代理實現。
首先建立佔坑Activity:
public class StubActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stub);
}
}
複製程式碼
建立外掛Activity:
public class TargetActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_target);
}
}
複製程式碼
並在AndroidManifest.xml中註冊佔坑Activity:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.glh.haiproject01">
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
tools:ignore="AllowBackup,GoogleAppIndexingWarning">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".StubActivity" />
</application>
</manifest>
複製程式碼
在AndroidManifest.xml中沒有註冊外掛Activity,這時如果啟動外掛Activity會報錯。
接著開始Hook IActivityManager,建立代理類IActivityManagerProxy:
public class IActivityManagerProxy implements InvocationHandler {
private Object mActivityManager;
public IActivityManagerProxy(Object activityManager){
this.mActivityManager=activityManager;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if("startActivity".equals(method.getName())){
//攔截startActivity
Intent intent=null;
int index=0;
for(int i=0,length=args.length;i<length;i++){
if(args[i] instanceof Intent){
index=i;
break;
}
}
//獲取外掛Activity的Intent
intent= (Intent) args[index];
//建立佔坑Activity的Intent
Intent subIntent=new Intent();
subIntent.setClassName("com.glh.haiproject01","com.glh.haiproject01.StubActivity");
//儲存外掛Activity的Intent
subIntent.putExtra(HookHelper.REQUEST_TARGET_INTENT_NAME,intent);
//替換為佔坑Activity
args[index]=subIntent;
}
return method.invoke(mActivityManager,args);
}
}
複製程式碼
IActivityManagerProxy代理類的invoke非常簡單,就是將外掛Activity的Intent替換為佔坑Activity的Intent,並儲存外掛Activity的Intent,方便後續還原。
private void hookIActivityManager(){
Object defaultSingleton;
if(Build.VERSION.SDK_INT==26){
//Android 8.0
defaultSingleton=getIActivityManagerSingleton();
}else{
defaultSingleton=getDefault();
}
try {
Class<?> singletonClazz=Class.forName("android.util.Singleton");
Field instanceField=singletonClazz.getDeclaredField("mInstance");
instanceField.setAccessible(true);
//獲取defaultSingleton中IActivityManager型別的mInstance成員變數
Object iActivityManager=instanceField.get(defaultSingleton);
Class<?> iActivityManagerClazz=Class.forName("android.app.IActivityManager");
Object proxy=Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
new Class<?>[]{iActivityManagerClazz},new IActivityManagerProxy(iActivityManager));
//替換為代理類IActivityManagerProxy
instanceField.set(defaultSingleton,proxy);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
private Object getIActivityManagerSingleton(){
try {
Class<?> activityManagerClazz=Class.forName("android.app.ActivityManager");
Field field=activityManagerClazz.getDeclaredField("IActivityManagerSingleton");
field.setAccessible(true);
return field.get(null);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
private Object getDefault(){
try {
Class<?> activityManagerClazz=Class.forName("android.app.ActivityManagerNative");
Field field=activityManagerClazz.getDeclaredField("gDefault");
field.setAccessible(true);
return field.get(null);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
複製程式碼
以上程式碼主要就是將Singleton的IActivityManager型別的成員變數mInstance替換成通過動態代理物件。當我們向AMS請求啟動Activity時,會執行代理類IActivityManagerProxy的invoke方法進行狸貓換太子。
當AMS通過驗證後需要還原外掛Activity的Intent,在Android 8.0和Android 7.0(其他版本原始碼有可能不同)中,AMS通過Binder跨程式呼叫scheduleLaunchActivity,scheduleLaunchActivity方法在應用程式程式的Binder執行緒池中,通過mH傳送LAUNCH_ACTIVITY訊息(100)切換到主執行緒中建立並啟動Activity。
mH的型別是ActivityThread中的內部類H,H繼承自Handler並實現了handleMessage方法,在Handler原始碼中,有這麼一段程式碼:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
複製程式碼
當mCallback不為null時會呼叫handleMessage方法,mCallback型別是Callback介面,因此我們可以Hook Callback,用自定的Callback替換Handler的mCallback。
代理Callback:
public class CallBackProxy implements Handler.Callback {
private Handler mHandler;
public CallBackProxy(Handler handler){
this.mHandler=handler;
}
@Override
public boolean handleMessage(Message msg) {
if(msg.what==100){
Object o=msg.obj;
try {
Field field=o.getClass().getDeclaredField("intent");
field.setAccessible(true);
//獲取佔坑Activity的Intent
Intent intent= (Intent) field.get(o);
//獲取之前儲存的外掛Activity的Intent
Intent targetIntent=intent.getParcelableExtra(HookHelper.REQUEST_TARGET_INTENT_NAME);
//將佔坑的Activity替換為外掛Activity
intent.setComponent(targetIntent.getComponent());
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
mHandler.handleMessage(msg);
return true;
}
}
複製程式碼
將Handler的mCallback替換為代理類CallBackProxy:
private void hookHandler(){
try {
Class<?> activityThreadClazz=Class.forName("android.app.ActivityThread");
Field currentActivityThreadField=activityThreadClazz.getDeclaredField("sCurrentActivityThread");
currentActivityThreadField.setAccessible(true);
Object currentActivityThread=currentActivityThreadField.get(null);
Field handlerField=activityThreadClazz.getDeclaredField("mH");
handlerField.setAccessible(true);
Handler mH= (Handler) handlerField.get(currentActivityThread);
Field callbackField=Handler.class.getDeclaredField("mCallback");
callbackField.setAccessible(true);
//Handler的mCallback替換為CallBackProxy
callbackField.set(mH,new CallBackProxy(mH));
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
複製程式碼
至此,Hook IActivityManager方案已經完成,在主介面中啟動外掛Activity:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn_startActivity).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(MainActivity.this,TargetActivity.class);
startActivity(intent);
}
});
}
}
複製程式碼
執行效果: