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