AndroidRuntime.cpp revision 9c99c7935d17115e94e183e040d97b818f0621b5
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#define ATRACE_TAG ATRACE_TAG_DALVIK 18#define LOG_TAG "AndroidRuntime" 19//#define LOG_NDEBUG 0 20 21#include <android_runtime/AndroidRuntime.h> 22#include <binder/IBinder.h> 23#include <binder/IPCThreadState.h> 24#include <binder/IServiceManager.h> 25#include <utils/Log.h> 26#include <utils/misc.h> 27#include <utils/Trace.h> 28#include <binder/Parcel.h> 29#include <utils/threads.h> 30#include <cutils/properties.h> 31 32#include <SkGraphics.h> 33#include <SkImageDecoder.h> 34 35#include "jni.h" 36#include "JNIHelp.h" 37#include "JniInvocation.h" 38#include "android_util_Binder.h" 39 40#include <stdio.h> 41#include <signal.h> 42#include <sys/stat.h> 43#include <sys/types.h> 44#include <signal.h> 45#include <dirent.h> 46#include <assert.h> 47 48#include <string> 49#include <vector> 50 51 52using namespace android; 53 54extern int register_android_os_Binder(JNIEnv* env); 55extern int register_android_os_Process(JNIEnv* env); 56extern int register_android_graphics_Bitmap(JNIEnv*); 57extern int register_android_graphics_BitmapFactory(JNIEnv*); 58extern int register_android_graphics_BitmapRegionDecoder(JNIEnv*); 59extern int register_android_graphics_Camera(JNIEnv* env); 60extern int register_android_graphics_CreateJavaOutputStreamAdaptor(JNIEnv* env); 61extern int register_android_graphics_Graphics(JNIEnv* env); 62extern int register_android_graphics_Interpolator(JNIEnv* env); 63extern int register_android_graphics_MaskFilter(JNIEnv* env); 64extern int register_android_graphics_Movie(JNIEnv* env); 65extern int register_android_graphics_NinePatch(JNIEnv*); 66extern int register_android_graphics_PathEffect(JNIEnv* env); 67extern int register_android_graphics_Shader(JNIEnv* env); 68extern int register_android_graphics_Typeface(JNIEnv* env); 69extern int register_android_graphics_YuvImage(JNIEnv* env); 70 71extern int register_com_google_android_gles_jni_EGLImpl(JNIEnv* env); 72extern int register_com_google_android_gles_jni_GLImpl(JNIEnv* env); 73extern int register_android_opengl_jni_EGL14(JNIEnv* env); 74extern int register_android_opengl_jni_EGLExt(JNIEnv* env); 75extern int register_android_opengl_jni_GLES10(JNIEnv* env); 76extern int register_android_opengl_jni_GLES10Ext(JNIEnv* env); 77extern int register_android_opengl_jni_GLES11(JNIEnv* env); 78extern int register_android_opengl_jni_GLES11Ext(JNIEnv* env); 79extern int register_android_opengl_jni_GLES20(JNIEnv* env); 80extern int register_android_opengl_jni_GLES30(JNIEnv* env); 81extern int register_android_opengl_jni_GLES31(JNIEnv* env); 82extern int register_android_opengl_jni_GLES31Ext(JNIEnv* env); 83 84extern int register_android_hardware_Camera(JNIEnv *env); 85extern int register_android_hardware_camera2_CameraMetadata(JNIEnv *env); 86extern int register_android_hardware_camera2_legacy_LegacyCameraDevice(JNIEnv *env); 87extern int register_android_hardware_camera2_legacy_PerfMeasurement(JNIEnv *env); 88extern int register_android_hardware_camera2_DngCreator(JNIEnv *env); 89extern int register_android_hardware_Radio(JNIEnv *env); 90extern int register_android_hardware_SensorManager(JNIEnv *env); 91extern int register_android_hardware_SerialPort(JNIEnv *env); 92extern int register_android_hardware_SoundTrigger(JNIEnv *env); 93extern int register_android_hardware_UsbDevice(JNIEnv *env); 94extern int register_android_hardware_UsbDeviceConnection(JNIEnv *env); 95extern int register_android_hardware_UsbRequest(JNIEnv *env); 96extern int register_android_hardware_location_ActivityRecognitionHardware(JNIEnv* env); 97 98extern int register_android_media_AudioRecord(JNIEnv *env); 99extern int register_android_media_AudioSystem(JNIEnv *env); 100extern int register_android_media_AudioTrack(JNIEnv *env); 101extern int register_android_media_JetPlayer(JNIEnv *env); 102extern int register_android_media_ToneGenerator(JNIEnv *env); 103 104namespace android { 105 106/* 107 * JNI-based registration functions. Note these are properly contained in 108 * namespace android. 109 */ 110extern int register_android_content_AssetManager(JNIEnv* env); 111extern int register_android_util_EventLog(JNIEnv* env); 112extern int register_android_util_Log(JNIEnv* env); 113extern int register_android_content_StringBlock(JNIEnv* env); 114extern int register_android_content_XmlBlock(JNIEnv* env); 115extern int register_android_graphics_Canvas(JNIEnv* env); 116extern int register_android_graphics_CanvasProperty(JNIEnv* env); 117extern int register_android_graphics_ColorFilter(JNIEnv* env); 118extern int register_android_graphics_DrawFilter(JNIEnv* env); 119extern int register_android_graphics_FontFamily(JNIEnv* env); 120extern int register_android_graphics_LayerRasterizer(JNIEnv*); 121extern int register_android_graphics_Matrix(JNIEnv* env); 122extern int register_android_graphics_Paint(JNIEnv* env); 123extern int register_android_graphics_Path(JNIEnv* env); 124extern int register_android_graphics_PathMeasure(JNIEnv* env); 125extern int register_android_graphics_Picture(JNIEnv*); 126extern int register_android_graphics_PorterDuff(JNIEnv* env); 127extern int register_android_graphics_Rasterizer(JNIEnv* env); 128extern int register_android_graphics_Region(JNIEnv* env); 129extern int register_android_graphics_SurfaceTexture(JNIEnv* env); 130extern int register_android_graphics_Xfermode(JNIEnv* env); 131extern int register_android_graphics_pdf_PdfDocument(JNIEnv* env); 132extern int register_android_graphics_pdf_PdfEditor(JNIEnv* env); 133extern int register_android_graphics_pdf_PdfRenderer(JNIEnv* env); 134extern int register_android_view_DisplayEventReceiver(JNIEnv* env); 135extern int register_android_view_DisplayListCanvas(JNIEnv* env); 136extern int register_android_view_GraphicBuffer(JNIEnv* env); 137extern int register_android_view_HardwareLayer(JNIEnv* env); 138extern int register_android_view_RenderNode(JNIEnv* env); 139extern int register_android_view_RenderNodeAnimator(JNIEnv* env); 140extern int register_android_view_Surface(JNIEnv* env); 141extern int register_android_view_SurfaceControl(JNIEnv* env); 142extern int register_android_view_SurfaceSession(JNIEnv* env); 143extern int register_android_view_TextureView(JNIEnv* env); 144extern int register_android_view_ThreadedRenderer(JNIEnv* env); 145extern int register_com_android_internal_view_animation_NativeInterpolatorFactoryHelper(JNIEnv *env); 146extern int register_android_database_CursorWindow(JNIEnv* env); 147extern int register_android_database_SQLiteConnection(JNIEnv* env); 148extern int register_android_database_SQLiteGlobal(JNIEnv* env); 149extern int register_android_database_SQLiteDebug(JNIEnv* env); 150extern int register_android_nio_utils(JNIEnv* env); 151extern int register_android_os_Debug(JNIEnv* env); 152extern int register_android_os_MessageQueue(JNIEnv* env); 153extern int register_android_os_Parcel(JNIEnv* env); 154extern int register_android_os_SELinux(JNIEnv* env); 155extern int register_android_os_SystemProperties(JNIEnv *env); 156extern int register_android_os_SystemClock(JNIEnv* env); 157extern int register_android_os_Trace(JNIEnv* env); 158extern int register_android_os_FileObserver(JNIEnv *env); 159extern int register_android_os_UEventObserver(JNIEnv* env); 160extern int register_android_os_MemoryFile(JNIEnv* env); 161extern int register_android_net_LocalSocketImpl(JNIEnv* env); 162extern int register_android_net_NetworkUtils(JNIEnv* env); 163extern int register_android_net_TrafficStats(JNIEnv* env); 164extern int register_android_text_AndroidCharacter(JNIEnv *env); 165extern int register_android_text_StaticLayout(JNIEnv *env); 166extern int register_android_text_AndroidBidi(JNIEnv *env); 167extern int register_android_opengl_classes(JNIEnv *env); 168extern int register_android_ddm_DdmHandleNativeHeap(JNIEnv *env); 169extern int register_android_server_NetworkManagementSocketTagger(JNIEnv* env); 170extern int register_android_backup_BackupDataInput(JNIEnv *env); 171extern int register_android_backup_BackupDataOutput(JNIEnv *env); 172extern int register_android_backup_FileBackupHelperBase(JNIEnv *env); 173extern int register_android_backup_BackupHelperDispatcher(JNIEnv *env); 174extern int register_android_app_backup_FullBackup(JNIEnv *env); 175extern int register_android_app_ActivityThread(JNIEnv *env); 176extern int register_android_app_NativeActivity(JNIEnv *env); 177extern int register_android_media_RemoteDisplay(JNIEnv *env); 178extern int register_android_view_InputChannel(JNIEnv* env); 179extern int register_android_view_InputDevice(JNIEnv* env); 180extern int register_android_view_InputEventReceiver(JNIEnv* env); 181extern int register_android_view_InputEventSender(JNIEnv* env); 182extern int register_android_view_InputQueue(JNIEnv* env); 183extern int register_android_view_KeyCharacterMap(JNIEnv *env); 184extern int register_android_view_KeyEvent(JNIEnv* env); 185extern int register_android_view_MotionEvent(JNIEnv* env); 186extern int register_android_view_PointerIcon(JNIEnv* env); 187extern int register_android_view_VelocityTracker(JNIEnv* env); 188extern int register_android_content_res_ObbScanner(JNIEnv* env); 189extern int register_android_content_res_Configuration(JNIEnv* env); 190extern int register_android_animation_PropertyValuesHolder(JNIEnv *env); 191extern int register_com_android_internal_content_NativeLibraryHelper(JNIEnv *env); 192extern int register_com_android_internal_net_NetworkStatsFactory(JNIEnv *env); 193extern int register_com_android_internal_os_Zygote(JNIEnv *env); 194extern int register_com_android_internal_util_VirtualRefBasePtr(JNIEnv *env); 195 196static AndroidRuntime* gCurRuntime = NULL; 197 198/* 199 * Code written in the Java Programming Language calls here from main(). 200 */ 201static void com_android_internal_os_RuntimeInit_nativeFinishInit(JNIEnv* env, jobject clazz) 202{ 203 gCurRuntime->onStarted(); 204} 205 206static void com_android_internal_os_RuntimeInit_nativeZygoteInit(JNIEnv* env, jobject clazz) 207{ 208 gCurRuntime->onZygoteInit(); 209} 210 211static void com_android_internal_os_RuntimeInit_nativeSetExitWithoutCleanup(JNIEnv* env, 212 jobject clazz, jboolean exitWithoutCleanup) 213{ 214 gCurRuntime->setExitWithoutCleanup(exitWithoutCleanup); 215} 216 217/* 218 * JNI registration. 219 */ 220static const JNINativeMethod gMethods[] = { 221 { "nativeFinishInit", "()V", 222 (void*) com_android_internal_os_RuntimeInit_nativeFinishInit }, 223 { "nativeZygoteInit", "()V", 224 (void*) com_android_internal_os_RuntimeInit_nativeZygoteInit }, 225 { "nativeSetExitWithoutCleanup", "(Z)V", 226 (void*) com_android_internal_os_RuntimeInit_nativeSetExitWithoutCleanup }, 227}; 228 229int register_com_android_internal_os_RuntimeInit(JNIEnv* env) 230{ 231 return jniRegisterNativeMethods(env, "com/android/internal/os/RuntimeInit", 232 gMethods, NELEM(gMethods)); 233} 234 235// ---------------------------------------------------------------------- 236 237/*static*/ JavaVM* AndroidRuntime::mJavaVM = NULL; 238 239AndroidRuntime::AndroidRuntime(char* argBlockStart, const size_t argBlockLength) : 240 mExitWithoutCleanup(false), 241 mArgBlockStart(argBlockStart), 242 mArgBlockLength(argBlockLength) 243{ 244 SkGraphics::Init(); 245 // There is also a global font cache, but its budget is specified by 246 // SK_DEFAULT_FONT_CACHE_COUNT_LIMIT and SK_DEFAULT_FONT_CACHE_LIMIT. 247 248 // Pre-allocate enough space to hold a fair number of options. 249 mOptions.setCapacity(20); 250 251 assert(gCurRuntime == NULL); // one per process 252 gCurRuntime = this; 253} 254 255AndroidRuntime::~AndroidRuntime() 256{ 257 SkGraphics::Term(); 258} 259 260/* 261 * Register native methods using JNI. 262 */ 263/*static*/ int AndroidRuntime::registerNativeMethods(JNIEnv* env, 264 const char* className, const JNINativeMethod* gMethods, int numMethods) 265{ 266 return jniRegisterNativeMethods(env, className, gMethods, numMethods); 267} 268 269void AndroidRuntime::setArgv0(const char* argv0) { 270 memset(mArgBlockStart, 0, mArgBlockLength); 271 strlcpy(mArgBlockStart, argv0, mArgBlockLength); 272} 273 274status_t AndroidRuntime::callMain(const String8& className, jclass clazz, 275 const Vector<String8>& args) 276{ 277 JNIEnv* env; 278 jmethodID methodId; 279 280 ALOGD("Calling main entry %s", className.string()); 281 282 env = getJNIEnv(); 283 if (clazz == NULL || env == NULL) { 284 return UNKNOWN_ERROR; 285 } 286 287 methodId = env->GetStaticMethodID(clazz, "main", "([Ljava/lang/String;)V"); 288 if (methodId == NULL) { 289 ALOGE("ERROR: could not find method %s.main(String[])\n", className.string()); 290 return UNKNOWN_ERROR; 291 } 292 293 /* 294 * We want to call main() with a String array with our arguments in it. 295 * Create an array and populate it. 296 */ 297 jclass stringClass; 298 jobjectArray strArray; 299 300 const size_t numArgs = args.size(); 301 stringClass = env->FindClass("java/lang/String"); 302 strArray = env->NewObjectArray(numArgs, stringClass, NULL); 303 304 for (size_t i = 0; i < numArgs; i++) { 305 jstring argStr = env->NewStringUTF(args[i].string()); 306 env->SetObjectArrayElement(strArray, i, argStr); 307 } 308 309 env->CallStaticVoidMethod(clazz, methodId, strArray); 310 return NO_ERROR; 311} 312 313/* 314 * The VM calls this through the "exit" hook. 315 */ 316static void runtime_exit(int code) 317{ 318 gCurRuntime->exit(code); 319} 320 321/* 322 * The VM calls this through the "vfprintf" hook. 323 * 324 * We ignore "fp" and just write the results to the log file. 325 */ 326static void runtime_vfprintf(FILE* fp, const char* format, va_list ap) 327{ 328 LOG_PRI_VA(ANDROID_LOG_INFO, "vm-printf", format, ap); 329} 330 331/** 332 * The VM calls this when mutex contention debugging is enabled to 333 * determine whether or not the blocked thread was a "sensitive thread" 334 * for user responsiveness/smoothess. 335 * 336 * Our policy for this is whether or not we're tracing any StrictMode 337 * events on this thread (which we might've inherited via Binder calls 338 * into us) 339 */ 340static bool runtime_isSensitiveThread() { 341 IPCThreadState* state = IPCThreadState::selfOrNull(); 342 return state && state->getStrictModePolicy() != 0; 343} 344 345static int hasDir(const char* dir) 346{ 347 struct stat s; 348 int res = stat(dir, &s); 349 if (res == 0) { 350 return S_ISDIR(s.st_mode); 351 } 352 return 0; 353} 354 355static bool hasFile(const char* file) { 356 struct stat s; 357 int res = stat(file, &s); 358 if (res == 0) { 359 return S_ISREG(s.st_mode); 360 } 361 return false; 362} 363 364// Convenience wrapper over the property API that returns an 365// std::string. 366std::string getProperty(const char* key, const char* defaultValue) { 367 std::vector<char> temp(PROPERTY_VALUE_MAX); 368 const int len = property_get(key, &temp[0], defaultValue); 369 if (len < 0) { 370 return ""; 371 } 372 return std::string(&temp[0], len); 373} 374 375/* 376 * Read the persistent locale. Inspects the following system properties 377 * (in order) and returns the first non-empty property in the list : 378 * 379 * (1) persist.sys.locale 380 * (2) persist.sys.language/country/localevar (country and localevar are 381 * inspected iff. language is non-empty. 382 * (3) ro.product.locale 383 * (4) ro.product.locale.language/region 384 * 385 * Note that we need to inspect persist.sys.language/country/localevar to 386 * preserve language settings for devices that are upgrading from Lollipop 387 * to M. The same goes for ro.product.locale.language/region as well. 388 */ 389const std::string readLocale() 390{ 391 const std::string locale = getProperty("persist.sys.locale", ""); 392 if (!locale.empty()) { 393 return locale; 394 } 395 396 const std::string language = getProperty("persist.sys.language", ""); 397 if (!language.empty()) { 398 const std::string country = getProperty("persist.sys.country", ""); 399 const std::string variant = getProperty("persist.sys.localevar", ""); 400 401 std::string out = language; 402 if (!country.empty()) { 403 out = out + "-" + country; 404 } 405 406 if (!variant.empty()) { 407 out = out + "-" + variant; 408 } 409 410 return out; 411 } 412 413 const std::string productLocale = getProperty("ro.product.locale", ""); 414 if (!productLocale.empty()) { 415 return productLocale; 416 } 417 418 // If persist.sys.locale and ro.product.locale are missing, 419 // construct a locale value from the individual locale components. 420 const std::string productLanguage = getProperty("ro.product.locale.language", "en"); 421 const std::string productRegion = getProperty("ro.product.locale.region", "US"); 422 423 return productLanguage + "-" + productRegion; 424} 425 426void AndroidRuntime::addOption(const char* optionString, void* extraInfo) 427{ 428 JavaVMOption opt; 429 opt.optionString = optionString; 430 opt.extraInfo = extraInfo; 431 mOptions.add(opt); 432} 433 434/* 435 * Parse a property containing space-separated options that should be 436 * passed directly to the VM, e.g. "-Xmx32m -verbose:gc -Xregenmap". 437 * 438 * This will cut up "extraOptsBuf" as we chop it into individual options. 439 * 440 * If "quotingArg" is non-null, it is passed before each extra option in mOptions. 441 * 442 * Adds the strings, if any, to mOptions. 443 */ 444void AndroidRuntime::parseExtraOpts(char* extraOptsBuf, const char* quotingArg) 445{ 446 char* start = extraOptsBuf; 447 char* end = NULL; 448 while (*start != '\0') { 449 while (*start == ' ') /* skip leading whitespace */ 450 start++; 451 if (*start == '\0') /* was trailing ws, bail */ 452 break; 453 454 end = start+1; 455 while (*end != ' ' && *end != '\0') /* find end of token */ 456 end++; 457 if (*end == ' ') 458 *end++ = '\0'; /* mark end, advance to indicate more */ 459 460 if (quotingArg != NULL) { 461 addOption(quotingArg); 462 } 463 addOption(start); 464 start = end; 465 } 466} 467 468/* 469 * Reads a "property" into "buffer" with a default of "defaultArg". If 470 * the property is non-empty, it is treated as a runtime option such 471 * as "-Xmx32m". 472 * 473 * The "runtimeArg" is a prefix for the option such as "-Xms" or "-Xmx". 474 * 475 * If an argument is found, it is added to mOptions. 476 * 477 * If an option is found, it is added to mOptions and true is 478 * returned. Otherwise false is returned. 479 */ 480bool AndroidRuntime::parseRuntimeOption(const char* property, 481 char* buffer, 482 const char* runtimeArg, 483 const char* defaultArg) 484{ 485 strcpy(buffer, runtimeArg); 486 size_t runtimeArgLen = strlen(runtimeArg); 487 property_get(property, buffer+runtimeArgLen, defaultArg); 488 if (buffer[runtimeArgLen] == '\0') { 489 return false; 490 } 491 addOption(buffer); 492 return true; 493} 494 495/* 496 * Reads a "property" into "buffer". If the property is non-empty, it 497 * is treated as a dex2oat compiler option that should be 498 * passed as a quoted option, e.g. "-Ximage-compiler-option --compiler-filter=verify-none". 499 * 500 * The "compilerArg" is a prefix for the option such as "--compiler-filter=". 501 * 502 * The "quotingArg" should be "-Ximage-compiler-option" or "-Xcompiler-option". 503 * 504 * If an option is found, it is added to mOptions and true is 505 * returned. Otherwise false is returned. 506 */ 507bool AndroidRuntime::parseCompilerOption(const char* property, 508 char* buffer, 509 const char* compilerArg, 510 const char* quotingArg) 511{ 512 strcpy(buffer, compilerArg); 513 size_t compilerArgLen = strlen(compilerArg); 514 property_get(property, buffer+compilerArgLen, ""); 515 if (buffer[compilerArgLen] == '\0') { 516 return false; 517 } 518 addOption(quotingArg); 519 addOption(buffer); 520 return true; 521} 522 523/* 524 * Reads a "property" into "buffer". If the property is non-empty, it 525 * is treated as a dex2oat compiler runtime option that should be 526 * passed as a quoted option, e.g. "-Ximage-compiler-option 527 * --runtime-arg -Ximage-compiler-option -Xmx32m". 528 * 529 * The "runtimeArg" is a prefix for the option such as "-Xms" or "-Xmx". 530 * 531 * The "quotingArg" should be "-Ximage-compiler-option" or "-Xcompiler-option". 532 * 533 * If an option is found, it is added to mOptions and true is 534 * returned. Otherwise false is returned. 535 */ 536bool AndroidRuntime::parseCompilerRuntimeOption(const char* property, 537 char* buffer, 538 const char* runtimeArg, 539 const char* quotingArg) 540{ 541 strcpy(buffer, runtimeArg); 542 size_t runtimeArgLen = strlen(runtimeArg); 543 property_get(property, buffer+runtimeArgLen, ""); 544 if (buffer[runtimeArgLen] == '\0') { 545 return false; 546 } 547 addOption(quotingArg); 548 addOption("--runtime-arg"); 549 addOption(quotingArg); 550 addOption(buffer); 551 return true; 552} 553 554/* 555 * Start the Dalvik Virtual Machine. 556 * 557 * Various arguments, most determined by system properties, are passed in. 558 * The "mOptions" vector is updated. 559 * 560 * CAUTION: when adding options in here, be careful not to put the 561 * char buffer inside a nested scope. Adding the buffer to the 562 * options using mOptions.add() does not copy the buffer, so if the 563 * buffer goes out of scope the option may be overwritten. It's best 564 * to put the buffer at the top of the function so that it is more 565 * unlikely that someone will surround it in a scope at a later time 566 * and thus introduce a bug. 567 * 568 * Returns 0 on success. 569 */ 570int AndroidRuntime::startVm(JavaVM** pJavaVM, JNIEnv** pEnv, bool zygote) 571{ 572 JavaVMInitArgs initArgs; 573 char propBuf[PROPERTY_VALUE_MAX]; 574 char stackTraceFileBuf[sizeof("-Xstacktracefile:")-1 + PROPERTY_VALUE_MAX]; 575 char jniOptsBuf[sizeof("-Xjniopts:")-1 + PROPERTY_VALUE_MAX]; 576 char heapstartsizeOptsBuf[sizeof("-Xms")-1 + PROPERTY_VALUE_MAX]; 577 char heapsizeOptsBuf[sizeof("-Xmx")-1 + PROPERTY_VALUE_MAX]; 578 char heapgrowthlimitOptsBuf[sizeof("-XX:HeapGrowthLimit=")-1 + PROPERTY_VALUE_MAX]; 579 char heapminfreeOptsBuf[sizeof("-XX:HeapMinFree=")-1 + PROPERTY_VALUE_MAX]; 580 char heapmaxfreeOptsBuf[sizeof("-XX:HeapMaxFree=")-1 + PROPERTY_VALUE_MAX]; 581 char usejitOptsBuf[sizeof("-Xusejit:")-1 + PROPERTY_VALUE_MAX]; 582 char jitcodecachesizeOptsBuf[sizeof("-Xjitcodecachesize:")-1 + PROPERTY_VALUE_MAX]; 583 char jitthresholdOptsBuf[sizeof("-Xjitthreshold:")-1 + PROPERTY_VALUE_MAX]; 584 char gctypeOptsBuf[sizeof("-Xgc:")-1 + PROPERTY_VALUE_MAX]; 585 char backgroundgcOptsBuf[sizeof("-XX:BackgroundGC=")-1 + PROPERTY_VALUE_MAX]; 586 char heaptargetutilizationOptsBuf[sizeof("-XX:HeapTargetUtilization=")-1 + PROPERTY_VALUE_MAX]; 587 char cachePruneBuf[sizeof("-Xzygote-max-boot-retry=")-1 + PROPERTY_VALUE_MAX]; 588 char dex2oatXmsImageFlagsBuf[sizeof("-Xms")-1 + PROPERTY_VALUE_MAX]; 589 char dex2oatXmxImageFlagsBuf[sizeof("-Xmx")-1 + PROPERTY_VALUE_MAX]; 590 char dex2oatXmsFlagsBuf[sizeof("-Xms")-1 + PROPERTY_VALUE_MAX]; 591 char dex2oatXmxFlagsBuf[sizeof("-Xmx")-1 + PROPERTY_VALUE_MAX]; 592 char dex2oatCompilerFilterBuf[sizeof("--compiler-filter=")-1 + PROPERTY_VALUE_MAX]; 593 char dex2oatImageCompilerFilterBuf[sizeof("--compiler-filter=")-1 + PROPERTY_VALUE_MAX]; 594 char dex2oatThreadsBuf[sizeof("-j")-1 + PROPERTY_VALUE_MAX]; 595 char dex2oatThreadsImageBuf[sizeof("-j")-1 + PROPERTY_VALUE_MAX]; 596 char dex2oat_isa_variant_key[PROPERTY_KEY_MAX]; 597 char dex2oat_isa_variant[sizeof("--instruction-set-variant=") -1 + PROPERTY_VALUE_MAX]; 598 char dex2oat_isa_features_key[PROPERTY_KEY_MAX]; 599 char dex2oat_isa_features[sizeof("--instruction-set-features=") -1 + PROPERTY_VALUE_MAX]; 600 char dex2oatFlagsBuf[PROPERTY_VALUE_MAX]; 601 char dex2oatImageFlagsBuf[PROPERTY_VALUE_MAX]; 602 char extraOptsBuf[PROPERTY_VALUE_MAX]; 603 char voldDecryptBuf[PROPERTY_VALUE_MAX]; 604 enum { 605 kEMDefault, 606 kEMIntPortable, 607 kEMIntFast, 608 kEMJitCompiler, 609 } executionMode = kEMDefault; 610 char profilePeriod[sizeof("-Xprofile-period:")-1 + PROPERTY_VALUE_MAX]; 611 char profileDuration[sizeof("-Xprofile-duration:")-1 + PROPERTY_VALUE_MAX]; 612 char profileInterval[sizeof("-Xprofile-interval:")-1 + PROPERTY_VALUE_MAX]; 613 char profileBackoff[sizeof("-Xprofile-backoff:")-1 + PROPERTY_VALUE_MAX]; 614 char profileTopKThreshold[sizeof("-Xprofile-top-k-threshold:")-1 + PROPERTY_VALUE_MAX]; 615 char profileTopKChangeThreshold[sizeof("-Xprofile-top-k-change-threshold:")-1 + 616 PROPERTY_VALUE_MAX]; 617 char profileType[sizeof("-Xprofile-type:")-1 + PROPERTY_VALUE_MAX]; 618 char profileMaxStackDepth[sizeof("-Xprofile-max-stack-depth:")-1 + PROPERTY_VALUE_MAX]; 619 char localeOption[sizeof("-Duser.locale=") + PROPERTY_VALUE_MAX]; 620 char lockProfThresholdBuf[sizeof("-Xlockprofthreshold:")-1 + PROPERTY_VALUE_MAX]; 621 char nativeBridgeLibrary[sizeof("-XX:NativeBridge=") + PROPERTY_VALUE_MAX]; 622 char cpuAbiListBuf[sizeof("--cpu-abilist=") + PROPERTY_VALUE_MAX]; 623 char methodTraceFileBuf[sizeof("-Xmethod-trace-file:") + PROPERTY_VALUE_MAX]; 624 char methodTraceFileSizeBuf[sizeof("-Xmethod-trace-file-size:") + PROPERTY_VALUE_MAX]; 625 char fingerprintBuf[sizeof("-Xfingerprint:") + PROPERTY_VALUE_MAX]; 626 627 bool checkJni = false; 628 property_get("dalvik.vm.checkjni", propBuf, ""); 629 if (strcmp(propBuf, "true") == 0) { 630 checkJni = true; 631 } else if (strcmp(propBuf, "false") != 0) { 632 /* property is neither true nor false; fall back on kernel parameter */ 633 property_get("ro.kernel.android.checkjni", propBuf, ""); 634 if (propBuf[0] == '1') { 635 checkJni = true; 636 } 637 } 638 ALOGD("CheckJNI is %s\n", checkJni ? "ON" : "OFF"); 639 if (checkJni) { 640 /* extended JNI checking */ 641 addOption("-Xcheck:jni"); 642 643 /* with -Xcheck:jni, this provides a JNI function call trace */ 644 //addOption("-verbose:jni"); 645 } 646 647 property_get("dalvik.vm.execution-mode", propBuf, ""); 648 if (strcmp(propBuf, "int:portable") == 0) { 649 executionMode = kEMIntPortable; 650 } else if (strcmp(propBuf, "int:fast") == 0) { 651 executionMode = kEMIntFast; 652 } else if (strcmp(propBuf, "int:jit") == 0) { 653 executionMode = kEMJitCompiler; 654 } 655 656 parseRuntimeOption("dalvik.vm.stack-trace-file", stackTraceFileBuf, "-Xstacktracefile:"); 657 658 strcpy(jniOptsBuf, "-Xjniopts:"); 659 if (parseRuntimeOption("dalvik.vm.jniopts", jniOptsBuf, "-Xjniopts:")) { 660 ALOGI("JNI options: '%s'\n", jniOptsBuf); 661 } 662 663 /* route exit() to our handler */ 664 addOption("exit", (void*) runtime_exit); 665 666 /* route fprintf() to our handler */ 667 addOption("vfprintf", (void*) runtime_vfprintf); 668 669 /* register the framework-specific "is sensitive thread" hook */ 670 addOption("sensitiveThread", (void*) runtime_isSensitiveThread); 671 672 /* enable verbose; standard options are { jni, gc, class } */ 673 //addOption("-verbose:jni"); 674 addOption("-verbose:gc"); 675 //addOption("-verbose:class"); 676 677 /* 678 * The default starting and maximum size of the heap. Larger 679 * values should be specified in a product property override. 680 */ 681 parseRuntimeOption("dalvik.vm.heapstartsize", heapstartsizeOptsBuf, "-Xms", "4m"); 682 parseRuntimeOption("dalvik.vm.heapsize", heapsizeOptsBuf, "-Xmx", "16m"); 683 684 parseRuntimeOption("dalvik.vm.heapgrowthlimit", heapgrowthlimitOptsBuf, "-XX:HeapGrowthLimit="); 685 parseRuntimeOption("dalvik.vm.heapminfree", heapminfreeOptsBuf, "-XX:HeapMinFree="); 686 parseRuntimeOption("dalvik.vm.heapmaxfree", heapmaxfreeOptsBuf, "-XX:HeapMaxFree="); 687 parseRuntimeOption("dalvik.vm.heaptargetutilization", 688 heaptargetutilizationOptsBuf, 689 "-XX:HeapTargetUtilization="); 690 691 /* 692 * JIT related options. 693 */ 694 parseRuntimeOption("dalvik.vm.usejit", usejitOptsBuf, "-Xusejit:"); 695 parseRuntimeOption("dalvik.vm.jitcodecachesize", jitcodecachesizeOptsBuf, "-Xjitcodecachesize:"); 696 parseRuntimeOption("dalvik.vm.jitthreshold", jitthresholdOptsBuf, "-Xjitthreshold:"); 697 698 property_get("ro.config.low_ram", propBuf, ""); 699 if (strcmp(propBuf, "true") == 0) { 700 addOption("-XX:LowMemoryMode"); 701 } 702 703 parseRuntimeOption("dalvik.vm.gctype", gctypeOptsBuf, "-Xgc:"); 704 parseRuntimeOption("dalvik.vm.backgroundgctype", backgroundgcOptsBuf, "-XX:BackgroundGC="); 705 706 /* 707 * Enable debugging only for apps forked from zygote. 708 * Set suspend=y to pause during VM init and use android ADB transport. 709 */ 710 if (zygote) { 711 addOption("-agentlib:jdwp=transport=dt_android_adb,suspend=n,server=y"); 712 } 713 714 parseRuntimeOption("dalvik.vm.lockprof.threshold", 715 lockProfThresholdBuf, 716 "-Xlockprofthreshold:"); 717 718 if (executionMode == kEMIntPortable) { 719 addOption("-Xint:portable"); 720 } else if (executionMode == kEMIntFast) { 721 addOption("-Xint:fast"); 722 } else if (executionMode == kEMJitCompiler) { 723 addOption("-Xint:jit"); 724 } 725 726 // If we are booting without the real /data, don't spend time compiling. 727 property_get("vold.decrypt", voldDecryptBuf, ""); 728 bool skip_compilation = ((strcmp(voldDecryptBuf, "trigger_restart_min_framework") == 0) || 729 (strcmp(voldDecryptBuf, "1") == 0)); 730 731 // Extra options for boot.art/boot.oat image generation. 732 parseCompilerRuntimeOption("dalvik.vm.image-dex2oat-Xms", dex2oatXmsImageFlagsBuf, 733 "-Xms", "-Ximage-compiler-option"); 734 parseCompilerRuntimeOption("dalvik.vm.image-dex2oat-Xmx", dex2oatXmxImageFlagsBuf, 735 "-Xmx", "-Ximage-compiler-option"); 736 if (skip_compilation) { 737 addOption("-Ximage-compiler-option"); 738 addOption("--compiler-filter=verify-none"); 739 } else { 740 parseCompilerOption("dalvik.vm.image-dex2oat-filter", dex2oatImageCompilerFilterBuf, 741 "--compiler-filter=", "-Ximage-compiler-option"); 742 } 743 744 // Make sure there is a preloaded-classes file. 745 if (!hasFile("/system/etc/preloaded-classes")) { 746 ALOGE("Missing preloaded-classes file, /system/etc/preloaded-classes not found: %s\n", 747 strerror(errno)); 748 return -1; 749 } 750 addOption("-Ximage-compiler-option"); 751 addOption("--image-classes=/system/etc/preloaded-classes"); 752 753 // If there is a compiled-classes file, push it. 754 if (hasFile("/system/etc/compiled-classes")) { 755 addOption("-Ximage-compiler-option"); 756 addOption("--compiled-classes=/system/etc/compiled-classes"); 757 } 758 759 property_get("dalvik.vm.image-dex2oat-flags", dex2oatImageFlagsBuf, ""); 760 parseExtraOpts(dex2oatImageFlagsBuf, "-Ximage-compiler-option"); 761 762 // Extra options for DexClassLoader. 763 parseCompilerRuntimeOption("dalvik.vm.dex2oat-Xms", dex2oatXmsFlagsBuf, 764 "-Xms", "-Xcompiler-option"); 765 parseCompilerRuntimeOption("dalvik.vm.dex2oat-Xmx", dex2oatXmxFlagsBuf, 766 "-Xmx", "-Xcompiler-option"); 767 if (skip_compilation) { 768 addOption("-Xcompiler-option"); 769 addOption("--compiler-filter=verify-none"); 770 771 // We skip compilation when a minimal runtime is brought up for decryption. In that case 772 // /data is temporarily backed by a tmpfs, which is usually small. 773 // If the system image contains prebuilts, they will be relocated into the tmpfs. In this 774 // specific situation it is acceptable to *not* relocate and run out of the prebuilts 775 // directly instead. 776 addOption("--runtime-arg"); 777 addOption("-Xnorelocate"); 778 } else { 779 parseCompilerOption("dalvik.vm.dex2oat-filter", dex2oatCompilerFilterBuf, 780 "--compiler-filter=", "-Xcompiler-option"); 781 } 782 parseCompilerOption("dalvik.vm.dex2oat-threads", dex2oatThreadsBuf, "-j", "-Xcompiler-option"); 783 parseCompilerOption("dalvik.vm.image-dex2oat-threads", dex2oatThreadsImageBuf, "-j", 784 "-Ximage-compiler-option"); 785 786 // The runtime will compile a boot image, when necessary, not using installd. Thus, we need to 787 // pass the instruction-set-features/variant as an image-compiler-option. 788 // TODO: Find a better way for the instruction-set. 789#if defined(__arm__) 790 constexpr const char* instruction_set = "arm"; 791#elif defined(__aarch64__) 792 constexpr const char* instruction_set = "arm64"; 793#elif defined(__mips__) && !defined(__LP64__) 794 constexpr const char* instruction_set = "mips"; 795#elif defined(__mips__) && defined(__LP64__) 796 constexpr const char* instruction_set = "mips64"; 797#elif defined(__i386__) 798 constexpr const char* instruction_set = "x86"; 799#elif defined(__x86_64__) 800 constexpr const char* instruction_set = "x86_64"; 801#else 802 constexpr const char* instruction_set = "unknown"; 803#endif 804 // Note: it is OK to reuse the buffer, as the values are exactly the same between 805 // * compiler-option, used for runtime compilation (DexClassLoader) 806 // * image-compiler-option, used for boot-image compilation on device 807 808 // Copy the variant. 809 sprintf(dex2oat_isa_variant_key, "dalvik.vm.isa.%s.variant", instruction_set); 810 parseCompilerOption(dex2oat_isa_variant_key, dex2oat_isa_variant, 811 "--instruction-set-variant=", "-Ximage-compiler-option"); 812 parseCompilerOption(dex2oat_isa_variant_key, dex2oat_isa_variant, 813 "--instruction-set-variant=", "-Xcompiler-option"); 814 // Copy the features. 815 sprintf(dex2oat_isa_features_key, "dalvik.vm.isa.%s.features", instruction_set); 816 parseCompilerOption(dex2oat_isa_features_key, dex2oat_isa_features, 817 "--instruction-set-features=", "-Ximage-compiler-option"); 818 parseCompilerOption(dex2oat_isa_features_key, dex2oat_isa_features, 819 "--instruction-set-features=", "-Xcompiler-option"); 820 821 822 property_get("dalvik.vm.dex2oat-flags", dex2oatFlagsBuf, ""); 823 parseExtraOpts(dex2oatFlagsBuf, "-Xcompiler-option"); 824 825 /* extra options; parse this late so it overrides others */ 826 property_get("dalvik.vm.extra-opts", extraOptsBuf, ""); 827 parseExtraOpts(extraOptsBuf, NULL); 828 829 /* Set the properties for locale */ 830 { 831 strcpy(localeOption, "-Duser.locale="); 832 const std::string locale = readLocale(); 833 strncat(localeOption, locale.c_str(), PROPERTY_VALUE_MAX); 834 addOption(localeOption); 835 } 836 837 /* 838 * Set profiler options 839 */ 840 // Whether or not the profiler should be enabled. 841 property_get("dalvik.vm.profiler", propBuf, "0"); 842 if (propBuf[0] == '1') { 843 addOption("-Xenable-profiler"); 844 } 845 846 // Whether the profile should start upon app startup or be delayed by some random offset 847 // (in seconds) that is bound between 0 and a fixed value. 848 property_get("dalvik.vm.profile.start-immed", propBuf, "0"); 849 if (propBuf[0] == '1') { 850 addOption("-Xprofile-start-immediately"); 851 } 852 853 // Number of seconds during profile runs. 854 parseRuntimeOption("dalvik.vm.profile.period-secs", profilePeriod, "-Xprofile-period:"); 855 856 // Length of each profile run (seconds). 857 parseRuntimeOption("dalvik.vm.profile.duration-secs", 858 profileDuration, 859 "-Xprofile-duration:"); 860 861 // Polling interval during profile run (microseconds). 862 parseRuntimeOption("dalvik.vm.profile.interval-us", profileInterval, "-Xprofile-interval:"); 863 864 // Coefficient for period backoff. The the period is multiplied 865 // by this value after each profile run. 866 parseRuntimeOption("dalvik.vm.profile.backoff-coeff", profileBackoff, "-Xprofile-backoff:"); 867 868 // Top K% of samples that are considered relevant when 869 // deciding if the app should be recompiled. 870 parseRuntimeOption("dalvik.vm.profile.top-k-thr", 871 profileTopKThreshold, 872 "-Xprofile-top-k-threshold:"); 873 874 // The threshold after which a change in the structure of the 875 // top K% profiled samples becomes significant and triggers 876 // recompilation. A change in profile is considered 877 // significant if X% (top-k-change-threshold) of the top K% 878 // (top-k-threshold property) samples has changed. 879 parseRuntimeOption("dalvik.vm.profile.top-k-ch-thr", 880 profileTopKChangeThreshold, 881 "-Xprofile-top-k-change-threshold:"); 882 883 // Type of profile data. 884 parseRuntimeOption("dalvik.vm.profiler.type", profileType, "-Xprofile-type:"); 885 886 // Depth of bounded stack data 887 parseRuntimeOption("dalvik.vm.profile.stack-depth", 888 profileMaxStackDepth, 889 "-Xprofile-max-stack-depth:"); 890 891 // Trace files are stored in /data/misc/trace which is writable only in debug mode. 892 property_get("ro.debuggable", propBuf, "0"); 893 if (strcmp(propBuf, "1") == 0) { 894 property_get("dalvik.vm.method-trace", propBuf, "false"); 895 if (strcmp(propBuf, "true") == 0) { 896 addOption("-Xmethod-trace"); 897 parseRuntimeOption("dalvik.vm.method-trace-file", 898 methodTraceFileBuf, 899 "-Xmethod-trace-file:"); 900 parseRuntimeOption("dalvik.vm.method-trace-file-siz", 901 methodTraceFileSizeBuf, 902 "-Xmethod-trace-file-size:"); 903 property_get("dalvik.vm.method-trace-stream", propBuf, "false"); 904 if (strcmp(propBuf, "true") == 0) { 905 addOption("-Xmethod-trace-stream"); 906 } 907 } 908 } 909 910 // Native bridge library. "0" means that native bridge is disabled. 911 property_get("ro.dalvik.vm.native.bridge", propBuf, ""); 912 if (propBuf[0] == '\0') { 913 ALOGW("ro.dalvik.vm.native.bridge is not expected to be empty"); 914 } else if (strcmp(propBuf, "0") != 0) { 915 snprintf(nativeBridgeLibrary, sizeof("-XX:NativeBridge=") + PROPERTY_VALUE_MAX, 916 "-XX:NativeBridge=%s", propBuf); 917 addOption(nativeBridgeLibrary); 918 } 919 920#if defined(__LP64__) 921 const char* cpu_abilist_property_name = "ro.product.cpu.abilist64"; 922#else 923 const char* cpu_abilist_property_name = "ro.product.cpu.abilist32"; 924#endif // defined(__LP64__) 925 property_get(cpu_abilist_property_name, propBuf, ""); 926 if (propBuf[0] == '\0') { 927 ALOGE("%s is not expected to be empty", cpu_abilist_property_name); 928 return -1; 929 } 930 snprintf(cpuAbiListBuf, sizeof(cpuAbiListBuf), "--cpu-abilist=%s", propBuf); 931 addOption(cpuAbiListBuf); 932 933 // Dalvik-cache pruning counter. 934 parseRuntimeOption("dalvik.vm.zygote.max-boot-retry", cachePruneBuf, 935 "-Xzygote-max-boot-retry="); 936 937 /* 938 * When running with debug.generate-debug-info, add --generate-debug-info to 939 * the compiler options so that the boot image, if it is compiled on device, 940 * will include native debugging information. 941 */ 942 property_get("debug.generate-debug-info", propBuf, ""); 943 if (strcmp(propBuf, "true") == 0) { 944 addOption("-Xcompiler-option"); 945 addOption("--generate-debug-info"); 946 addOption("-Ximage-compiler-option"); 947 addOption("--generate-debug-info"); 948 } 949 950 /* 951 * Retrieve the build fingerprint and provide it to the runtime. That way, ANR dumps will 952 * contain the fingerprint and can be parsed. 953 */ 954 parseRuntimeOption("ro.build.fingerprint", fingerprintBuf, "-Xfingerprint:"); 955 956 initArgs.version = JNI_VERSION_1_4; 957 initArgs.options = mOptions.editArray(); 958 initArgs.nOptions = mOptions.size(); 959 initArgs.ignoreUnrecognized = JNI_FALSE; 960 961 /* 962 * Initialize the VM. 963 * 964 * The JavaVM* is essentially per-process, and the JNIEnv* is per-thread. 965 * If this call succeeds, the VM is ready, and we can start issuing 966 * JNI calls. 967 */ 968 if (JNI_CreateJavaVM(pJavaVM, pEnv, &initArgs) < 0) { 969 ALOGE("JNI_CreateJavaVM failed\n"); 970 return -1; 971 } 972 973 return 0; 974} 975 976char* AndroidRuntime::toSlashClassName(const char* className) 977{ 978 char* result = strdup(className); 979 for (char* cp = result; *cp != '\0'; cp++) { 980 if (*cp == '.') { 981 *cp = '/'; 982 } 983 } 984 return result; 985} 986 987/** Create a Java string from an ASCII or Latin-1 string */ 988jstring AndroidRuntime::NewStringLatin1(JNIEnv* env, const char* bytes) { 989 if (!bytes) return NULL; 990 int length = strlen(bytes); 991 jchar* buffer = (jchar *)alloca(length * sizeof(jchar)); 992 if (!buffer) return NULL; 993 jchar* chp = buffer; 994 for (int i = 0; i < length; i++) { 995 *chp++ = *bytes++; 996 } 997 return env->NewString(buffer, length); 998} 999 1000 1001/* 1002 * Start the Android runtime. This involves starting the virtual machine 1003 * and calling the "static void main(String[] args)" method in the class 1004 * named by "className". 1005 * 1006 * Passes the main function two arguments, the class name and the specified 1007 * options string. 1008 */ 1009void AndroidRuntime::start(const char* className, const Vector<String8>& options, bool zygote) 1010{ 1011 ALOGD(">>>>>> START %s uid %d <<<<<<\n", 1012 className != NULL ? className : "(unknown)", getuid()); 1013 1014 static const String8 startSystemServer("start-system-server"); 1015 1016 /* 1017 * 'startSystemServer == true' means runtime is obsolete and not run from 1018 * init.rc anymore, so we print out the boot start event here. 1019 */ 1020 for (size_t i = 0; i < options.size(); ++i) { 1021 if (options[i] == startSystemServer) { 1022 /* track our progress through the boot sequence */ 1023 const int LOG_BOOT_PROGRESS_START = 3000; 1024 LOG_EVENT_LONG(LOG_BOOT_PROGRESS_START, ns2ms(systemTime(SYSTEM_TIME_MONOTONIC))); 1025 } 1026 } 1027 1028 const char* rootDir = getenv("ANDROID_ROOT"); 1029 if (rootDir == NULL) { 1030 rootDir = "/system"; 1031 if (!hasDir("/system")) { 1032 LOG_FATAL("No root directory specified, and /android does not exist."); 1033 return; 1034 } 1035 setenv("ANDROID_ROOT", rootDir, 1); 1036 } 1037 1038 //const char* kernelHack = getenv("LD_ASSUME_KERNEL"); 1039 //ALOGD("Found LD_ASSUME_KERNEL='%s'\n", kernelHack); 1040 1041 /* start the virtual machine */ 1042 JniInvocation jni_invocation; 1043 jni_invocation.Init(NULL); 1044 JNIEnv* env; 1045 if (startVm(&mJavaVM, &env, zygote) != 0) { 1046 return; 1047 } 1048 onVmCreated(env); 1049 1050 /* 1051 * Register android functions. 1052 */ 1053 if (startReg(env) < 0) { 1054 ALOGE("Unable to register all android natives\n"); 1055 return; 1056 } 1057 1058 /* 1059 * We want to call main() with a String array with arguments in it. 1060 * At present we have two arguments, the class name and an option string. 1061 * Create an array to hold them. 1062 */ 1063 jclass stringClass; 1064 jobjectArray strArray; 1065 jstring classNameStr; 1066 1067 stringClass = env->FindClass("java/lang/String"); 1068 assert(stringClass != NULL); 1069 strArray = env->NewObjectArray(options.size() + 1, stringClass, NULL); 1070 assert(strArray != NULL); 1071 classNameStr = env->NewStringUTF(className); 1072 assert(classNameStr != NULL); 1073 env->SetObjectArrayElement(strArray, 0, classNameStr); 1074 1075 for (size_t i = 0; i < options.size(); ++i) { 1076 jstring optionsStr = env->NewStringUTF(options.itemAt(i).string()); 1077 assert(optionsStr != NULL); 1078 env->SetObjectArrayElement(strArray, i + 1, optionsStr); 1079 } 1080 1081 /* 1082 * Start VM. This thread becomes the main thread of the VM, and will 1083 * not return until the VM exits. 1084 */ 1085 char* slashClassName = toSlashClassName(className); 1086 jclass startClass = env->FindClass(slashClassName); 1087 if (startClass == NULL) { 1088 ALOGE("JavaVM unable to locate class '%s'\n", slashClassName); 1089 /* keep going */ 1090 } else { 1091 jmethodID startMeth = env->GetStaticMethodID(startClass, "main", 1092 "([Ljava/lang/String;)V"); 1093 if (startMeth == NULL) { 1094 ALOGE("JavaVM unable to find main() in '%s'\n", className); 1095 /* keep going */ 1096 } else { 1097 env->CallStaticVoidMethod(startClass, startMeth, strArray); 1098 1099#if 0 1100 if (env->ExceptionCheck()) 1101 threadExitUncaughtException(env); 1102#endif 1103 } 1104 } 1105 free(slashClassName); 1106 1107 ALOGD("Shutting down VM\n"); 1108 if (mJavaVM->DetachCurrentThread() != JNI_OK) 1109 ALOGW("Warning: unable to detach main thread\n"); 1110 if (mJavaVM->DestroyJavaVM() != 0) 1111 ALOGW("Warning: VM did not shut down cleanly\n"); 1112} 1113 1114void AndroidRuntime::exit(int code) 1115{ 1116 if (mExitWithoutCleanup) { 1117 ALOGI("VM exiting with result code %d, cleanup skipped.", code); 1118 ::_exit(code); 1119 } else { 1120 ALOGI("VM exiting with result code %d.", code); 1121 onExit(code); 1122 ::exit(code); 1123 } 1124} 1125 1126void AndroidRuntime::onVmCreated(JNIEnv* env) 1127{ 1128 // If AndroidRuntime had anything to do here, we'd have done it in 'start'. 1129} 1130 1131/* 1132 * Get the JNIEnv pointer for this thread. 1133 * 1134 * Returns NULL if the slot wasn't allocated or populated. 1135 */ 1136/*static*/ JNIEnv* AndroidRuntime::getJNIEnv() 1137{ 1138 JNIEnv* env; 1139 JavaVM* vm = AndroidRuntime::getJavaVM(); 1140 assert(vm != NULL); 1141 1142 if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) 1143 return NULL; 1144 return env; 1145} 1146 1147/* 1148 * Makes the current thread visible to the VM. 1149 * 1150 * The JNIEnv pointer returned is only valid for the current thread, and 1151 * thus must be tucked into thread-local storage. 1152 */ 1153static int javaAttachThread(const char* threadName, JNIEnv** pEnv) 1154{ 1155 JavaVMAttachArgs args; 1156 JavaVM* vm; 1157 jint result; 1158 1159 vm = AndroidRuntime::getJavaVM(); 1160 assert(vm != NULL); 1161 1162 args.version = JNI_VERSION_1_4; 1163 args.name = (char*) threadName; 1164 args.group = NULL; 1165 1166 result = vm->AttachCurrentThread(pEnv, (void*) &args); 1167 if (result != JNI_OK) 1168 ALOGI("NOTE: attach of thread '%s' failed\n", threadName); 1169 1170 return result; 1171} 1172 1173/* 1174 * Detach the current thread from the set visible to the VM. 1175 */ 1176static int javaDetachThread(void) 1177{ 1178 JavaVM* vm; 1179 jint result; 1180 1181 vm = AndroidRuntime::getJavaVM(); 1182 assert(vm != NULL); 1183 1184 result = vm->DetachCurrentThread(); 1185 if (result != JNI_OK) 1186 ALOGE("ERROR: thread detach failed\n"); 1187 return result; 1188} 1189 1190/* 1191 * When starting a native thread that will be visible from the VM, we 1192 * bounce through this to get the right attach/detach action. 1193 * Note that this function calls free(args) 1194 */ 1195/*static*/ int AndroidRuntime::javaThreadShell(void* args) { 1196 void* start = ((void**)args)[0]; 1197 void* userData = ((void **)args)[1]; 1198 char* name = (char*) ((void **)args)[2]; // we own this storage 1199 free(args); 1200 JNIEnv* env; 1201 int result; 1202 1203 /* hook us into the VM */ 1204 if (javaAttachThread(name, &env) != JNI_OK) 1205 return -1; 1206 1207 /* start the thread running */ 1208 result = (*(android_thread_func_t)start)(userData); 1209 1210 /* unhook us */ 1211 javaDetachThread(); 1212 free(name); 1213 1214 return result; 1215} 1216 1217/* 1218 * This is invoked from androidCreateThreadEtc() via the callback 1219 * set with androidSetCreateThreadFunc(). 1220 * 1221 * We need to create the new thread in such a way that it gets hooked 1222 * into the VM before it really starts executing. 1223 */ 1224/*static*/ int AndroidRuntime::javaCreateThreadEtc( 1225 android_thread_func_t entryFunction, 1226 void* userData, 1227 const char* threadName, 1228 int32_t threadPriority, 1229 size_t threadStackSize, 1230 android_thread_id_t* threadId) 1231{ 1232 void** args = (void**) malloc(3 * sizeof(void*)); // javaThreadShell must free 1233 int result; 1234 1235 if (!threadName) 1236 threadName = "unnamed thread"; 1237 1238 args[0] = (void*) entryFunction; 1239 args[1] = userData; 1240 args[2] = (void*) strdup(threadName); // javaThreadShell must free 1241 1242 result = androidCreateRawThreadEtc(AndroidRuntime::javaThreadShell, args, 1243 threadName, threadPriority, threadStackSize, threadId); 1244 return result; 1245} 1246 1247/* 1248 * Create a thread that is visible from the VM. 1249 * 1250 * This is called from elsewhere in the library. 1251 */ 1252/*static*/ android_thread_id_t AndroidRuntime::createJavaThread(const char* name, 1253 void (*start)(void *), void* arg) 1254{ 1255 android_thread_id_t threadId = 0; 1256 javaCreateThreadEtc((android_thread_func_t) start, arg, name, 1257 ANDROID_PRIORITY_DEFAULT, 0, &threadId); 1258 return threadId; 1259} 1260 1261#if 0 1262static void quickTest(void* arg) 1263{ 1264 const char* str = (const char*) arg; 1265 1266 printf("In quickTest: %s\n", str); 1267} 1268#endif 1269 1270#ifdef NDEBUG 1271 #define REG_JNI(name) { name } 1272 struct RegJNIRec { 1273 int (*mProc)(JNIEnv*); 1274 }; 1275#else 1276 #define REG_JNI(name) { name, #name } 1277 struct RegJNIRec { 1278 int (*mProc)(JNIEnv*); 1279 const char* mName; 1280 }; 1281#endif 1282 1283typedef void (*RegJAMProc)(); 1284 1285static int register_jni_procs(const RegJNIRec array[], size_t count, JNIEnv* env) 1286{ 1287 for (size_t i = 0; i < count; i++) { 1288 if (array[i].mProc(env) < 0) { 1289#ifndef NDEBUG 1290 ALOGD("----------!!! %s failed to load\n", array[i].mName); 1291#endif 1292 return -1; 1293 } 1294 } 1295 return 0; 1296} 1297 1298static const RegJNIRec gRegJNI[] = { 1299 REG_JNI(register_com_android_internal_os_RuntimeInit), 1300 REG_JNI(register_android_os_SystemClock), 1301 REG_JNI(register_android_util_EventLog), 1302 REG_JNI(register_android_util_Log), 1303 REG_JNI(register_android_content_AssetManager), 1304 REG_JNI(register_android_content_StringBlock), 1305 REG_JNI(register_android_content_XmlBlock), 1306 REG_JNI(register_android_text_AndroidCharacter), 1307 REG_JNI(register_android_text_StaticLayout), 1308 REG_JNI(register_android_text_AndroidBidi), 1309 REG_JNI(register_android_view_InputDevice), 1310 REG_JNI(register_android_view_KeyCharacterMap), 1311 REG_JNI(register_android_os_Process), 1312 REG_JNI(register_android_os_SystemProperties), 1313 REG_JNI(register_android_os_Binder), 1314 REG_JNI(register_android_os_Parcel), 1315 REG_JNI(register_android_nio_utils), 1316 REG_JNI(register_android_graphics_Graphics), 1317 REG_JNI(register_android_view_DisplayEventReceiver), 1318 REG_JNI(register_android_view_RenderNode), 1319 REG_JNI(register_android_view_RenderNodeAnimator), 1320 REG_JNI(register_android_view_GraphicBuffer), 1321 REG_JNI(register_android_view_DisplayListCanvas), 1322 REG_JNI(register_android_view_HardwareLayer), 1323 REG_JNI(register_android_view_ThreadedRenderer), 1324 REG_JNI(register_android_view_Surface), 1325 REG_JNI(register_android_view_SurfaceControl), 1326 REG_JNI(register_android_view_SurfaceSession), 1327 REG_JNI(register_android_view_TextureView), 1328 REG_JNI(register_com_android_internal_view_animation_NativeInterpolatorFactoryHelper), 1329 REG_JNI(register_com_google_android_gles_jni_EGLImpl), 1330 REG_JNI(register_com_google_android_gles_jni_GLImpl), 1331 REG_JNI(register_android_opengl_jni_EGL14), 1332 REG_JNI(register_android_opengl_jni_EGLExt), 1333 REG_JNI(register_android_opengl_jni_GLES10), 1334 REG_JNI(register_android_opengl_jni_GLES10Ext), 1335 REG_JNI(register_android_opengl_jni_GLES11), 1336 REG_JNI(register_android_opengl_jni_GLES11Ext), 1337 REG_JNI(register_android_opengl_jni_GLES20), 1338 REG_JNI(register_android_opengl_jni_GLES30), 1339 REG_JNI(register_android_opengl_jni_GLES31), 1340 REG_JNI(register_android_opengl_jni_GLES31Ext), 1341 1342 REG_JNI(register_android_graphics_Bitmap), 1343 REG_JNI(register_android_graphics_BitmapFactory), 1344 REG_JNI(register_android_graphics_BitmapRegionDecoder), 1345 REG_JNI(register_android_graphics_Camera), 1346 REG_JNI(register_android_graphics_CreateJavaOutputStreamAdaptor), 1347 REG_JNI(register_android_graphics_Canvas), 1348 REG_JNI(register_android_graphics_CanvasProperty), 1349 REG_JNI(register_android_graphics_ColorFilter), 1350 REG_JNI(register_android_graphics_DrawFilter), 1351 REG_JNI(register_android_graphics_FontFamily), 1352 REG_JNI(register_android_graphics_Interpolator), 1353 REG_JNI(register_android_graphics_LayerRasterizer), 1354 REG_JNI(register_android_graphics_MaskFilter), 1355 REG_JNI(register_android_graphics_Matrix), 1356 REG_JNI(register_android_graphics_Movie), 1357 REG_JNI(register_android_graphics_NinePatch), 1358 REG_JNI(register_android_graphics_Paint), 1359 REG_JNI(register_android_graphics_Path), 1360 REG_JNI(register_android_graphics_PathMeasure), 1361 REG_JNI(register_android_graphics_PathEffect), 1362 REG_JNI(register_android_graphics_Picture), 1363 REG_JNI(register_android_graphics_PorterDuff), 1364 REG_JNI(register_android_graphics_Rasterizer), 1365 REG_JNI(register_android_graphics_Region), 1366 REG_JNI(register_android_graphics_Shader), 1367 REG_JNI(register_android_graphics_SurfaceTexture), 1368 REG_JNI(register_android_graphics_Typeface), 1369 REG_JNI(register_android_graphics_Xfermode), 1370 REG_JNI(register_android_graphics_YuvImage), 1371 REG_JNI(register_android_graphics_pdf_PdfDocument), 1372 REG_JNI(register_android_graphics_pdf_PdfEditor), 1373 REG_JNI(register_android_graphics_pdf_PdfRenderer), 1374 1375 REG_JNI(register_android_database_CursorWindow), 1376 REG_JNI(register_android_database_SQLiteConnection), 1377 REG_JNI(register_android_database_SQLiteGlobal), 1378 REG_JNI(register_android_database_SQLiteDebug), 1379 REG_JNI(register_android_os_Debug), 1380 REG_JNI(register_android_os_FileObserver), 1381 REG_JNI(register_android_os_MessageQueue), 1382 REG_JNI(register_android_os_SELinux), 1383 REG_JNI(register_android_os_Trace), 1384 REG_JNI(register_android_os_UEventObserver), 1385 REG_JNI(register_android_net_LocalSocketImpl), 1386 REG_JNI(register_android_net_NetworkUtils), 1387 REG_JNI(register_android_net_TrafficStats), 1388 REG_JNI(register_android_os_MemoryFile), 1389 REG_JNI(register_com_android_internal_os_Zygote), 1390 REG_JNI(register_com_android_internal_util_VirtualRefBasePtr), 1391 REG_JNI(register_android_hardware_Camera), 1392 REG_JNI(register_android_hardware_camera2_CameraMetadata), 1393 REG_JNI(register_android_hardware_camera2_legacy_LegacyCameraDevice), 1394 REG_JNI(register_android_hardware_camera2_legacy_PerfMeasurement), 1395 REG_JNI(register_android_hardware_camera2_DngCreator), 1396 REG_JNI(register_android_hardware_Radio), 1397 REG_JNI(register_android_hardware_SensorManager), 1398 REG_JNI(register_android_hardware_SerialPort), 1399 REG_JNI(register_android_hardware_SoundTrigger), 1400 REG_JNI(register_android_hardware_UsbDevice), 1401 REG_JNI(register_android_hardware_UsbDeviceConnection), 1402 REG_JNI(register_android_hardware_UsbRequest), 1403 REG_JNI(register_android_hardware_location_ActivityRecognitionHardware), 1404 REG_JNI(register_android_media_AudioRecord), 1405 REG_JNI(register_android_media_AudioSystem), 1406 REG_JNI(register_android_media_AudioTrack), 1407 REG_JNI(register_android_media_JetPlayer), 1408 REG_JNI(register_android_media_RemoteDisplay), 1409 REG_JNI(register_android_media_ToneGenerator), 1410 1411 REG_JNI(register_android_opengl_classes), 1412 REG_JNI(register_android_server_NetworkManagementSocketTagger), 1413 REG_JNI(register_android_ddm_DdmHandleNativeHeap), 1414 REG_JNI(register_android_backup_BackupDataInput), 1415 REG_JNI(register_android_backup_BackupDataOutput), 1416 REG_JNI(register_android_backup_FileBackupHelperBase), 1417 REG_JNI(register_android_backup_BackupHelperDispatcher), 1418 REG_JNI(register_android_app_backup_FullBackup), 1419 REG_JNI(register_android_app_ActivityThread), 1420 REG_JNI(register_android_app_NativeActivity), 1421 REG_JNI(register_android_view_InputChannel), 1422 REG_JNI(register_android_view_InputEventReceiver), 1423 REG_JNI(register_android_view_InputEventSender), 1424 REG_JNI(register_android_view_InputQueue), 1425 REG_JNI(register_android_view_KeyEvent), 1426 REG_JNI(register_android_view_MotionEvent), 1427 REG_JNI(register_android_view_PointerIcon), 1428 REG_JNI(register_android_view_VelocityTracker), 1429 1430 REG_JNI(register_android_content_res_ObbScanner), 1431 REG_JNI(register_android_content_res_Configuration), 1432 1433 REG_JNI(register_android_animation_PropertyValuesHolder), 1434 REG_JNI(register_com_android_internal_content_NativeLibraryHelper), 1435 REG_JNI(register_com_android_internal_net_NetworkStatsFactory), 1436}; 1437 1438/* 1439 * Register android native functions with the VM. 1440 */ 1441/*static*/ int AndroidRuntime::startReg(JNIEnv* env) 1442{ 1443 ATRACE_NAME("RegisterAndroidNatives"); 1444 /* 1445 * This hook causes all future threads created in this process to be 1446 * attached to the JavaVM. (This needs to go away in favor of JNI 1447 * Attach calls.) 1448 */ 1449 androidSetCreateThreadFunc((android_create_thread_fn) javaCreateThreadEtc); 1450 1451 ALOGV("--- registering native functions ---\n"); 1452 1453 /* 1454 * Every "register" function calls one or more things that return 1455 * a local reference (e.g. FindClass). Because we haven't really 1456 * started the VM yet, they're all getting stored in the base frame 1457 * and never released. Use Push/Pop to manage the storage. 1458 */ 1459 env->PushLocalFrame(200); 1460 1461 if (register_jni_procs(gRegJNI, NELEM(gRegJNI), env) < 0) { 1462 env->PopLocalFrame(NULL); 1463 return -1; 1464 } 1465 env->PopLocalFrame(NULL); 1466 1467 //createJavaThread("fubar", quickTest, (void*) "hello"); 1468 1469 return 0; 1470} 1471 1472AndroidRuntime* AndroidRuntime::getRuntime() 1473{ 1474 return gCurRuntime; 1475} 1476 1477/** 1478 * Used by surface flinger's DdmConnection to register native methods from 1479 * the framework. 1480 */ 1481extern "C" jint registerFrameworkNatives(JNIEnv* env) { 1482 return register_jni_procs(gRegJNI, NELEM(gRegJNI), env); 1483} 1484} // namespace android 1485