什么是Binder?
Binder是linux IPC机制的其中一种。它贯穿于应用层,framework层,以及linux Core层。
在kernel空间,Binder是虚拟的物理设备的驱动。
Android应用层的Service, broadcast, ContentProvider,Activity间的通信都是以Binder为核心。
什么是IPC?
跨进程通信, InterProcess Communication.
IPC机制都有哪些?
- 通道
- 信号量
- 消息队列
- Binder
- Socket
- 共享内存
Binder的创建
每一个进程/Service都有一个Binder.
frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
public static Runnable zygoteInit(int targetSdkVersion, long[] disabledCompatChanges,
String[] argv, ClassLoader classLoader) {
if (RuntimeInit.DEBUG) {
Slog.d(RuntimeInit.TAG, "RuntimeInit: Starting application from zygote");
}
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ZygoteInit");
RuntimeInit.redirectLogStreams();
RuntimeInit.commonInit();
ZygoteInit.nativeZygoteInit();
//zygote进程,启动一个新的Application
return RuntimeInit.applicationInit(targetSdkVersion, disabledCompatChanges, argv,
classLoader);
}
frameworks/base/core/java/com/android/internal/os/RuntimeInit.java
protected static Runnable applicationInit(int targetSdkVersion, long[] disabledCompatChanges,
String[] argv, ClassLoader classLoader) {
// If the application calls System.exit(), terminate the process
// immediately without running any shutdown hooks. It is not possible to
// shutdown an Android application gracefully. Among other things, the
// Android runtime shutdown hooks close the Binder driver, which can cause
// leftover running threads to crash before the process actually exits.
nativeSetExitWithoutCleanup(true);
VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion);
VMRuntime.getRuntime().setDisabledCompatChanges(disabledCompatChanges);
final Arguments args = new Arguments(argv);
// The end of of the RuntimeInit event (see #zygoteInit).
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
// Remaining arguments are passed to the start class's static main
return findStaticMain(args.startClass, args.startArgs, classLoader);
}
Binder的管理
SM来管理Binder
Binder的原理
利用mmap,让内核空间跟用户空间共享一块内存(1M减8K),
疑问
- zygote为何在fork进程的时候使用socket,而非binder.除了zygote进程之外,任何进程都有binder.
- 多进程开发有何优势?
- 可以突破单一进程的内存限制
- 隔离风险,
- 降低APP崩溃风险
- 规避系统内存泄漏,例如webview.
- 用户空间和内核空间
- 内核空间提供系统内核和设备驱动使用。
- 用户空间提供用户程序和用户进程使用。
- 用户空间通过系统调用ioctl访问内核空间。内核空间访问用户空间则相对容易。
- 为了保护系统的稳定性和安全性,Android 系统设计了一些安全机制来限制用户空间对内核空间的访问。例如,权限管理、沙箱机制、SELinux 等都是为了确保只有经过授权和合法的操作才能访问和修改内核空间
-
AMS,activity manage service. android 10之前,四大组件由AMS管理。之后,ATMS单独管理activity.
-
ATMS, activity task manage service.
AIDL
AIDL是对IBinder的封装,降低使用Binder的复杂度。
AIDL, Android Interface Definition Languag, it is a language that defines the interface for interprocess communication (IPC) in Android.
HIDL
HAL interface definition language or HIDL is an interface description language (IDL) to specify the interface between a HAL and its users