1 /* //device/libs/android_runtime/AndroidRuntime.cpp
3 ** Copyright 2006, The Android Open Source Project
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
9 ** http://www.apache.org/licenses/LICENSE-2.0
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.
18 #define LOG_TAG "AndroidRuntime"
19 //#define LOG_NDEBUG 0
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>
31 #include <SkGraphics.h>
32 #include <SkImageDecoder.h>
33 #include <SkImageRef_GlobalPool.h>
37 #include "android_util_Binder.h"
42 #include <sys/types.h>
48 using namespace android;
50 extern void register_BindTest();
52 extern int register_android_os_Binder(JNIEnv* env);
53 extern int register_android_os_Process(JNIEnv* env);
54 extern int register_android_graphics_Bitmap(JNIEnv*);
55 extern int register_android_graphics_BitmapFactory(JNIEnv*);
56 extern int register_android_graphics_BitmapRegionDecoder(JNIEnv*);
57 extern int register_android_graphics_Camera(JNIEnv* env);
58 extern int register_android_graphics_Graphics(JNIEnv* env);
59 extern int register_android_graphics_Interpolator(JNIEnv* env);
60 extern int register_android_graphics_LayerRasterizer(JNIEnv*);
61 extern int register_android_graphics_MaskFilter(JNIEnv* env);
62 extern int register_android_graphics_Movie(JNIEnv* env);
63 extern int register_android_graphics_NinePatch(JNIEnv*);
64 extern int register_android_graphics_PathEffect(JNIEnv* env);
65 extern int register_android_graphics_Region(JNIEnv* env);
66 extern int register_android_graphics_Shader(JNIEnv* env);
67 extern int register_android_graphics_Typeface(JNIEnv* env);
68 extern int register_android_graphics_YuvImage(JNIEnv* env);
70 extern int register_com_google_android_gles_jni_EGLImpl(JNIEnv* env);
71 extern int register_com_google_android_gles_jni_GLImpl(JNIEnv* env);
72 extern int register_android_opengl_jni_GLES10(JNIEnv* env);
73 extern int register_android_opengl_jni_GLES10Ext(JNIEnv* env);
74 extern int register_android_opengl_jni_GLES11(JNIEnv* env);
75 extern int register_android_opengl_jni_GLES11Ext(JNIEnv* env);
76 extern int register_android_opengl_jni_GLES20(JNIEnv* env);
78 extern int register_android_hardware_Camera(JNIEnv *env);
80 extern int register_android_hardware_SensorManager(JNIEnv *env);
82 extern int register_android_media_AudioRecord(JNIEnv *env);
83 extern int register_android_media_AudioSystem(JNIEnv *env);
84 extern int register_android_media_AudioTrack(JNIEnv *env);
85 extern int register_android_media_JetPlayer(JNIEnv *env);
86 extern int register_android_media_ToneGenerator(JNIEnv *env);
88 extern int register_android_message_digest_sha1(JNIEnv *env);
90 extern int register_android_util_FloatMath(JNIEnv* env);
95 * JNI-based registration functions. Note these are properly contained in
98 extern int register_android_content_AssetManager(JNIEnv* env);
99 extern int register_android_util_EventLog(JNIEnv* env);
100 extern int register_android_util_Log(JNIEnv* env);
101 extern int register_android_content_StringBlock(JNIEnv* env);
102 extern int register_android_content_XmlBlock(JNIEnv* env);
103 extern int register_android_emoji_EmojiFactory(JNIEnv* env);
104 extern int register_android_graphics_Canvas(JNIEnv* env);
105 extern int register_android_graphics_ColorFilter(JNIEnv* env);
106 extern int register_android_graphics_DrawFilter(JNIEnv* env);
107 extern int register_android_graphics_Matrix(JNIEnv* env);
108 extern int register_android_graphics_Paint(JNIEnv* env);
109 extern int register_android_graphics_Path(JNIEnv* env);
110 extern int register_android_graphics_PathMeasure(JNIEnv* env);
111 extern int register_android_graphics_Picture(JNIEnv*);
112 extern int register_android_graphics_PorterDuff(JNIEnv* env);
113 extern int register_android_graphics_Rasterizer(JNIEnv* env);
114 extern int register_android_graphics_Xfermode(JNIEnv* env);
115 extern int register_android_graphics_PixelFormat(JNIEnv* env);
116 extern int register_com_android_internal_graphics_NativeUtils(JNIEnv *env);
117 extern int register_android_view_Display(JNIEnv* env);
118 extern int register_android_view_Surface(JNIEnv* env);
119 extern int register_android_view_ViewRoot(JNIEnv* env);
120 extern int register_android_database_CursorWindow(JNIEnv* env);
121 extern int register_android_database_SQLiteCompiledSql(JNIEnv* env);
122 extern int register_android_database_SQLiteDatabase(JNIEnv* env);
123 extern int register_android_database_SQLiteDebug(JNIEnv* env);
124 extern int register_android_database_SQLiteProgram(JNIEnv* env);
125 extern int register_android_database_SQLiteQuery(JNIEnv* env);
126 extern int register_android_database_SQLiteStatement(JNIEnv* env);
127 extern int register_android_debug_JNITest(JNIEnv* env);
128 extern int register_android_nio_utils(JNIEnv* env);
129 extern int register_android_nfc_NdefMessage(JNIEnv *env);
130 extern int register_android_nfc_NdefRecord(JNIEnv *env);
131 extern int register_android_pim_EventRecurrence(JNIEnv* env);
132 extern int register_android_text_format_Time(JNIEnv* env);
133 extern int register_android_os_Debug(JNIEnv* env);
134 extern int register_android_os_MessageQueue(JNIEnv* env);
135 extern int register_android_os_ParcelFileDescriptor(JNIEnv *env);
136 extern int register_android_os_Power(JNIEnv *env);
137 extern int register_android_os_StatFs(JNIEnv *env);
138 extern int register_android_os_SystemProperties(JNIEnv *env);
139 extern int register_android_os_SystemClock(JNIEnv* env);
140 extern int register_android_os_FileObserver(JNIEnv *env);
141 extern int register_android_os_FileUtils(JNIEnv *env);
142 extern int register_android_os_UEventObserver(JNIEnv* env);
143 extern int register_android_os_MemoryFile(JNIEnv* env);
144 extern int register_android_net_LocalSocketImpl(JNIEnv* env);
145 extern int register_android_net_NetworkUtils(JNIEnv* env);
146 extern int register_android_net_TrafficStats(JNIEnv* env);
147 extern int register_android_net_wifi_WifiManager(JNIEnv* env);
148 extern int register_android_security_Md5MessageDigest(JNIEnv *env);
149 extern int register_android_text_AndroidCharacter(JNIEnv *env);
150 extern int register_android_text_AndroidBidi(JNIEnv *env);
151 extern int register_android_text_KeyCharacterMap(JNIEnv *env);
152 extern int register_android_opengl_classes(JNIEnv *env);
153 extern int register_android_bluetooth_HeadsetBase(JNIEnv* env);
154 extern int register_android_bluetooth_BluetoothAudioGateway(JNIEnv* env);
155 extern int register_android_bluetooth_BluetoothSocket(JNIEnv *env);
156 extern int register_android_bluetooth_ScoSocket(JNIEnv *env);
157 extern int register_android_server_BluetoothService(JNIEnv* env);
158 extern int register_android_server_BluetoothEventLoop(JNIEnv *env);
159 extern int register_android_server_BluetoothA2dpService(JNIEnv* env);
160 extern int register_android_server_Watchdog(JNIEnv* env);
161 extern int register_android_ddm_DdmHandleNativeHeap(JNIEnv *env);
162 extern int register_com_android_internal_os_ZygoteInit(JNIEnv* env);
163 extern int register_android_backup_BackupDataInput(JNIEnv *env);
164 extern int register_android_backup_BackupDataOutput(JNIEnv *env);
165 extern int register_android_backup_FileBackupHelperBase(JNIEnv *env);
166 extern int register_android_backup_BackupHelperDispatcher(JNIEnv *env);
167 extern int register_android_app_NativeActivity(JNIEnv *env);
168 extern int register_android_view_InputChannel(JNIEnv* env);
169 extern int register_android_view_InputQueue(JNIEnv* env);
170 extern int register_android_view_KeyEvent(JNIEnv* env);
171 extern int register_android_view_MotionEvent(JNIEnv* env);
172 extern int register_android_content_res_ObbScanner(JNIEnv* env);
173 extern int register_android_content_res_Configuration(JNIEnv* env);
175 static AndroidRuntime* gCurRuntime = NULL;
177 static void doThrow(JNIEnv* env, const char* exc, const char* msg = NULL)
179 if (jniThrowException(env, exc, msg) != 0)
184 * Code written in the Java Programming Language calls here from main().
186 static void com_android_internal_os_RuntimeInit_finishInit(JNIEnv* env, jobject clazz)
188 gCurRuntime->onStarted();
191 static void com_android_internal_os_RuntimeInit_zygoteInit(JNIEnv* env, jobject clazz)
193 gCurRuntime->onZygoteInit();
196 static jint com_android_internal_os_RuntimeInit_isComputerOn(JNIEnv* env, jobject clazz)
201 static void com_android_internal_os_RuntimeInit_turnComputerOn(JNIEnv* env, jobject clazz)
205 static jint com_android_internal_os_RuntimeInit_getQwertyKeyboard(JNIEnv* env, jobject clazz)
207 char* value = getenv("qwerty");
208 if (value != NULL && strcmp(value, "true") == 0) {
218 static JNINativeMethod gMethods[] = {
219 { "finishInit", "()V",
220 (void*) com_android_internal_os_RuntimeInit_finishInit },
221 { "zygoteInitNative", "()V",
222 (void*) com_android_internal_os_RuntimeInit_zygoteInit },
223 { "isComputerOn", "()I",
224 (void*) com_android_internal_os_RuntimeInit_isComputerOn },
225 { "turnComputerOn", "()V",
226 (void*) com_android_internal_os_RuntimeInit_turnComputerOn },
227 { "getQwertyKeyboard", "()I",
228 (void*) com_android_internal_os_RuntimeInit_getQwertyKeyboard },
231 int register_com_android_internal_os_RuntimeInit(JNIEnv* env)
233 return jniRegisterNativeMethods(env, "com/android/internal/os/RuntimeInit",
234 gMethods, NELEM(gMethods));
237 // ----------------------------------------------------------------------
239 /*static*/ JavaVM* AndroidRuntime::mJavaVM = NULL;
242 AndroidRuntime::AndroidRuntime()
245 // this sets our preference for 16bit images during decode
246 // in case the src is opaque and 24bit
247 SkImageDecoder::SetDeviceConfig(SkBitmap::kRGB_565_Config);
248 // This cache is shared between browser native images, and java "purgeable"
249 // bitmaps. This globalpool is for images that do not either use the java
250 // heap, or are not backed by ashmem. See BitmapFactory.cpp for the key
252 SkImageRef_GlobalPool::SetRAMBudget(512 * 1024);
253 // There is also a global font cache, but its budget is specified in code
254 // see SkFontHost_android.cpp
256 // Pre-allocate enough space to hold a fair number of options.
257 mOptions.setCapacity(20);
259 assert(gCurRuntime == NULL); // one per process
263 AndroidRuntime::~AndroidRuntime()
269 * Register native methods using JNI.
271 /*static*/ int AndroidRuntime::registerNativeMethods(JNIEnv* env,
272 const char* className, const JNINativeMethod* gMethods, int numMethods)
274 return jniRegisterNativeMethods(env, className, gMethods, numMethods);
278 * Call a static Java Programming Language function that takes no arguments and returns void.
280 status_t AndroidRuntime::callStatic(const char* className, const char* methodName)
288 return UNKNOWN_ERROR;
290 clazz = findClass(env, className);
292 LOGE("ERROR: could not find class '%s'\n", className);
293 return UNKNOWN_ERROR;
295 methodId = env->GetStaticMethodID(clazz, methodName, "()V");
296 if (methodId == NULL) {
297 LOGE("ERROR: could not find method %s.%s\n", className, methodName);
298 return UNKNOWN_ERROR;
301 env->CallStaticVoidMethod(clazz, methodId);
306 status_t AndroidRuntime::callMain(
307 const char* className, int argc, const char* const argv[])
313 LOGD("Calling main entry %s", className);
317 return UNKNOWN_ERROR;
319 clazz = findClass(env, className);
321 LOGE("ERROR: could not find class '%s'\n", className);
322 return UNKNOWN_ERROR;
325 methodId = env->GetStaticMethodID(clazz, "main", "([Ljava/lang/String;)V");
326 if (methodId == NULL) {
327 LOGE("ERROR: could not find method %s.main(String[])\n", className);
328 return UNKNOWN_ERROR;
332 * We want to call main() with a String array with our arguments in it.
333 * Create an array and populate it.
336 jobjectArray strArray;
338 stringClass = env->FindClass("java/lang/String");
339 strArray = env->NewObjectArray(argc, stringClass, NULL);
341 for (int i = 0; i < argc; i++) {
342 jstring argStr = env->NewStringUTF(argv[i]);
343 env->SetObjectArrayElement(strArray, i, argStr);
346 env->CallStaticVoidMethod(clazz, methodId, strArray);
351 * Find the named class.
353 jclass AndroidRuntime::findClass(JNIEnv* env, const char* className)
355 char* convName = NULL;
357 if (env->ExceptionCheck()) {
358 LOGE("ERROR: exception pending on entry to findClass()\n");
363 * JNI FindClass uses class names with slashes, but ClassLoader.loadClass
364 * uses the dotted "binary name" format. We don't need to convert the
365 * name with the new approach.
368 /* (convName only created if necessary -- use className) */
369 for (char* cp = const_cast<char*>(className); *cp != '\0'; cp++) {
371 if (convName == NULL) {
372 convName = strdup(className);
373 cp = convName + (cp-className);
374 className = convName;
382 * This is a little awkward because the JNI FindClass call uses the
383 * class loader associated with the native method we're executing in.
384 * Because this native method is part of a "boot" class, JNI doesn't
385 * look for the class in CLASSPATH, which unfortunately is a likely
386 * location for it. (Had we issued the FindClass call before calling
387 * into the VM -- at which point there isn't a native method frame on
388 * the stack -- the VM would have checked CLASSPATH. We have to do
389 * this because we call into Java Programming Language code and
392 * JNI lacks a "find class in a specific class loader" operation, so we
393 * have to do things the hard way.
396 //cls = env->FindClass(className);
398 jclass javaLangClassLoader;
399 jmethodID getSystemClassLoader, loadClass;
400 jobject systemClassLoader;
401 jstring strClassName;
403 /* find the "system" class loader; none of this is expected to fail */
404 javaLangClassLoader = env->FindClass("java/lang/ClassLoader");
405 assert(javaLangClassLoader != NULL);
406 getSystemClassLoader = env->GetStaticMethodID(javaLangClassLoader,
407 "getSystemClassLoader", "()Ljava/lang/ClassLoader;");
408 loadClass = env->GetMethodID(javaLangClassLoader,
409 "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
410 assert(getSystemClassLoader != NULL && loadClass != NULL);
411 systemClassLoader = env->CallStaticObjectMethod(javaLangClassLoader,
412 getSystemClassLoader);
413 assert(systemClassLoader != NULL);
415 /* create an object for the class name string; alloc could fail */
416 strClassName = env->NewStringUTF(className);
417 if (env->ExceptionCheck()) {
418 LOGE("ERROR: unable to convert '%s' to string\n", className);
421 LOGV("system class loader is %p, loading %p (%s)\n",
422 systemClassLoader, strClassName, className);
424 /* try to find the named class */
425 cls = (jclass) env->CallObjectMethod(systemClassLoader, loadClass,
427 if (env->ExceptionCheck()) {
428 LOGE("ERROR: unable to load class '%s' from %p\n",
429 className, systemClassLoader);
440 * The VM calls this through the "exit" hook.
442 static void runtime_exit(int code)
444 gCurRuntime->onExit(code);
449 * The VM calls this through the "vfprintf" hook.
451 * We ignore "fp" and just write the results to the log file.
453 static void runtime_vfprintf(FILE* fp, const char* format, va_list ap)
455 LOG_PRI_VA(ANDROID_LOG_INFO, "vm-printf", format, ap);
460 * Add VM arguments to the to-be-executed VM
461 * Stops at first non '-' argument (also stops at an argument of '--')
462 * Returns the number of args consumed
464 int AndroidRuntime::addVmArguments(int argc, const char* const argv[])
468 for (i = 0; i<argc; i++) {
469 if (argv[i][0] != '-') {
472 if (argv[i][1] == '-' && argv[i][2] == 0) {
477 memset(&opt, 0, sizeof(opt));
478 opt.optionString = (char*)argv[i];
484 static int hasDir(const char* dir)
487 int res = stat(dir, &s);
489 return S_ISDIR(s.st_mode);
495 * We just want failed write() calls to just return with an error.
497 static void blockSigpipe()
502 sigaddset(&mask, SIGPIPE);
503 if (sigprocmask(SIG_BLOCK, &mask, NULL) != 0)
504 LOGW("WARNING: SIGPIPE not blocked\n");
508 * Read the persistent locale.
510 static void readLocale(char* language, char* region)
512 char propLang[PROPERTY_VALUE_MAX], propRegn[PROPERTY_VALUE_MAX];
514 property_get("persist.sys.language", propLang, "");
515 property_get("persist.sys.country", propRegn, "");
516 if (*propLang == 0 && *propRegn == 0) {
517 /* Set to ro properties, default is en_US */
518 property_get("ro.product.locale.language", propLang, "en");
519 property_get("ro.product.locale.region", propRegn, "US");
521 strncat(language, propLang, 2);
522 strncat(region, propRegn, 2);
523 //LOGD("language=%s region=%s\n", language, region);
527 * Parse a property containing space-separated options that should be
528 * passed directly to the VM, e.g. "-Xmx32m -verbose:gc -Xregenmap".
530 * This will cut up "extraOptsBuf" as we chop it into individual options.
532 * Adds the strings, if any, to mOptions.
534 void AndroidRuntime::parseExtraOpts(char* extraOptsBuf)
540 memset(&opt, 0, sizeof(opt));
541 start = extraOptsBuf;
542 while (*start != '\0') {
543 while (*start == ' ') /* skip leading whitespace */
545 if (*start == '\0') /* was trailing ws, bail */
549 while (*end != ' ' && *end != '\0') /* find end of token */
552 *end++ = '\0'; /* mark end, advance to indicate more */
554 opt.optionString = start;
561 * Start the Dalvik Virtual Machine.
563 * Various arguments, most determined by system properties, are passed in.
564 * The "mOptions" vector is updated.
566 * Returns 0 on success.
568 int AndroidRuntime::startVm(JavaVM** pJavaVM, JNIEnv** pEnv)
571 JavaVMInitArgs initArgs;
573 char propBuf[PROPERTY_VALUE_MAX];
574 char stackTraceFileBuf[PROPERTY_VALUE_MAX];
575 char dexoptFlagsBuf[PROPERTY_VALUE_MAX];
576 char enableAssertBuf[sizeof("-ea:")-1 + PROPERTY_VALUE_MAX];
577 char jniOptsBuf[sizeof("-Xjniopts:")-1 + PROPERTY_VALUE_MAX];
578 char heapsizeOptsBuf[sizeof("-Xmx")-1 + PROPERTY_VALUE_MAX];
579 char extraOptsBuf[PROPERTY_VALUE_MAX];
580 char* stackTraceFile = NULL;
581 bool checkJni = false;
582 bool checkDexSum = false;
583 bool logStdio = false;
588 #if defined(WITH_JIT)
591 } executionMode = kEMDefault;
594 property_get("dalvik.vm.checkjni", propBuf, "");
595 if (strcmp(propBuf, "true") == 0) {
597 } else if (strcmp(propBuf, "false") != 0) {
598 /* property is neither true nor false; fall back on kernel parameter */
599 property_get("ro.kernel.android.checkjni", propBuf, "");
600 if (propBuf[0] == '1') {
605 property_get("dalvik.vm.execution-mode", propBuf, "");
606 if (strcmp(propBuf, "int:portable") == 0) {
607 executionMode = kEMIntPortable;
608 } else if (strcmp(propBuf, "int:fast") == 0) {
609 executionMode = kEMIntFast;
610 #if defined(WITH_JIT)
611 } else if (strcmp(propBuf, "int:jit") == 0) {
612 executionMode = kEMJitCompiler;
616 property_get("dalvik.vm.stack-trace-file", stackTraceFileBuf, "");
618 property_get("dalvik.vm.check-dex-sum", propBuf, "");
619 if (strcmp(propBuf, "true") == 0) {
623 property_get("log.redirect-stdio", propBuf, "");
624 if (strcmp(propBuf, "true") == 0) {
628 strcpy(enableAssertBuf, "-ea:");
629 property_get("dalvik.vm.enableassertions", enableAssertBuf+4, "");
631 strcpy(jniOptsBuf, "-Xjniopts:");
632 property_get("dalvik.vm.jniopts", jniOptsBuf+10, "");
634 /* route exit() to our handler */
635 opt.extraInfo = (void*) runtime_exit;
636 opt.optionString = "exit";
639 /* route fprintf() to our handler */
640 opt.extraInfo = (void*) runtime_vfprintf;
641 opt.optionString = "vfprintf";
644 opt.extraInfo = NULL;
646 /* enable verbose; standard options are { jni, gc, class } */
647 //options[curOpt++].optionString = "-verbose:jni";
648 opt.optionString = "-verbose:gc";
650 //options[curOpt++].optionString = "-verbose:class";
652 strcpy(heapsizeOptsBuf, "-Xmx");
653 property_get("dalvik.vm.heapsize", heapsizeOptsBuf+4, "16m");
654 //LOGI("Heap size: %s", heapsizeOptsBuf);
655 opt.optionString = heapsizeOptsBuf;
659 * Enable or disable dexopt features, such as bytecode verification and
660 * calculation of register maps for precise GC.
662 property_get("dalvik.vm.dexopt-flags", dexoptFlagsBuf, "");
663 if (dexoptFlagsBuf[0] != '\0') {
667 opc = strstr(dexoptFlagsBuf, "v="); /* verification */
670 case 'n': val = "-Xverify:none"; break;
671 case 'r': val = "-Xverify:remote"; break;
672 case 'a': val = "-Xverify:all"; break;
673 default: val = NULL; break;
677 opt.optionString = val;
682 opc = strstr(dexoptFlagsBuf, "o="); /* optimization */
685 case 'n': val = "-Xdexopt:none"; break;
686 case 'v': val = "-Xdexopt:verified"; break;
687 case 'a': val = "-Xdexopt:all"; break;
688 default: val = NULL; break;
692 opt.optionString = val;
697 opc = strstr(dexoptFlagsBuf, "m=y"); /* register map */
699 opt.optionString = "-Xgenregmap";
702 /* turn on precise GC while we're at it */
703 opt.optionString = "-Xgc:precise";
708 /* enable debugging; set suspend=y to pause during VM init */
709 #ifdef HAVE_ANDROID_OS
710 /* use android ADB transport */
712 "-agentlib:jdwp=transport=dt_android_adb,suspend=n,server=y";
714 /* use TCP socket; address=0 means start at port 8000 and probe up */
715 LOGI("Using TCP socket for JDWP\n");
717 "-agentlib:jdwp=transport=dt_socket,suspend=n,server=y,address=0";
721 char enableDPBuf[sizeof("-Xdeadlockpredict:") + PROPERTY_VALUE_MAX];
722 property_get("dalvik.vm.deadlock-predict", propBuf, "");
723 if (strlen(propBuf) > 0) {
724 strcpy(enableDPBuf, "-Xdeadlockpredict:");
725 strcat(enableDPBuf, propBuf);
726 opt.optionString = enableDPBuf;
730 LOGD("CheckJNI is %s\n", checkJni ? "ON" : "OFF");
732 /* extended JNI checking */
733 opt.optionString = "-Xcheck:jni";
736 /* set a cap on JNI global references */
737 opt.optionString = "-Xjnigreflimit:2000";
740 /* with -Xcheck:jni, this provides a JNI function call trace */
741 //opt.optionString = "-verbose:jni";
745 char lockProfThresholdBuf[sizeof("-Xlockprofthreshold:") + sizeof(propBuf)];
746 property_get("dalvik.vm.lockprof.threshold", propBuf, "");
747 if (strlen(propBuf) > 0) {
748 strcpy(lockProfThresholdBuf, "-Xlockprofthreshold:");
749 strcat(lockProfThresholdBuf, propBuf);
750 opt.optionString = lockProfThresholdBuf;
754 #if defined(WITH_JIT)
755 /* Force interpreter-only mode for selected opcodes. Eg "1-0a,3c,f1-ff" */
756 char jitOpBuf[sizeof("-Xjitop:") + PROPERTY_VALUE_MAX];
757 property_get("dalvik.vm.jit.op", propBuf, "");
758 if (strlen(propBuf) > 0) {
759 strcpy(jitOpBuf, "-Xjitop:");
760 strcat(jitOpBuf, propBuf);
761 opt.optionString = jitOpBuf;
765 /* Force interpreter-only mode for selected methods */
766 char jitMethodBuf[sizeof("-Xjitmethod:") + PROPERTY_VALUE_MAX];
767 property_get("dalvik.vm.jit.method", propBuf, "");
768 if (strlen(propBuf) > 0) {
769 strcpy(jitMethodBuf, "-Xjitmethod:");
770 strcat(jitMethodBuf, propBuf);
771 opt.optionString = jitMethodBuf;
776 if (executionMode == kEMIntPortable) {
777 opt.optionString = "-Xint:portable";
779 } else if (executionMode == kEMIntFast) {
780 opt.optionString = "-Xint:fast";
782 #if defined(WITH_JIT)
783 } else if (executionMode == kEMJitCompiler) {
784 opt.optionString = "-Xint:jit";
790 /* perform additional DEX checksum tests */
791 opt.optionString = "-Xcheckdexsum";
796 /* convert stdout/stderr to log messages */
797 opt.optionString = "-Xlog-stdio";
801 if (enableAssertBuf[4] != '\0') {
802 /* accept "all" to mean "all classes and packages" */
803 if (strcmp(enableAssertBuf+4, "all") == 0)
804 enableAssertBuf[3] = '\0';
805 LOGI("Assertions enabled: '%s'\n", enableAssertBuf);
806 opt.optionString = enableAssertBuf;
809 LOGV("Assertions disabled\n");
812 if (jniOptsBuf[10] != '\0') {
813 LOGI("JNI options: '%s'\n", jniOptsBuf);
814 opt.optionString = jniOptsBuf;
818 if (stackTraceFileBuf[0] != '\0') {
819 static const char* stfOptName = "-Xstacktracefile:";
821 stackTraceFile = (char*) malloc(strlen(stfOptName) +
822 strlen(stackTraceFileBuf) +1);
823 strcpy(stackTraceFile, stfOptName);
824 strcat(stackTraceFile, stackTraceFileBuf);
825 opt.optionString = stackTraceFile;
829 /* extra options; parse this late so it overrides others */
830 property_get("dalvik.vm.extra-opts", extraOptsBuf, "");
831 parseExtraOpts(extraOptsBuf);
833 /* Set the properties for locale */
835 char langOption[sizeof("-Duser.language=") + 3];
836 char regionOption[sizeof("-Duser.region=") + 3];
837 strcpy(langOption, "-Duser.language=");
838 strcpy(regionOption, "-Duser.region=");
839 readLocale(langOption, regionOption);
840 opt.extraInfo = NULL;
841 opt.optionString = langOption;
843 opt.optionString = regionOption;
848 * We don't have /tmp on the device, but we often have an SD card. Apps
849 * shouldn't use this, but some test suites might want to exercise it.
851 opt.optionString = "-Djava.io.tmpdir=/sdcard";
854 initArgs.version = JNI_VERSION_1_4;
855 initArgs.options = mOptions.editArray();
856 initArgs.nOptions = mOptions.size();
857 initArgs.ignoreUnrecognized = JNI_FALSE;
862 * The JavaVM* is essentially per-process, and the JNIEnv* is per-thread.
863 * If this call succeeds, the VM is ready, and we can start issuing
866 if (JNI_CreateJavaVM(pJavaVM, pEnv, &initArgs) < 0) {
867 LOGE("JNI_CreateJavaVM failed\n");
874 free(stackTraceFile);
879 * Start the Android runtime. This involves starting the virtual machine
880 * and calling the "static void main(String[] args)" method in the class
881 * named by "className".
883 void AndroidRuntime::start(const char* className, const bool startSystemServer)
885 LOGD("\n>>>>>> AndroidRuntime START %s <<<<<<\n",
886 className != NULL ? className : "(unknown)");
888 char* slashClassName = NULL;
895 * 'startSystemServer == true' means runtime is obslete and not run from
896 * init.rc anymore, so we print out the boot start event here.
898 if (startSystemServer) {
899 /* track our progress through the boot sequence */
900 const int LOG_BOOT_PROGRESS_START = 3000;
901 LOG_EVENT_LONG(LOG_BOOT_PROGRESS_START,
902 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
905 const char* rootDir = getenv("ANDROID_ROOT");
906 if (rootDir == NULL) {
908 if (!hasDir("/system")) {
909 LOG_FATAL("No root directory specified, and /android does not exist.");
912 setenv("ANDROID_ROOT", rootDir, 1);
915 //const char* kernelHack = getenv("LD_ASSUME_KERNEL");
916 //LOGD("Found LD_ASSUME_KERNEL='%s'\n", kernelHack);
918 /* start the virtual machine */
919 if (startVm(&mJavaVM, &env) != 0)
923 * Register android functions.
925 if (startReg(env) < 0) {
926 LOGE("Unable to register all android natives\n");
931 * We want to call main() with a String array with arguments in it.
932 * At present we only have one argument, the class name. Create an
936 jobjectArray strArray;
937 jstring classNameStr;
938 jstring startSystemServerStr;
940 stringClass = env->FindClass("java/lang/String");
941 assert(stringClass != NULL);
942 strArray = env->NewObjectArray(2, stringClass, NULL);
943 assert(strArray != NULL);
944 classNameStr = env->NewStringUTF(className);
945 assert(classNameStr != NULL);
946 env->SetObjectArrayElement(strArray, 0, classNameStr);
947 startSystemServerStr = env->NewStringUTF(startSystemServer ?
949 env->SetObjectArrayElement(strArray, 1, startSystemServerStr);
952 * Start VM. This thread becomes the main thread of the VM, and will
953 * not return until the VM exits.
958 slashClassName = strdup(className);
959 for (cp = slashClassName; *cp != '\0'; cp++)
963 startClass = env->FindClass(slashClassName);
964 if (startClass == NULL) {
965 LOGE("JavaVM unable to locate class '%s'\n", slashClassName);
968 startMeth = env->GetStaticMethodID(startClass, "main",
969 "([Ljava/lang/String;)V");
970 if (startMeth == NULL) {
971 LOGE("JavaVM unable to find main() in '%s'\n", className);
974 env->CallStaticVoidMethod(startClass, startMeth, strArray);
977 if (env->ExceptionCheck())
978 threadExitUncaughtException(env);
983 LOGD("Shutting down VM\n");
984 if (mJavaVM->DetachCurrentThread() != JNI_OK)
985 LOGW("Warning: unable to detach main thread\n");
986 if (mJavaVM->DestroyJavaVM() != 0)
987 LOGW("Warning: VM did not shut down cleanly\n");
990 free(slashClassName);
993 void AndroidRuntime::start()
995 start("com.android.internal.os.RuntimeInit",
996 false /* Don't start the system server */);
999 void AndroidRuntime::onExit(int code)
1001 LOGV("AndroidRuntime onExit calling exit(%d)", code);
1006 * Get the JNIEnv pointer for this thread.
1008 * Returns NULL if the slot wasn't allocated or populated.
1010 /*static*/ JNIEnv* AndroidRuntime::getJNIEnv()
1013 JavaVM* vm = AndroidRuntime::getJavaVM();
1016 if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK)
1022 * Makes the current thread visible to the VM.
1024 * The JNIEnv pointer returned is only valid for the current thread, and
1025 * thus must be tucked into thread-local storage.
1027 static int javaAttachThread(const char* threadName, JNIEnv** pEnv)
1029 JavaVMAttachArgs args;
1033 vm = AndroidRuntime::getJavaVM();
1036 args.version = JNI_VERSION_1_4;
1037 args.name = (char*) threadName;
1040 result = vm->AttachCurrentThread(pEnv, (void*) &args);
1041 if (result != JNI_OK)
1042 LOGI("NOTE: attach of thread '%s' failed\n", threadName);
1048 * Detach the current thread from the set visible to the VM.
1050 static int javaDetachThread(void)
1055 vm = AndroidRuntime::getJavaVM();
1058 result = vm->DetachCurrentThread();
1059 if (result != JNI_OK)
1060 LOGE("ERROR: thread detach failed\n");
1065 * When starting a native thread that will be visible from the VM, we
1066 * bounce through this to get the right attach/detach action.
1067 * Note that this function calls free(args)
1069 /*static*/ int AndroidRuntime::javaThreadShell(void* args) {
1070 void* start = ((void**)args)[0];
1071 void* userData = ((void **)args)[1];
1072 char* name = (char*) ((void **)args)[2]; // we own this storage
1077 /* hook us into the VM */
1078 if (javaAttachThread(name, &env) != JNI_OK)
1081 /* start the thread running */
1082 result = (*(android_thread_func_t)start)(userData);
1092 * This is invoked from androidCreateThreadEtc() via the callback
1093 * set with androidSetCreateThreadFunc().
1095 * We need to create the new thread in such a way that it gets hooked
1096 * into the VM before it really starts executing.
1098 /*static*/ int AndroidRuntime::javaCreateThreadEtc(
1099 android_thread_func_t entryFunction,
1101 const char* threadName,
1102 int32_t threadPriority,
1103 size_t threadStackSize,
1104 android_thread_id_t* threadId)
1106 void** args = (void**) malloc(3 * sizeof(void*)); // javaThreadShell must free
1109 assert(threadName != NULL);
1111 args[0] = (void*) entryFunction;
1113 args[2] = (void*) strdup(threadName); // javaThreadShell must free
1115 result = androidCreateRawThreadEtc(AndroidRuntime::javaThreadShell, args,
1116 threadName, threadPriority, threadStackSize, threadId);
1121 * Create a thread that is visible from the VM.
1123 * This is called from elsewhere in the library.
1125 /*static*/ android_thread_id_t AndroidRuntime::createJavaThread(const char* name,
1126 void (*start)(void *), void* arg)
1128 android_thread_id_t threadId = 0;
1129 javaCreateThreadEtc((android_thread_func_t) start, arg, name,
1130 ANDROID_PRIORITY_DEFAULT, 0, &threadId);
1135 static void quickTest(void* arg)
1137 const char* str = (const char*) arg;
1139 printf("In quickTest: %s\n", str);
1144 #define REG_JNI(name) { name }
1146 int (*mProc)(JNIEnv*);
1149 #define REG_JNI(name) { name, #name }
1151 int (*mProc)(JNIEnv*);
1156 typedef void (*RegJAMProc)();
1158 static int register_jni_procs(const RegJNIRec array[], size_t count, JNIEnv* env)
1160 for (size_t i = 0; i < count; i++) {
1161 if (array[i].mProc(env) < 0) {
1163 LOGD("----------!!! %s failed to load\n", array[i].mName);
1171 static void register_jam_procs(const RegJAMProc array[], size_t count)
1173 for (size_t i = 0; i < count; i++) {
1178 static const RegJNIRec gRegJNI[] = {
1179 REG_JNI(register_android_debug_JNITest),
1180 REG_JNI(register_com_android_internal_os_RuntimeInit),
1181 REG_JNI(register_android_os_SystemClock),
1182 REG_JNI(register_android_util_EventLog),
1183 REG_JNI(register_android_util_Log),
1184 REG_JNI(register_android_util_FloatMath),
1185 REG_JNI(register_android_text_format_Time),
1186 REG_JNI(register_android_pim_EventRecurrence),
1187 REG_JNI(register_android_content_AssetManager),
1188 REG_JNI(register_android_content_StringBlock),
1189 REG_JNI(register_android_content_XmlBlock),
1190 REG_JNI(register_android_emoji_EmojiFactory),
1191 REG_JNI(register_android_security_Md5MessageDigest),
1192 REG_JNI(register_android_text_AndroidCharacter),
1193 REG_JNI(register_android_text_AndroidBidi),
1194 REG_JNI(register_android_text_KeyCharacterMap),
1195 REG_JNI(register_android_os_Process),
1196 REG_JNI(register_android_os_Binder),
1197 REG_JNI(register_android_view_Display),
1198 REG_JNI(register_android_nio_utils),
1199 REG_JNI(register_android_graphics_PixelFormat),
1200 REG_JNI(register_android_graphics_Graphics),
1201 REG_JNI(register_android_view_Surface),
1202 REG_JNI(register_android_view_ViewRoot),
1203 REG_JNI(register_com_google_android_gles_jni_EGLImpl),
1204 REG_JNI(register_com_google_android_gles_jni_GLImpl),
1205 REG_JNI(register_android_opengl_jni_GLES10),
1206 REG_JNI(register_android_opengl_jni_GLES10Ext),
1207 REG_JNI(register_android_opengl_jni_GLES11),
1208 REG_JNI(register_android_opengl_jni_GLES11Ext),
1209 REG_JNI(register_android_opengl_jni_GLES20),
1211 REG_JNI(register_android_graphics_Bitmap),
1212 REG_JNI(register_android_graphics_BitmapFactory),
1213 REG_JNI(register_android_graphics_BitmapRegionDecoder),
1214 REG_JNI(register_android_graphics_Camera),
1215 REG_JNI(register_android_graphics_Canvas),
1216 REG_JNI(register_android_graphics_ColorFilter),
1217 REG_JNI(register_android_graphics_DrawFilter),
1218 REG_JNI(register_android_graphics_Interpolator),
1219 REG_JNI(register_android_graphics_LayerRasterizer),
1220 REG_JNI(register_android_graphics_MaskFilter),
1221 REG_JNI(register_android_graphics_Matrix),
1222 REG_JNI(register_android_graphics_Movie),
1223 REG_JNI(register_android_graphics_NinePatch),
1224 REG_JNI(register_android_graphics_Paint),
1225 REG_JNI(register_android_graphics_Path),
1226 REG_JNI(register_android_graphics_PathMeasure),
1227 REG_JNI(register_android_graphics_PathEffect),
1228 REG_JNI(register_android_graphics_Picture),
1229 REG_JNI(register_android_graphics_PorterDuff),
1230 REG_JNI(register_android_graphics_Rasterizer),
1231 REG_JNI(register_android_graphics_Region),
1232 REG_JNI(register_android_graphics_Shader),
1233 REG_JNI(register_android_graphics_Typeface),
1234 REG_JNI(register_android_graphics_Xfermode),
1235 REG_JNI(register_android_graphics_YuvImage),
1236 REG_JNI(register_com_android_internal_graphics_NativeUtils),
1238 REG_JNI(register_android_database_CursorWindow),
1239 REG_JNI(register_android_database_SQLiteCompiledSql),
1240 REG_JNI(register_android_database_SQLiteDatabase),
1241 REG_JNI(register_android_database_SQLiteDebug),
1242 REG_JNI(register_android_database_SQLiteProgram),
1243 REG_JNI(register_android_database_SQLiteQuery),
1244 REG_JNI(register_android_database_SQLiteStatement),
1245 REG_JNI(register_android_os_Debug),
1246 REG_JNI(register_android_os_FileObserver),
1247 REG_JNI(register_android_os_FileUtils),
1248 REG_JNI(register_android_os_MessageQueue),
1249 REG_JNI(register_android_os_ParcelFileDescriptor),
1250 REG_JNI(register_android_os_Power),
1251 REG_JNI(register_android_os_StatFs),
1252 REG_JNI(register_android_os_SystemProperties),
1253 REG_JNI(register_android_os_UEventObserver),
1254 REG_JNI(register_android_net_LocalSocketImpl),
1255 REG_JNI(register_android_net_NetworkUtils),
1256 REG_JNI(register_android_net_TrafficStats),
1257 REG_JNI(register_android_net_wifi_WifiManager),
1258 REG_JNI(register_android_nfc_NdefMessage),
1259 REG_JNI(register_android_nfc_NdefRecord),
1260 REG_JNI(register_android_os_MemoryFile),
1261 REG_JNI(register_com_android_internal_os_ZygoteInit),
1262 REG_JNI(register_android_hardware_Camera),
1263 REG_JNI(register_android_hardware_SensorManager),
1264 REG_JNI(register_android_media_AudioRecord),
1265 REG_JNI(register_android_media_AudioSystem),
1266 REG_JNI(register_android_media_AudioTrack),
1267 REG_JNI(register_android_media_JetPlayer),
1268 REG_JNI(register_android_media_ToneGenerator),
1270 REG_JNI(register_android_opengl_classes),
1271 REG_JNI(register_android_bluetooth_HeadsetBase),
1272 REG_JNI(register_android_bluetooth_BluetoothAudioGateway),
1273 REG_JNI(register_android_bluetooth_BluetoothSocket),
1274 REG_JNI(register_android_bluetooth_ScoSocket),
1275 REG_JNI(register_android_server_BluetoothService),
1276 REG_JNI(register_android_server_BluetoothEventLoop),
1277 REG_JNI(register_android_server_BluetoothA2dpService),
1278 REG_JNI(register_android_server_Watchdog),
1279 REG_JNI(register_android_message_digest_sha1),
1280 REG_JNI(register_android_ddm_DdmHandleNativeHeap),
1281 REG_JNI(register_android_backup_BackupDataInput),
1282 REG_JNI(register_android_backup_BackupDataOutput),
1283 REG_JNI(register_android_backup_FileBackupHelperBase),
1284 REG_JNI(register_android_backup_BackupHelperDispatcher),
1286 REG_JNI(register_android_app_NativeActivity),
1287 REG_JNI(register_android_view_InputChannel),
1288 REG_JNI(register_android_view_InputQueue),
1289 REG_JNI(register_android_view_KeyEvent),
1290 REG_JNI(register_android_view_MotionEvent),
1292 REG_JNI(register_android_content_res_ObbScanner),
1293 REG_JNI(register_android_content_res_Configuration),
1297 * Register android native functions with the VM.
1299 /*static*/ int AndroidRuntime::startReg(JNIEnv* env)
1302 * This hook causes all future threads created in this process to be
1303 * attached to the JavaVM. (This needs to go away in favor of JNI
1306 androidSetCreateThreadFunc((android_create_thread_fn) javaCreateThreadEtc);
1308 LOGV("--- registering native functions ---\n");
1311 * Every "register" function calls one or more things that return
1312 * a local reference (e.g. FindClass). Because we haven't really
1313 * started the VM yet, they're all getting stored in the base frame
1314 * and never released. Use Push/Pop to manage the storage.
1316 env->PushLocalFrame(200);
1318 if (register_jni_procs(gRegJNI, NELEM(gRegJNI), env) < 0) {
1319 env->PopLocalFrame(NULL);
1322 env->PopLocalFrame(NULL);
1324 //createJavaThread("fubar", quickTest, (void*) "hello");
1329 AndroidRuntime* AndroidRuntime::getRuntime()
1335 * Used by WithFramework to register native functions.
1338 jint Java_com_android_internal_util_WithFramework_registerNatives(
1339 JNIEnv* env, jclass clazz) {
1340 return register_jni_procs(gRegJNI, NELEM(gRegJNI), env);
1344 * Used by LoadClass to register native functions.
1347 jint Java_LoadClass_registerNatives(JNIEnv* env, jclass clazz) {
1348 return register_jni_procs(gRegJNI, NELEM(gRegJNI), env);
1351 } // namespace android