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