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