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