blob: 6ad9e20360e09305fbc821659f27f75834fdd147 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.internal.os;
18
Elliott Hughes894724b2014-12-15 12:39:51 -080019import static android.system.OsConstants.POLLIN;
Elliott Hughesa9569ff2014-04-28 20:53:52 -070020import static android.system.OsConstants.S_IRWXG;
21import static android.system.OsConstants.S_IRWXO;
Kenny Root4c74f8c2012-08-17 08:45:55 -070022
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023import android.content.res.Resources;
24import android.content.res.TypedArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.net.LocalServerSocket;
Romain Guy74c69122013-05-08 17:54:20 -070026import android.opengl.EGL14;
Jeff Brownebed7d62011-05-16 17:08:42 -070027import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.os.SystemClock;
Romain Guyc5e36382013-05-09 11:08:17 -070029import android.os.SystemProperties;
Jamie Gennis6ad04522013-04-15 18:53:24 -070030import android.os.Trace;
Bill Yi9a76e9b2014-04-29 18:52:48 -070031import android.system.ErrnoException;
Elliott Hughes860c5912014-04-28 19:19:13 -070032import android.system.Os;
33import android.system.OsConstants;
Elliott Hughes894724b2014-12-15 12:39:51 -080034import android.system.StructPollfd;
Raph Levienc3dd1c12015-04-06 10:37:57 -070035import android.text.Hyphenator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.util.EventLog;
37import android.util.Log;
Torne (Richard Coles)08cfaf62014-05-08 16:07:05 +010038import android.webkit.WebViewFactory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039
Jeff Sharkeyfdeeeea2016-01-11 17:34:24 -070040import com.android.internal.os.InstallerConnection.InstallerException;
41
Narayan Kamath29564cd2014-08-07 10:57:40 +010042import dalvik.system.DexFile;
43import dalvik.system.PathClassLoader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import dalvik.system.VMRuntime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045
Brian Carlstrom46703b02011-04-06 15:41:29 -070046import libcore.io.IoUtils;
47
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import java.io.BufferedReader;
49import java.io.FileDescriptor;
Ying Wangd0c45352014-11-13 15:22:47 -080050import java.io.FileInputStream;
51import java.io.FileNotFoundException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import java.io.IOException;
53import java.io.InputStream;
54import java.io.InputStreamReader;
55import java.lang.reflect.InvocationTargetException;
56import java.lang.reflect.Method;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import java.util.ArrayList;
58
59/**
60 * Startup class for the zygote process.
61 *
62 * Pre-initializes some classes, and then waits for commands on a UNIX domain
Elliott Hughese1dfcb72011-07-08 11:08:07 -070063 * socket. Based on these commands, forks off child processes that inherit
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064 * the initial state of the VM.
65 *
66 * Please see {@link ZygoteConnection.Arguments} for documentation on the
67 * client protocol.
68 *
69 * @hide
70 */
71public class ZygoteInit {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072 private static final String TAG = "Zygote";
73
Romain Guyc5e36382013-05-09 11:08:17 -070074 private static final String PROPERTY_DISABLE_OPENGL_PRELOADING = "ro.zygote.disable_gl_preload";
Luis Hector Chavez5dd239a2015-10-06 14:01:45 -070075 private static final String PROPERTY_RUNNING_IN_CONTAINER = "ro.boot.container";
Romain Guyc5e36382013-05-09 11:08:17 -070076
Narayan Kamathc41638c2014-04-07 13:56:15 +010077 private static final String ANDROID_SOCKET_PREFIX = "ANDROID_SOCKET_";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078
79 private static final int LOG_BOOT_PROGRESS_PRELOAD_START = 3020;
80 private static final int LOG_BOOT_PROGRESS_PRELOAD_END = 3030;
81
82 /** when preloading, GC after allocating this many bytes */
83 private static final int PRELOAD_GC_THRESHOLD = 50000;
84
Narayan Kamathc41638c2014-04-07 13:56:15 +010085 private static final String ABI_LIST_ARG = "--abi-list=";
86
87 private static final String SOCKET_NAME_ARG = "--socket-name=";
Barry Hayes0b3533a2010-01-20 12:46:47 -080088
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089 private static LocalServerSocket sServerSocket;
90
91 /**
92 * Used to pre-load resources. We hold a global reference on it so it
93 * never gets destroyed.
94 */
95 private static Resources mResources;
Bob Leee5408332009-09-04 18:31:17 -070096
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097 /**
Ying Wangd0c45352014-11-13 15:22:47 -080098 * The path of a file that contains classes to preload.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099 */
Ying Wangd0c45352014-11-13 15:22:47 -0800100 private static final String PRELOADED_CLASSES = "/system/etc/preloaded-classes";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101
102 /** Controls whether we should preload resources during zygote init. */
Steve Paik3c27a232015-06-10 18:25:44 -0700103 public static final boolean PRELOAD_RESOURCES = true;
Andy McFadden599c9182009-04-08 00:35:56 -0700104
105 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106 * Registers a server socket for zygote command connections
107 *
108 * @throws RuntimeException when open fails
109 */
Narayan Kamathc41638c2014-04-07 13:56:15 +0100110 private static void registerZygoteSocket(String socketName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111 if (sServerSocket == null) {
112 int fileDesc;
Narayan Kamathc41638c2014-04-07 13:56:15 +0100113 final String fullSocketName = ANDROID_SOCKET_PREFIX + socketName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114 try {
Narayan Kamathc41638c2014-04-07 13:56:15 +0100115 String env = System.getenv(fullSocketName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116 fileDesc = Integer.parseInt(env);
117 } catch (RuntimeException ex) {
Narayan Kamathc41638c2014-04-07 13:56:15 +0100118 throw new RuntimeException(fullSocketName + " unset or invalid", ex);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119 }
120
121 try {
Elliott Hughes3fe59512014-12-12 14:07:34 -0800122 FileDescriptor fd = new FileDescriptor();
123 fd.setInt$(fileDesc);
124 sServerSocket = new LocalServerSocket(fd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125 } catch (IOException ex) {
126 throw new RuntimeException(
127 "Error binding to local socket '" + fileDesc + "'", ex);
128 }
129 }
130 }
131
132 /**
133 * Waits for and accepts a single command connection. Throws
134 * RuntimeException on failure.
135 */
Narayan Kamathc41638c2014-04-07 13:56:15 +0100136 private static ZygoteConnection acceptCommandPeer(String abiList) {
Bob Leee5408332009-09-04 18:31:17 -0700137 try {
Narayan Kamathc41638c2014-04-07 13:56:15 +0100138 return new ZygoteConnection(sServerSocket.accept(), abiList);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139 } catch (IOException ex) {
140 throw new RuntimeException(
141 "IOException during accept()", ex);
142 }
143 }
144
145 /**
146 * Close and clean up zygote sockets. Called on shutdown and on the
147 * child's exit path.
148 */
149 static void closeServerSocket() {
150 try {
151 if (sServerSocket != null) {
Dave Platt02f042d2013-12-12 15:45:49 -0800152 FileDescriptor fd = sServerSocket.getFileDescriptor();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153 sServerSocket.close();
Dave Platt02f042d2013-12-12 15:45:49 -0800154 if (fd != null) {
Bill Yi9a76e9b2014-04-29 18:52:48 -0700155 Os.close(fd);
Dave Platt02f042d2013-12-12 15:45:49 -0800156 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157 }
158 } catch (IOException ex) {
159 Log.e(TAG, "Zygote: error closing sockets", ex);
Bill Yi9a76e9b2014-04-29 18:52:48 -0700160 } catch (ErrnoException ex) {
Dave Platt02f042d2013-12-12 15:45:49 -0800161 Log.e(TAG, "Zygote: error closing descriptor", ex);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162 }
163
164 sServerSocket = null;
165 }
166
Dave Platt89d4c892014-02-05 17:06:42 -0800167 /**
168 * Return the server socket's underlying file descriptor, so that
169 * ZygoteConnection can pass it to the native code for proper
170 * closure after a child process is forked off.
171 */
172
173 static FileDescriptor getServerSocketFileDescriptor() {
174 return sServerSocket.getFileDescriptor();
175 }
176
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177 private static final int UNPRIVILEGED_UID = 9999;
178 private static final int UNPRIVILEGED_GID = 9999;
179
180 private static final int ROOT_UID = 0;
181 private static final int ROOT_GID = 0;
182
Jeff Brown0c2313d2011-06-10 22:46:40 -0700183 static void preload() {
Bill Yi9a76e9b2014-04-29 18:52:48 -0700184 Log.d(TAG, "begin preload");
Yasuhiro Matsuda25878b22015-09-03 16:18:21 +0900185 Trace.traceBegin(Trace.TRACE_TAG_DALVIK, "PreloadClasses");
186 preloadClasses();
187 Trace.traceEnd(Trace.TRACE_TAG_DALVIK);
188 Trace.traceBegin(Trace.TRACE_TAG_DALVIK, "PreloadResources");
189 preloadResources();
190 Trace.traceEnd(Trace.TRACE_TAG_DALVIK);
191 Trace.traceBegin(Trace.TRACE_TAG_DALVIK, "PreloadOpenGL");
Romain Guy74c69122013-05-08 17:54:20 -0700192 preloadOpenGL();
Yasuhiro Matsuda25878b22015-09-03 16:18:21 +0900193 Trace.traceEnd(Trace.TRACE_TAG_DALVIK);
Brian Carlstrom6c9af962014-09-11 15:36:00 -0700194 preloadSharedLibraries();
Raph Levienc3dd1c12015-04-06 10:37:57 -0700195 preloadTextResources();
Torne (Richard Coles)08cfaf62014-05-08 16:07:05 +0100196 // Ask the WebViewFactory to do any initialization that must run in the zygote process,
197 // for memory sharing purposes.
198 WebViewFactory.prepareWebViewInZygote();
Bill Yi9a76e9b2014-04-29 18:52:48 -0700199 Log.d(TAG, "end preload");
Romain Guy74c69122013-05-08 17:54:20 -0700200 }
201
Brian Carlstrom6c9af962014-09-11 15:36:00 -0700202 private static void preloadSharedLibraries() {
203 Log.i(TAG, "Preloading shared libraries...");
204 System.loadLibrary("android");
205 System.loadLibrary("compiler_rt");
206 System.loadLibrary("jnigraphics");
207 }
208
Romain Guy74c69122013-05-08 17:54:20 -0700209 private static void preloadOpenGL() {
Romain Guyc5e36382013-05-09 11:08:17 -0700210 if (!SystemProperties.getBoolean(PROPERTY_DISABLE_OPENGL_PRELOADING, false)) {
211 EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY);
212 }
Jeff Brown0c2313d2011-06-10 22:46:40 -0700213 }
214
Raph Levienc3dd1c12015-04-06 10:37:57 -0700215 private static void preloadTextResources() {
216 Hyphenator.init();
217 }
218
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219 /**
220 * Performs Zygote process initialization. Loads and initializes
221 * commonly used classes.
222 *
223 * Most classes only cause a few hundred bytes to be allocated, but
224 * a few will allocate a dozen Kbytes (in one case, 500+K).
225 */
226 private static void preloadClasses() {
227 final VMRuntime runtime = VMRuntime.getRuntime();
Bob Leee5408332009-09-04 18:31:17 -0700228
Ying Wangd0c45352014-11-13 15:22:47 -0800229 InputStream is;
230 try {
231 is = new FileInputStream(PRELOADED_CLASSES);
232 } catch (FileNotFoundException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233 Log.e(TAG, "Couldn't find " + PRELOADED_CLASSES + ".");
Ying Wangd0c45352014-11-13 15:22:47 -0800234 return;
235 }
Bob Leee5408332009-09-04 18:31:17 -0700236
Ying Wangd0c45352014-11-13 15:22:47 -0800237 Log.i(TAG, "Preloading classes...");
238 long startTime = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239
Ying Wangd0c45352014-11-13 15:22:47 -0800240 // Drop root perms while running static initializers.
Narayan Kamath23e68782015-01-16 17:22:41 +0000241 final int reuid = Os.getuid();
242 final int regid = Os.getgid();
243
244 // We need to drop root perms only if we're already root. In the case of "wrapped"
245 // processes (see WrapperInit), this function is called from an unprivileged uid
246 // and gid.
247 boolean droppedPriviliges = false;
248 if (reuid == ROOT_UID && regid == ROOT_GID) {
249 try {
250 Os.setregid(ROOT_GID, UNPRIVILEGED_GID);
251 Os.setreuid(ROOT_UID, UNPRIVILEGED_UID);
252 } catch (ErrnoException ex) {
253 throw new RuntimeException("Failed to drop root", ex);
254 }
255
256 droppedPriviliges = true;
Elliott Hughes26b56e62014-12-17 12:28:29 -0800257 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800258
Ying Wangd0c45352014-11-13 15:22:47 -0800259 // Alter the target heap utilization. With explicit GCs this
260 // is not likely to have any effect.
261 float defaultUtilization = runtime.getTargetHeapUtilization();
262 runtime.setTargetHeapUtilization(0.8f);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800263
Ying Wangd0c45352014-11-13 15:22:47 -0800264 try {
265 BufferedReader br
266 = new BufferedReader(new InputStreamReader(is), 256);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800267
Ying Wangd0c45352014-11-13 15:22:47 -0800268 int count = 0;
269 String line;
270 while ((line = br.readLine()) != null) {
271 // Skip comments and blank lines.
272 line = line.trim();
273 if (line.startsWith("#") || line.equals("")) {
274 continue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800275 }
276
Yasuhiro Matsuda25878b22015-09-03 16:18:21 +0900277 Trace.traceBegin(Trace.TRACE_TAG_DALVIK, "PreloadClass " + line);
Ying Wangd0c45352014-11-13 15:22:47 -0800278 try {
279 if (false) {
280 Log.v(TAG, "Preloading " + line + "...");
281 }
Andreas Gampedd8e5fb2015-04-21 09:01:51 -0700282 // Load and explicitly initialize the given class. Use
283 // Class.forName(String, boolean, ClassLoader) to avoid repeated stack lookups
284 // (to derive the caller's class-loader). Use true to force initialization, and
285 // null for the boot classpath class-loader (could as well cache the
286 // class-loader of this class in a variable).
Andreas Gampec917f742015-04-20 19:16:37 -0700287 Class.forName(line, true, null);
Ying Wangd0c45352014-11-13 15:22:47 -0800288 count++;
289 } catch (ClassNotFoundException e) {
290 Log.w(TAG, "Class not found for preloading: " + line);
291 } catch (UnsatisfiedLinkError e) {
292 Log.w(TAG, "Problem preloading " + line + ": " + e);
293 } catch (Throwable t) {
294 Log.e(TAG, "Error preloading " + line + ".", t);
295 if (t instanceof Error) {
296 throw (Error) t;
297 }
298 if (t instanceof RuntimeException) {
299 throw (RuntimeException) t;
300 }
301 throw new RuntimeException(t);
302 }
Yasuhiro Matsuda25878b22015-09-03 16:18:21 +0900303 Trace.traceEnd(Trace.TRACE_TAG_DALVIK);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800304 }
Ying Wangd0c45352014-11-13 15:22:47 -0800305
306 Log.i(TAG, "...preloaded " + count + " classes in "
307 + (SystemClock.uptimeMillis()-startTime) + "ms.");
308 } catch (IOException e) {
309 Log.e(TAG, "Error reading " + PRELOADED_CLASSES + ".", e);
310 } finally {
311 IoUtils.closeQuietly(is);
312 // Restore default.
313 runtime.setTargetHeapUtilization(defaultUtilization);
314
315 // Fill in dex caches with classes, fields, and methods brought in by preloading.
Yasuhiro Matsuda1ab43d52015-06-30 17:07:32 +0900316 Trace.traceBegin(Trace.TRACE_TAG_DALVIK, "PreloadDexCaches");
Ying Wangd0c45352014-11-13 15:22:47 -0800317 runtime.preloadDexCaches();
Yasuhiro Matsuda1ab43d52015-06-30 17:07:32 +0900318 Trace.traceEnd(Trace.TRACE_TAG_DALVIK);
Ying Wangd0c45352014-11-13 15:22:47 -0800319
Narayan Kamath23e68782015-01-16 17:22:41 +0000320 // Bring back root. We'll need it later if we're in the zygote.
321 if (droppedPriviliges) {
322 try {
323 Os.setreuid(ROOT_UID, ROOT_UID);
324 Os.setregid(ROOT_GID, ROOT_GID);
325 } catch (ErrnoException ex) {
326 throw new RuntimeException("Failed to restore root", ex);
327 }
Elliott Hughes26b56e62014-12-17 12:28:29 -0800328 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800329 }
330 }
331
332 /**
333 * Load in commonly used resources, so they can be shared across
334 * processes.
335 *
336 * These tend to be a few Kbytes, but are frequently in the 20-40K
337 * range, and occasionally even larger.
338 */
339 private static void preloadResources() {
340 final VMRuntime runtime = VMRuntime.getRuntime();
Bob Leee5408332009-09-04 18:31:17 -0700341
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800342 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800343 mResources = Resources.getSystem();
344 mResources.startPreloading();
345 if (PRELOAD_RESOURCES) {
346 Log.i(TAG, "Preloading resources...");
347
348 long startTime = SystemClock.uptimeMillis();
349 TypedArray ar = mResources.obtainTypedArray(
350 com.android.internal.R.array.preloaded_drawables);
Filip Gruszczynski811dc3b2015-11-23 12:34:22 -0800351 int N = preloadDrawables(ar);
Jeff Brown14577c42012-03-08 16:40:14 -0800352 ar.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800353 Log.i(TAG, "...preloaded " + N + " resources in "
354 + (SystemClock.uptimeMillis()-startTime) + "ms.");
355
356 startTime = SystemClock.uptimeMillis();
357 ar = mResources.obtainTypedArray(
358 com.android.internal.R.array.preloaded_color_state_lists);
Filip Gruszczynski811dc3b2015-11-23 12:34:22 -0800359 N = preloadColorStateLists(ar);
Jeff Brown14577c42012-03-08 16:40:14 -0800360 ar.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800361 Log.i(TAG, "...preloaded " + N + " resources in "
362 + (SystemClock.uptimeMillis()-startTime) + "ms.");
Filip Gruszczynski811dc3b2015-11-23 12:34:22 -0800363
364 if (mResources.getBoolean(
365 com.android.internal.R.bool.config_freeformWindowManagement)) {
366 startTime = SystemClock.uptimeMillis();
367 ar = mResources.obtainTypedArray(
368 com.android.internal.R.array.preloaded_freeform_multi_window_drawables);
369 N = preloadDrawables(ar);
370 ar.recycle();
371 Log.i(TAG, "...preloaded " + N + " resource in "
372 + (SystemClock.uptimeMillis() - startTime) + "ms.");
373 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800374 }
375 mResources.finishPreloading();
376 } catch (RuntimeException e) {
377 Log.w(TAG, "Failure preloading resources", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800378 }
379 }
380
Filip Gruszczynski811dc3b2015-11-23 12:34:22 -0800381 private static int preloadColorStateLists(TypedArray ar) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800382 int N = ar.length();
383 for (int i=0; i<N; i++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800384 int id = ar.getResourceId(i, 0);
Joe Onorato43a17652011-04-06 19:22:23 -0700385 if (false) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800386 Log.v(TAG, "Preloading resource #" + Integer.toHexString(id));
387 }
388 if (id != 0) {
Alan Viverette77bb6f12015-02-11 17:24:33 -0800389 if (mResources.getColorStateList(id, null) == null) {
Dianne Hackborndde331c2012-08-03 14:01:57 -0700390 throw new IllegalArgumentException(
391 "Unable to find preloaded color resource #0x"
392 + Integer.toHexString(id)
393 + " (" + ar.getString(i) + ")");
394 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800395 }
396 }
397 return N;
398 }
399
400
Filip Gruszczynski811dc3b2015-11-23 12:34:22 -0800401 private static int preloadDrawables(TypedArray ar) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800402 int N = ar.length();
403 for (int i=0; i<N; i++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800404 int id = ar.getResourceId(i, 0);
Joe Onorato43a17652011-04-06 19:22:23 -0700405 if (false) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800406 Log.v(TAG, "Preloading resource #" + Integer.toHexString(id));
407 }
408 if (id != 0) {
Alan Viverette84e001a2014-09-22 00:04:22 -0700409 if (mResources.getDrawable(id, null) == null) {
Dianne Hackborndde331c2012-08-03 14:01:57 -0700410 throw new IllegalArgumentException(
411 "Unable to find preloaded drawable resource #0x"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800412 + Integer.toHexString(id)
Dianne Hackborndde331c2012-08-03 14:01:57 -0700413 + " (" + ar.getString(i) + ")");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800414 }
415 }
416 }
417 return N;
418 }
419
420 /**
421 * Runs several special GCs to try to clean up a few generations of
422 * softly- and final-reachable objects, along with any other garbage.
423 * This is only useful just before a fork().
424 */
Mathieu Chartier9a88f102014-08-20 10:24:11 -0700425 /*package*/ static void gcAndFinalize() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800426 final VMRuntime runtime = VMRuntime.getRuntime();
427
428 /* runFinalizationSync() lets finalizers be called in Zygote,
429 * which doesn't have a HeapWorker thread.
430 */
Brian Carlstrom08065b92011-04-01 15:49:41 -0700431 System.gc();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800432 runtime.runFinalizationSync();
Brian Carlstrom08065b92011-04-01 15:49:41 -0700433 System.gc();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800434 }
435
436 /**
437 * Finish remaining work for the newly forked system server process.
438 */
439 private static void handleSystemServerProcess(
440 ZygoteConnection.Arguments parsedArgs)
441 throws ZygoteInit.MethodAndArgsCaller {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800442
443 closeServerSocket();
444
Mike Lockwood90960e82010-08-06 09:15:25 -0400445 // set umask to 0077 so new files and directories will default to owner-only permissions.
Elliott Hughes860c5912014-04-28 19:19:13 -0700446 Os.umask(S_IRWXG | S_IRWXO);
Mike Lockwood90960e82010-08-06 09:15:25 -0400447
Jeff Brownebed7d62011-05-16 17:08:42 -0700448 if (parsedArgs.niceName != null) {
449 Process.setArgV0(parsedArgs.niceName);
450 }
451
Narayan Kamath29564cd2014-08-07 10:57:40 +0100452 final String systemServerClasspath = Os.getenv("SYSTEMSERVERCLASSPATH");
453 if (systemServerClasspath != null) {
454 performSystemServerDexOpt(systemServerClasspath);
455 }
456
Jeff Brownebed7d62011-05-16 17:08:42 -0700457 if (parsedArgs.invokeWith != null) {
Narayan Kamath29564cd2014-08-07 10:57:40 +0100458 String[] args = parsedArgs.remainingArgs;
459 // If we have a non-null system server class path, we'll have to duplicate the
460 // existing arguments and append the classpath to it. ART will handle the classpath
461 // correctly when we exec a new process.
462 if (systemServerClasspath != null) {
463 String[] amendedArgs = new String[args.length + 2];
464 amendedArgs[0] = "-cp";
465 amendedArgs[1] = systemServerClasspath;
466 System.arraycopy(parsedArgs.remainingArgs, 0, amendedArgs, 2, parsedArgs.remainingArgs.length);
467 }
468
Jeff Brownebed7d62011-05-16 17:08:42 -0700469 WrapperInit.execApplication(parsedArgs.invokeWith,
Elliott Hughese1dfcb72011-07-08 11:08:07 -0700470 parsedArgs.niceName, parsedArgs.targetSdkVersion,
Narayan Kamath37ad4b02015-01-19 16:05:24 +0000471 VMRuntime.getCurrentInstructionSet(), null, args);
Jeff Brownebed7d62011-05-16 17:08:42 -0700472 } else {
Narayan Kamath29564cd2014-08-07 10:57:40 +0100473 ClassLoader cl = null;
474 if (systemServerClasspath != null) {
475 cl = new PathClassLoader(systemServerClasspath, ClassLoader.getSystemClassLoader());
476 Thread.currentThread().setContextClassLoader(cl);
477 }
478
Jeff Brownebed7d62011-05-16 17:08:42 -0700479 /*
480 * Pass the remaining arguments to SystemServer.
481 */
Narayan Kamath29564cd2014-08-07 10:57:40 +0100482 RuntimeInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs, cl);
Jeff Brownebed7d62011-05-16 17:08:42 -0700483 }
484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800485 /* should never reach here */
486 }
487
488 /**
Narayan Kamath29564cd2014-08-07 10:57:40 +0100489 * Performs dex-opt on the elements of {@code classPath}, if needed. We
490 * choose the instruction set of the current runtime.
491 */
492 private static void performSystemServerDexOpt(String classPath) {
493 final String[] classPathElements = classPath.split(":");
494 final InstallerConnection installer = new InstallerConnection();
Makoto Onukic8a2cfe2015-06-23 16:33:48 -0700495 installer.waitForConnection();
Narayan Kamath29564cd2014-08-07 10:57:40 +0100496 final String instructionSet = VMRuntime.getRuntime().vmInstructionSet();
497
498 try {
499 for (String classPathElement : classPathElements) {
Richard Uhler7b08b352015-03-25 16:25:57 -0700500 final int dexoptNeeded = DexFile.getDexOptNeeded(
501 classPathElement, "*", instructionSet, false /* defer */);
502 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
Calin Juravledb4a79a2015-12-23 18:55:08 +0200503 // System server is fully AOTed and never profiled
504 // for profile guided compilation.
Todd Kennedyfa54ab72015-09-25 07:46:12 -0700505 installer.dexopt(classPathElement, Process.SYSTEM_UID, instructionSet,
Calin Juravledb4a79a2015-12-23 18:55:08 +0200506 dexoptNeeded, 0 /*dexFlags*/, null /*volumeUuid*/,
507 false /*useProfiles*/);
Narayan Kamath29564cd2014-08-07 10:57:40 +0100508 }
509 }
Jeff Sharkeyfdeeeea2016-01-11 17:34:24 -0700510 } catch (IOException | InstallerException e) {
511 throw new RuntimeException("Error starting system_server", e);
Narayan Kamath29564cd2014-08-07 10:57:40 +0100512 } finally {
513 installer.disconnect();
514 }
515 }
516
517 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800518 * Prepare the arguments and fork for the system server process.
519 */
Narayan Kamath64cd9072014-05-13 13:35:14 +0100520 private static boolean startSystemServer(String abiList, String socketName)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800521 throws MethodAndArgsCaller, RuntimeException {
Alex Klyubin48a06e72013-04-19 10:01:42 -0700522 long capabilities = posixCapabilitiesAsBits(
523 OsConstants.CAP_KILL,
524 OsConstants.CAP_NET_ADMIN,
525 OsConstants.CAP_NET_BIND_SERVICE,
526 OsConstants.CAP_NET_BROADCAST,
527 OsConstants.CAP_NET_RAW,
Alex Klyubin48a06e72013-04-19 10:01:42 -0700528 OsConstants.CAP_SYS_MODULE,
529 OsConstants.CAP_SYS_NICE,
530 OsConstants.CAP_SYS_RESOURCE,
531 OsConstants.CAP_SYS_TIME,
532 OsConstants.CAP_SYS_TTY_CONFIG
533 );
Luis Hector Chavez5dd239a2015-10-06 14:01:45 -0700534 /* Containers run without this capability, so avoid setting it in that case */
535 if (!SystemProperties.getBoolean(PROPERTY_RUNNING_IN_CONTAINER, false)) {
536 capabilities |= posixCapabilitiesAsBits(OsConstants.CAP_BLOCK_SUSPEND);
537 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800538 /* Hardcoded command line to start the system server */
539 String args[] = {
540 "--setuid=1000",
541 "--setgid=1000",
Pavlin Radoslavov70166252015-11-23 17:13:25 -0800542 "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1032,3001,3002,3003,3006,3007,3009,3010",
Alex Klyubin48a06e72013-04-19 10:01:42 -0700543 "--capabilities=" + capabilities + "," + capabilities,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800544 "--nice-name=system_server",
Narayan Kamathb6b044a2015-02-13 17:31:25 +0000545 "--runtime-args",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800546 "com.android.server.SystemServer",
547 };
548 ZygoteConnection.Arguments parsedArgs = null;
549
550 int pid;
551
552 try {
553 parsedArgs = new ZygoteConnection.Arguments(args);
Jeff Brownebed7d62011-05-16 17:08:42 -0700554 ZygoteConnection.applyDebuggerSystemProperty(parsedArgs);
555 ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800556
557 /* Request to fork the system server process */
558 pid = Zygote.forkSystemServer(
559 parsedArgs.uid, parsedArgs.gid,
Elliott Hughese1dfcb72011-07-08 11:08:07 -0700560 parsedArgs.gids,
561 parsedArgs.debugFlags,
562 null,
Andy McFadden1b4c7962010-10-27 11:26:05 -0700563 parsedArgs.permittedCapabilities,
564 parsedArgs.effectiveCapabilities);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800565 } catch (IllegalArgumentException ex) {
566 throw new RuntimeException(ex);
Bob Leee5408332009-09-04 18:31:17 -0700567 }
568
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800569 /* For child process */
570 if (pid == 0) {
Narayan Kamath64cd9072014-05-13 13:35:14 +0100571 if (hasSecondZygote(abiList)) {
572 waitForSecondaryZygote(socketName);
573 }
574
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 handleSystemServerProcess(parsedArgs);
576 }
577
578 return true;
579 }
580
Alex Klyubin48a06e72013-04-19 10:01:42 -0700581 /**
582 * Gets the bit array representation of the provided list of POSIX capabilities.
583 */
584 private static long posixCapabilitiesAsBits(int... capabilities) {
585 long result = 0;
586 for (int capability : capabilities) {
587 if ((capability < 0) || (capability > OsConstants.CAP_LAST_CAP)) {
588 throw new IllegalArgumentException(String.valueOf(capability));
589 }
590 result |= (1L << capability);
591 }
592 return result;
593 }
594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595 public static void main(String argv[]) {
596 try {
Yasuhiro Matsuda25878b22015-09-03 16:18:21 +0900597 Trace.traceBegin(Trace.TRACE_TAG_DALVIK, "ZygoteInit");
598 RuntimeInit.enableDdms();
599 // Start profiling the zygote initialization.
600 SamplingProfilerIntegration.start();
601
Narayan Kamathc41638c2014-04-07 13:56:15 +0100602 boolean startSystemServer = false;
603 String socketName = "zygote";
604 String abiList = null;
Yasuhiro Matsuda25878b22015-09-03 16:18:21 +0900605 for (int i = 1; i < argv.length; i++) {
606 if ("start-system-server".equals(argv[i])) {
607 startSystemServer = true;
608 } else if (argv[i].startsWith(ABI_LIST_ARG)) {
609 abiList = argv[i].substring(ABI_LIST_ARG.length());
610 } else if (argv[i].startsWith(SOCKET_NAME_ARG)) {
611 socketName = argv[i].substring(SOCKET_NAME_ARG.length());
612 } else {
613 throw new RuntimeException("Unknown command line argument: " + argv[i]);
Narayan Kamathc41638c2014-04-07 13:56:15 +0100614 }
615 }
616
Yasuhiro Matsuda25878b22015-09-03 16:18:21 +0900617 if (abiList == null) {
618 throw new RuntimeException("No ABI list supplied.");
619 }
620
621 registerZygoteSocket(socketName);
622 Trace.traceBegin(Trace.TRACE_TAG_DALVIK, "ZygotePreload");
623 EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START,
624 SystemClock.uptimeMillis());
625 preload();
626 EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_END,
627 SystemClock.uptimeMillis());
628 Trace.traceEnd(Trace.TRACE_TAG_DALVIK);
629
630 // Finish profiling the zygote initialization.
631 SamplingProfilerIntegration.writeZygoteSnapshot();
632
633 // Do an initial gc to clean up after startup
634 Trace.traceBegin(Trace.TRACE_TAG_DALVIK, "PostZygoteInitGC");
635 gcAndFinalize();
636 Trace.traceEnd(Trace.TRACE_TAG_DALVIK);
637
638 Trace.traceEnd(Trace.TRACE_TAG_DALVIK);
639
Jamie Gennis6ad04522013-04-15 18:53:24 -0700640 // Disable tracing so that forked processes do not inherit stale tracing tags from
641 // Zygote.
642 Trace.setTracingEnabled(false);
643
Narayan Kamathc41638c2014-04-07 13:56:15 +0100644 if (startSystemServer) {
Narayan Kamath64cd9072014-05-13 13:35:14 +0100645 startSystemServer(abiList, socketName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800646 }
647
648 Log.i(TAG, "Accepting command socket connections");
Narayan Kamathc41638c2014-04-07 13:56:15 +0100649 runSelectLoop(abiList);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800650
651 closeServerSocket();
652 } catch (MethodAndArgsCaller caller) {
653 caller.run();
654 } catch (RuntimeException ex) {
655 Log.e(TAG, "Zygote died with exception", ex);
656 closeServerSocket();
657 throw ex;
658 }
659 }
660
661 /**
Narayan Kamath64cd9072014-05-13 13:35:14 +0100662 * Return {@code true} if this device configuration has another zygote.
663 *
664 * We determine this by comparing the device ABI list with this zygotes
665 * list. If this zygote supports all ABIs this device supports, there won't
666 * be another zygote.
667 */
668 private static boolean hasSecondZygote(String abiList) {
669 return !SystemProperties.get("ro.product.cpu.abilist").equals(abiList);
670 }
671
672 private static void waitForSecondaryZygote(String socketName) {
673 String otherZygoteName = Process.ZYGOTE_SOCKET.equals(socketName) ?
674 Process.SECONDARY_ZYGOTE_SOCKET : Process.ZYGOTE_SOCKET;
675 while (true) {
676 try {
677 final Process.ZygoteState zs = Process.ZygoteState.connect(otherZygoteName);
678 zs.close();
679 break;
680 } catch (IOException ioe) {
681 Log.w(TAG, "Got error connecting to zygote, retrying. msg= " + ioe.getMessage());
682 }
683
684 try {
685 Thread.sleep(1000);
686 } catch (InterruptedException ie) {
687 }
688 }
689 }
690
691 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692 * Runs the zygote process's select loop. Accepts new connections as
693 * they happen, and reads commands from connections one spawn-request's
694 * worth at a time.
695 *
696 * @throws MethodAndArgsCaller in a child process when a main() should
697 * be executed.
698 */
Narayan Kamathc41638c2014-04-07 13:56:15 +0100699 private static void runSelectLoop(String abiList) throws MethodAndArgsCaller {
Nick Kralevichcae3d9f2013-01-30 09:51:40 -0800700 ArrayList<FileDescriptor> fds = new ArrayList<FileDescriptor>();
701 ArrayList<ZygoteConnection> peers = new ArrayList<ZygoteConnection>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800702
703 fds.add(sServerSocket.getFileDescriptor());
704 peers.add(null);
705
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706 while (true) {
Elliott Hughes894724b2014-12-15 12:39:51 -0800707 StructPollfd[] pollFds = new StructPollfd[fds.size()];
708 for (int i = 0; i < pollFds.length; ++i) {
709 pollFds[i] = new StructPollfd();
710 pollFds[i].fd = fds.get(i);
711 pollFds[i].events = (short) POLLIN;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800712 }
Elliott Hughes894724b2014-12-15 12:39:51 -0800713 try {
714 Os.poll(pollFds, -1);
715 } catch (ErrnoException ex) {
716 throw new RuntimeException("poll failed", ex);
717 }
718 for (int i = pollFds.length - 1; i >= 0; --i) {
719 if ((pollFds[i].revents & POLLIN) == 0) {
720 continue;
721 }
722 if (i == 0) {
723 ZygoteConnection newPeer = acceptCommandPeer(abiList);
724 peers.add(newPeer);
725 fds.add(newPeer.getFileDesciptor());
726 } else {
727 boolean done = peers.get(i).runOnce();
728 if (done) {
729 peers.remove(i);
730 fds.remove(i);
731 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800732 }
733 }
734 }
735 }
736
737 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800738 * Class not instantiable.
739 */
740 private ZygoteInit() {
741 }
742
743 /**
744 * Helper exception class which holds a method and arguments and
745 * can call them. This is used as part of a trampoline to get rid of
746 * the initial process setup stack frames.
747 */
748 public static class MethodAndArgsCaller extends Exception
749 implements Runnable {
750 /** method to call */
751 private final Method mMethod;
752
753 /** argument array */
754 private final String[] mArgs;
755
756 public MethodAndArgsCaller(Method method, String[] args) {
757 mMethod = method;
758 mArgs = args;
759 }
760
761 public void run() {
762 try {
763 mMethod.invoke(null, new Object[] { mArgs });
764 } catch (IllegalAccessException ex) {
765 throw new RuntimeException(ex);
766 } catch (InvocationTargetException ex) {
767 Throwable cause = ex.getCause();
768 if (cause instanceof RuntimeException) {
769 throw (RuntimeException) cause;
770 } else if (cause instanceof Error) {
771 throw (Error) cause;
772 }
773 throw new RuntimeException(ex);
774 }
775 }
776 }
777}