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