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