《Android 系统源代码情景分析》
- SystemServer进程,主要用于创建系统服务,像AMS WMS PMS都是由运行在SS进程中的线程操纵.
- ServiceManager进程,它由init进程启动(像Zygote也是init进程启动的),它负责管理系统中的AMS,WMS等服务,同时也肩负着向Client端提供Service服务端代理对象服务.
源码分析
- ZygoteInit.mian()
Zygote
进程启动时会辗转调到ZygoteInit.main()
,最后会调用startSystemServer()
,开启SS进程.
// ZygoteInit.java
public static void main(String argv[]) {
try {
...
if (argv[1].equals("true")) {
startSystemServer();
}
...
closeServerSocket();
} catch (MethodAndArgsCaller caller) {
caller.run();
} catch (RuntimeException ex) {
closeServerSocket();
throw ex;
}
}
private static boolean startSystemServer() throws MethodAndArgsCaller, RuntimeException {
/* Hardcoded command line to start the system server */
String args[] = {
"--setuid=1000",
"--setgid=1000",
"--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,3001,3002,3003",
"--capabilities=130104352,130104352",
"--runtime-init",
"--nice-name=system_server",
"com.android.server.SystemServer",//最后会调用该类中的main()
};
ZygoteConnection.Arguments parsedArgs = null;
int pid;
try {
parsedArgs = new ZygoteConnection.Arguments(args);
// fork出一个进程,该方法是一次调用两次返回
pid = Zygote.forkSystemServer(
parsedArgs.uid, parsedArgs.gid,
parsedArgs.gids, debugFlags, null,
parsedArgs.permittedCapabilities,
parsedArgs.effectiveCapabilities);
} catch (IllegalArgumentException ex) {
throw new RuntimeException(ex);
}
if (pid == 0) {
// 如果是Zygote子进程,其实走到这里就走到了SS进程中了
handleSystemServerProcess(parsedArgs);
}
return true;
}
private static void handleSystemServerProcess(
ZygoteConnection.Arguments parsedArgs)
throws ZygoteInit.MethodAndArgsCaller {
...
// 继续向下看
RuntimeInit.zygoteInit(parsedArgs.remainingArgs);
}
- RuntimeInit.zygoteInit()
// RuntimeInit.java
public static final void zygoteInit(String[] argv)
throws ZygoteInit.MethodAndArgsCaller {
...
// 初始化一些东西
commonInit();
// 开启Binder线程池,方便进程中通信
zygoteInitNative();
...
String startClass = argv[curArg++];
String[] startArgs = new String[argv.length - curArg];
System.arraycopy(argv, curArg, startArgs, 0, startArgs.length);
// com.android.server.SystemServer
// 最终是调用其中的main()
invokeStaticMain(startClass, startArgs);
}
private static void invokeStaticMain(String className, String[] argv)
throws ZygoteInit.MethodAndArgsCaller {
...
Class<?> cl;
try {
cl = Class.forName(className);
}
...
Method m;
try {
m = cl.getMethod("main", new Class[] { String[].class });
}
...
// 这里是一个异常,最后被ZygoteInit.main()中捕获, 然后调用MethodAndArgsCaller对象的run()
throw new ZygoteInit.MethodAndArgsCaller(m, argv);
}
- ZygoteInit.MethodAndArgsCaller.run()
- 这里最终调用到了SystemServer.main()
public static class MethodAndArgsCaller extends Exception
implements Runnable {
private final Method mMethod;
private final String[] mArgs;
public MethodAndArgsCaller(Method method, String[] args) {
mMethod = method;
mArgs = args;
}
public void run() {
try {
// 从这里可以看出最终调用了main()
mMethod.invoke(null, new Object[] { mArgs });
} ...
}
}
- SystemServer.main()
public static void main(String[] args) {
...
init1(args);
}
// 去C++看看
native public static void init1(String[] args);
- android_server_SystemServer.android_server_SystemServer_init1()
//android_server_SystemServer.cpp
static void android_server_SystemServer_init1(JNIEnv* env, jobject clazz)
{
system_init();
}
// system_init.cpp
extern "C" status_t system_init()
{
sp<ProcessState> proc(ProcessState::self());
sp<IServiceManager> sm = defaultServiceManager();
// 死亡通知接收者
sp<GrimReaper> grim = new GrimReaper();
sm->asBinder()->linkToDeath(grim, grim.get(), 0);
char propBuf[PROPERTY_VALUE_MAX];
property_get("system_init.startsurfaceflinger", propBuf, "1");
if (strcmp(propBuf, "1") == 0) {
// SurfaceFlinger服务开启
SurfaceFlinger::instantiate();
}
// 传感器服务开启
SensorService::instantiate();
...
AndroidRuntime* runtime = AndroidRuntime::getRuntime();
// 调用SystemServer.init2()
runtime->callStatic("com/android/server/SystemServer", "init2");
...
return NO_ERROR;
}
- SystemServer.init2()
// SystemServer.java
public static final void init2() {
Thread thr = new ServerThread();
thr.setName("android.server.ServerThread");
thr.start();
}
// ServerThread.java
class ServerThread extends Thread {
// 创建looper
Looper.prepare();
// 开启各种各样的服务
try {
ServiceManager.addService("entropy", new EntropyService());
power = new PowerManagerService();
ServiceManager.addService(Context.POWER_SERVICE, power);
context = ActivityManagerService.main(factoryTest);
ServiceManager.addService("telephony.registry", new TelephonyRegistry(context));
AttributeCache.init(context);
pm = PackageManagerService.main(context,factoryTest != SystemServer.FACTORY_TEST_OFF);
ActivityManagerService.setSystemProcess();
mContentResolver = context.getContentResolver();
try {
ServiceManager.addService(Context.ACCOUNT_SERVICE, new AccountManagerService(context));
} catch (Throwable e) {
}
ContentService.main(context,factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL);
ActivityManagerService.installSystemProviders();
battery = new BatteryService(context);
ServiceManager.addService("battery", battery);
lights = new LightsService(context);
ServiceManager.addService("vibrator", new VibratorService(context));
power.init(context, lights, ActivityManagerService.getDefault(), battery);
AlarmManagerService alarm = new AlarmManagerService(context);
ServiceManager.addService(Context.ALARM_SERVICE, alarm);
Watchdog.getInstance().init(context, battery, power, alarm,ActivityManagerService.self());
wm = WindowManagerService.main(context, power,
factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL);
ServiceManager.addService(Context.WINDOW_SERVICE, wm);
((ActivityManagerService)ServiceManager.getService("activity")).setWindowManager(wm);
if (SystemProperties.get("ro.kernel.qemu").equals("1")) {
ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, null);
} else if (factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, null);
} else {
bluetooth = new BluetoothService(context);
ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, bluetooth);
bluetooth.initAfterRegistration();
bluetoothA2dp = new BluetoothA2dpService(context, bluetooth);
ServiceManager.addService(BluetoothA2dpService.BLUETOOTH_A2DP_SERVICE,bluetoothA2dp);
int bluetoothOn = Settings.Secure.getInt(mContentResolver,Settings.Secure.BLUETOOTH_ON, 0);
if (bluetoothOn > 0) {
bluetooth.enable();
}
}
} catch (RuntimeException e) {
}
//开启消息循环
Looper.loop();
}
- AMS创建
- 这里只是为AMS创建了线程,并且启动了消息循环,还没有将AMS注册到SM中
// ServerThread.java
public void run() {
// 创建AMS服务
context = ActivityManagerService.main(factoryTest);
}
// ActivityManagerService.java
public static final Context main(int factoryTest) {
AThread thr = new AThread();
// 当AThread线程运行起来
thr.start();
...
return context;
}
// ActivityManagerService.AThread.java
static class AThread extends Thread {
ActivityManagerService mService;
boolean mReady = false;
public AThread() {
super("ActivityManager");
}
// 启动AThread线程
public void run() {
// 准备Looper对象
Looper.prepare();
// 设置线程优先级
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_FOREGROUND);
android.os.Process.setCanSelfBackground(false);
// 创建AMS对象
ActivityManagerService m = new ActivityManagerService();
synchronized (this) {
// 当AMS对象创建成功
mService = m;
notifyAll();
}
...
// 开启消息循环.
Looper.loop();
}
}
- PMS创建注册
// ServerThread.java
public void run() {
// 创建AMS服务
context = ActivityManagerService.main(factoryTest);
...
pm = PackageManagerService.main(context,factoryTest != SystemServer.FACTORY_TEST_OFF);
// 这里将会把AMS注册到SS中
ActivityManagerService.setSystemProcess();
}
// PackageManagerService.java
public static final IPackageManager main(Context context, boolean factoryTest) {
// 创建PMS,并注册到SM服务中
PackageManagerService m = new PackageManagerService(context, factoryTest);
// 将PMS注册到SS中
ServiceManager.addService("package", m);
return m;
}
// ServiceManager.java
public final class ServiceManager {
public static void addService(String name, IBinder service) {
try {
// 将服务注册到SS中
getIServiceManager().addService(name, service);
} catch (RemoteException e) {
Log.e(TAG, "error in addService", e);
}
}
// 返回一个Binder代理对象
private static IServiceManager getIServiceManager() {
if (sServiceManager != null) {
return sServiceManager;
}
sServiceManager = ServiceManagerNative.asInterface(BinderInternal.getContextObject());
return sServiceManager;
}
}
//ServiceManagerNative.java
public abstract class ServiceManagerNative extends Binder implements IServiceManager{
static public IServiceManager asInterface(IBinder obj)
{
if (obj == null) {
return null;
}
IServiceManager in = (IServiceManager)obj.queryLocalInterface(descriptor);
if (in != null) {
return in;
}
return new ServiceManagerProxy(obj);
}
}
// ServiceManagerProxy.java
class ServiceManagerProxy implements IServiceManager {
// 看到这里,ServiceManagerProxy对象是Binder代理对象.
public ServiceManagerProxy(IBinder remote) {
mRemote = remote;
}
}
- WMS创建
// ServerThread.java
public void run() {
// 创建WMS
wm = WindowManagerService.main(context, power,factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL);
// 注册WMS
ServiceManager.addService(Context.WINDOW_SERVICE, wm);
}
// WindowManagerService.java
public class WindowManagerService extends IWindowManager.Stub mplements Watchdog.Monitor {
public static WindowManagerService main(Context context,PowerManagerService pm, boolean haveInputMethods) {
WMThread thr = new WMThread(context, pm, haveInputMethods);
thr.start();
...
return thr.mService;
}
// WMS的线程
static class WMThread extends Thread {
WindowManagerService mService;
private final Context mContext;
private final PowerManagerService mPM;
private final boolean mHaveInputMethods;
public WMThread(Context context, PowerManagerService pm,
boolean haveInputMethods) {
super("WindowManager");
mContext = context;
mPM = pm;
mHaveInputMethods = haveInputMethods;
}
public void run() {
// 准备WMS线程专用的Looper
Looper.prepare();
// 创建WMS
WindowManagerService s = new WindowManagerService(mContext, mPM, mHaveInputMethods);
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_DISPLAY);
android.os.Process.setCanSelfBackground(false);
synchronized (this) {
mService = s;
notifyAll();
}
// 为WMS 开启消息轮询
Looper.loop();
}
}
}