l Init进程
源码:system\core\init\init.c
说明:Android系统在启动时首先会启动Linux系统,引导加载Linux Kernel并启动init进程。Init进程是一个由内核启动的用户级进程,是Android系统的第一个进程。
在main函数中,有如下代码:
open_devnull_stdio();
log_init();
INFO("reading config file\n");
init_parse_config_file("/init.rc");
/* pull the kernel commandline and ramdisk properties file in */
import_kernel_cmdline(0);
get_hardware_name(hardware, &revision);
snprintf(tmp, sizeof(tmp), "/init.%s.rc", hardware);
init_parse_config_file(tmp);
这里会加载解析init.rc和init.hardware.rc两个初始化脚本。*.rc文件定义了在init进程中需要启动哪些进程服务和执行哪些动作。其详细说明参见platform\system\core\init\reademe.txt。init.rc见如下定义:
service servicemanager /system/bin/servicemanager
user system
critical
onrestart restart zygote
onrestart restart media
service vold /system/bin/vold
socket vold stream 0660 root mount
ioprio be 2
service netd /system/bin/netd
socket netd stream 0660 root system
socket dnsproxyd stream 0660 root inet
service debuggerd /system/bin/debuggerd
service ril-daemon /system/bin/rild
socket rild stream 660 root radio
socket rild-debug stream 660 radio system
user root
group radio cache inet misc audio sdcard_rw
service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server
socket zygote stream 666
onrestart write /sys/android_power/request_state wake
onrestart write /sys/power/state on
onrestart restart media
onrestart restart netd
service drm /system/bin/drmserver
user drm
group system root inet
具体解析过程见system\core\init\Init_parser.c。解析所得服务添加到service_list中,动作添加到action_list中。
接下来在main函数中执行动作和启动进程服务:
execute_one_command();
restart_processes()
通常init过程需要创建一些系统文件夹并启动USB守护进程、Android Debug Bridge守护进程、Debug守护进程、ServiceManager进程、Zygote进程等。这里的服务都是linux底层服务。
l ServiceManager进程
源码:frameworks\base\cmd\servicemanager\Service_manager.cpp
命令:/system/bin/servicemanager
说明:ServiceManager进程是所有服务的管理器。
在main函数中有如下代码:
int main(int argc, char **argv)
{
struct binder_state *bs;
void *svcmgr = BINDER_SERVICE_MANAGER;
bs = binder_open(128*1024);
if (binder_become_context_manager(bs)) {
LOGE("cannot become context manager (%s)\n", strerror(errno));
return -1;
}
svcmgr_handle = svcmgr;
binder_loop(bs, svcmgr_handler);
return 0;
}
首先调用binder_open()打开Binder设备(/dev/binder),调用binder_become_context_manager()把当前进程设置为ServiceManager。ServiceManager本身就是一个服务。
int binder_become_context_manager(struct binder_state *bs)
{
return ioctl(bs->fd, BINDER_SET_CONTEXT_MGR, 0);
}
最后binder_loop()进入循环状态,并设置svcmgr_handler回调函数等待添加、查询、获取服务等请求。
l 创建VM并在VM中开启Zygote进程
源码:frameworks\base\cmds\app_process\App_main.cpp
frameworks/base/core/jni/AndroidRuntime.cpp
frameworks\base\core\java\com\android\internal\os\ZygoteInit.java
命令:/system/bin/app_process
在main@App_main.cpp函数中有如下代码:
if (0 == strcmp("--zygote", arg)) {
bool startSystemServer = (i < argc) ?
strcmp(argv[i], "--start-system-server") == 0 : false;
setArgv0(argv0, "zygote");
set_process_name("zygote");
runtime.start("com.android.internal.os.ZygoteInit",
startSystemServer);
} else {
set_process_name(argv0);
runtime.mClassName = arg;
// Remainder of args get passed to startup class main()
runtime.mArgC = argc-i;
runtime.mArgV = argv+i;
LOGV("App process is starting with pid=%d, class=%s.\n",
getpid(), runtime.getClassName());
runtime.start();
}
appRuntime是AndroidRuntime的子类,所以这里的runtime.start()其实调用的是AndroidRuntime::start()并传递参数ZygoteInit。
AndroidRuntime::start()(@AndroidRuntime.cpp)有如下代码:
在start中建立了一个Dalvik虚拟机;注册JNI接口;通过com.android.internal.os.ZygoteInit参数在Dalvik虚拟机中运行ZygoteInit.java的main(),这样ZygoteInit就是VM的主进程。
l VM中Zygote进程
在其main()@ZygoteInit.java中,如下所示:
(1)registerZygoteSocket()登记端口
(2)preloadClasses()装载相关类。这里大概要装载1000多个类,具体装载类见frameworks\base\preloaded-classes。(preloaded-classes的生成见附件)。
(3)preloadResources()预加载资源。
(4)startSystemServer()启动SystemServer进程。
(5)main()最后会调用runSelectLoopMode(),进入while循环,由peers创建新的进程。
startSystemServer()代码:
/* 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",
};
ZygoteConnection.Arguments parsedArgs = null;
int pid;
try {
parsedArgs = new ZygoteConnection.Arguments(args);
/*
* Enable debugging of the system process if *either* the command line flags
* indicate it should be debuggable or the ro.debuggable system property
* is set to "1"
*/
int debugFlags = parsedArgs.debugFlags;
if ("1".equals(SystemProperties.get("ro.debuggable")))
debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
/* Request to fork the system server process */
pid = Zygote.forkSystemServer(
parsedArgs.uid, parsedArgs.gid,
parsedArgs.gids, debugFlags, null,
parsedArgs.permittedCapabilities,
parsedArgs.effectiveCapabilities)
Zygote包装了Linux的fork。forkSystemServer()调用forkAndSpecialize(),最终穿过虚拟机调用dalvik\vm\native\dalvik_system_Zygote.c中Dalvik_dalvik_system_Zygote_forkAndSpecialize()。由dalvik完成fork新的进程。
l SystemService进程
源码:frameworks/base/services/java/com/android/server/SystemServer.java
framewroks/base/services/jni/com_android_server_SystemServer.cpp
Frameworks/base/cmds/system_server/library/System_init.cpp
说明:被zygote启动,用于创建init.rc定义的服务之外的所有服务,包括native服务和java空间服务。
在main()的最后有如下代码:
// The system server has to run all of the time, so it needs to be
// as efficient as possible with its memory usage.
VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
System.loadLibrary("android_servers");
init1(args);
Init1()是在native空间实现的,用于启动native空间的服务,其实现在com_android_server_SystemServer.cpp中的android_server_SystemServer_init1():
static void android_server_SystemServer_init1(JNIEnv* env, jobject clazz)
{
system_init();
}
system_init()(frameworks\base\cmds\system_server\library)部分代码如下:
(1)启动SurfaceFlinger,(在里面启动开机动画bootanim)
(2)服务初始化创建native层的各个服务:
(3)回到android runtime的SystemServer.java,调用init2()。
public static final void init2() {
Slog.i(TAG, "Entered the Android system server!");
Thread thr = new ServerThread();
thr.setName("android.server.ServerThread");
thr.start();
}
Init2启动一个线程,专门用来启动java空间的所有服务。
附件1:preloaded-classes的生成过程
这个文件有WritePreloadedClassFile类自动生成。分析该类的main函数,有如下一段筛选类的代码:
// Preload classes that were loaded by at least 2 processes. Hopefully,
// the memory associated with these classes will be shared.
for (LoadedClass loadedClass : root.loadedClasses.values()) {
Set<String> names = loadedClass.processNames();
if (!Policy.isPreloadable(loadedClass)) {
continue;
}
if (names.size() >= MIN_PROCESSES ||
(loadedClass.medianTimeMicros() > MIN_LOAD_TIME_MICROS && names.size() > 1)) {
toPreload.add(loadedClass);
}
}
int initialSize = toPreload.size();
System.out.println(initialSize
+ " classses were loaded by more than one app.");
// Preload eligable classes from applications (not long-running
// services).
for (Proc proc : root.processes.values()) {
if (proc.fromZygote() && !Policy.isService(proc.name)) {
for (Operation operation : proc.operations) {
LoadedClass loadedClass = operation.loadedClass;
if (shouldPreload(loadedClass)) {
toPreload.add(loadedClass);
}
}
}
}
其中MIN_LOAD_TIME_MICROS等于1250,当类的装载时间大于1.25ms,则需要预装载。
Policy.isPreloadable()定于如下:
/**Reports if the given class should be preloaded. */
public static boolean isPreloadable(LoadedClass clazz) {
return clazz.systemClass && !EXCLUDED_CLASSES.contains(clazz.name);
}
其中EXCLUDED_CLASSES如下定义:
/**
* Classes which we shouldn't load from the Zygote.
*/
private static final Set<String> EXCLUDED_CLASSES
= new HashSet<String>(Arrays.asList(
// Binders
"android.app.AlarmManager",
"android.app.SearchManager",
"android.os.FileObserver",
"com.android.server.PackageManagerService$AppDirObserver",
// Threads
"android.os.AsyncTask",
"android.pim.ContactsAsyncHelper",
"java.lang.ProcessManager"
));
这几个Binders和Thread是不会被预加载的。
另外还有一些application需要装载,要求满足条件proc.fromZygote()且不是属于常驻内存的服务。SERVICES定义如下:
/**
* Long running services. These are restricted in their contribution to the
* preloader because their launch time is less critical.
*/
// TODO: Generate this automatically from package manager.
private static final Set<String> SERVICES = new HashSet<String>(Arrays.asList(
"system_server",
"com.google.process.content",
"android.process.media",
"com.android.bluetooth",
"com.android.calendar",
"com.android.inputmethod.latin",
"com.android.phone",
"com.google.android.apps.maps.FriendService", // pre froyo
"com.google.android.apps.maps:FriendService", // froyo
"com.google.android.apps.maps.LocationFriendService",
"com.google.android.deskclock",
"com.google.process.gapps",
"android.tts"
));
preloaded-classes是在下载源码的时候生成,WritePreloadedClassFile类并没有被用到,但可以通过这个类了解Android系统对预加载类的默认要求,参考修改preloaded-classes文件,减少开机初始化时要预加载的类,提高开机速度。
产生preload-classes的方法是在Android根目录下执行以下命令:
$java -Xss512M -cp /path/to/preload.jar WritePreloadedClassFile /path/to/.compiled
1517 classses were loaded by more than one app.
Added 147 more to speed up applications.
1664 total classes will be preloaded.
Writing object model...
Done!
在该命令中,/path/to/preload.jar是指out/host/darwin-x86/framework/preload.jar,该Jar是由frameworks/base/tools/preload子项目编译而成的。
/path/to/.compiled/是指frameworks/base/tools/preload目录下的那几个.compiled文件。
参数-Xss用于执行该程序所需要的Java虚拟机栈大小,此处使用512MB,默认的大小不能满足该程序的运行,会抛出java.lang.StackOverflowError错误信息。
WritePreloadedClassFile是要执行的具体类。
执行完以上命令后,会在frameworks/base目录下产生preload-classes文本文件。在Android源码编译的时候,会最终把preload-classes文件打包到framework.jar中。
附件2:SystemService进程中的ServerThread线程
Slog.i(TAG, "Content Manager");
ContentService.main(context,
factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL);
Slog.i(TAG, "System Content Providers");
ActivityManagerService.installSystemProviders();
Slog.i(TAG, "Battery Service");
battery = new BatteryService(context);
ServiceManager.addService("battery", battery);
Slog.i(TAG, "Lights Service");
lights = new LightsService(context);
Slog.i(TAG, "Vibrator Service");
ServiceManager.addService("vibrator", new VibratorService(context));
// only initialize the power service after we have started the
// lights service, content providers and the battery service.
power.init(context, lights, ActivityManagerService.getDefault(), battery);
Slog.i(TAG, "Alarm Manager");
AlarmManagerService alarm = new AlarmManagerService(context);
ServiceManager.addService(Context.ALARM_SERVICE, alarm);
并且把这些服务添加到ServiceManager中,以便管理和进程间通讯。其中较费时的服务是PackageManagerService(见附件)。
在该线程后半部分,ActivityManagerService会等待AppWidget、WallPaper、IMM等systemReady后调用自身的systemReady()。
((ActivityManagerService)ActivityManagerNative.getDefault())
.systemReady(new Runnable(){....})
源码:frameworks\base\services\java\com\android\server\am\ActivityManagerService.java
public void systemReady(final Runnable goingCallback){
... ...
resumeTopActivityLocked(null); // 这里启动Home应用程序
}
resumeTopActivityLocked代码中,由于Activity管理栈为空,因此启动Launcher。
// Find the first activity that is not finishing.
ActivityRecord next = topRunningActivityLocked(null);
// Remember how we'll process this pause/resume situation, and ensure
// that the state is reset however we wind up proceeding.
final boolean userLeaving = mUserLeaving;
mUserLeaving = false;
if (next == null) {
// There are no more activities! Let's just start up the
// Launcher...
return startHomeActivityLocked();
}
在startHomeActivityLocked()中创建一个带Category为CATEGORY_HOME的Intent,由此去启动相应Activity,即Launcher。
Intent intent = new Intent(
mTopAction,
mTopData != null ? Uri.parse(mTopData) : null);
intent.setComponent(mTopComponent);
if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
intent.addCategory(Intent.CATEGORY_HOME);
}
这样,Android系统便启动起来进入到待机界面。
附件3:PackageManagerService
源码:frameworks\base\services\java\com\android\server\PackageManagerService.java
说明:由SystemServer中init2()在启动java空间服务时启动的服务之一。调用过程如下:
main(context, factoryTest)
PackageManagerService(context, factoryTest)(扫描/system/framework /system/app /data/app data/app-private)
scanDirLI(dir, flags, mode)
scanPackageLI(file, file resfile, flags, mode)
parsePackage(file, dest filename, metrics, flags)
parsePackage(file, dest, metrics, flags)
openXmlResourceParser(cookie, filename) (“AndroidManifest.xml“)
openXmlBlockAsset(cookie, filename)
openXmlAssetNative(cookie, filename)
Android_content_AssetManager_openXmlAssetNative
openNonAsset(cookie, filename, flag)
openNonAssetInPathLocked(filename, mode, asset_path)
getZipFileLocked(asset_path)
getZip(ap.path)
get(path)
getZip()
SharedZip(path, modWhen)
ZipFileRO::open(path)
parseZipArchive(void)
get4LE(ptr)
(memory access)
最终的zip文件(apk)读取是在下面这两个函数:
/*
* Open the specified file read-only. We memory-map the entire thing and
* close the file before returning.
*/
status_t ZipFileRO::open(const char* zipFileName)
{
int fd = -1;
off_t length;
assert(mFileMap == NULL);
LOGD("opening zip '%s'\n", zipFileName);
/*
* Open and map the specified file.
*/
fd = ::open(zipFileName, O_RDONLY);
if (fd < 0) {
LOGW("Unable to open zip '%s': %s\n", zipFileName, strerror(errno));
return NAME_NOT_FOUND;
}
length = lseek(fd, 0, SEEK_END);
if (length < 0) {
close(fd);
return UNKNOWN_ERROR;
}
mFileMap = new FileMap();
if (mFileMap == NULL) {
close(fd);
return NO_MEMORY;
}
if (!mFileMap->create(zipFileName, fd, 0, length, true)) {
LOGW("Unable to map '%s': %s\n", zipFileName, strerror(errno));
close(fd);
return UNKNOWN_ERROR;
}
mFd = fd;
/*
* Got it mapped, verify it and create data structures for fast access.
*/
if (!parseZipArchive()) {
mFileMap->release();
mFileMap = NULL;
return UNKNOWN_ERROR;
}
LOGD("done opening zip\n");
return OK;
}
/*
* Parse the Zip archive, verifying its contents and initializing internal
* data structures.
*/
bool ZipFileRO::parseZipArchive(void)
{
#define CHECK_OFFSET(_off) { \
if ((unsigned int) (_off) >= maxOffset) { \
LOGE("ERROR: bad offset %u (max %d): %s\n", \
(unsigned int) (_off), maxOffset, #_off); \
goto bail; \
} \
}
const unsigned char* basePtr = (const unsigned char*)mFileMap->getDataPtr();
const unsigned char* ptr;
size_t length = mFileMap->getDataLength();
bool result = false;
unsigned int i, numEntries, cdOffset;
unsigned int val;
/*
* The first 4 bytes of the file will either be the local header
* signature for the first file (kLFHSignature) or, if the archive doesn't
* have any files in it, the end-of-central-directory signature
* (kEOCDSignature).
*/
val = get4LE(basePtr);
if (val == kEOCDSignature) {
LOGI("Found Zip archive, but it looks empty\n");
goto bail;
} else if (val != kLFHSignature) {
LOGV("Not a Zip archive (found 0x%08x)\n", val);
goto bail;
}
/*
* Find the EOCD. We'll find it immediately unless they have a file
* comment.
*/
ptr = basePtr + length - kEOCDLen;
while (ptr >= basePtr) {
if (*ptr == (kEOCDSignature & 0xff) && get4LE(ptr) == kEOCDSignature)
break;
ptr--;
}
if (ptr < basePtr) {
LOGI("Could not find end-of-central-directory in Zip\n");
goto bail;
}
/*
* There are two interesting items in the EOCD block: the number of
* entries in the file, and the file offset of the start of the
* central directory.
*
* (There's actually a count of the #of entries in this file, and for
* all files which comprise a spanned archive, but for our purposes
* we're only interested in the current file. Besides, we expect the
* two to be equivalent for our stuff.)
*/
numEntries = get2LE(ptr + kEOCDNumEntries);
cdOffset = get4LE(ptr + kEOCDFileOffset);
/* valid offsets are [0,EOCD] */
unsigned int maxOffset;
maxOffset = (ptr - basePtr) +1;
LOGV("+++ numEntries=%d cdOffset=%d\n", numEntries, cdOffset);
if (numEntries == 0 || cdOffset >= length) {
LOGW("Invalid entries=%d offset=%d (len=%zd)\n",
numEntries, cdOffset, length);
goto bail;
}
/*
* Create hash table. We have a minimum 75% load factor, possibly as
* low as 50% after we round off to a power of 2.
*/
mNumEntries = numEntries;
mHashTableSize = roundUpPower2(1 + ((numEntries * 4) / 3));
mHashTable = (HashEntry*) calloc(1, sizeof(HashEntry) * mHashTableSize);
/*
* Walk through the central directory, adding entries to the hash
* table.
*/
ptr = basePtr + cdOffset;
for (i = 0; i < numEntries; i++) {
unsigned int fileNameLen, extraLen, commentLen, localHdrOffset;
const unsigned char* localHdr;
unsigned int hash;
if (get4LE(ptr) != kCDESignature) {
LOGW("Missed a central dir sig (at %d)\n", i);
goto bail;
}
if (ptr + kCDELen > basePtr + length) {
LOGW("Ran off the end (at %d)\n", i);
goto bail;
}
localHdrOffset = get4LE(ptr + kCDELocalOffset);
CHECK_OFFSET(localHdrOffset);
fileNameLen = get2LE(ptr + kCDENameLen);
extraLen = get2LE(ptr + kCDEExtraLen);
commentLen = get2LE(ptr + kCDECommentLen);
//LOGV("+++ %d: localHdr=%d fnl=%d el=%d cl=%d\n",
// i, localHdrOffset, fileNameLen, extraLen, commentLen);
//LOGV(" '%.*s'\n", fileNameLen, ptr + kCDELen);
/* add the CDE filename to the hash table */
hash = computeHash((const char*)ptr + kCDELen, fileNameLen);
addToHash((const char*)ptr + kCDELen, fileNameLen, hash);
// localHdr = basePtr + localHdrOffset;
// if (get4LE(localHdr) != kLFHSignature) {
// LOGW("Bad offset to local header: %d (at %d)\n",
// localHdrOffset, i);
// goto bail;
// }
ptr += kCDELen + fileNameLen + extraLen + commentLen;
CHECK_OFFSET(ptr - basePtr);
}
result = true;
bail:
return result;
#undef CHECK_OFFSET
}
附件3:android提高启动速度的调试工具
Bootchart
是一个用于linux启动过程性能分析的开源软件工具,在系统启动过程自动收集CPU占用率、进程等信息,并以图形方式显示分析结果,可用作指导优化系统启动过程。目前Android已自带bootchart,但缺省时不被编译。要使用bootchart,可依循如下步骤(已在3200版本上验证通过):
1) 设置环境变量INIT_BOOTCHART=true,重新编译Android源码目录树下的system/core/init/
$ touch system/core/init/init.c
$ m INIT_BOOTCHART=true
编译生成新的可执行文件init,该文件在手机文件系统位于根/下,对应的flash image是boot.img,为此需重新烧写含有新的init的boot.img。
2) 在手机上创建文件/data/bootchart-start,其内容是bootchart的采样时间:
adb shell 'echo $TIMEOUT > /data/bootchart-start'
其中$TIMEOUT是期望采样的时间,单位为秒,例如要采样两分钟,则执行:
adb shell 'echo 120 > /data/bootchart-start'
3) 重启手机,init运行时将自动创建文件夹/data/bootchart/,并在其中保存采样数据,采样数据由5个文件组成:
header
proc_stat.log
proc_ps.log
proc_diskstats.log
kernel_pacct
需要注意,在手机上运行bootchart采样完成后若不再使用bootchart则需手工删除文件/data/bootchart-start,否则手机每次重启时都会运行bootchart。
4) 将上述5个文件上传到PC上并打包成bootchart.tgz,可借助Android源码目录树下提供的工具脚本system/core/init/grab-bootchart.sh自动完成这些过程,或手工通过adb pull将这5个文件上传到PC并打包。
5) 从www.bootchart.org下载安装bootchart在PC上的结果图表生成工具,我已下载uBuntu上的deb包bootchart_0.9-0ubuntu6_all.deb,安装即可:
dpkg -i bootchart_0.9-0ubuntu6_all.deb
会安装如下jar文件:
/usr/share/bootchart/bootchart.jar
6) 执行下面的命令生成分析结果图表,缺省生成png格式的图像文件bootchart.png:
java -jar /usr/share/bootchart/bootchart.jar /path/to/bootchart.tgz
7) 用看图软件查看分析结果bootchart.png。
8) 结果分析参见bootchart官方网站文档或android源码中的readme。