OSDN Git Service

am 0acf9d2f: am de138276: docs: Fix typos in the L preview docs. Bug: 16240486
[android-x86/frameworks-base.git] / core / java / com / android / internal / os / RuntimeInit.java
1 /*
2  * Copyright (C) 2006 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
17 package com.android.internal.os;
18
19 import android.app.ActivityManagerNative;
20 import android.app.ActivityThread;
21 import android.app.ApplicationErrorReport;
22 import android.os.Build;
23 import android.os.Debug;
24 import android.os.IBinder;
25 import android.os.Process;
26 import android.os.SystemProperties;
27 import android.util.Log;
28 import android.util.Slog;
29 import com.android.internal.logging.AndroidConfig;
30 import com.android.server.NetworkManagementSocketTagger;
31 import dalvik.system.VMRuntime;
32 import java.lang.reflect.Method;
33 import java.lang.reflect.Modifier;
34 import java.util.TimeZone;
35 import java.util.logging.LogManager;
36 import org.apache.harmony.luni.internal.util.TimezoneGetter;
37
38 /**
39  * Main entry point for runtime initialization.  Not for
40  * public consumption.
41  * @hide
42  */
43 public class RuntimeInit {
44     private final static String TAG = "AndroidRuntime";
45     private final static boolean DEBUG = false;
46
47     /** true if commonInit() has been called */
48     private static boolean initialized;
49
50     private static IBinder mApplicationObject;
51
52     private static volatile boolean mCrashing = false;
53
54     private static final native void nativeZygoteInit();
55     private static final native void nativeFinishInit();
56     private static final native void nativeSetExitWithoutCleanup(boolean exitWithoutCleanup);
57
58     private static int Clog_e(String tag, String msg, Throwable tr) {
59         return Log.println_native(Log.LOG_ID_CRASH, Log.ERROR, tag,
60                 msg + '\n' + Log.getStackTraceString(tr));
61     }
62
63     /**
64      * Use this to log a message when a thread exits due to an uncaught
65      * exception.  The framework catches these for the main threads, so
66      * this should only matter for threads created by applications.
67      */
68     private static class UncaughtHandler implements Thread.UncaughtExceptionHandler {
69         public void uncaughtException(Thread t, Throwable e) {
70             try {
71                 // Don't re-enter -- avoid infinite loops if crash-reporting crashes.
72                 if (mCrashing) return;
73                 mCrashing = true;
74
75                 if (mApplicationObject == null) {
76                     Clog_e(TAG, "*** FATAL EXCEPTION IN SYSTEM PROCESS: " + t.getName(), e);
77                 } else {
78                     StringBuilder message = new StringBuilder();
79                     message.append("FATAL EXCEPTION: ").append(t.getName()).append("\n");
80                     final String processName = ActivityThread.currentProcessName();
81                     if (processName != null) {
82                         message.append("Process: ").append(processName).append(", ");
83                     }
84                     message.append("PID: ").append(Process.myPid());
85                     Clog_e(TAG, message.toString(), e);
86                 }
87
88                 // Bring up crash dialog, wait for it to be dismissed
89                 ActivityManagerNative.getDefault().handleApplicationCrash(
90                         mApplicationObject, new ApplicationErrorReport.CrashInfo(e));
91             } catch (Throwable t2) {
92                 try {
93                     Clog_e(TAG, "Error reporting crash", t2);
94                 } catch (Throwable t3) {
95                     // Even Clog_e() fails!  Oh well.
96                 }
97             } finally {
98                 // Try everything to make sure this process goes away.
99                 Process.killProcess(Process.myPid());
100                 System.exit(10);
101             }
102         }
103     }
104
105     private static final void commonInit() {
106         if (DEBUG) Slog.d(TAG, "Entered RuntimeInit!");
107
108         /* set default handler; this applies to all threads in the VM */
109         Thread.setDefaultUncaughtExceptionHandler(new UncaughtHandler());
110
111         /*
112          * Install a TimezoneGetter subclass for ZoneInfo.db
113          */
114         TimezoneGetter.setInstance(new TimezoneGetter() {
115             @Override
116             public String getId() {
117                 return SystemProperties.get("persist.sys.timezone");
118             }
119         });
120         TimeZone.setDefault(null);
121
122         /*
123          * Sets handler for java.util.logging to use Android log facilities.
124          * The odd "new instance-and-then-throw-away" is a mirror of how
125          * the "java.util.logging.config.class" system property works. We
126          * can't use the system property here since the logger has almost
127          * certainly already been initialized.
128          */
129         LogManager.getLogManager().reset();
130         new AndroidConfig();
131
132         /*
133          * Sets the default HTTP User-Agent used by HttpURLConnection.
134          */
135         String userAgent = getDefaultUserAgent();
136         System.setProperty("http.agent", userAgent);
137
138         /*
139          * Wire socket tagging to traffic stats.
140          */
141         NetworkManagementSocketTagger.install();
142
143         /*
144          * If we're running in an emulator launched with "-trace", put the
145          * VM into emulator trace profiling mode so that the user can hit
146          * F9/F10 at any time to capture traces.  This has performance
147          * consequences, so it's not something you want to do always.
148          */
149         String trace = SystemProperties.get("ro.kernel.android.tracing");
150         if (trace.equals("1")) {
151             Slog.i(TAG, "NOTE: emulator trace profiling enabled");
152             Debug.enableEmulatorTraceOutput();
153         }
154
155         initialized = true;
156     }
157
158     /**
159      * Returns an HTTP user agent of the form
160      * "Dalvik/1.1.0 (Linux; U; Android Eclair Build/MASTER)".
161      */
162     private static String getDefaultUserAgent() {
163         StringBuilder result = new StringBuilder(64);
164         result.append("Dalvik/");
165         result.append(System.getProperty("java.vm.version")); // such as 1.1.0
166         result.append(" (Linux; U; Android ");
167
168         String version = Build.VERSION.RELEASE; // "1.0" or "3.4b5"
169         result.append(version.length() > 0 ? version : "1.0");
170
171         // add the model for the release build
172         if ("REL".equals(Build.VERSION.CODENAME)) {
173             String model = Build.MODEL;
174             if (model.length() > 0) {
175                 result.append("; ");
176                 result.append(model);
177             }
178         }
179         String id = Build.ID; // "MASTER" or "M4-rc20"
180         if (id.length() > 0) {
181             result.append(" Build/");
182             result.append(id);
183         }
184         result.append(")");
185         return result.toString();
186     }
187
188     /**
189      * Invokes a static "main(argv[]) method on class "className".
190      * Converts various failing exceptions into RuntimeExceptions, with
191      * the assumption that they will then cause the VM instance to exit.
192      *
193      * @param className Fully-qualified class name
194      * @param argv Argument vector for main()
195      */
196     private static void invokeStaticMain(String className, String[] argv)
197             throws ZygoteInit.MethodAndArgsCaller {
198         Class<?> cl;
199
200         try {
201             cl = Class.forName(className);
202         } catch (ClassNotFoundException ex) {
203             throw new RuntimeException(
204                     "Missing class when invoking static main " + className,
205                     ex);
206         }
207
208         Method m;
209         try {
210             m = cl.getMethod("main", new Class[] { String[].class });
211         } catch (NoSuchMethodException ex) {
212             throw new RuntimeException(
213                     "Missing static main on " + className, ex);
214         } catch (SecurityException ex) {
215             throw new RuntimeException(
216                     "Problem getting static main on " + className, ex);
217         }
218
219         int modifiers = m.getModifiers();
220         if (! (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) {
221             throw new RuntimeException(
222                     "Main method is not public and static on " + className);
223         }
224
225         /*
226          * This throw gets caught in ZygoteInit.main(), which responds
227          * by invoking the exception's run() method. This arrangement
228          * clears up all the stack frames that were required in setting
229          * up the process.
230          */
231         throw new ZygoteInit.MethodAndArgsCaller(m, argv);
232     }
233
234     public static final void main(String[] argv) {
235         if (argv.length == 2 && argv[1].equals("application")) {
236             if (DEBUG) Slog.d(TAG, "RuntimeInit: Starting application");
237             redirectLogStreams();
238         } else {
239             if (DEBUG) Slog.d(TAG, "RuntimeInit: Starting tool");
240         }
241
242         commonInit();
243
244         /*
245          * Now that we're running in interpreted code, call back into native code
246          * to run the system.
247          */
248         nativeFinishInit();
249
250         if (DEBUG) Slog.d(TAG, "Leaving RuntimeInit!");
251     }
252
253     /**
254      * The main function called when started through the zygote process. This
255      * could be unified with main(), if the native code in nativeFinishInit()
256      * were rationalized with Zygote startup.<p>
257      *
258      * Current recognized args:
259      * <ul>
260      *   <li> <code> [--] &lt;start class name&gt;  &lt;args&gt;
261      * </ul>
262      *
263      * @param targetSdkVersion target SDK version
264      * @param argv arg strings
265      */
266     public static final void zygoteInit(int targetSdkVersion, String[] argv)
267             throws ZygoteInit.MethodAndArgsCaller {
268         if (DEBUG) Slog.d(TAG, "RuntimeInit: Starting application from zygote");
269
270         redirectLogStreams();
271
272         commonInit();
273         nativeZygoteInit();
274
275         applicationInit(targetSdkVersion, argv);
276     }
277
278     /**
279      * The main function called when an application is started through a
280      * wrapper process.
281      *
282      * When the wrapper starts, the runtime starts {@link RuntimeInit#main}
283      * which calls {@link WrapperInit#main} which then calls this method.
284      * So we don't need to call commonInit() here.
285      *
286      * @param targetSdkVersion target SDK version
287      * @param argv arg strings
288      */
289     public static void wrapperInit(int targetSdkVersion, String[] argv)
290             throws ZygoteInit.MethodAndArgsCaller {
291         if (DEBUG) Slog.d(TAG, "RuntimeInit: Starting application from wrapper");
292
293         applicationInit(targetSdkVersion, argv);
294     }
295
296     private static void applicationInit(int targetSdkVersion, String[] argv)
297             throws ZygoteInit.MethodAndArgsCaller {
298         // If the application calls System.exit(), terminate the process
299         // immediately without running any shutdown hooks.  It is not possible to
300         // shutdown an Android application gracefully.  Among other things, the
301         // Android runtime shutdown hooks close the Binder driver, which can cause
302         // leftover running threads to crash before the process actually exits.
303         nativeSetExitWithoutCleanup(true);
304
305         // We want to be fairly aggressive about heap utilization, to avoid
306         // holding on to a lot of memory that isn't needed.
307         VMRuntime.getRuntime().setTargetHeapUtilization(0.75f);
308         VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion);
309
310         final Arguments args;
311         try {
312             args = new Arguments(argv);
313         } catch (IllegalArgumentException ex) {
314             Slog.e(TAG, ex.getMessage());
315             // let the process exit
316             return;
317         }
318
319         // Remaining arguments are passed to the start class's static main
320         invokeStaticMain(args.startClass, args.startArgs);
321     }
322
323     /**
324      * Redirect System.out and System.err to the Android log.
325      */
326     public static void redirectLogStreams() {
327         System.out.close();
328         System.setOut(new AndroidPrintStream(Log.INFO, "System.out"));
329         System.err.close();
330         System.setErr(new AndroidPrintStream(Log.WARN, "System.err"));
331     }
332
333     /**
334      * Report a serious error in the current process.  May or may not cause
335      * the process to terminate (depends on system settings).
336      *
337      * @param tag to record with the error
338      * @param t exception describing the error site and conditions
339      */
340     public static void wtf(String tag, Throwable t) {
341         try {
342             if (ActivityManagerNative.getDefault().handleApplicationWtf(
343                     mApplicationObject, tag, new ApplicationErrorReport.CrashInfo(t))) {
344                 // The Activity Manager has already written us off -- now exit.
345                 Process.killProcess(Process.myPid());
346                 System.exit(10);
347             }
348         } catch (Throwable t2) {
349             Slog.e(TAG, "Error reporting WTF", t2);
350             Slog.e(TAG, "Original WTF:", t);
351         }
352     }
353
354     /**
355      * Set the object identifying this application/process, for reporting VM
356      * errors.
357      */
358     public static final void setApplicationObject(IBinder app) {
359         mApplicationObject = app;
360     }
361
362     public static final IBinder getApplicationObject() {
363         return mApplicationObject;
364     }
365
366     /**
367      * Enable debugging features.
368      */
369     static {
370         // Register handlers for DDM messages.
371         android.ddm.DdmRegister.registerHandlers();
372     }
373
374     /**
375      * Handles argument parsing for args related to the runtime.
376      *
377      * Current recognized args:
378      * <ul>
379      *   <li> <code> [--] &lt;start class name&gt;  &lt;args&gt;
380      * </ul>
381      */
382     static class Arguments {
383         /** first non-option argument */
384         String startClass;
385
386         /** all following arguments */
387         String[] startArgs;
388
389         /**
390          * Constructs instance and parses args
391          * @param args runtime command-line args
392          * @throws IllegalArgumentException
393          */
394         Arguments(String args[]) throws IllegalArgumentException {
395             parseArgs(args);
396         }
397
398         /**
399          * Parses the commandline arguments intended for the Runtime.
400          */
401         private void parseArgs(String args[])
402                 throws IllegalArgumentException {
403             int curArg = 0;
404             for (; curArg < args.length; curArg++) {
405                 String arg = args[curArg];
406
407                 if (arg.equals("--")) {
408                     curArg++;
409                     break;
410                 } else if (!arg.startsWith("--")) {
411                     break;
412                 }
413             }
414
415             if (curArg == args.length) {
416                 throw new IllegalArgumentException("Missing classname argument to RuntimeInit!");
417             }
418
419             startClass = args[curArg++];
420             startArgs = new String[args.length - curArg];
421             System.arraycopy(args, curArg, startArgs, 0, startArgs.length);
422         }
423     }
424 }