AndroidRuntime.cpp revision 84d8d693bd79082069d1781284213030006841b7
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 logStdio = false;
516    enum { kEMDefault, kEMIntPortable, kEMIntFast } executionMode = kEMDefault;
517
518
519    property_get("dalvik.vm.checkjni", propBuf, "");
520    if (strcmp(propBuf, "true") == 0) {
521        checkJni = true;
522    } else if (strcmp(propBuf, "false") != 0) {
523        /* property is neither true nor false; fall back on kernel parameter */
524        property_get("ro.kernel.android.checkjni", propBuf, "");
525        if (propBuf[0] == '1') {
526            checkJni = true;
527        }
528    }
529
530    property_get("dalvik.vm.execution-mode", propBuf, "");
531    if (strcmp(propBuf, "int:portable") == 0) {
532        executionMode = kEMIntPortable;
533    } else if (strcmp(propBuf, "int:fast") == 0) {
534        executionMode = kEMIntFast;
535    }
536
537    property_get("dalvik.vm.stack-trace-file", stackTraceFileBuf, "");
538
539    property_get("log.redirect-stdio", propBuf, "");
540    if (strcmp(propBuf, "true") == 0) {
541        logStdio = true;
542    }
543
544    strcpy(enableAssertBuf, "-ea:");
545    property_get("dalvik.vm.enableassertions", enableAssertBuf+4, "");
546
547    strcpy(jniOptsBuf, "-Xjniopts:");
548    property_get("dalvik.vm.jniopts", jniOptsBuf+10, "");
549
550    /* route exit() to our handler */
551    opt.extraInfo = (void*) runtime_exit;
552    opt.optionString = "exit";
553    mOptions.add(opt);
554
555    /* route fprintf() to our handler */
556    opt.extraInfo = (void*) runtime_vfprintf;
557    opt.optionString = "vfprintf";
558    mOptions.add(opt);
559
560    opt.extraInfo = NULL;
561
562    /* enable verbose; standard options are { jni, gc, class } */
563    //options[curOpt++].optionString = "-verbose:jni";
564    opt.optionString = "-verbose:gc";
565    mOptions.add(opt);
566    //options[curOpt++].optionString = "-verbose:class";
567
568#ifdef CUSTOM_RUNTIME_HEAP_MAX
569#define __make_max_heap_opt(val) #val
570#define _make_max_heap_opt(val) "-Xmx" __make_max_heap_opt(val)
571    opt.optionString = _make_max_heap_opt(CUSTOM_RUNTIME_HEAP_MAX);
572#undef __make_max_heap_opt
573#undef _make_max_heap_opt
574#else
575    /* limit memory use to 16MB */
576    opt.optionString = "-Xmx16m";
577#endif
578    mOptions.add(opt);
579
580    /*
581     * Enable or disable dexopt features, such as bytecode verification and
582     * calculation of register maps for precise GC.
583     */
584    property_get("dalvik.vm.dexopt-flags", dexoptFlagsBuf, "");
585    if (dexoptFlagsBuf[0] != '\0') {
586        const char* opc;
587        const char* val;
588
589        opc = strstr(dexoptFlagsBuf, "v=");     /* verification */
590        if (opc != NULL) {
591            switch (*(opc+2)) {
592            case 'n':   val = "-Xverify:none";      break;
593            case 'r':   val = "-Xverify:remote";    break;
594            case 'a':   val = "-Xverify:all";       break;
595            default:    val = NULL;                 break;
596            }
597
598            if (val != NULL) {
599                opt.optionString = val;
600                mOptions.add(opt);
601            }
602        }
603
604        opc = strstr(dexoptFlagsBuf, "o=");     /* optimization */
605        if (opc != NULL) {
606            switch (*(opc+2)) {
607            case 'n':   val = "-Xdexopt:none";      break;
608            case 'v':   val = "-Xdexopt:verified";  break;
609            case 'a':   val = "-Xdexopt:all";       break;
610            default:    val = NULL;                 break;
611            }
612
613            if (val != NULL) {
614                opt.optionString = val;
615                mOptions.add(opt);
616            }
617        }
618
619        opc = strstr(dexoptFlagsBuf, "m=y");    /* register map */
620        if (opc != NULL) {
621            opt.optionString = "-Xgenregmap";
622            mOptions.add(opt);
623
624            /* turn on precise GC while we're at it */
625            opt.optionString = "-Xgc:precise";
626            mOptions.add(opt);
627        }
628    }
629
630    /* enable debugging; set suspend=y to pause during VM init */
631#ifdef HAVE_ANDROID_OS
632    /* use android ADB transport */
633    opt.optionString =
634        "-agentlib:jdwp=transport=dt_android_adb,suspend=n,server=y";
635#else
636    /* use TCP socket; address=0 means start at port 8000 and probe up */
637    LOGI("Using TCP socket for JDWP\n");
638    opt.optionString =
639        "-agentlib:jdwp=transport=dt_socket,suspend=n,server=y,address=0";
640#endif
641    mOptions.add(opt);
642
643    char enableDPBuf[sizeof("-Xdeadlockpredict:") + PROPERTY_VALUE_MAX];
644    property_get("dalvik.vm.deadlock-predict", propBuf, "");
645    if (strlen(propBuf) > 0) {
646        strcpy(enableDPBuf, "-Xdeadlockpredict:");
647        strcat(enableDPBuf, propBuf);
648        opt.optionString = enableDPBuf;
649        mOptions.add(opt);
650    }
651
652    LOGD("CheckJNI is %s\n", checkJni ? "ON" : "OFF");
653    if (checkJni) {
654        /* extended JNI checking */
655        opt.optionString = "-Xcheck:jni";
656        mOptions.add(opt);
657
658        /* set a cap on JNI global references */
659        opt.optionString = "-Xjnigreflimit:2000";
660        mOptions.add(opt);
661
662        /* with -Xcheck:jni, this provides a JNI function call trace */
663        //opt.optionString = "-verbose:jni";
664        //mOptions.add(opt);
665    }
666    if (executionMode == kEMIntPortable) {
667        opt.optionString = "-Xint:portable";
668        mOptions.add(opt);
669    } else if (executionMode == kEMIntFast) {
670        opt.optionString = "-Xint:fast";
671        mOptions.add(opt);
672    }
673    if (logStdio) {
674        /* convert stdout/stderr to log messages */
675        opt.optionString = "-Xlog-stdio";
676        mOptions.add(opt);
677    }
678
679    if (enableAssertBuf[4] != '\0') {
680        /* accept "all" to mean "all classes and packages" */
681        if (strcmp(enableAssertBuf+4, "all") == 0)
682            enableAssertBuf[3] = '\0';
683        LOGI("Assertions enabled: '%s'\n", enableAssertBuf);
684        opt.optionString = enableAssertBuf;
685        mOptions.add(opt);
686    } else {
687        LOGV("Assertions disabled\n");
688    }
689
690    if (jniOptsBuf[10] != '\0') {
691        LOGI("JNI options: '%s'\n", jniOptsBuf);
692        opt.optionString = jniOptsBuf;
693        mOptions.add(opt);
694    }
695
696    if (stackTraceFileBuf[0] != '\0') {
697        static const char* stfOptName = "-Xstacktracefile:";
698
699        stackTraceFile = (char*) malloc(strlen(stfOptName) +
700            strlen(stackTraceFileBuf) +1);
701        strcpy(stackTraceFile, stfOptName);
702        strcat(stackTraceFile, stackTraceFileBuf);
703        opt.optionString = stackTraceFile;
704        mOptions.add(opt);
705    }
706
707    /* Set the properties for locale */
708    {
709        char langOption[sizeof("-Duser.language=") + 3];
710        char regionOption[sizeof("-Duser.region=") + 3];
711        strcpy(langOption, "-Duser.language=");
712        strcpy(regionOption, "-Duser.region=");
713        readLocale(langOption, regionOption);
714        opt.extraInfo = NULL;
715        opt.optionString = langOption;
716        mOptions.add(opt);
717        opt.optionString = regionOption;
718        mOptions.add(opt);
719    }
720
721    /*
722     * We don't have /tmp on the device, but we often have an SD card.  Apps
723     * shouldn't use this, but some test suites might want to exercise it.
724     */
725    opt.optionString = "-Djava.io.tmpdir=/sdcard";
726    mOptions.add(opt);
727
728    initArgs.version = JNI_VERSION_1_4;
729    initArgs.options = mOptions.editArray();
730    initArgs.nOptions = mOptions.size();
731    initArgs.ignoreUnrecognized = JNI_FALSE;
732
733    /*
734     * Initialize the VM.
735     *
736     * The JavaVM* is essentially per-process, and the JNIEnv* is per-thread.
737     * If this call succeeds, the VM is ready, and we can start issuing
738     * JNI calls.
739     */
740    if (JNI_CreateJavaVM(pJavaVM, pEnv, &initArgs) < 0) {
741        LOGE("JNI_CreateJavaVM failed\n");
742        goto bail;
743    }
744
745    result = 0;
746
747bail:
748    free(stackTraceFile);
749    return result;
750}
751
752/*
753 * Start the Android runtime.  This involves starting the virtual machine
754 * and calling the "static void main(String[] args)" method in the class
755 * named by "className".
756 */
757void AndroidRuntime::start(const char* className, const bool startSystemServer)
758{
759    LOGD("\n>>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<<\n");
760
761    char* slashClassName = NULL;
762    char* cp;
763    JNIEnv* env;
764
765    blockSigpipe();
766
767    /*
768     * 'startSystemServer == true' means runtime is obslete and not run from
769     * init.rc anymore, so we print out the boot start event here.
770     */
771    if (startSystemServer) {
772        /* track our progress through the boot sequence */
773        const int LOG_BOOT_PROGRESS_START = 3000;
774        LOG_EVENT_LONG(LOG_BOOT_PROGRESS_START,
775                       ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
776    }
777
778    const char* rootDir = getenv("ANDROID_ROOT");
779    if (rootDir == NULL) {
780        rootDir = "/system";
781        if (!hasDir("/system")) {
782            LOG_FATAL("No root directory specified, and /android does not exist.");
783            goto bail;
784        }
785        setenv("ANDROID_ROOT", rootDir, 1);
786    }
787
788    //const char* kernelHack = getenv("LD_ASSUME_KERNEL");
789    //LOGD("Found LD_ASSUME_KERNEL='%s'\n", kernelHack);
790
791    /* start the virtual machine */
792    if (startVm(&mJavaVM, &env) != 0)
793        goto bail;
794
795    /*
796     * Register android functions.
797     */
798    if (startReg(env) < 0) {
799        LOGE("Unable to register all android natives\n");
800        goto bail;
801    }
802
803    /*
804     * We want to call main() with a String array with arguments in it.
805     * At present we only have one argument, the class name.  Create an
806     * array to hold it.
807     */
808    jclass stringClass;
809    jobjectArray strArray;
810    jstring classNameStr;
811    jstring startSystemServerStr;
812
813    stringClass = env->FindClass("java/lang/String");
814    assert(stringClass != NULL);
815    strArray = env->NewObjectArray(2, stringClass, NULL);
816    assert(strArray != NULL);
817    classNameStr = env->NewStringUTF(className);
818    assert(classNameStr != NULL);
819    env->SetObjectArrayElement(strArray, 0, classNameStr);
820    startSystemServerStr = env->NewStringUTF(startSystemServer ?
821                                                 "true" : "false");
822    env->SetObjectArrayElement(strArray, 1, startSystemServerStr);
823
824    /*
825     * Start VM.  This thread becomes the main thread of the VM, and will
826     * not return until the VM exits.
827     */
828    jclass startClass;
829    jmethodID startMeth;
830
831    slashClassName = strdup(className);
832    for (cp = slashClassName; *cp != '\0'; cp++)
833        if (*cp == '.')
834            *cp = '/';
835
836    startClass = env->FindClass(slashClassName);
837    if (startClass == NULL) {
838        LOGE("JavaVM unable to locate class '%s'\n", slashClassName);
839        /* keep going */
840    } else {
841        startMeth = env->GetStaticMethodID(startClass, "main",
842            "([Ljava/lang/String;)V");
843        if (startMeth == NULL) {
844            LOGE("JavaVM unable to find main() in '%s'\n", className);
845            /* keep going */
846        } else {
847            env->CallStaticVoidMethod(startClass, startMeth, strArray);
848
849#if 0
850            if (env->ExceptionCheck())
851                threadExitUncaughtException(env);
852#endif
853        }
854    }
855
856    LOGD("Shutting down VM\n");
857    if (mJavaVM->DetachCurrentThread() != JNI_OK)
858        LOGW("Warning: unable to detach main thread\n");
859    if (mJavaVM->DestroyJavaVM() != 0)
860        LOGW("Warning: VM did not shut down cleanly\n");
861
862bail:
863    free(slashClassName);
864}
865
866void AndroidRuntime::start()
867{
868    start("com.android.internal.os.RuntimeInit",
869        false /* Don't start the system server */);
870}
871
872void AndroidRuntime::onExit(int code)
873{
874    LOGI("AndroidRuntime onExit calling exit(%d)", code);
875    exit(code);
876}
877
878/*
879 * Get the JNIEnv pointer for this thread.
880 *
881 * Returns NULL if the slot wasn't allocated or populated.
882 */
883/*static*/ JNIEnv* AndroidRuntime::getJNIEnv()
884{
885    JNIEnv* env;
886    JavaVM* vm = AndroidRuntime::getJavaVM();
887    assert(vm != NULL);
888
889    if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK)
890        return NULL;
891    return env;
892}
893
894/*
895 * Makes the current thread visible to the VM.
896 *
897 * The JNIEnv pointer returned is only valid for the current thread, and
898 * thus must be tucked into thread-local storage.
899 */
900static int javaAttachThread(const char* threadName, JNIEnv** pEnv)
901{
902    JavaVMAttachArgs args;
903    JavaVM* vm;
904    jint result;
905
906    vm = AndroidRuntime::getJavaVM();
907    assert(vm != NULL);
908
909    args.version = JNI_VERSION_1_4;
910    args.name = (char*) threadName;
911    args.group = NULL;
912
913    result = vm->AttachCurrentThread(pEnv, (void*) &args);
914    if (result != JNI_OK)
915        LOGE("ERROR: thread attach failed\n");
916
917    return result;
918}
919
920/*
921 * Detach the current thread from the set visible to the VM.
922 */
923static int javaDetachThread(void)
924{
925    JavaVM* vm;
926    jint result;
927
928    vm = AndroidRuntime::getJavaVM();
929    assert(vm != NULL);
930
931    result = vm->DetachCurrentThread();
932    if (result != JNI_OK)
933        LOGE("ERROR: thread detach failed\n");
934    return result;
935}
936
937/*
938 * When starting a native thread that will be visible from the VM, we
939 * bounce through this to get the right attach/detach action.
940 * Note that this function calls free(args)
941 */
942/*static*/ int AndroidRuntime::javaThreadShell(void* args) {
943    void* start = ((void**)args)[0];
944    void* userData = ((void **)args)[1];
945    char* name = (char*) ((void **)args)[2];        // we own this storage
946    free(args);
947    JNIEnv* env;
948    int result;
949
950    /* hook us into the VM */
951    if (javaAttachThread(name, &env) != JNI_OK)
952        return -1;
953
954    /* start the thread running */
955    result = (*(android_thread_func_t)start)(userData);
956
957    /* unhook us */
958    javaDetachThread();
959    free(name);
960
961    return result;
962}
963
964/*
965 * This is invoked from androidCreateThreadEtc() via the callback
966 * set with androidSetCreateThreadFunc().
967 *
968 * We need to create the new thread in such a way that it gets hooked
969 * into the VM before it really starts executing.
970 */
971/*static*/ int AndroidRuntime::javaCreateThreadEtc(
972                                android_thread_func_t entryFunction,
973                                void* userData,
974                                const char* threadName,
975                                int32_t threadPriority,
976                                size_t threadStackSize,
977                                android_thread_id_t* threadId)
978{
979    void** args = (void**) malloc(3 * sizeof(void*));   // javaThreadShell must free
980    int result;
981
982    assert(threadName != NULL);
983
984    args[0] = (void*) entryFunction;
985    args[1] = userData;
986    args[2] = (void*) strdup(threadName);   // javaThreadShell must free
987
988    result = androidCreateRawThreadEtc(AndroidRuntime::javaThreadShell, args,
989        threadName, threadPriority, threadStackSize, threadId);
990    return result;
991}
992
993/*
994 * Create a thread that is visible from the VM.
995 *
996 * This is called from elsewhere in the library.
997 */
998/*static*/ void AndroidRuntime::createJavaThread(const char* name,
999    void (*start)(void *), void* arg)
1000{
1001    javaCreateThreadEtc((android_thread_func_t) start, arg, name,
1002        ANDROID_PRIORITY_DEFAULT, 0, NULL);
1003}
1004
1005#if 0
1006static void quickTest(void* arg)
1007{
1008    const char* str = (const char*) arg;
1009
1010    printf("In quickTest: %s\n", str);
1011}
1012#endif
1013
1014#ifdef NDEBUG
1015    #define REG_JNI(name)      { name }
1016    struct RegJNIRec {
1017        int (*mProc)(JNIEnv*);
1018    };
1019#else
1020    #define REG_JNI(name)      { name, #name }
1021    struct RegJNIRec {
1022        int (*mProc)(JNIEnv*);
1023        const char* mName;
1024    };
1025#endif
1026
1027typedef void (*RegJAMProc)();
1028
1029static int register_jni_procs(const RegJNIRec array[], size_t count, JNIEnv* env)
1030{
1031    for (size_t i = 0; i < count; i++) {
1032        if (array[i].mProc(env) < 0) {
1033#ifndef NDEBUG
1034            LOGD("----------!!! %s failed to load\n", array[i].mName);
1035#endif
1036            return -1;
1037        }
1038    }
1039    return 0;
1040}
1041
1042static void register_jam_procs(const RegJAMProc array[], size_t count)
1043{
1044    for (size_t i = 0; i < count; i++) {
1045        array[i]();
1046    }
1047}
1048
1049static const RegJNIRec gRegJNI[] = {
1050    REG_JNI(register_android_debug_JNITest),
1051    REG_JNI(register_com_android_internal_os_RuntimeInit),
1052    REG_JNI(register_android_os_SystemClock),
1053    REG_JNI(register_android_util_EventLog),
1054    REG_JNI(register_android_util_Log),
1055    REG_JNI(register_android_util_FloatMath),
1056    REG_JNI(register_android_text_format_Time),
1057    REG_JNI(register_android_pim_EventRecurrence),
1058    REG_JNI(register_android_content_AssetManager),
1059    REG_JNI(register_android_content_StringBlock),
1060    REG_JNI(register_android_content_XmlBlock),
1061    REG_JNI(register_android_emoji_EmojiFactory),
1062    REG_JNI(register_android_security_Md5MessageDigest),
1063    REG_JNI(register_android_text_AndroidCharacter),
1064    REG_JNI(register_android_text_KeyCharacterMap),
1065    REG_JNI(register_android_os_Process),
1066    REG_JNI(register_android_os_Binder),
1067    REG_JNI(register_android_os_Hardware),
1068    REG_JNI(register_android_view_Display),
1069    REG_JNI(register_android_nio_utils),
1070    REG_JNI(register_android_graphics_PixelFormat),
1071    REG_JNI(register_android_graphics_Graphics),
1072    REG_JNI(register_android_view_Surface),
1073    REG_JNI(register_android_view_ViewRoot),
1074    REG_JNI(register_com_google_android_gles_jni_EGLImpl),
1075    REG_JNI(register_com_google_android_gles_jni_GLImpl),
1076
1077    REG_JNI(register_android_graphics_Bitmap),
1078    REG_JNI(register_android_graphics_BitmapFactory),
1079    REG_JNI(register_android_graphics_Camera),
1080    REG_JNI(register_android_graphics_Canvas),
1081    REG_JNI(register_android_graphics_ColorFilter),
1082    REG_JNI(register_android_graphics_DrawFilter),
1083    REG_JNI(register_android_graphics_Interpolator),
1084    REG_JNI(register_android_graphics_LayerRasterizer),
1085    REG_JNI(register_android_graphics_MaskFilter),
1086    REG_JNI(register_android_graphics_Matrix),
1087    REG_JNI(register_android_graphics_Movie),
1088    REG_JNI(register_android_graphics_NinePatch),
1089    REG_JNI(register_android_graphics_Paint),
1090    REG_JNI(register_android_graphics_Path),
1091    REG_JNI(register_android_graphics_PathMeasure),
1092    REG_JNI(register_android_graphics_PathEffect),
1093    REG_JNI(register_android_graphics_Picture),
1094    REG_JNI(register_android_graphics_PorterDuff),
1095    REG_JNI(register_android_graphics_Rasterizer),
1096    REG_JNI(register_android_graphics_Region),
1097    REG_JNI(register_android_graphics_Shader),
1098    REG_JNI(register_android_graphics_Typeface),
1099    REG_JNI(register_android_graphics_Xfermode),
1100    REG_JNI(register_com_android_internal_graphics_NativeUtils),
1101
1102    REG_JNI(register_android_database_CursorWindow),
1103    REG_JNI(register_android_database_SQLiteDatabase),
1104    REG_JNI(register_android_database_SQLiteDebug),
1105    REG_JNI(register_android_database_SQLiteProgram),
1106    REG_JNI(register_android_database_SQLiteQuery),
1107    REG_JNI(register_android_database_SQLiteStatement),
1108    REG_JNI(register_android_os_Debug),
1109    REG_JNI(register_android_os_FileObserver),
1110    REG_JNI(register_android_os_FileUtils),
1111    REG_JNI(register_android_os_ParcelFileDescriptor),
1112    REG_JNI(register_android_os_Power),
1113    REG_JNI(register_android_os_StatFs),
1114    REG_JNI(register_android_os_SystemProperties),
1115    REG_JNI(register_android_os_UEventObserver),
1116    REG_JNI(register_android_net_LocalSocketImpl),
1117    REG_JNI(register_android_net_NetworkUtils),
1118    REG_JNI(register_android_net_wifi_WifiManager),
1119    REG_JNI(register_android_os_MemoryFile),
1120    REG_JNI(register_com_android_internal_os_ZygoteInit),
1121    REG_JNI(register_android_hardware_Camera),
1122    REG_JNI(register_android_hardware_SensorManager),
1123    REG_JNI(register_android_media_AudioRecord),
1124    REG_JNI(register_android_media_AudioSystem),
1125    REG_JNI(register_android_media_AudioTrack),
1126    REG_JNI(register_android_media_JetPlayer),
1127    REG_JNI(register_android_media_ToneGenerator),
1128
1129    REG_JNI(register_android_opengl_classes),
1130    REG_JNI(register_android_bluetooth_Database),
1131    REG_JNI(register_android_bluetooth_HeadsetBase),
1132    REG_JNI(register_android_bluetooth_BluetoothAudioGateway),
1133    REG_JNI(register_android_bluetooth_RfcommSocket),
1134    REG_JNI(register_android_bluetooth_ScoSocket),
1135    REG_JNI(register_android_server_BluetoothDeviceService),
1136    REG_JNI(register_android_server_BluetoothEventLoop),
1137    REG_JNI(register_android_server_BluetoothA2dpService),
1138    REG_JNI(register_android_message_digest_sha1),
1139    REG_JNI(register_android_ddm_DdmHandleNativeHeap),
1140    REG_JNI(register_android_util_Base64),
1141    REG_JNI(register_android_location_GpsLocationProvider),
1142};
1143
1144/*
1145 * Register android native functions with the VM.
1146 */
1147/*static*/ int AndroidRuntime::startReg(JNIEnv* env)
1148{
1149    /*
1150     * This hook causes all future threads created in this process to be
1151     * attached to the JavaVM.  (This needs to go away in favor of JNI
1152     * Attach calls.)
1153     */
1154    androidSetCreateThreadFunc((android_create_thread_fn) javaCreateThreadEtc);
1155
1156    LOGD("--- registering native functions ---\n");
1157
1158    /*
1159     * Every "register" function calls one or more things that return
1160     * a local reference (e.g. FindClass).  Because we haven't really
1161     * started the VM yet, they're all getting stored in the base frame
1162     * and never released.  Use Push/Pop to manage the storage.
1163     */
1164    env->PushLocalFrame(200);
1165
1166    if (register_jni_procs(gRegJNI, NELEM(gRegJNI), env) < 0) {
1167        env->PopLocalFrame(NULL);
1168        return -1;
1169    }
1170    env->PopLocalFrame(NULL);
1171
1172    //createJavaThread("fubar", quickTest, (void*) "hello");
1173
1174    return 0;
1175}
1176
1177AndroidRuntime* AndroidRuntime::getRuntime()
1178{
1179    return gCurRuntime;
1180}
1181
1182/**
1183 * Used by WithFramework to register native functions.
1184 */
1185extern "C"
1186jint Java_com_android_internal_util_WithFramework_registerNatives(
1187        JNIEnv* env, jclass clazz) {
1188    return register_jni_procs(gRegJNI, NELEM(gRegJNI), env);
1189}
1190
1191/**
1192 * Used by LoadClass to register native functions.
1193 */
1194extern "C"
1195jint Java_LoadClass_registerNatives(JNIEnv* env, jclass clazz) {
1196    return register_jni_procs(gRegJNI, NELEM(gRegJNI), env);
1197}
1198
1199}   // namespace android
1200