AndroidRuntime.cpp revision 0b6955a48bad9aee01ae2f0c06d3f168ca603ab7
1/* //device/libs/android_runtime/AndroidRuntime.cpp 2** 3** Copyright 2006, The Android Open Source Project 4** 5** Licensed under the Apache License, Version 2.0 (the "License"); 6** you may not use this file except in compliance with the License. 7** You may obtain a copy of the License at 8** 9** http://www.apache.org/licenses/LICENSE-2.0 10** 11** Unless required by applicable law or agreed to in writing, software 12** distributed under the License is distributed on an "AS IS" BASIS, 13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14** See the License for the specific language governing permissions and 15** limitations under the License. 16*/ 17 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/IServiceManager.h> 24#include <utils/Log.h> 25#include <utils/misc.h> 26#include <binder/Parcel.h> 27#include <utils/string_array.h> 28#include <utils/threads.h> 29#include <cutils/properties.h> 30 31#include <SkGraphics.h> 32#include <SkImageDecoder.h> 33#include <SkImageRef_GlobalPool.h> 34 35#include "jni.h" 36#include "JNIHelp.h" 37#include "android_util_Binder.h" 38 39#include <stdio.h> 40#include <signal.h> 41#include <sys/stat.h> 42#include <sys/types.h> 43#include <signal.h> 44#include <dirent.h> 45#include <assert.h> 46 47 48using namespace android; 49 50extern void register_BindTest(); 51 52extern int register_android_os_Binder(JNIEnv* env); 53extern int register_android_os_Process(JNIEnv* env); 54extern int register_android_graphics_Bitmap(JNIEnv*); 55extern int register_android_graphics_BitmapFactory(JNIEnv*); 56extern int register_android_graphics_Camera(JNIEnv* env); 57extern int register_android_graphics_Graphics(JNIEnv* env); 58extern int register_android_graphics_Interpolator(JNIEnv* env); 59extern int register_android_graphics_LayerRasterizer(JNIEnv*); 60extern int register_android_graphics_MaskFilter(JNIEnv* env); 61extern int register_android_graphics_Movie(JNIEnv* env); 62extern int register_android_graphics_NinePatch(JNIEnv*); 63extern int register_android_graphics_PathEffect(JNIEnv* env); 64extern int register_android_graphics_Region(JNIEnv* env); 65extern int register_android_graphics_Shader(JNIEnv* env); 66extern int register_android_graphics_Typeface(JNIEnv* env); 67 68extern int register_com_google_android_gles_jni_EGLImpl(JNIEnv* env); 69extern int register_com_google_android_gles_jni_GLImpl(JNIEnv* env); 70extern int register_android_opengl_jni_GLES10(JNIEnv* env); 71extern int register_android_opengl_jni_GLES10Ext(JNIEnv* env); 72extern int register_android_opengl_jni_GLES11(JNIEnv* env); 73extern int register_android_opengl_jni_GLES11Ext(JNIEnv* env); 74 75extern int register_android_hardware_Camera(JNIEnv *env); 76 77extern int register_android_hardware_SensorManager(JNIEnv *env); 78 79extern int register_android_media_AudioRecord(JNIEnv *env); 80extern int register_android_media_AudioSystem(JNIEnv *env); 81extern int register_android_media_AudioTrack(JNIEnv *env); 82extern int register_android_media_JetPlayer(JNIEnv *env); 83extern int register_android_media_ToneGenerator(JNIEnv *env); 84 85extern int register_android_message_digest_sha1(JNIEnv *env); 86 87extern int register_android_util_FloatMath(JNIEnv* env); 88 89namespace android { 90 91/* 92 * JNI-based registration functions. Note these are properly contained in 93 * namespace android. 94 */ 95extern int register_android_content_AssetManager(JNIEnv* env); 96extern int register_android_util_EventLog(JNIEnv* env); 97extern int register_android_util_Log(JNIEnv* env); 98extern int register_android_content_StringBlock(JNIEnv* env); 99extern int register_android_content_XmlBlock(JNIEnv* env); 100extern int register_android_emoji_EmojiFactory(JNIEnv* env); 101extern int register_android_graphics_Canvas(JNIEnv* env); 102extern int register_android_graphics_ColorFilter(JNIEnv* env); 103extern int register_android_graphics_DrawFilter(JNIEnv* env); 104extern int register_android_graphics_Matrix(JNIEnv* env); 105extern int register_android_graphics_Paint(JNIEnv* env); 106extern int register_android_graphics_Path(JNIEnv* env); 107extern int register_android_graphics_PathMeasure(JNIEnv* env); 108extern int register_android_graphics_Picture(JNIEnv*); 109extern int register_android_graphics_PorterDuff(JNIEnv* env); 110extern int register_android_graphics_Rasterizer(JNIEnv* env); 111extern int register_android_graphics_Xfermode(JNIEnv* env); 112extern int register_android_graphics_PixelFormat(JNIEnv* env); 113extern int register_com_android_internal_graphics_NativeUtils(JNIEnv *env); 114extern int register_android_view_Display(JNIEnv* env); 115extern int register_android_view_Surface(JNIEnv* env); 116extern int register_android_view_ViewRoot(JNIEnv* env); 117extern int register_android_database_CursorWindow(JNIEnv* env); 118extern int register_android_database_SQLiteDatabase(JNIEnv* env); 119extern int register_android_database_SQLiteDebug(JNIEnv* env); 120extern int register_android_database_SQLiteProgram(JNIEnv* env); 121extern int register_android_database_SQLiteQuery(JNIEnv* env); 122extern int register_android_database_SQLiteStatement(JNIEnv* env); 123extern int register_android_debug_JNITest(JNIEnv* env); 124extern int register_android_nio_utils(JNIEnv* env); 125extern int register_android_pim_EventRecurrence(JNIEnv* env); 126extern int register_android_text_format_Time(JNIEnv* env); 127extern int register_android_os_Debug(JNIEnv* env); 128extern int register_android_os_ParcelFileDescriptor(JNIEnv *env); 129extern int register_android_os_Power(JNIEnv *env); 130extern int register_android_os_StatFs(JNIEnv *env); 131extern int register_android_os_SystemProperties(JNIEnv *env); 132extern int register_android_os_Hardware(JNIEnv* env); 133extern int register_android_os_SystemClock(JNIEnv* env); 134extern int register_android_os_FileObserver(JNIEnv *env); 135extern int register_android_os_FileUtils(JNIEnv *env); 136extern int register_android_os_UEventObserver(JNIEnv* env); 137extern int register_android_os_MemoryFile(JNIEnv* env); 138extern int register_android_net_LocalSocketImpl(JNIEnv* env); 139extern int register_android_net_NetworkUtils(JNIEnv* env); 140extern int register_android_net_wifi_WifiManager(JNIEnv* env); 141extern int register_android_security_Md5MessageDigest(JNIEnv *env); 142extern int register_android_text_AndroidCharacter(JNIEnv *env); 143extern int register_android_text_KeyCharacterMap(JNIEnv *env); 144extern int register_android_opengl_classes(JNIEnv *env); 145extern int register_android_bluetooth_HeadsetBase(JNIEnv* env); 146extern int register_android_bluetooth_BluetoothAudioGateway(JNIEnv* env); 147extern int register_android_bluetooth_BluetoothSocket(JNIEnv *env); 148extern int register_android_bluetooth_ScoSocket(JNIEnv *env); 149extern int register_android_server_BluetoothDeviceService(JNIEnv* env); 150extern int register_android_server_BluetoothEventLoop(JNIEnv *env); 151extern int register_android_server_BluetoothA2dpService(JNIEnv* env); 152extern int register_android_ddm_DdmHandleNativeHeap(JNIEnv *env); 153extern int register_com_android_internal_os_ZygoteInit(JNIEnv* env); 154extern int register_android_util_Base64(JNIEnv* env); 155extern int register_android_location_GpsLocationProvider(JNIEnv* env); 156extern int register_android_backup_BackupDataOutput(JNIEnv *env); 157extern int register_android_backup_FileBackupHelper(JNIEnv *env); 158 159static AndroidRuntime* gCurRuntime = NULL; 160 161static void doThrow(JNIEnv* env, const char* exc, const char* msg = NULL) 162{ 163 if (jniThrowException(env, exc, msg) != 0) 164 assert(false); 165} 166 167/* 168 * Code written in the Java Programming Language calls here from main(). 169 */ 170static void com_android_internal_os_RuntimeInit_finishInit(JNIEnv* env, jobject clazz) 171{ 172 gCurRuntime->onStarted(); 173} 174 175static void com_android_internal_os_RuntimeInit_zygoteInit(JNIEnv* env, jobject clazz) 176{ 177 gCurRuntime->onZygoteInit(); 178} 179 180static jint com_android_internal_os_RuntimeInit_isComputerOn(JNIEnv* env, jobject clazz) 181{ 182 return 1; 183} 184 185static void com_android_internal_os_RuntimeInit_turnComputerOn(JNIEnv* env, jobject clazz) 186{ 187} 188 189static jint com_android_internal_os_RuntimeInit_getQwertyKeyboard(JNIEnv* env, jobject clazz) 190{ 191 char* value = getenv("qwerty"); 192 if (value != NULL && strcmp(value, "true") == 0) { 193 return 1; 194 } 195 196 return 0; 197} 198 199/* 200 * JNI registration. 201 */ 202static JNINativeMethod gMethods[] = { 203 { "finishInit", "()V", 204 (void*) com_android_internal_os_RuntimeInit_finishInit }, 205 { "zygoteInitNative", "()V", 206 (void*) com_android_internal_os_RuntimeInit_zygoteInit }, 207 { "isComputerOn", "()I", 208 (void*) com_android_internal_os_RuntimeInit_isComputerOn }, 209 { "turnComputerOn", "()V", 210 (void*) com_android_internal_os_RuntimeInit_turnComputerOn }, 211 { "getQwertyKeyboard", "()I", 212 (void*) com_android_internal_os_RuntimeInit_getQwertyKeyboard }, 213}; 214 215int register_com_android_internal_os_RuntimeInit(JNIEnv* env) 216{ 217 return jniRegisterNativeMethods(env, "com/android/internal/os/RuntimeInit", 218 gMethods, NELEM(gMethods)); 219} 220 221// ---------------------------------------------------------------------- 222 223/*static*/ JavaVM* AndroidRuntime::mJavaVM = NULL; 224 225 226AndroidRuntime::AndroidRuntime() 227{ 228 SkGraphics::Init(); 229 // this sets our preference for 16bit images during decode 230 // in case the src is opaque and 24bit 231 SkImageDecoder::SetDeviceConfig(SkBitmap::kRGB_565_Config); 232 // This cache is shared between browser native images, and java "purgeable" 233 // bitmaps. This globalpool is for images that do not either use the java 234 // heap, or are not backed by ashmem. See BitmapFactory.cpp for the key 235 // java call site. 236 SkImageRef_GlobalPool::SetRAMBudget(512 * 1024); 237 // There is also a global font cache, but its budget is specified in code 238 // see SkFontHost_android.cpp 239 240 // Pre-allocate enough space to hold a fair number of options. 241 mOptions.setCapacity(20); 242 243 assert(gCurRuntime == NULL); // one per process 244 gCurRuntime = this; 245} 246 247AndroidRuntime::~AndroidRuntime() 248{ 249 SkGraphics::Term(); 250} 251 252/* 253 * Register native methods using JNI. 254 */ 255/*static*/ int AndroidRuntime::registerNativeMethods(JNIEnv* env, 256 const char* className, const JNINativeMethod* gMethods, int numMethods) 257{ 258 return jniRegisterNativeMethods(env, className, gMethods, numMethods); 259} 260 261/* 262 * Call a static Java Programming Language function that takes no arguments and returns void. 263 */ 264status_t AndroidRuntime::callStatic(const char* className, const char* methodName) 265{ 266 JNIEnv* env; 267 jclass clazz; 268 jmethodID methodId; 269 270 env = getJNIEnv(); 271 if (env == NULL) 272 return UNKNOWN_ERROR; 273 274 clazz = findClass(env, className); 275 if (clazz == NULL) { 276 LOGE("ERROR: could not find class '%s'\n", className); 277 return UNKNOWN_ERROR; 278 } 279 methodId = env->GetStaticMethodID(clazz, methodName, "()V"); 280 if (methodId == NULL) { 281 LOGE("ERROR: could not find method %s.%s\n", className, methodName); 282 return UNKNOWN_ERROR; 283 } 284 285 env->CallStaticVoidMethod(clazz, methodId); 286 287 return NO_ERROR; 288} 289 290status_t AndroidRuntime::callMain( 291 const char* className, int argc, const char* const argv[]) 292{ 293 JNIEnv* env; 294 jclass clazz; 295 jmethodID methodId; 296 297 env = getJNIEnv(); 298 if (env == NULL) 299 return UNKNOWN_ERROR; 300 301 clazz = findClass(env, className); 302 if (clazz == NULL) { 303 LOGE("ERROR: could not find class '%s'\n", className); 304 return UNKNOWN_ERROR; 305 } 306 307 methodId = env->GetStaticMethodID(clazz, "main", "([Ljava/lang/String;)V"); 308 if (methodId == NULL) { 309 LOGE("ERROR: could not find method %s.main(String[])\n", className); 310 return UNKNOWN_ERROR; 311 } 312 313 /* 314 * We want to call main() with a String array with our arguments in it. 315 * Create an array and populate it. 316 */ 317 jclass stringClass; 318 jobjectArray strArray; 319 320 stringClass = env->FindClass("java/lang/String"); 321 strArray = env->NewObjectArray(argc, stringClass, NULL); 322 323 for (int i = 0; i < argc; i++) { 324 jstring argStr = env->NewStringUTF(argv[i]); 325 env->SetObjectArrayElement(strArray, i, argStr); 326 } 327 328 env->CallStaticVoidMethod(clazz, methodId, strArray); 329 return NO_ERROR; 330} 331 332/* 333 * Find the named class. 334 */ 335jclass AndroidRuntime::findClass(JNIEnv* env, const char* className) 336{ 337 char* convName = NULL; 338 339 if (env->ExceptionCheck()) { 340 LOGE("ERROR: exception pending on entry to findClass()\n"); 341 return NULL; 342 } 343 344 /* 345 * JNI FindClass uses class names with slashes, but ClassLoader.loadClass 346 * uses the dotted "binary name" format. We don't need to convert the 347 * name with the new approach. 348 */ 349#if 0 350 /* (convName only created if necessary -- use className) */ 351 for (char* cp = const_cast<char*>(className); *cp != '\0'; cp++) { 352 if (*cp == '.') { 353 if (convName == NULL) { 354 convName = strdup(className); 355 cp = convName + (cp-className); 356 className = convName; 357 } 358 *cp = '/'; 359 } 360 } 361#endif 362 363 /* 364 * This is a little awkward because the JNI FindClass call uses the 365 * class loader associated with the native method we're executing in. 366 * Because this native method is part of a "boot" class, JNI doesn't 367 * look for the class in CLASSPATH, which unfortunately is a likely 368 * location for it. (Had we issued the FindClass call before calling 369 * into the VM -- at which point there isn't a native method frame on 370 * the stack -- the VM would have checked CLASSPATH. We have to do 371 * this because we call into Java Programming Language code and 372 * bounce back out.) 373 * 374 * JNI lacks a "find class in a specific class loader" operation, so we 375 * have to do things the hard way. 376 */ 377 jclass cls = NULL; 378 //cls = env->FindClass(className); 379 380 jclass javaLangClassLoader; 381 jmethodID getSystemClassLoader, loadClass; 382 jobject systemClassLoader; 383 jstring strClassName; 384 385 /* find the "system" class loader; none of this is expected to fail */ 386 javaLangClassLoader = env->FindClass("java/lang/ClassLoader"); 387 assert(javaLangClassLoader != NULL); 388 getSystemClassLoader = env->GetStaticMethodID(javaLangClassLoader, 389 "getSystemClassLoader", "()Ljava/lang/ClassLoader;"); 390 loadClass = env->GetMethodID(javaLangClassLoader, 391 "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;"); 392 assert(getSystemClassLoader != NULL && loadClass != NULL); 393 systemClassLoader = env->CallStaticObjectMethod(javaLangClassLoader, 394 getSystemClassLoader); 395 assert(systemClassLoader != NULL); 396 397 /* create an object for the class name string; alloc could fail */ 398 strClassName = env->NewStringUTF(className); 399 if (env->ExceptionCheck()) { 400 LOGE("ERROR: unable to convert '%s' to string\n", className); 401 goto bail; 402 } 403 LOGV("system class loader is %p, loading %p (%s)\n", 404 systemClassLoader, strClassName, className); 405 406 /* try to find the named class */ 407 cls = (jclass) env->CallObjectMethod(systemClassLoader, loadClass, 408 strClassName); 409 if (env->ExceptionCheck()) { 410 LOGE("ERROR: unable to load class '%s' from %p\n", 411 className, systemClassLoader); 412 cls = NULL; 413 goto bail; 414 } 415 416bail: 417 free(convName); 418 return cls; 419} 420 421/* 422 * The VM calls this through the "exit" hook. 423 */ 424static void runtime_exit(int code) 425{ 426 gCurRuntime->onExit(code); 427 exit(code); 428} 429 430/* 431 * The VM calls this through the "vfprintf" hook. 432 * 433 * We ignore "fp" and just write the results to the log file. 434 */ 435static void runtime_vfprintf(FILE* fp, const char* format, va_list ap) 436{ 437 LOG_PRI_VA(ANDROID_LOG_INFO, "vm-printf", format, ap); 438} 439 440 441/** 442 * Add VM arguments to the to-be-executed VM 443 * Stops at first non '-' argument (also stops at an argument of '--') 444 * Returns the number of args consumed 445 */ 446int AndroidRuntime::addVmArguments(int argc, const char* const argv[]) 447{ 448 int i; 449 450 for (i = 0; i<argc; i++) { 451 if (argv[i][0] != '-') { 452 return i; 453 } 454 if (argv[i][1] == '-' && argv[i][2] == 0) { 455 return i+1; 456 } 457 458 JavaVMOption opt; 459 memset(&opt, 0, sizeof(opt)); 460 opt.optionString = (char*)argv[i]; 461 mOptions.add(opt); 462 } 463 return i; 464} 465 466static int hasDir(const char* dir) 467{ 468 struct stat s; 469 int res = stat(dir, &s); 470 if (res == 0) { 471 return S_ISDIR(s.st_mode); 472 } 473 return 0; 474} 475 476/* 477 * We just want failed write() calls to just return with an error. 478 */ 479static void blockSigpipe() 480{ 481 sigset_t mask; 482 483 sigemptyset(&mask); 484 sigaddset(&mask, SIGPIPE); 485 if (sigprocmask(SIG_BLOCK, &mask, NULL) != 0) 486 LOGW("WARNING: SIGPIPE not blocked\n"); 487} 488 489/* 490 * Read the persistent locale. 491 */ 492static void readLocale(char* language, char* region) 493{ 494 char propLang[PROPERTY_VALUE_MAX], propRegn[PROPERTY_VALUE_MAX]; 495 496 property_get("persist.sys.language", propLang, ""); 497 property_get("persist.sys.country", propRegn, ""); 498 if (*propLang == 0 && *propRegn == 0) { 499 /* Set to ro properties, default is en_US */ 500 property_get("ro.product.locale.language", propLang, "en"); 501 property_get("ro.product.locale.region", propRegn, "US"); 502 } 503 strncat(language, propLang, 2); 504 strncat(region, propRegn, 2); 505 //LOGD("language=%s region=%s\n", language, region); 506} 507 508/* 509 * Start the Dalvik Virtual Machine. 510 * 511 * Various arguments, most determined by system properties, are passed in. 512 * The "mOptions" vector is updated. 513 * 514 * Returns 0 on success. 515 */ 516int AndroidRuntime::startVm(JavaVM** pJavaVM, JNIEnv** pEnv) 517{ 518 int result = -1; 519 JavaVMInitArgs initArgs; 520 JavaVMOption opt; 521 char propBuf[PROPERTY_VALUE_MAX]; 522 char stackTraceFileBuf[PROPERTY_VALUE_MAX]; 523 char dexoptFlagsBuf[PROPERTY_VALUE_MAX]; 524 char enableAssertBuf[sizeof("-ea:")-1 + PROPERTY_VALUE_MAX]; 525 char jniOptsBuf[sizeof("-Xjniopts:")-1 + PROPERTY_VALUE_MAX]; 526 char* stackTraceFile = NULL; 527 bool checkJni = false; 528 bool checkDexSum = false; 529 bool logStdio = false; 530 enum { kEMDefault, kEMIntPortable, kEMIntFast } executionMode = kEMDefault; 531 532 533 property_get("dalvik.vm.checkjni", propBuf, ""); 534 if (strcmp(propBuf, "true") == 0) { 535 checkJni = true; 536 } else if (strcmp(propBuf, "false") != 0) { 537 /* property is neither true nor false; fall back on kernel parameter */ 538 property_get("ro.kernel.android.checkjni", propBuf, ""); 539 if (propBuf[0] == '1') { 540 checkJni = true; 541 } 542 } 543 544 property_get("dalvik.vm.execution-mode", propBuf, ""); 545 if (strcmp(propBuf, "int:portable") == 0) { 546 executionMode = kEMIntPortable; 547 } else if (strcmp(propBuf, "int:fast") == 0) { 548 executionMode = kEMIntFast; 549 } 550 551 property_get("dalvik.vm.stack-trace-file", stackTraceFileBuf, ""); 552 553 property_get("dalvik.vm.check-dex-sum", propBuf, ""); 554 if (strcmp(propBuf, "true") == 0) { 555 checkDexSum = true; 556 } 557 558 property_get("log.redirect-stdio", propBuf, ""); 559 if (strcmp(propBuf, "true") == 0) { 560 logStdio = true; 561 } 562 563 strcpy(enableAssertBuf, "-ea:"); 564 property_get("dalvik.vm.enableassertions", enableAssertBuf+4, ""); 565 566 strcpy(jniOptsBuf, "-Xjniopts:"); 567 property_get("dalvik.vm.jniopts", jniOptsBuf+10, ""); 568 569 /* route exit() to our handler */ 570 opt.extraInfo = (void*) runtime_exit; 571 opt.optionString = "exit"; 572 mOptions.add(opt); 573 574 /* route fprintf() to our handler */ 575 opt.extraInfo = (void*) runtime_vfprintf; 576 opt.optionString = "vfprintf"; 577 mOptions.add(opt); 578 579 opt.extraInfo = NULL; 580 581 /* enable verbose; standard options are { jni, gc, class } */ 582 //options[curOpt++].optionString = "-verbose:jni"; 583 opt.optionString = "-verbose:gc"; 584 mOptions.add(opt); 585 //options[curOpt++].optionString = "-verbose:class"; 586 587#ifdef CUSTOM_RUNTIME_HEAP_MAX 588#define __make_max_heap_opt(val) #val 589#define _make_max_heap_opt(val) "-Xmx" __make_max_heap_opt(val) 590 opt.optionString = _make_max_heap_opt(CUSTOM_RUNTIME_HEAP_MAX); 591#undef __make_max_heap_opt 592#undef _make_max_heap_opt 593#else 594 /* limit memory use to 16MB */ 595 opt.optionString = "-Xmx16m"; 596#endif 597 mOptions.add(opt); 598 599 /* 600 * Enable or disable dexopt features, such as bytecode verification and 601 * calculation of register maps for precise GC. 602 */ 603 property_get("dalvik.vm.dexopt-flags", dexoptFlagsBuf, ""); 604 if (dexoptFlagsBuf[0] != '\0') { 605 const char* opc; 606 const char* val; 607 608 opc = strstr(dexoptFlagsBuf, "v="); /* verification */ 609 if (opc != NULL) { 610 switch (*(opc+2)) { 611 case 'n': val = "-Xverify:none"; break; 612 case 'r': val = "-Xverify:remote"; break; 613 case 'a': val = "-Xverify:all"; break; 614 default: val = NULL; break; 615 } 616 617 if (val != NULL) { 618 opt.optionString = val; 619 mOptions.add(opt); 620 } 621 } 622 623 opc = strstr(dexoptFlagsBuf, "o="); /* optimization */ 624 if (opc != NULL) { 625 switch (*(opc+2)) { 626 case 'n': val = "-Xdexopt:none"; break; 627 case 'v': val = "-Xdexopt:verified"; break; 628 case 'a': val = "-Xdexopt:all"; break; 629 default: val = NULL; break; 630 } 631 632 if (val != NULL) { 633 opt.optionString = val; 634 mOptions.add(opt); 635 } 636 } 637 638 opc = strstr(dexoptFlagsBuf, "m=y"); /* register map */ 639 if (opc != NULL) { 640 opt.optionString = "-Xgenregmap"; 641 mOptions.add(opt); 642 643 /* turn on precise GC while we're at it */ 644 opt.optionString = "-Xgc:precise"; 645 mOptions.add(opt); 646 } 647 } 648 649 /* enable debugging; set suspend=y to pause during VM init */ 650#ifdef HAVE_ANDROID_OS 651 /* use android ADB transport */ 652 opt.optionString = 653 "-agentlib:jdwp=transport=dt_android_adb,suspend=n,server=y"; 654#else 655 /* use TCP socket; address=0 means start at port 8000 and probe up */ 656 LOGI("Using TCP socket for JDWP\n"); 657 opt.optionString = 658 "-agentlib:jdwp=transport=dt_socket,suspend=n,server=y,address=0"; 659#endif 660 mOptions.add(opt); 661 662 char enableDPBuf[sizeof("-Xdeadlockpredict:") + PROPERTY_VALUE_MAX]; 663 property_get("dalvik.vm.deadlock-predict", propBuf, ""); 664 if (strlen(propBuf) > 0) { 665 strcpy(enableDPBuf, "-Xdeadlockpredict:"); 666 strcat(enableDPBuf, propBuf); 667 opt.optionString = enableDPBuf; 668 mOptions.add(opt); 669 } 670 671 LOGD("CheckJNI is %s\n", checkJni ? "ON" : "OFF"); 672 if (checkJni) { 673 /* extended JNI checking */ 674 opt.optionString = "-Xcheck:jni"; 675 mOptions.add(opt); 676 677 /* set a cap on JNI global references */ 678 opt.optionString = "-Xjnigreflimit:2000"; 679 mOptions.add(opt); 680 681 /* with -Xcheck:jni, this provides a JNI function call trace */ 682 //opt.optionString = "-verbose:jni"; 683 //mOptions.add(opt); 684 } 685 if (executionMode == kEMIntPortable) { 686 opt.optionString = "-Xint:portable"; 687 mOptions.add(opt); 688 } else if (executionMode == kEMIntFast) { 689 opt.optionString = "-Xint:fast"; 690 mOptions.add(opt); 691 } 692 693 if (checkDexSum) { 694 /* perform additional DEX checksum tests */ 695 opt.optionString = "-Xcheckdexsum"; 696 mOptions.add(opt); 697 } 698 699 if (logStdio) { 700 /* convert stdout/stderr to log messages */ 701 opt.optionString = "-Xlog-stdio"; 702 mOptions.add(opt); 703 } 704 705 if (enableAssertBuf[4] != '\0') { 706 /* accept "all" to mean "all classes and packages" */ 707 if (strcmp(enableAssertBuf+4, "all") == 0) 708 enableAssertBuf[3] = '\0'; 709 LOGI("Assertions enabled: '%s'\n", enableAssertBuf); 710 opt.optionString = enableAssertBuf; 711 mOptions.add(opt); 712 } else { 713 LOGV("Assertions disabled\n"); 714 } 715 716 if (jniOptsBuf[10] != '\0') { 717 LOGI("JNI options: '%s'\n", jniOptsBuf); 718 opt.optionString = jniOptsBuf; 719 mOptions.add(opt); 720 } 721 722 if (stackTraceFileBuf[0] != '\0') { 723 static const char* stfOptName = "-Xstacktracefile:"; 724 725 stackTraceFile = (char*) malloc(strlen(stfOptName) + 726 strlen(stackTraceFileBuf) +1); 727 strcpy(stackTraceFile, stfOptName); 728 strcat(stackTraceFile, stackTraceFileBuf); 729 opt.optionString = stackTraceFile; 730 mOptions.add(opt); 731 } 732 733 /* Set the properties for locale */ 734 { 735 char langOption[sizeof("-Duser.language=") + 3]; 736 char regionOption[sizeof("-Duser.region=") + 3]; 737 strcpy(langOption, "-Duser.language="); 738 strcpy(regionOption, "-Duser.region="); 739 readLocale(langOption, regionOption); 740 opt.extraInfo = NULL; 741 opt.optionString = langOption; 742 mOptions.add(opt); 743 opt.optionString = regionOption; 744 mOptions.add(opt); 745 } 746 747 /* 748 * We don't have /tmp on the device, but we often have an SD card. Apps 749 * shouldn't use this, but some test suites might want to exercise it. 750 */ 751 opt.optionString = "-Djava.io.tmpdir=/sdcard"; 752 mOptions.add(opt); 753 754 initArgs.version = JNI_VERSION_1_4; 755 initArgs.options = mOptions.editArray(); 756 initArgs.nOptions = mOptions.size(); 757 initArgs.ignoreUnrecognized = JNI_FALSE; 758 759 /* 760 * Initialize the VM. 761 * 762 * The JavaVM* is essentially per-process, and the JNIEnv* is per-thread. 763 * If this call succeeds, the VM is ready, and we can start issuing 764 * JNI calls. 765 */ 766 if (JNI_CreateJavaVM(pJavaVM, pEnv, &initArgs) < 0) { 767 LOGE("JNI_CreateJavaVM failed\n"); 768 goto bail; 769 } 770 771 result = 0; 772 773bail: 774 free(stackTraceFile); 775 return result; 776} 777 778/* 779 * Start the Android runtime. This involves starting the virtual machine 780 * and calling the "static void main(String[] args)" method in the class 781 * named by "className". 782 */ 783void AndroidRuntime::start(const char* className, const bool startSystemServer) 784{ 785 LOGD("\n>>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<<\n"); 786 787 char* slashClassName = NULL; 788 char* cp; 789 JNIEnv* env; 790 791 blockSigpipe(); 792 793 /* 794 * 'startSystemServer == true' means runtime is obslete and not run from 795 * init.rc anymore, so we print out the boot start event here. 796 */ 797 if (startSystemServer) { 798 /* track our progress through the boot sequence */ 799 const int LOG_BOOT_PROGRESS_START = 3000; 800 LOG_EVENT_LONG(LOG_BOOT_PROGRESS_START, 801 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC))); 802 } 803 804 const char* rootDir = getenv("ANDROID_ROOT"); 805 if (rootDir == NULL) { 806 rootDir = "/system"; 807 if (!hasDir("/system")) { 808 LOG_FATAL("No root directory specified, and /android does not exist."); 809 goto bail; 810 } 811 setenv("ANDROID_ROOT", rootDir, 1); 812 } 813 814 //const char* kernelHack = getenv("LD_ASSUME_KERNEL"); 815 //LOGD("Found LD_ASSUME_KERNEL='%s'\n", kernelHack); 816 817 /* start the virtual machine */ 818 if (startVm(&mJavaVM, &env) != 0) 819 goto bail; 820 821 /* 822 * Register android functions. 823 */ 824 if (startReg(env) < 0) { 825 LOGE("Unable to register all android natives\n"); 826 goto bail; 827 } 828 829 /* 830 * We want to call main() with a String array with arguments in it. 831 * At present we only have one argument, the class name. Create an 832 * array to hold it. 833 */ 834 jclass stringClass; 835 jobjectArray strArray; 836 jstring classNameStr; 837 jstring startSystemServerStr; 838 839 stringClass = env->FindClass("java/lang/String"); 840 assert(stringClass != NULL); 841 strArray = env->NewObjectArray(2, stringClass, NULL); 842 assert(strArray != NULL); 843 classNameStr = env->NewStringUTF(className); 844 assert(classNameStr != NULL); 845 env->SetObjectArrayElement(strArray, 0, classNameStr); 846 startSystemServerStr = env->NewStringUTF(startSystemServer ? 847 "true" : "false"); 848 env->SetObjectArrayElement(strArray, 1, startSystemServerStr); 849 850 /* 851 * Start VM. This thread becomes the main thread of the VM, and will 852 * not return until the VM exits. 853 */ 854 jclass startClass; 855 jmethodID startMeth; 856 857 slashClassName = strdup(className); 858 for (cp = slashClassName; *cp != '\0'; cp++) 859 if (*cp == '.') 860 *cp = '/'; 861 862 startClass = env->FindClass(slashClassName); 863 if (startClass == NULL) { 864 LOGE("JavaVM unable to locate class '%s'\n", slashClassName); 865 /* keep going */ 866 } else { 867 startMeth = env->GetStaticMethodID(startClass, "main", 868 "([Ljava/lang/String;)V"); 869 if (startMeth == NULL) { 870 LOGE("JavaVM unable to find main() in '%s'\n", className); 871 /* keep going */ 872 } else { 873 env->CallStaticVoidMethod(startClass, startMeth, strArray); 874 875#if 0 876 if (env->ExceptionCheck()) 877 threadExitUncaughtException(env); 878#endif 879 } 880 } 881 882 LOGD("Shutting down VM\n"); 883 if (mJavaVM->DetachCurrentThread() != JNI_OK) 884 LOGW("Warning: unable to detach main thread\n"); 885 if (mJavaVM->DestroyJavaVM() != 0) 886 LOGW("Warning: VM did not shut down cleanly\n"); 887 888bail: 889 free(slashClassName); 890} 891 892void AndroidRuntime::start() 893{ 894 start("com.android.internal.os.RuntimeInit", 895 false /* Don't start the system server */); 896} 897 898void AndroidRuntime::onExit(int code) 899{ 900 LOGI("AndroidRuntime onExit calling exit(%d)", code); 901 exit(code); 902} 903 904/* 905 * Get the JNIEnv pointer for this thread. 906 * 907 * Returns NULL if the slot wasn't allocated or populated. 908 */ 909/*static*/ JNIEnv* AndroidRuntime::getJNIEnv() 910{ 911 JNIEnv* env; 912 JavaVM* vm = AndroidRuntime::getJavaVM(); 913 assert(vm != NULL); 914 915 if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) 916 return NULL; 917 return env; 918} 919 920/* 921 * Makes the current thread visible to the VM. 922 * 923 * The JNIEnv pointer returned is only valid for the current thread, and 924 * thus must be tucked into thread-local storage. 925 */ 926static int javaAttachThread(const char* threadName, JNIEnv** pEnv) 927{ 928 JavaVMAttachArgs args; 929 JavaVM* vm; 930 jint result; 931 932 vm = AndroidRuntime::getJavaVM(); 933 assert(vm != NULL); 934 935 args.version = JNI_VERSION_1_4; 936 args.name = (char*) threadName; 937 args.group = NULL; 938 939 result = vm->AttachCurrentThread(pEnv, (void*) &args); 940 if (result != JNI_OK) 941 LOGE("ERROR: thread attach failed\n"); 942 943 return result; 944} 945 946/* 947 * Detach the current thread from the set visible to the VM. 948 */ 949static int javaDetachThread(void) 950{ 951 JavaVM* vm; 952 jint result; 953 954 vm = AndroidRuntime::getJavaVM(); 955 assert(vm != NULL); 956 957 result = vm->DetachCurrentThread(); 958 if (result != JNI_OK) 959 LOGE("ERROR: thread detach failed\n"); 960 return result; 961} 962 963/* 964 * When starting a native thread that will be visible from the VM, we 965 * bounce through this to get the right attach/detach action. 966 * Note that this function calls free(args) 967 */ 968/*static*/ int AndroidRuntime::javaThreadShell(void* args) { 969 void* start = ((void**)args)[0]; 970 void* userData = ((void **)args)[1]; 971 char* name = (char*) ((void **)args)[2]; // we own this storage 972 free(args); 973 JNIEnv* env; 974 int result; 975 976 /* hook us into the VM */ 977 if (javaAttachThread(name, &env) != JNI_OK) 978 return -1; 979 980 /* start the thread running */ 981 result = (*(android_thread_func_t)start)(userData); 982 983 /* unhook us */ 984 javaDetachThread(); 985 free(name); 986 987 return result; 988} 989 990/* 991 * This is invoked from androidCreateThreadEtc() via the callback 992 * set with androidSetCreateThreadFunc(). 993 * 994 * We need to create the new thread in such a way that it gets hooked 995 * into the VM before it really starts executing. 996 */ 997/*static*/ int AndroidRuntime::javaCreateThreadEtc( 998 android_thread_func_t entryFunction, 999 void* userData, 1000 const char* threadName, 1001 int32_t threadPriority, 1002 size_t threadStackSize, 1003 android_thread_id_t* threadId) 1004{ 1005 void** args = (void**) malloc(3 * sizeof(void*)); // javaThreadShell must free 1006 int result; 1007 1008 assert(threadName != NULL); 1009 1010 args[0] = (void*) entryFunction; 1011 args[1] = userData; 1012 args[2] = (void*) strdup(threadName); // javaThreadShell must free 1013 1014 result = androidCreateRawThreadEtc(AndroidRuntime::javaThreadShell, args, 1015 threadName, threadPriority, threadStackSize, threadId); 1016 return result; 1017} 1018 1019/* 1020 * Create a thread that is visible from the VM. 1021 * 1022 * This is called from elsewhere in the library. 1023 */ 1024/*static*/ void AndroidRuntime::createJavaThread(const char* name, 1025 void (*start)(void *), void* arg) 1026{ 1027 javaCreateThreadEtc((android_thread_func_t) start, arg, name, 1028 ANDROID_PRIORITY_DEFAULT, 0, NULL); 1029} 1030 1031#if 0 1032static void quickTest(void* arg) 1033{ 1034 const char* str = (const char*) arg; 1035 1036 printf("In quickTest: %s\n", str); 1037} 1038#endif 1039 1040#ifdef NDEBUG 1041 #define REG_JNI(name) { name } 1042 struct RegJNIRec { 1043 int (*mProc)(JNIEnv*); 1044 }; 1045#else 1046 #define REG_JNI(name) { name, #name } 1047 struct RegJNIRec { 1048 int (*mProc)(JNIEnv*); 1049 const char* mName; 1050 }; 1051#endif 1052 1053typedef void (*RegJAMProc)(); 1054 1055static int register_jni_procs(const RegJNIRec array[], size_t count, JNIEnv* env) 1056{ 1057 for (size_t i = 0; i < count; i++) { 1058 if (array[i].mProc(env) < 0) { 1059#ifndef NDEBUG 1060 LOGD("----------!!! %s failed to load\n", array[i].mName); 1061#endif 1062 return -1; 1063 } 1064 } 1065 return 0; 1066} 1067 1068static void register_jam_procs(const RegJAMProc array[], size_t count) 1069{ 1070 for (size_t i = 0; i < count; i++) { 1071 array[i](); 1072 } 1073} 1074 1075static const RegJNIRec gRegJNI[] = { 1076 REG_JNI(register_android_debug_JNITest), 1077 REG_JNI(register_com_android_internal_os_RuntimeInit), 1078 REG_JNI(register_android_os_SystemClock), 1079 REG_JNI(register_android_util_EventLog), 1080 REG_JNI(register_android_util_Log), 1081 REG_JNI(register_android_util_FloatMath), 1082 REG_JNI(register_android_text_format_Time), 1083 REG_JNI(register_android_pim_EventRecurrence), 1084 REG_JNI(register_android_content_AssetManager), 1085 REG_JNI(register_android_content_StringBlock), 1086 REG_JNI(register_android_content_XmlBlock), 1087 REG_JNI(register_android_emoji_EmojiFactory), 1088 REG_JNI(register_android_security_Md5MessageDigest), 1089 REG_JNI(register_android_text_AndroidCharacter), 1090 REG_JNI(register_android_text_KeyCharacterMap), 1091 REG_JNI(register_android_os_Process), 1092 REG_JNI(register_android_os_Binder), 1093 REG_JNI(register_android_os_Hardware), 1094 REG_JNI(register_android_view_Display), 1095 REG_JNI(register_android_nio_utils), 1096 REG_JNI(register_android_graphics_PixelFormat), 1097 REG_JNI(register_android_graphics_Graphics), 1098 REG_JNI(register_android_view_Surface), 1099 REG_JNI(register_android_view_ViewRoot), 1100 REG_JNI(register_com_google_android_gles_jni_EGLImpl), 1101 REG_JNI(register_com_google_android_gles_jni_GLImpl), 1102 REG_JNI(register_android_opengl_jni_GLES10), 1103 REG_JNI(register_android_opengl_jni_GLES10Ext), 1104 REG_JNI(register_android_opengl_jni_GLES11), 1105 REG_JNI(register_android_opengl_jni_GLES11Ext), 1106 1107 REG_JNI(register_android_graphics_Bitmap), 1108 REG_JNI(register_android_graphics_BitmapFactory), 1109 REG_JNI(register_android_graphics_Camera), 1110 REG_JNI(register_android_graphics_Canvas), 1111 REG_JNI(register_android_graphics_ColorFilter), 1112 REG_JNI(register_android_graphics_DrawFilter), 1113 REG_JNI(register_android_graphics_Interpolator), 1114 REG_JNI(register_android_graphics_LayerRasterizer), 1115 REG_JNI(register_android_graphics_MaskFilter), 1116 REG_JNI(register_android_graphics_Matrix), 1117 REG_JNI(register_android_graphics_Movie), 1118 REG_JNI(register_android_graphics_NinePatch), 1119 REG_JNI(register_android_graphics_Paint), 1120 REG_JNI(register_android_graphics_Path), 1121 REG_JNI(register_android_graphics_PathMeasure), 1122 REG_JNI(register_android_graphics_PathEffect), 1123 REG_JNI(register_android_graphics_Picture), 1124 REG_JNI(register_android_graphics_PorterDuff), 1125 REG_JNI(register_android_graphics_Rasterizer), 1126 REG_JNI(register_android_graphics_Region), 1127 REG_JNI(register_android_graphics_Shader), 1128 REG_JNI(register_android_graphics_Typeface), 1129 REG_JNI(register_android_graphics_Xfermode), 1130 REG_JNI(register_com_android_internal_graphics_NativeUtils), 1131 1132 REG_JNI(register_android_database_CursorWindow), 1133 REG_JNI(register_android_database_SQLiteDatabase), 1134 REG_JNI(register_android_database_SQLiteDebug), 1135 REG_JNI(register_android_database_SQLiteProgram), 1136 REG_JNI(register_android_database_SQLiteQuery), 1137 REG_JNI(register_android_database_SQLiteStatement), 1138 REG_JNI(register_android_os_Debug), 1139 REG_JNI(register_android_os_FileObserver), 1140 REG_JNI(register_android_os_FileUtils), 1141 REG_JNI(register_android_os_ParcelFileDescriptor), 1142 REG_JNI(register_android_os_Power), 1143 REG_JNI(register_android_os_StatFs), 1144 REG_JNI(register_android_os_SystemProperties), 1145 REG_JNI(register_android_os_UEventObserver), 1146 REG_JNI(register_android_net_LocalSocketImpl), 1147 REG_JNI(register_android_net_NetworkUtils), 1148 REG_JNI(register_android_net_wifi_WifiManager), 1149 REG_JNI(register_android_os_MemoryFile), 1150 REG_JNI(register_com_android_internal_os_ZygoteInit), 1151 REG_JNI(register_android_hardware_Camera), 1152 REG_JNI(register_android_hardware_SensorManager), 1153 REG_JNI(register_android_media_AudioRecord), 1154 REG_JNI(register_android_media_AudioSystem), 1155 REG_JNI(register_android_media_AudioTrack), 1156 REG_JNI(register_android_media_JetPlayer), 1157 REG_JNI(register_android_media_ToneGenerator), 1158 1159 REG_JNI(register_android_opengl_classes), 1160 REG_JNI(register_android_bluetooth_HeadsetBase), 1161 REG_JNI(register_android_bluetooth_BluetoothAudioGateway), 1162 REG_JNI(register_android_bluetooth_BluetoothSocket), 1163 REG_JNI(register_android_bluetooth_ScoSocket), 1164 REG_JNI(register_android_server_BluetoothDeviceService), 1165 REG_JNI(register_android_server_BluetoothEventLoop), 1166 REG_JNI(register_android_server_BluetoothA2dpService), 1167 REG_JNI(register_android_message_digest_sha1), 1168 REG_JNI(register_android_ddm_DdmHandleNativeHeap), 1169 REG_JNI(register_android_util_Base64), 1170 REG_JNI(register_android_location_GpsLocationProvider), 1171 REG_JNI(register_android_backup_BackupDataOutput), 1172 REG_JNI(register_android_backup_FileBackupHelper), 1173}; 1174 1175/* 1176 * Register android native functions with the VM. 1177 */ 1178/*static*/ int AndroidRuntime::startReg(JNIEnv* env) 1179{ 1180 /* 1181 * This hook causes all future threads created in this process to be 1182 * attached to the JavaVM. (This needs to go away in favor of JNI 1183 * Attach calls.) 1184 */ 1185 androidSetCreateThreadFunc((android_create_thread_fn) javaCreateThreadEtc); 1186 1187 LOGD("--- registering native functions ---\n"); 1188 1189 /* 1190 * Every "register" function calls one or more things that return 1191 * a local reference (e.g. FindClass). Because we haven't really 1192 * started the VM yet, they're all getting stored in the base frame 1193 * and never released. Use Push/Pop to manage the storage. 1194 */ 1195 env->PushLocalFrame(200); 1196 1197 if (register_jni_procs(gRegJNI, NELEM(gRegJNI), env) < 0) { 1198 env->PopLocalFrame(NULL); 1199 return -1; 1200 } 1201 env->PopLocalFrame(NULL); 1202 1203 //createJavaThread("fubar", quickTest, (void*) "hello"); 1204 1205 return 0; 1206} 1207 1208AndroidRuntime* AndroidRuntime::getRuntime() 1209{ 1210 return gCurRuntime; 1211} 1212 1213/** 1214 * Used by WithFramework to register native functions. 1215 */ 1216extern "C" 1217jint Java_com_android_internal_util_WithFramework_registerNatives( 1218 JNIEnv* env, jclass clazz) { 1219 return register_jni_procs(gRegJNI, NELEM(gRegJNI), env); 1220} 1221 1222/** 1223 * Used by LoadClass to register native functions. 1224 */ 1225extern "C" 1226jint Java_LoadClass_registerNatives(JNIEnv* env, jclass clazz) { 1227 return register_jni_procs(gRegJNI, NELEM(gRegJNI), env); 1228} 1229 1230} // namespace android 1231