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