Android startup process
How does the computer start
Computer hardware includes: CPU, memory, hard disk, graphics card, display, keyboard and mouse input and output equipment. All software is stored in the hard disk, program execution, the program needs to be read from the hard disk into memory, and then loaded into the CPU to run. When you press the power button, there is nothing in memory, so you need some way to load the operating system into memory, and the BIOS does that.
- The boot stage
BIOS: BIOS is a program on the motherboard chip, the computer power, the first thing is to read BIOS.
The BIOS starts with hardware detection to check whether the computer hardware can meet the basic conditions for running. If there is a problem with the hardware, the motherboard makes a different beep, starts and stops. If there is no problem, the screen displays CPU, memory, and hard disk information.
After the hardware self-check is complete, the BIOS cedes control to the next stage of the boot program. The BIOS needs to know on which device the next boot program is stored. The BIOS requires a sort of external storage device. Give priority to the first device in line. This is the boot sort we set up in BIOS.
When the first storage device is activated, the device reads the first sector of the device, which is the first 512 bytes. If the last two bytes of these 512 bytes are 0x55 and 0xAA, the device is available for system boot. If not, the next device is started sequentially.
These first 512 bytes are called the Master boot record (MBR). It is responsible for the disk operating system to read and write hard disk partition legitimate type judgment, partition boot information location. MBR does not belong to any CIA system, it is called into memory before the operating system, and functions. Control is then handed over to the operating system in the primary partition and the primary partition information is used to manage the hard disk.
The MAIN function of the MBR is to tell the computer where to find the operating system on the hard disk. After reading the first 446 bytes of machine code from the MBR, the computer no longer transfers control. Instead, it runs a boot Loader that implements the installation, and the user chooses which operating system to boot.
- Kernel loading phase
After selecting the operating system, control is given to the operating system, and the operating system kernel is loaded into memory.
In Linux, load the kernel under /boot. After the kernel is loaded, run the first program, /sbin/init. It generates the init process from the configuration file. It is the first process that Linux started with a PID of 1. All other processes are its descendants.
The init thread then loads each module of the system. For example, window programs and network programs, until the /bin/login program is executed, the login page is displayed, and the user enters the user name and password.
At this point, the system startup is complete.
Android startup process
Android is based on Linux. But it doesn’t have a BIOS program. Instead, it has a BootLoader. Similar to the BIOS, it is used to initialize hardware devices before the system is loaded and finally call the system kernel to prepare the environment. In Android, there is no hard disk, but ROM, which is similar to the hard disk that holds the operating system, user programs, and so on. The ROM, like the hard disk, is divided into different areas for storing different programs. In Android, there are mainly the following areas:
- /boot: Stores the boot programs, including the kernel and memory operators
- /system: is equivalent to the C drive of a computer, storing the Android system and system applications
- /recover: Restores the partition. You can access this zone for system recovery
- /data: User data area, which contains user data: contacts, SMS, Settings, and user installed programs
- /cache: The Android system cache, which stores frequently accessed data and applications
- / MISC: Miscellaneous items
- /sdcard: user’s own storage area. Store photos and videos
The Android system starts like a PC. When booting up, the BootLoader is first loaded, which reads the ROM to find the system and loads the kernel into RAM.
When the kernel is started, it initializes various software and hardware environments, loads drivers, and mounts file systems. The final stage starts executing the first user-space process, init.
The init process
Init is the user’s first process, pid=1. Kernal starts will call/system/core/init/init. CPP’s main () method.
int main(int argc,char ** argv){...if(is_first_stage){
// Create and mount the file directory required for startup
mount("tmpfs"."/dev"."tmpfs",MS_NOSUID,"mode=0755");
mkdir("/dev/pts".0755);
// Create and hang in many.... }...// Initialize the properties service
property_init(a); .// It is used to set the signal handler function of the child process (such as Zygote). If the child process exits unexpectedly, the init process will call the signal handler function set in this function to handle it
signal_handler_init(a); .// Start the properties service
start_property_service(a); .// Parse the init.rc configuration file
parser.ParseConfig("/init.rc");
}
Copy the code
Initialize the Kernel log, create a shared memory space, load /default.prop, and parse init.rc.
Init. Rc file
The init.rc file is an important configuration file for the Android system and is located in the /system/core/rootdir/ directory. The main function is to define a series of actions that need to be executed when the system is started, perform specific actions, set environment variables and attributes, and execute specific services.
The init process starts these services by creating sub-processes. These services are native services that run in Linux space and provide specific services to the upper layer through sockets. And runs in the background as a daemon.
The following important services are started with the init.rc script:
- Service_manager: Starts binder IPC to manage all Android services
- Mountd: device installation Daemon, responsible for device installation and status notification
- Debuggerd: Starts the debug system and processes the requests of the debugging process
- Rild: Starts the Radio Interface Layer Daemon service to process telephone-related events and requests
- Media_server: Starts AudioFlinger, MediaPlayerService, and CameraService, which are responsible for functions related to multimedia playback, including audio and video decoding
- Surface_flinger: Starts SurfaceFlinger to display output
- Zygote: The process incubator, which starts Android Java VMRuntime and starts SystemServer, is responsible for the incubation of Android application processes. At this stage, you can see the “Android” logo on the device screen.
The init process will enter the loop state.
Service_manager process
The ServiceManager is a daemon of the Binder IPC communication process and a Binder service. The ServiceManager process starts Binder to query and register services.
Surface_flinger process
SurfaceFlinger is responsible for image rendering, is the integration of the application UI, and its function is to synthesize all the Surface and render to the display device. The SurfaceFlinger process starts the FrameBuffer and initializes the display system.
Media_server process
The MediaServer process mainly starts the AudioFlinger audio service and CameraService CameraService. Responsible for audio parsing playback, camera related processing.
The Zygote process
Zygote has two functions: starting systemService and incubating application processes.
The Zygote process incubates all Android application processes and is the basis of the Android Framework. The start of the Zygote process also marks the start of the Framework Framework initialization.
Zygote starts the Zygote process by calling the start method of AppRuntime in main() of app_main.cpp
int main(int argc,char* const argv[]){
while( i < argc ){
const char* arg=argv[i++];
if(strcmp(arg,"--zygote") = =0) {// If the current process is in Zygote, set Zygote =true
zygote=true;
niceName=ZYGOTE_NICE_NAME;
}else if(strcmp(arg,"--start-system-server") = =0) {// if the current process is in SystemServer, startSystemServer=true
startSystemServer=true; }}// continue the code in the Init process above
if(zygote){
// Start Zygote
runtime.start("com.android.internal.os.ZygoteInit",args,zygote); }}Copy the code
The Zygote service process provides the following functions:
- Register the underlying functionality of JNI functions to the virtual machine
- Preload Java classes and resources
- Fork and start the system_server core process
- Listens to handle requests for “incubate a new process” as a daemon
When Zygote is started, the main() method of the frameworks/base/ CMDS /app_process/ app_main.cpp file is executed.
System_server process
The system_server process is fork from the Zygote process.
/ / will first call ZygoteInit. StartSystemServer () method
ZygoteInit.startSystemServer()
//fork subprocess system_server to enter the system_server process.
ZygoteInit.handleSystemServerProcess()
// Set the name of the current process to "system_server" and create the PathClassLoader.
RuntimeInit.zygoteInit()
// Redirect log output, general initialization (set default exception catching method, time zone, etc.), initialize Zygote -> nativeZygoteInit().
nativeZygoteInit()
// The onZygoteInit() method in app_main.cpp goes through several layers of calls.
app_main::onZygoteInit()// Start a new Binder thread.
applicationInit()
Through layer upon layer calls, / / method throws an exception ZygoteInit. MethodAndArgsCaller (m, argv), ZygoteInit. The main () will catch the exception.
ZygoteInit.main()
// Enable DDMS function, preload() to load resources, preload OpenGL, call systemServer.main ().
SystemServer.main()
// Initialize the SystemServer object before calling its run() method.
SystemServer.run()
/ / to the main thread, which is loaded android_servers. So library, the library contains the source code in the frameworks/base/services/directory.
Copy the code
After the system_server process starts, it initializes the system context (setting the theme), creates the SystemServiceManager SystemServiceManager, and then starts various system services
startBootstrapServices(); // Start the boot service
ActivityManagerService, PowerManagerService, LightsService, DisplayManagerService, PackageManagerService, UserManagerService.
// Set ActivityManagerService to start the sensor service.
startCoreServices(); // Start the core service
// This method is main
BatteryService Is used to count battery power. LightService is required.
// Start the UsageStatsService to collect statistics on application usage.
// Start service WebViewUpdateService.
startOtherServices(); // Start other services
// This method starts services InputManagerService, WindowManagerService.
// Wait for the ServiceManager and SurfaceFlinger to complete startup. Then the startup screen is displayed.
// Start service StatusBarManagerService,
// Prepare the window, power, package, display service:
// - WindowManagerService.systemReady()
// - PowerManagerService.systemReady()
// - PackageManagerService.systemReady()
// - DisplayManagerService.systemReady()
Copy the code
All services are registered with the ServiceManager after they are started.
ActivityManagerService service startup is completed, will enter ActivityManagerService. SystemReady (), and then start the SystemUI, WebViewFactory, Watchdog, Finally, start the desktop Launcher App.
Finally, looper.loop () is entered.
ActivityManagerService start
Start the desktop Launcher App and wait for ActivityManagerService to complete. Let’s look at the ActivityManagerService startup process.
ActivityManagerService(Context)
// Create a foreground thread named "ActivityManager" and get the mHandler.
// Create a thread named "android. UI" using the UiThread class.
// Create foreground and background broadcast receivers.
// Create directory /data/system.
// Create BatteryStatsService.
ActivityManagerService.start(a)// Start the battery statistics service, create LocalService, and add it to LocalServices.
ActivityManagerService.startOtherServices() - >installSystemProviders(a)// Install all system providers.
ActivityManagerService.systemReady(a)// Restore the latest task in the taskbar.
// Start WebView, SystemUI, Watchdog, and desktop Launcher App.
// Send system broadcast.
Copy the code
To start the desktop Launcher App, the Zygote process will first fork a new process as the App process, then create Application, create and start the Activity, and finally the user will see the desktop.
Complete startup flowchart
Source code analysis project address: github.com/kailaisi/an…
Synchronous public number [open Ken]