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