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.ActivityManager; 20 import android.app.ActivityThread; 21 import android.app.ApplicationErrorReport; 22 import android.app.IActivityManager; 23 import android.compat.annotation.UnsupportedAppUsage; 24 import android.content.type.DefaultMimeMapFactory; 25 import android.os.Build; 26 import android.os.DeadObjectException; 27 import android.os.IBinder; 28 import android.os.Process; 29 import android.os.SystemProperties; 30 import android.os.Trace; 31 import android.util.Log; 32 import android.util.Slog; 33 34 import com.android.internal.logging.AndroidConfig; 35 import com.android.server.NetworkManagementSocketTagger; 36 37 import dalvik.system.RuntimeHooks; 38 import dalvik.system.VMRuntime; 39 40 import libcore.content.type.MimeMap; 41 42 import java.lang.reflect.InvocationTargetException; 43 import java.lang.reflect.Method; 44 import java.lang.reflect.Modifier; 45 import java.util.Objects; 46 import java.util.logging.LogManager; 47 48 /** 49 * Main entry point for runtime initialization. Not for 50 * public consumption. 51 * @hide 52 */ 53 public class RuntimeInit { 54 final static String TAG = "AndroidRuntime"; 55 final static boolean DEBUG = false; 56 57 /** true if commonInit() has been called */ 58 @UnsupportedAppUsage 59 private static boolean initialized; 60 61 @UnsupportedAppUsage 62 private static IBinder mApplicationObject; 63 64 private static volatile boolean mCrashing = false; 65 66 private static volatile ApplicationWtfHandler sDefaultApplicationWtfHandler; 67 nativeFinishInit()68 private static final native void nativeFinishInit(); nativeSetExitWithoutCleanup(boolean exitWithoutCleanup)69 private static final native void nativeSetExitWithoutCleanup(boolean exitWithoutCleanup); 70 Clog_e(String tag, String msg, Throwable tr)71 private static int Clog_e(String tag, String msg, Throwable tr) { 72 return Log.printlns(Log.LOG_ID_CRASH, Log.ERROR, tag, msg, tr); 73 } 74 logUncaught(String threadName, String processName, int pid, Throwable e)75 public static void logUncaught(String threadName, String processName, int pid, Throwable e) { 76 StringBuilder message = new StringBuilder(); 77 // The "FATAL EXCEPTION" string is still used on Android even though 78 // apps can set a custom UncaughtExceptionHandler that renders uncaught 79 // exceptions non-fatal. 80 message.append("FATAL EXCEPTION: ").append(threadName).append("\n"); 81 if (processName != null) { 82 message.append("Process: ").append(processName).append(", "); 83 } 84 message.append("PID: ").append(pid); 85 Clog_e(TAG, message.toString(), e); 86 } 87 88 /** 89 * Logs a message when a thread encounters an uncaught exception. By 90 * default, {@link KillApplicationHandler} will terminate this process later, 91 * but apps can override that behavior. 92 */ 93 private static class LoggingHandler implements Thread.UncaughtExceptionHandler { 94 public volatile boolean mTriggered = false; 95 96 @Override uncaughtException(Thread t, Throwable e)97 public void uncaughtException(Thread t, Throwable e) { 98 mTriggered = true; 99 100 // Don't re-enter if KillApplicationHandler has already run 101 if (mCrashing) return; 102 103 // mApplicationObject is null for non-zygote java programs (e.g. "am") 104 // There are also apps running with the system UID. We don't want the 105 // first clause in either of these two cases, only for system_server. 106 if (mApplicationObject == null && (Process.SYSTEM_UID == Process.myUid())) { 107 Clog_e(TAG, "*** FATAL EXCEPTION IN SYSTEM PROCESS: " + t.getName(), e); 108 } else { 109 logUncaught(t.getName(), ActivityThread.currentProcessName(), Process.myPid(), e); 110 } 111 } 112 } 113 114 /** 115 * Handle application death from an uncaught exception. The framework 116 * catches these for the main threads, so this should only matter for 117 * threads created by applications. Before this method runs, the given 118 * instance of {@link LoggingHandler} should already have logged details 119 * (and if not it is run first). 120 */ 121 private static class KillApplicationHandler implements Thread.UncaughtExceptionHandler { 122 private final LoggingHandler mLoggingHandler; 123 124 /** 125 * Create a new KillApplicationHandler that follows the given LoggingHandler. 126 * If {@link #uncaughtException(Thread, Throwable) uncaughtException} is called 127 * on the created instance without {@code loggingHandler} having been triggered, 128 * {@link LoggingHandler#uncaughtException(Thread, Throwable) 129 * loggingHandler.uncaughtException} will be called first. 130 * 131 * @param loggingHandler the {@link LoggingHandler} expected to have run before 132 * this instance's {@link #uncaughtException(Thread, Throwable) uncaughtException} 133 * is being called. 134 */ KillApplicationHandler(LoggingHandler loggingHandler)135 public KillApplicationHandler(LoggingHandler loggingHandler) { 136 this.mLoggingHandler = Objects.requireNonNull(loggingHandler); 137 } 138 139 @Override uncaughtException(Thread t, Throwable e)140 public void uncaughtException(Thread t, Throwable e) { 141 try { 142 ensureLogging(t, e); 143 144 // Don't re-enter -- avoid infinite loops if crash-reporting crashes. 145 if (mCrashing) return; 146 mCrashing = true; 147 148 // Try to end profiling. If a profiler is running at this point, and we kill the 149 // process (below), the in-memory buffer will be lost. So try to stop, which will 150 // flush the buffer. (This makes method trace profiling useful to debug crashes.) 151 if (ActivityThread.currentActivityThread() != null) { 152 ActivityThread.currentActivityThread().stopProfiling(); 153 } 154 155 // Bring up crash dialog, wait for it to be dismissed 156 ActivityManager.getService().handleApplicationCrash( 157 mApplicationObject, new ApplicationErrorReport.ParcelableCrashInfo(e)); 158 } catch (Throwable t2) { 159 if (t2 instanceof DeadObjectException) { 160 // System process is dead; ignore 161 } else { 162 try { 163 Clog_e(TAG, "Error reporting crash", t2); 164 } catch (Throwable t3) { 165 // Even Clog_e() fails! Oh well. 166 } 167 } 168 } finally { 169 // Try everything to make sure this process goes away. 170 Process.killProcess(Process.myPid()); 171 System.exit(10); 172 } 173 } 174 175 /** 176 * Ensures that the logging handler has been triggered. 177 * 178 * See b/73380984. This reinstates the pre-O behavior of 179 * 180 * {@code thread.getUncaughtExceptionHandler().uncaughtException(thread, e);} 181 * 182 * logging the exception (in addition to killing the app). This behavior 183 * was never documented / guaranteed but helps in diagnostics of apps 184 * using the pattern. 185 * 186 * If this KillApplicationHandler is invoked the "regular" way (by 187 * {@link Thread#dispatchUncaughtException(Throwable) 188 * Thread.dispatchUncaughtException} in case of an uncaught exception) 189 * then the pre-handler (expected to be {@link #mLoggingHandler}) will already 190 * have run. Otherwise, we manually invoke it here. 191 */ ensureLogging(Thread t, Throwable e)192 private void ensureLogging(Thread t, Throwable e) { 193 if (!mLoggingHandler.mTriggered) { 194 try { 195 mLoggingHandler.uncaughtException(t, e); 196 } catch (Throwable loggingThrowable) { 197 // Ignored. 198 } 199 } 200 } 201 } 202 203 /** 204 * Common initialization that (unlike {@link #commonInit()} should happen prior to 205 * the Zygote fork. 206 */ preForkInit()207 public static void preForkInit() { 208 if (DEBUG) Slog.d(TAG, "Entered preForkInit."); 209 RuntimeInit.enableDdms(); 210 // TODO(b/142019040#comment13): Decide whether to load the default instance eagerly, i.e. 211 // MimeMap.setDefault(DefaultMimeMapFactory.create()); 212 /* 213 * Replace libcore's minimal default mapping between MIME types and file 214 * extensions with a mapping that's suitable for Android. Android's mapping 215 * contains many more entries that are derived from IANA registrations but 216 * with several customizations (extensions, overrides). 217 */ 218 MimeMap.setDefaultSupplier(DefaultMimeMapFactory::create); 219 } 220 221 @UnsupportedAppUsage commonInit()222 protected static final void commonInit() { 223 if (DEBUG) Slog.d(TAG, "Entered RuntimeInit!"); 224 225 /* 226 * set handlers; these apply to all threads in the VM. Apps can replace 227 * the default handler, but not the pre handler. 228 */ 229 LoggingHandler loggingHandler = new LoggingHandler(); 230 RuntimeHooks.setUncaughtExceptionPreHandler(loggingHandler); 231 Thread.setDefaultUncaughtExceptionHandler(new KillApplicationHandler(loggingHandler)); 232 233 /* 234 * Install a time zone supplier that uses the Android persistent time zone system property. 235 */ 236 RuntimeHooks.setTimeZoneIdSupplier(() -> SystemProperties.get("persist.sys.timezone")); 237 238 /* 239 * Sets handler for java.util.logging to use Android log facilities. 240 * The odd "new instance-and-then-throw-away" is a mirror of how 241 * the "java.util.logging.config.class" system property works. We 242 * can't use the system property here since the logger has almost 243 * certainly already been initialized. 244 */ 245 LogManager.getLogManager().reset(); 246 new AndroidConfig(); 247 248 /* 249 * Sets the default HTTP User-Agent used by HttpURLConnection. 250 */ 251 String userAgent = getDefaultUserAgent(); 252 System.setProperty("http.agent", userAgent); 253 254 /* 255 * Wire socket tagging to traffic stats. 256 */ 257 NetworkManagementSocketTagger.install(); 258 259 initialized = true; 260 } 261 262 /** 263 * Returns an HTTP user agent of the form 264 * "Dalvik/1.1.0 (Linux; U; Android Eclair Build/MAIN)". 265 */ getDefaultUserAgent()266 private static String getDefaultUserAgent() { 267 StringBuilder result = new StringBuilder(64); 268 result.append("Dalvik/"); 269 result.append(System.getProperty("java.vm.version")); // such as 1.1.0 270 result.append(" (Linux; U; Android "); 271 272 String version = Build.VERSION.RELEASE_OR_CODENAME; // "1.0" or "3.4b5" 273 result.append(version.length() > 0 ? version : "1.0"); 274 275 // add the model for the release build 276 if ("REL".equals(Build.VERSION.CODENAME)) { 277 String model = Build.MODEL; 278 if (model.length() > 0) { 279 result.append("; "); 280 result.append(model); 281 } 282 } 283 String id = Build.ID; // "MAIN" or "M4-rc20" 284 if (id.length() > 0) { 285 result.append(" Build/"); 286 result.append(id); 287 } 288 result.append(")"); 289 return result.toString(); 290 } 291 292 /** 293 * Invokes a static "main(argv[]) method on class "className". 294 * Converts various failing exceptions into RuntimeExceptions, with 295 * the assumption that they will then cause the VM instance to exit. 296 * 297 * @param className Fully-qualified class name 298 * @param argv Argument vector for main() 299 * @param classLoader the classLoader to load {@className} with 300 */ findStaticMain(String className, String[] argv, ClassLoader classLoader)301 protected static Runnable findStaticMain(String className, String[] argv, 302 ClassLoader classLoader) { 303 Class<?> cl; 304 305 try { 306 cl = Class.forName(className, true, classLoader); 307 } catch (ClassNotFoundException ex) { 308 throw new RuntimeException( 309 "Missing class when invoking static main " + className, 310 ex); 311 } 312 313 Method m; 314 try { 315 m = cl.getMethod("main", new Class[] { String[].class }); 316 } catch (NoSuchMethodException ex) { 317 throw new RuntimeException( 318 "Missing static main on " + className, ex); 319 } catch (SecurityException ex) { 320 throw new RuntimeException( 321 "Problem getting static main on " + className, ex); 322 } 323 324 int modifiers = m.getModifiers(); 325 if (! (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) { 326 throw new RuntimeException( 327 "Main method is not public and static on " + className); 328 } 329 330 /* 331 * This throw gets caught in ZygoteInit.main(), which responds 332 * by invoking the exception's run() method. This arrangement 333 * clears up all the stack frames that were required in setting 334 * up the process. 335 */ 336 return new MethodAndArgsCaller(m, argv); 337 } 338 339 @UnsupportedAppUsage main(String[] argv)340 public static final void main(String[] argv) { 341 preForkInit(); 342 if (argv.length == 2 && argv[1].equals("application")) { 343 if (DEBUG) Slog.d(TAG, "RuntimeInit: Starting application"); 344 redirectLogStreams(); 345 } else { 346 if (DEBUG) Slog.d(TAG, "RuntimeInit: Starting tool"); 347 } 348 349 commonInit(); 350 351 /* 352 * Now that we're running in interpreted code, call back into native code 353 * to run the system. 354 */ 355 nativeFinishInit(); 356 357 if (DEBUG) Slog.d(TAG, "Leaving RuntimeInit!"); 358 } 359 applicationInit(int targetSdkVersion, long[] disabledCompatChanges, String[] argv, ClassLoader classLoader)360 protected static Runnable applicationInit(int targetSdkVersion, long[] disabledCompatChanges, 361 String[] argv, ClassLoader classLoader) { 362 // If the application calls System.exit(), terminate the process 363 // immediately without running any shutdown hooks. It is not possible to 364 // shutdown an Android application gracefully. Among other things, the 365 // Android runtime shutdown hooks close the Binder driver, which can cause 366 // leftover running threads to crash before the process actually exits. 367 nativeSetExitWithoutCleanup(true); 368 369 VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion); 370 VMRuntime.getRuntime().setDisabledCompatChanges(disabledCompatChanges); 371 372 final Arguments args = new Arguments(argv); 373 374 // The end of of the RuntimeInit event (see #zygoteInit). 375 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 376 377 // Remaining arguments are passed to the start class's static main 378 return findStaticMain(args.startClass, args.startArgs, classLoader); 379 } 380 381 /** 382 * Redirect System.out and System.err to the Android log. 383 */ redirectLogStreams()384 public static void redirectLogStreams() { 385 System.out.close(); 386 System.setOut(new AndroidPrintStream(Log.INFO, "System.out")); 387 System.err.close(); 388 System.setErr(new AndroidPrintStream(Log.WARN, "System.err")); 389 } 390 391 /** 392 * Report a serious error in the current process. May or may not cause 393 * the process to terminate (depends on system settings). 394 * 395 * @param tag to record with the error 396 * @param t exception describing the error site and conditions 397 */ wtf(String tag, Throwable t, boolean system)398 public static void wtf(String tag, Throwable t, boolean system) { 399 try { 400 boolean exit = false; 401 final IActivityManager am = ActivityManager.getService(); 402 if (am != null) { 403 exit = am.handleApplicationWtf( 404 mApplicationObject, tag, system, 405 new ApplicationErrorReport.ParcelableCrashInfo(t), 406 Process.myPid()); 407 } else { 408 // Unlikely but possible in early system boot 409 final ApplicationWtfHandler handler = sDefaultApplicationWtfHandler; 410 if (handler != null) { 411 exit = handler.handleApplicationWtf( 412 mApplicationObject, tag, system, 413 new ApplicationErrorReport.ParcelableCrashInfo(t), 414 Process.myPid()); 415 } else { 416 // Simply log the error 417 Slog.e(TAG, "Original WTF:", t); 418 } 419 } 420 if (exit) { 421 // The Activity Manager has already written us off -- now exit. 422 Process.killProcess(Process.myPid()); 423 System.exit(10); 424 } 425 } catch (Throwable t2) { 426 if (t2 instanceof DeadObjectException) { 427 // System process is dead; ignore 428 } else { 429 Slog.e(TAG, "Error reporting WTF", t2); 430 Slog.e(TAG, "Original WTF:", t); 431 } 432 } 433 } 434 435 /** 436 * Set the default {@link ApplicationWtfHandler}, in case the ActivityManager is not ready yet. 437 */ setDefaultApplicationWtfHandler(final ApplicationWtfHandler handler)438 public static void setDefaultApplicationWtfHandler(final ApplicationWtfHandler handler) { 439 sDefaultApplicationWtfHandler = handler; 440 } 441 442 /** 443 * The handler to deal with the serious application errors. 444 */ 445 public interface ApplicationWtfHandler { 446 /** 447 * @param app object of the crashing app, null for the system server 448 * @param tag reported by the caller 449 * @param system whether this wtf is coming from the system 450 * @param crashInfo describing the context of the error 451 * @param immediateCallerPid the caller Pid 452 * @return true if the process should exit immediately (WTF is fatal) 453 */ handleApplicationWtf(IBinder app, String tag, boolean system, ApplicationErrorReport.ParcelableCrashInfo crashInfo, int immediateCallerPid)454 boolean handleApplicationWtf(IBinder app, String tag, boolean system, 455 ApplicationErrorReport.ParcelableCrashInfo crashInfo, int immediateCallerPid); 456 } 457 458 /** 459 * Set the object identifying this application/process, for reporting VM 460 * errors. 461 */ setApplicationObject(IBinder app)462 public static final void setApplicationObject(IBinder app) { 463 mApplicationObject = app; 464 } 465 466 @UnsupportedAppUsage getApplicationObject()467 public static final IBinder getApplicationObject() { 468 return mApplicationObject; 469 } 470 471 /** 472 * Enable DDMS. 473 */ enableDdms()474 private static void enableDdms() { 475 // Register handlers for DDM messages. 476 android.ddm.DdmRegister.registerHandlers(); 477 } 478 479 /** 480 * Handles argument parsing for args related to the runtime. 481 * 482 * Current recognized args: 483 * <ul> 484 * <li> <code> [--] <start class name> <args> 485 * </ul> 486 */ 487 static class Arguments { 488 /** first non-option argument */ 489 String startClass; 490 491 /** all following arguments */ 492 String[] startArgs; 493 494 /** 495 * Constructs instance and parses args 496 * @param args runtime command-line args 497 * @throws IllegalArgumentException 498 */ Arguments(String args[])499 Arguments(String args[]) throws IllegalArgumentException { 500 parseArgs(args); 501 } 502 503 /** 504 * Parses the commandline arguments intended for the Runtime. 505 */ parseArgs(String args[])506 private void parseArgs(String args[]) 507 throws IllegalArgumentException { 508 int curArg = 0; 509 for (; curArg < args.length; curArg++) { 510 String arg = args[curArg]; 511 512 if (arg.equals("--")) { 513 curArg++; 514 break; 515 } else if (!arg.startsWith("--")) { 516 break; 517 } 518 } 519 520 if (curArg == args.length) { 521 throw new IllegalArgumentException("Missing classname argument to RuntimeInit!"); 522 } 523 524 startClass = args[curArg++]; 525 startArgs = new String[args.length - curArg]; 526 System.arraycopy(args, curArg, startArgs, 0, startArgs.length); 527 } 528 } 529 530 /** 531 * Helper class which holds a method and arguments and can call them. This is used as part of 532 * a trampoline to get rid of the initial process setup stack frames. 533 */ 534 static class MethodAndArgsCaller implements Runnable { 535 /** method to call */ 536 private final Method mMethod; 537 538 /** argument array */ 539 private final String[] mArgs; 540 MethodAndArgsCaller(Method method, String[] args)541 public MethodAndArgsCaller(Method method, String[] args) { 542 mMethod = method; 543 mArgs = args; 544 } 545 run()546 public void run() { 547 try { 548 mMethod.invoke(null, new Object[] { mArgs }); 549 } catch (IllegalAccessException ex) { 550 throw new RuntimeException(ex); 551 } catch (InvocationTargetException ex) { 552 Throwable cause = ex.getCause(); 553 if (cause instanceof RuntimeException) { 554 throw (RuntimeException) cause; 555 } else if (cause instanceof Error) { 556 throw (Error) cause; 557 } 558 throw new RuntimeException(ex); 559 } 560 } 561 } 562 } 563