AndroidRuntime.cpp revision 112d9c7f116bec0a52badde81bd778e59e88cb63
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/threads.h>
28#include <cutils/properties.h>
29
30#include <SkGraphics.h>
31#include <SkImageDecoder.h>
32
33#include "jni.h"
34#include "JNIHelp.h"
35#include "JniInvocation.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 int register_android_os_Binder(JNIEnv* env);
50extern int register_android_os_Process(JNIEnv* env);
51extern int register_android_graphics_Bitmap(JNIEnv*);
52extern int register_android_graphics_BitmapFactory(JNIEnv*);
53extern int register_android_graphics_BitmapRegionDecoder(JNIEnv*);
54extern int register_android_graphics_Camera(JNIEnv* env);
55extern int register_android_graphics_CreateJavaOutputStreamAdaptor(JNIEnv* env);
56extern int register_android_graphics_Graphics(JNIEnv* env);
57extern int register_android_graphics_Interpolator(JNIEnv* env);
58extern int register_android_graphics_MaskFilter(JNIEnv* env);
59extern int register_android_graphics_Movie(JNIEnv* env);
60extern int register_android_graphics_NinePatch(JNIEnv*);
61extern int register_android_graphics_PathEffect(JNIEnv* env);
62extern int register_android_graphics_Shader(JNIEnv* env);
63extern int register_android_graphics_Typeface(JNIEnv* env);
64extern int register_android_graphics_YuvImage(JNIEnv* env);
65
66extern int register_com_google_android_gles_jni_EGLImpl(JNIEnv* env);
67extern int register_com_google_android_gles_jni_GLImpl(JNIEnv* env);
68extern int register_android_opengl_jni_EGL14(JNIEnv* env);
69extern int register_android_opengl_jni_EGLExt(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);
74extern int register_android_opengl_jni_GLES20(JNIEnv* env);
75extern int register_android_opengl_jni_GLES30(JNIEnv* env);
76extern int register_android_opengl_jni_GLES31(JNIEnv* env);
77extern int register_android_opengl_jni_GLES31Ext(JNIEnv* env);
78
79extern int register_android_hardware_Camera(JNIEnv *env);
80extern int register_android_hardware_camera2_CameraMetadata(JNIEnv *env);
81extern int register_android_hardware_camera2_legacy_LegacyCameraDevice(JNIEnv *env);
82extern int register_android_hardware_camera2_legacy_PerfMeasurement(JNIEnv *env);
83extern int register_android_hardware_camera2_DngCreator(JNIEnv *env);
84extern int register_android_hardware_Radio(JNIEnv *env);
85extern int register_android_hardware_SensorManager(JNIEnv *env);
86extern int register_android_hardware_SerialPort(JNIEnv *env);
87extern int register_android_hardware_SoundTrigger(JNIEnv *env);
88extern int register_android_hardware_UsbDevice(JNIEnv *env);
89extern int register_android_hardware_UsbDeviceConnection(JNIEnv *env);
90extern int register_android_hardware_UsbRequest(JNIEnv *env);
91extern int register_android_hardware_location_ActivityRecognitionHardware(JNIEnv* env);
92
93extern int register_android_media_AudioRecord(JNIEnv *env);
94extern int register_android_media_AudioSystem(JNIEnv *env);
95extern int register_android_media_AudioTrack(JNIEnv *env);
96extern int register_android_media_JetPlayer(JNIEnv *env);
97extern int register_android_media_ToneGenerator(JNIEnv *env);
98
99namespace android {
100
101/*
102 * JNI-based registration functions.  Note these are properly contained in
103 * namespace android.
104 */
105extern int register_android_content_AssetManager(JNIEnv* env);
106extern int register_android_util_EventLog(JNIEnv* env);
107extern int register_android_util_Log(JNIEnv* env);
108extern int register_android_content_StringBlock(JNIEnv* env);
109extern int register_android_content_XmlBlock(JNIEnv* env);
110extern int register_android_graphics_Canvas(JNIEnv* env);
111extern int register_android_graphics_CanvasProperty(JNIEnv* env);
112extern int register_android_graphics_ColorFilter(JNIEnv* env);
113extern int register_android_graphics_DrawFilter(JNIEnv* env);
114extern int register_android_graphics_FontFamily(JNIEnv* env);
115extern int register_android_graphics_LayerRasterizer(JNIEnv*);
116extern int register_android_graphics_Matrix(JNIEnv* env);
117extern int register_android_graphics_Paint(JNIEnv* env);
118extern int register_android_graphics_Path(JNIEnv* env);
119extern int register_android_graphics_PathMeasure(JNIEnv* env);
120extern int register_android_graphics_Picture(JNIEnv*);
121extern int register_android_graphics_PorterDuff(JNIEnv* env);
122extern int register_android_graphics_Rasterizer(JNIEnv* env);
123extern int register_android_graphics_Region(JNIEnv* env);
124extern int register_android_graphics_SurfaceTexture(JNIEnv* env);
125extern int register_android_graphics_Xfermode(JNIEnv* env);
126extern int register_android_graphics_pdf_PdfDocument(JNIEnv* env);
127extern int register_android_graphics_pdf_PdfEditor(JNIEnv* env);
128extern int register_android_graphics_pdf_PdfRenderer(JNIEnv* env);
129extern int register_android_view_DisplayEventReceiver(JNIEnv* env);
130extern int register_android_view_DisplayListCanvas(JNIEnv* env);
131extern int register_android_view_GraphicBuffer(JNIEnv* env);
132extern int register_android_view_HardwareLayer(JNIEnv* env);
133extern int register_android_view_RenderNode(JNIEnv* env);
134extern int register_android_view_RenderNodeAnimator(JNIEnv* env);
135extern int register_android_view_Surface(JNIEnv* env);
136extern int register_android_view_SurfaceControl(JNIEnv* env);
137extern int register_android_view_SurfaceSession(JNIEnv* env);
138extern int register_android_view_TextureView(JNIEnv* env);
139extern int register_android_view_ThreadedRenderer(JNIEnv* env);
140extern int register_com_android_internal_view_animation_NativeInterpolatorFactoryHelper(JNIEnv *env);
141extern int register_android_database_CursorWindow(JNIEnv* env);
142extern int register_android_database_SQLiteConnection(JNIEnv* env);
143extern int register_android_database_SQLiteGlobal(JNIEnv* env);
144extern int register_android_database_SQLiteDebug(JNIEnv* env);
145extern int register_android_nio_utils(JNIEnv* env);
146extern int register_android_os_Debug(JNIEnv* env);
147extern int register_android_os_MessageQueue(JNIEnv* env);
148extern int register_android_os_Parcel(JNIEnv* env);
149extern int register_android_os_SELinux(JNIEnv* env);
150extern int register_android_os_SystemProperties(JNIEnv *env);
151extern int register_android_os_SystemClock(JNIEnv* env);
152extern int register_android_os_Trace(JNIEnv* env);
153extern int register_android_os_FileObserver(JNIEnv *env);
154extern int register_android_os_UEventObserver(JNIEnv* env);
155extern int register_android_os_MemoryFile(JNIEnv* env);
156extern int register_android_net_LocalSocketImpl(JNIEnv* env);
157extern int register_android_net_NetworkUtils(JNIEnv* env);
158extern int register_android_net_TrafficStats(JNIEnv* env);
159extern int register_android_text_AndroidCharacter(JNIEnv *env);
160extern int register_android_text_StaticLayout(JNIEnv *env);
161extern int register_android_text_AndroidBidi(JNIEnv *env);
162extern int register_android_opengl_classes(JNIEnv *env);
163extern int register_android_ddm_DdmHandleNativeHeap(JNIEnv *env);
164extern int register_android_server_NetworkManagementSocketTagger(JNIEnv* env);
165extern int register_android_backup_BackupDataInput(JNIEnv *env);
166extern int register_android_backup_BackupDataOutput(JNIEnv *env);
167extern int register_android_backup_FileBackupHelperBase(JNIEnv *env);
168extern int register_android_backup_BackupHelperDispatcher(JNIEnv *env);
169extern int register_android_app_backup_FullBackup(JNIEnv *env);
170extern int register_android_app_ActivityThread(JNIEnv *env);
171extern int register_android_app_NativeActivity(JNIEnv *env);
172extern int register_android_media_RemoteDisplay(JNIEnv *env);
173extern int register_android_view_InputChannel(JNIEnv* env);
174extern int register_android_view_InputDevice(JNIEnv* env);
175extern int register_android_view_InputEventReceiver(JNIEnv* env);
176extern int register_android_view_InputEventSender(JNIEnv* env);
177extern int register_android_view_InputQueue(JNIEnv* env);
178extern int register_android_view_KeyCharacterMap(JNIEnv *env);
179extern int register_android_view_KeyEvent(JNIEnv* env);
180extern int register_android_view_MotionEvent(JNIEnv* env);
181extern int register_android_view_PointerIcon(JNIEnv* env);
182extern int register_android_view_VelocityTracker(JNIEnv* env);
183extern int register_android_content_res_ObbScanner(JNIEnv* env);
184extern int register_android_content_res_Configuration(JNIEnv* env);
185extern int register_android_animation_PropertyValuesHolder(JNIEnv *env);
186extern int register_com_android_internal_content_NativeLibraryHelper(JNIEnv *env);
187extern int register_com_android_internal_net_NetworkStatsFactory(JNIEnv *env);
188extern int register_com_android_internal_os_Zygote(JNIEnv *env);
189extern int register_com_android_internal_util_VirtualRefBasePtr(JNIEnv *env);
190
191static AndroidRuntime* gCurRuntime = NULL;
192
193/*
194 * Code written in the Java Programming Language calls here from main().
195 */
196static void com_android_internal_os_RuntimeInit_nativeFinishInit(JNIEnv* env, jobject clazz)
197{
198    gCurRuntime->onStarted();
199}
200
201static void com_android_internal_os_RuntimeInit_nativeZygoteInit(JNIEnv* env, jobject clazz)
202{
203    gCurRuntime->onZygoteInit();
204}
205
206static void com_android_internal_os_RuntimeInit_nativeSetExitWithoutCleanup(JNIEnv* env,
207        jobject clazz, jboolean exitWithoutCleanup)
208{
209    gCurRuntime->setExitWithoutCleanup(exitWithoutCleanup);
210}
211
212/*
213 * JNI registration.
214 */
215static JNINativeMethod gMethods[] = {
216    { "nativeFinishInit", "()V",
217        (void*) com_android_internal_os_RuntimeInit_nativeFinishInit },
218    { "nativeZygoteInit", "()V",
219        (void*) com_android_internal_os_RuntimeInit_nativeZygoteInit },
220    { "nativeSetExitWithoutCleanup", "(Z)V",
221        (void*) com_android_internal_os_RuntimeInit_nativeSetExitWithoutCleanup },
222};
223
224int register_com_android_internal_os_RuntimeInit(JNIEnv* env)
225{
226    return jniRegisterNativeMethods(env, "com/android/internal/os/RuntimeInit",
227        gMethods, NELEM(gMethods));
228}
229
230// ----------------------------------------------------------------------
231
232/*static*/ JavaVM* AndroidRuntime::mJavaVM = NULL;
233
234AndroidRuntime::AndroidRuntime(char* argBlockStart, const size_t argBlockLength) :
235        mExitWithoutCleanup(false),
236        mArgBlockStart(argBlockStart),
237        mArgBlockLength(argBlockLength)
238{
239    SkGraphics::Init();
240    // There is also a global font cache, but its budget is specified by
241    // SK_DEFAULT_FONT_CACHE_COUNT_LIMIT and SK_DEFAULT_FONT_CACHE_LIMIT.
242
243    // Pre-allocate enough space to hold a fair number of options.
244    mOptions.setCapacity(20);
245
246    assert(gCurRuntime == NULL);        // one per process
247    gCurRuntime = this;
248}
249
250AndroidRuntime::~AndroidRuntime()
251{
252    SkGraphics::Term();
253}
254
255/*
256 * Register native methods using JNI.
257 */
258/*static*/ int AndroidRuntime::registerNativeMethods(JNIEnv* env,
259    const char* className, const JNINativeMethod* gMethods, int numMethods)
260{
261    return jniRegisterNativeMethods(env, className, gMethods, numMethods);
262}
263
264void AndroidRuntime::setArgv0(const char* argv0) {
265    memset(mArgBlockStart, 0, mArgBlockLength);
266    strlcpy(mArgBlockStart, argv0, mArgBlockLength);
267}
268
269status_t AndroidRuntime::callMain(const String8& className, jclass clazz,
270    const Vector<String8>& args)
271{
272    JNIEnv* env;
273    jmethodID methodId;
274
275    ALOGD("Calling main entry %s", className.string());
276
277    env = getJNIEnv();
278    if (clazz == NULL || env == NULL) {
279        return UNKNOWN_ERROR;
280    }
281
282    methodId = env->GetStaticMethodID(clazz, "main", "([Ljava/lang/String;)V");
283    if (methodId == NULL) {
284        ALOGE("ERROR: could not find method %s.main(String[])\n", className.string());
285        return UNKNOWN_ERROR;
286    }
287
288    /*
289     * We want to call main() with a String array with our arguments in it.
290     * Create an array and populate it.
291     */
292    jclass stringClass;
293    jobjectArray strArray;
294
295    const size_t numArgs = args.size();
296    stringClass = env->FindClass("java/lang/String");
297    strArray = env->NewObjectArray(numArgs, stringClass, NULL);
298
299    for (size_t i = 0; i < numArgs; i++) {
300        jstring argStr = env->NewStringUTF(args[i].string());
301        env->SetObjectArrayElement(strArray, i, argStr);
302    }
303
304    env->CallStaticVoidMethod(clazz, methodId, strArray);
305    return NO_ERROR;
306}
307
308/*
309 * The VM calls this through the "exit" hook.
310 */
311static void runtime_exit(int code)
312{
313    gCurRuntime->exit(code);
314}
315
316/*
317 * The VM calls this through the "vfprintf" hook.
318 *
319 * We ignore "fp" and just write the results to the log file.
320 */
321static void runtime_vfprintf(FILE* fp, const char* format, va_list ap)
322{
323    LOG_PRI_VA(ANDROID_LOG_INFO, "vm-printf", format, ap);
324}
325
326/**
327 * The VM calls this when mutex contention debugging is enabled to
328 * determine whether or not the blocked thread was a "sensitive thread"
329 * for user responsiveness/smoothess.
330 *
331 * Our policy for this is whether or not we're tracing any StrictMode
332 * events on this thread (which we might've inherited via Binder calls
333 * into us)
334 */
335static bool runtime_isSensitiveThread() {
336    IPCThreadState* state = IPCThreadState::selfOrNull();
337    return state && state->getStrictModePolicy() != 0;
338}
339
340static int hasDir(const char* dir)
341{
342    struct stat s;
343    int res = stat(dir, &s);
344    if (res == 0) {
345        return S_ISDIR(s.st_mode);
346    }
347    return 0;
348}
349
350static bool hasFile(const char* file) {
351    struct stat s;
352    int res = stat(file, &s);
353    if (res == 0) {
354        return S_ISREG(s.st_mode);
355    }
356    return false;
357}
358
359/*
360 * Read the persistent locale. Attempts to read to persist.sys.locale
361 * and falls back to the default locale (ro.product.locale) if
362 * persist.sys.locale is empty.
363 */
364static void readLocale(char* locale)
365{
366    // Allocate 4 extra bytes because we might read a property into
367    // this array at offset 4.
368    char propLocale[PROPERTY_VALUE_MAX + 4];
369
370    property_get("persist.sys.locale", propLocale, "");
371    if (propLocale[0] == 0) {
372        property_get("ro.product.locale", propLocale, "");
373
374        if (propLocale[0] == 0) {
375            // If persist.sys.locale and ro.product.locale are missing,
376            // construct a locale value from the individual locale components.
377            property_get("ro.product.locale.language", propLocale, "en");
378
379            // The language code is either two or three chars in length. If it
380            // isn't 2 chars long, assume three. Anything else is an error
381            // anyway.
382            const int offset = (propLocale[2] == 0) ? 2 : 3;
383            propLocale[offset] = '-';
384
385            property_get("ro.product.locale.region", propLocale + offset + 1, "US");
386        }
387    }
388
389    strncat(locale, propLocale, PROPERTY_VALUE_MAX);
390    // ALOGD("[DEBUG] locale=%s", locale);
391}
392
393void AndroidRuntime::addOption(const char* optionString, void* extraInfo)
394{
395    JavaVMOption opt;
396    opt.optionString = optionString;
397    opt.extraInfo = extraInfo;
398    mOptions.add(opt);
399}
400
401/*
402 * Parse a property containing space-separated options that should be
403 * passed directly to the VM, e.g. "-Xmx32m -verbose:gc -Xregenmap".
404 *
405 * This will cut up "extraOptsBuf" as we chop it into individual options.
406 *
407 * If "quotingArg" is non-null, it is passed before each extra option in mOptions.
408 *
409 * Adds the strings, if any, to mOptions.
410 */
411void AndroidRuntime::parseExtraOpts(char* extraOptsBuf, const char* quotingArg)
412{
413    char* start = extraOptsBuf;
414    char* end = NULL;
415    while (*start != '\0') {
416        while (*start == ' ')                   /* skip leading whitespace */
417            start++;
418        if (*start == '\0')                     /* was trailing ws, bail */
419            break;
420
421        end = start+1;
422        while (*end != ' ' && *end != '\0')     /* find end of token */
423            end++;
424        if (*end == ' ')
425            *end++ = '\0';          /* mark end, advance to indicate more */
426
427        if (quotingArg != NULL) {
428            addOption(quotingArg);
429        }
430        addOption(start);
431        start = end;
432    }
433}
434
435/*
436 * Reads a "property" into "buffer" with a default of "defaultArg". If
437 * the property is non-empty, it is treated as a runtime option such
438 * as "-Xmx32m".
439 *
440 * The "runtimeArg" is a prefix for the option such as "-Xms" or "-Xmx".
441 *
442 * If an argument is found, it is added to mOptions.
443 *
444 * If an option is found, it is added to mOptions and true is
445 * returned. Otherwise false is returned.
446 */
447bool AndroidRuntime::parseRuntimeOption(const char* property,
448                                        char* buffer,
449                                        const char* runtimeArg,
450                                        const char* defaultArg)
451{
452    strcpy(buffer, runtimeArg);
453    size_t runtimeArgLen = strlen(runtimeArg);
454    property_get(property, buffer+runtimeArgLen, defaultArg);
455    if (buffer[runtimeArgLen] == '\0') {
456        return false;
457    }
458    addOption(buffer);
459    return true;
460}
461
462/*
463 * Reads a "property" into "buffer". If the property is non-empty, it
464 * is treated as a dex2oat compiler option that should be
465 * passed as a quoted option, e.g. "-Ximage-compiler-option --compiler-filter=verify-none".
466 *
467 * The "compilerArg" is a prefix for the option such as "--compiler-filter=".
468 *
469 * The "quotingArg" should be "-Ximage-compiler-option" or "-Xcompiler-option".
470 *
471 * If an option is found, it is added to mOptions and true is
472 * returned. Otherwise false is returned.
473 */
474bool AndroidRuntime::parseCompilerOption(const char* property,
475                                         char* buffer,
476                                         const char* compilerArg,
477                                         const char* quotingArg)
478{
479    strcpy(buffer, compilerArg);
480    size_t compilerArgLen = strlen(compilerArg);
481    property_get(property, buffer+compilerArgLen, "");
482    if (buffer[compilerArgLen] == '\0') {
483        return false;
484    }
485    addOption(quotingArg);
486    addOption(buffer);
487    return true;
488}
489
490/*
491 * Reads a "property" into "buffer". If the property is non-empty, it
492 * is treated as a dex2oat compiler runtime option that should be
493 * passed as a quoted option, e.g. "-Ximage-compiler-option
494 * --runtime-arg -Ximage-compiler-option -Xmx32m".
495 *
496 * The "runtimeArg" is a prefix for the option such as "-Xms" or "-Xmx".
497 *
498 * The "quotingArg" should be "-Ximage-compiler-option" or "-Xcompiler-option".
499 *
500 * If an option is found, it is added to mOptions and true is
501 * returned. Otherwise false is returned.
502 */
503bool AndroidRuntime::parseCompilerRuntimeOption(const char* property,
504                                                char* buffer,
505                                                const char* runtimeArg,
506                                                const char* quotingArg)
507{
508    strcpy(buffer, runtimeArg);
509    size_t runtimeArgLen = strlen(runtimeArg);
510    property_get(property, buffer+runtimeArgLen, "");
511    if (buffer[runtimeArgLen] == '\0') {
512        return false;
513    }
514    addOption(quotingArg);
515    addOption("--runtime-arg");
516    addOption(quotingArg);
517    addOption(buffer);
518    return true;
519}
520
521/*
522 * Start the Dalvik Virtual Machine.
523 *
524 * Various arguments, most determined by system properties, are passed in.
525 * The "mOptions" vector is updated.
526 *
527 * CAUTION: when adding options in here, be careful not to put the
528 * char buffer inside a nested scope.  Adding the buffer to the
529 * options using mOptions.add() does not copy the buffer, so if the
530 * buffer goes out of scope the option may be overwritten.  It's best
531 * to put the buffer at the top of the function so that it is more
532 * unlikely that someone will surround it in a scope at a later time
533 * and thus introduce a bug.
534 *
535 * Returns 0 on success.
536 */
537int AndroidRuntime::startVm(JavaVM** pJavaVM, JNIEnv** pEnv)
538{
539    JavaVMInitArgs initArgs;
540    char propBuf[PROPERTY_VALUE_MAX];
541    char stackTraceFileBuf[sizeof("-Xstacktracefile:")-1 + PROPERTY_VALUE_MAX];
542    char jniOptsBuf[sizeof("-Xjniopts:")-1 + PROPERTY_VALUE_MAX];
543    char heapstartsizeOptsBuf[sizeof("-Xms")-1 + PROPERTY_VALUE_MAX];
544    char heapsizeOptsBuf[sizeof("-Xmx")-1 + PROPERTY_VALUE_MAX];
545    char heapgrowthlimitOptsBuf[sizeof("-XX:HeapGrowthLimit=")-1 + PROPERTY_VALUE_MAX];
546    char heapminfreeOptsBuf[sizeof("-XX:HeapMinFree=")-1 + PROPERTY_VALUE_MAX];
547    char heapmaxfreeOptsBuf[sizeof("-XX:HeapMaxFree=")-1 + PROPERTY_VALUE_MAX];
548    char usejitOptsBuf[sizeof("-Xusejit:")-1 + PROPERTY_VALUE_MAX];
549    char jitcodecachesizeOptsBuf[sizeof("-Xjitcodecachesize:")-1 + PROPERTY_VALUE_MAX];
550    char jitthresholdOptsBuf[sizeof("-Xjitthreshold:")-1 + PROPERTY_VALUE_MAX];
551    char gctypeOptsBuf[sizeof("-Xgc:")-1 + PROPERTY_VALUE_MAX];
552    char backgroundgcOptsBuf[sizeof("-XX:BackgroundGC=")-1 + PROPERTY_VALUE_MAX];
553    char heaptargetutilizationOptsBuf[sizeof("-XX:HeapTargetUtilization=")-1 + PROPERTY_VALUE_MAX];
554    char cachePruneBuf[sizeof("-Xzygote-max-boot-retry=")-1 + PROPERTY_VALUE_MAX];
555    char dex2oatXmsImageFlagsBuf[sizeof("-Xms")-1 + PROPERTY_VALUE_MAX];
556    char dex2oatXmxImageFlagsBuf[sizeof("-Xmx")-1 + PROPERTY_VALUE_MAX];
557    char dex2oatXmsFlagsBuf[sizeof("-Xms")-1 + PROPERTY_VALUE_MAX];
558    char dex2oatXmxFlagsBuf[sizeof("-Xmx")-1 + PROPERTY_VALUE_MAX];
559    char dex2oatCompilerFilterBuf[sizeof("--compiler-filter=")-1 + PROPERTY_VALUE_MAX];
560    char dex2oatImageCompilerFilterBuf[sizeof("--compiler-filter=")-1 + PROPERTY_VALUE_MAX];
561    char dex2oatThreadsBuf[sizeof("-j")-1 + PROPERTY_VALUE_MAX];
562    char dex2oatThreadsImageBuf[sizeof("-j")-1 + PROPERTY_VALUE_MAX];
563    char dex2oat_isa_variant_key[PROPERTY_KEY_MAX];
564    char dex2oat_isa_variant[sizeof("--instruction-set-variant=") -1 + PROPERTY_VALUE_MAX];
565    char dex2oat_isa_features_key[PROPERTY_KEY_MAX];
566    char dex2oat_isa_features[sizeof("--instruction-set-features=") -1 + PROPERTY_VALUE_MAX];
567    char dex2oatFlagsBuf[PROPERTY_VALUE_MAX];
568    char dex2oatImageFlagsBuf[PROPERTY_VALUE_MAX];
569    char extraOptsBuf[PROPERTY_VALUE_MAX];
570    char voldDecryptBuf[PROPERTY_VALUE_MAX];
571    enum {
572      kEMDefault,
573      kEMIntPortable,
574      kEMIntFast,
575      kEMJitCompiler,
576    } executionMode = kEMDefault;
577    char profilePeriod[sizeof("-Xprofile-period:")-1 + PROPERTY_VALUE_MAX];
578    char profileDuration[sizeof("-Xprofile-duration:")-1 + PROPERTY_VALUE_MAX];
579    char profileInterval[sizeof("-Xprofile-interval:")-1 + PROPERTY_VALUE_MAX];
580    char profileBackoff[sizeof("-Xprofile-backoff:")-1 + PROPERTY_VALUE_MAX];
581    char profileTopKThreshold[sizeof("-Xprofile-top-k-threshold:")-1 + PROPERTY_VALUE_MAX];
582    char profileTopKChangeThreshold[sizeof("-Xprofile-top-k-change-threshold:")-1 +
583                                    PROPERTY_VALUE_MAX];
584    char profileType[sizeof("-Xprofile-type:")-1 + PROPERTY_VALUE_MAX];
585    char profileMaxStackDepth[sizeof("-Xprofile-max-stack-depth:")-1 + PROPERTY_VALUE_MAX];
586    char localeOption[sizeof("-Duser.locale=") + PROPERTY_VALUE_MAX];
587    char lockProfThresholdBuf[sizeof("-Xlockprofthreshold:")-1 + PROPERTY_VALUE_MAX];
588    char nativeBridgeLibrary[sizeof("-XX:NativeBridge=") + PROPERTY_VALUE_MAX];
589    char cpuAbiListBuf[sizeof("--cpu-abilist=") + PROPERTY_VALUE_MAX];
590    char methodTraceFileBuf[sizeof("-Xmethod-trace-file:") + PROPERTY_VALUE_MAX];
591    char methodTraceFileSizeBuf[sizeof("-Xmethod-trace-file-size:") + PROPERTY_VALUE_MAX];
592    char fingerprintBuf[sizeof("-Xfingerprint:") + PROPERTY_VALUE_MAX];
593
594    bool checkJni = false;
595    property_get("dalvik.vm.checkjni", propBuf, "");
596    if (strcmp(propBuf, "true") == 0) {
597        checkJni = true;
598    } else if (strcmp(propBuf, "false") != 0) {
599        /* property is neither true nor false; fall back on kernel parameter */
600        property_get("ro.kernel.android.checkjni", propBuf, "");
601        if (propBuf[0] == '1') {
602            checkJni = true;
603        }
604    }
605    ALOGD("CheckJNI is %s\n", checkJni ? "ON" : "OFF");
606    if (checkJni) {
607        /* extended JNI checking */
608        addOption("-Xcheck:jni");
609
610        /* with -Xcheck:jni, this provides a JNI function call trace */
611        //addOption("-verbose:jni");
612    }
613
614    property_get("dalvik.vm.execution-mode", propBuf, "");
615    if (strcmp(propBuf, "int:portable") == 0) {
616        executionMode = kEMIntPortable;
617    } else if (strcmp(propBuf, "int:fast") == 0) {
618        executionMode = kEMIntFast;
619    } else if (strcmp(propBuf, "int:jit") == 0) {
620        executionMode = kEMJitCompiler;
621    }
622
623    parseRuntimeOption("dalvik.vm.stack-trace-file", stackTraceFileBuf, "-Xstacktracefile:");
624
625    strcpy(jniOptsBuf, "-Xjniopts:");
626    if (parseRuntimeOption("dalvik.vm.jniopts", jniOptsBuf, "-Xjniopts:")) {
627        ALOGI("JNI options: '%s'\n", jniOptsBuf);
628    }
629
630    /* route exit() to our handler */
631    addOption("exit", (void*) runtime_exit);
632
633    /* route fprintf() to our handler */
634    addOption("vfprintf", (void*) runtime_vfprintf);
635
636    /* register the framework-specific "is sensitive thread" hook */
637    addOption("sensitiveThread", (void*) runtime_isSensitiveThread);
638
639    /* enable verbose; standard options are { jni, gc, class } */
640    //addOption("-verbose:jni");
641    addOption("-verbose:gc");
642    //addOption("-verbose:class");
643
644    /*
645     * The default starting and maximum size of the heap.  Larger
646     * values should be specified in a product property override.
647     */
648    parseRuntimeOption("dalvik.vm.heapstartsize", heapstartsizeOptsBuf, "-Xms", "4m");
649    parseRuntimeOption("dalvik.vm.heapsize", heapsizeOptsBuf, "-Xmx", "16m");
650
651    parseRuntimeOption("dalvik.vm.heapgrowthlimit", heapgrowthlimitOptsBuf, "-XX:HeapGrowthLimit=");
652    parseRuntimeOption("dalvik.vm.heapminfree", heapminfreeOptsBuf, "-XX:HeapMinFree=");
653    parseRuntimeOption("dalvik.vm.heapmaxfree", heapmaxfreeOptsBuf, "-XX:HeapMaxFree=");
654    parseRuntimeOption("dalvik.vm.heaptargetutilization",
655                       heaptargetutilizationOptsBuf,
656                       "-XX:HeapTargetUtilization=");
657
658    /*
659     * JIT related options.
660     */
661    parseRuntimeOption("dalvik.vm.usejit", usejitOptsBuf, "-Xusejit:");
662    parseRuntimeOption("dalvik.vm.jitcodecachesize", jitcodecachesizeOptsBuf, "-Xjitcodecachesize:");
663    parseRuntimeOption("dalvik.vm.jitthreshold", jitthresholdOptsBuf, "-Xjitthreshold:");
664
665    property_get("ro.config.low_ram", propBuf, "");
666    if (strcmp(propBuf, "true") == 0) {
667      addOption("-XX:LowMemoryMode");
668    }
669
670    parseRuntimeOption("dalvik.vm.gctype", gctypeOptsBuf, "-Xgc:");
671    parseRuntimeOption("dalvik.vm.backgroundgctype", backgroundgcOptsBuf, "-XX:BackgroundGC=");
672
673    /* enable debugging; set suspend=y to pause during VM init */
674    /* use android ADB transport */
675    addOption("-agentlib:jdwp=transport=dt_android_adb,suspend=n,server=y");
676
677    parseRuntimeOption("dalvik.vm.lockprof.threshold",
678                       lockProfThresholdBuf,
679                       "-Xlockprofthreshold:");
680
681    if (executionMode == kEMIntPortable) {
682        addOption("-Xint:portable");
683    } else if (executionMode == kEMIntFast) {
684        addOption("-Xint:fast");
685    } else if (executionMode == kEMJitCompiler) {
686        addOption("-Xint:jit");
687    }
688
689    // If we are booting without the real /data, don't spend time compiling.
690    property_get("vold.decrypt", voldDecryptBuf, "");
691    bool skip_compilation = ((strcmp(voldDecryptBuf, "trigger_restart_min_framework") == 0) ||
692                             (strcmp(voldDecryptBuf, "1") == 0));
693
694    // Extra options for boot.art/boot.oat image generation.
695    parseCompilerRuntimeOption("dalvik.vm.image-dex2oat-Xms", dex2oatXmsImageFlagsBuf,
696                               "-Xms", "-Ximage-compiler-option");
697    parseCompilerRuntimeOption("dalvik.vm.image-dex2oat-Xmx", dex2oatXmxImageFlagsBuf,
698                               "-Xmx", "-Ximage-compiler-option");
699    if (skip_compilation) {
700        addOption("-Ximage-compiler-option");
701        addOption("--compiler-filter=verify-none");
702    } else {
703        parseCompilerOption("dalvik.vm.image-dex2oat-filter", dex2oatImageCompilerFilterBuf,
704                            "--compiler-filter=", "-Ximage-compiler-option");
705    }
706
707    // Make sure there is a preloaded-classes file.
708    if (!hasFile("/system/etc/preloaded-classes")) {
709        ALOGE("Missing preloaded-classes file, /system/etc/preloaded-classes not found: %s\n",
710              strerror(errno));
711        return -1;
712    }
713    addOption("-Ximage-compiler-option");
714    addOption("--image-classes=/system/etc/preloaded-classes");
715
716    // If there is a compiled-classes file, push it.
717    if (hasFile("/system/etc/compiled-classes")) {
718        addOption("-Ximage-compiler-option");
719        addOption("--compiled-classes=/system/etc/compiled-classes");
720    }
721
722    property_get("dalvik.vm.image-dex2oat-flags", dex2oatImageFlagsBuf, "");
723    parseExtraOpts(dex2oatImageFlagsBuf, "-Ximage-compiler-option");
724
725    // Extra options for DexClassLoader.
726    parseCompilerRuntimeOption("dalvik.vm.dex2oat-Xms", dex2oatXmsFlagsBuf,
727                               "-Xms", "-Xcompiler-option");
728    parseCompilerRuntimeOption("dalvik.vm.dex2oat-Xmx", dex2oatXmxFlagsBuf,
729                               "-Xmx", "-Xcompiler-option");
730    if (skip_compilation) {
731        addOption("-Xcompiler-option");
732        addOption("--compiler-filter=verify-none");
733
734        // We skip compilation when a minimal runtime is brought up for decryption. In that case
735        // /data is temporarily backed by a tmpfs, which is usually small.
736        // If the system image contains prebuilts, they will be relocated into the tmpfs. In this
737        // specific situation it is acceptable to *not* relocate and run out of the prebuilts
738        // directly instead.
739        addOption("--runtime-arg");
740        addOption("-Xnorelocate");
741    } else {
742        parseCompilerOption("dalvik.vm.dex2oat-filter", dex2oatCompilerFilterBuf,
743                            "--compiler-filter=", "-Xcompiler-option");
744    }
745    parseCompilerOption("dalvik.vm.dex2oat-threads", dex2oatThreadsBuf, "-j", "-Xcompiler-option");
746    parseCompilerOption("dalvik.vm.image-dex2oat-threads", dex2oatThreadsImageBuf, "-j",
747                        "-Ximage-compiler-option");
748
749    // The runtime will compile a boot image, when necessary, not using installd. Thus, we need to
750    // pass the instruction-set-features/variant as an image-compiler-option.
751    // TODO: Find a better way for the instruction-set.
752#if defined(__arm__)
753    constexpr const char* instruction_set = "arm";
754#elif defined(__aarch64__)
755    constexpr const char* instruction_set = "arm64";
756#elif defined(__mips__) && !defined(__LP64__)
757    constexpr const char* instruction_set = "mips";
758#elif defined(__mips__) && defined(__LP64__)
759    constexpr const char* instruction_set = "mips64";
760#elif defined(__i386__)
761    constexpr const char* instruction_set = "x86";
762#elif defined(__x86_64__)
763    constexpr const char* instruction_set = "x86_64";
764#else
765    constexpr const char* instruction_set = "unknown";
766#endif
767    // Note: it is OK to reuse the buffer, as the values are exactly the same between
768    //       * compiler-option, used for runtime compilation (DexClassLoader)
769    //       * image-compiler-option, used for boot-image compilation on device
770
771    // Copy the variant.
772    sprintf(dex2oat_isa_variant_key, "dalvik.vm.isa.%s.variant", instruction_set);
773    parseCompilerOption(dex2oat_isa_variant_key, dex2oat_isa_variant,
774                        "--instruction-set-variant=", "-Ximage-compiler-option");
775    parseCompilerOption(dex2oat_isa_variant_key, dex2oat_isa_variant,
776                        "--instruction-set-variant=", "-Xcompiler-option");
777    // Copy the features.
778    sprintf(dex2oat_isa_features_key, "dalvik.vm.isa.%s.features", instruction_set);
779    parseCompilerOption(dex2oat_isa_features_key, dex2oat_isa_features,
780                        "--instruction-set-features=", "-Ximage-compiler-option");
781    parseCompilerOption(dex2oat_isa_features_key, dex2oat_isa_features,
782                        "--instruction-set-features=", "-Xcompiler-option");
783
784
785    property_get("dalvik.vm.dex2oat-flags", dex2oatFlagsBuf, "");
786    parseExtraOpts(dex2oatFlagsBuf, "-Xcompiler-option");
787
788    /* extra options; parse this late so it overrides others */
789    property_get("dalvik.vm.extra-opts", extraOptsBuf, "");
790    parseExtraOpts(extraOptsBuf, NULL);
791
792    /* Set the properties for locale */
793    {
794        strcpy(localeOption, "-Duser.locale=");
795        readLocale(localeOption);
796        addOption(localeOption);
797    }
798
799    /*
800     * Set profiler options
801     */
802    // Whether or not the profiler should be enabled.
803    property_get("dalvik.vm.profiler", propBuf, "0");
804    if (propBuf[0] == '1') {
805        addOption("-Xenable-profiler");
806    }
807
808    // Whether the profile should start upon app startup or be delayed by some random offset
809    // (in seconds) that is bound between 0 and a fixed value.
810    property_get("dalvik.vm.profile.start-immed", propBuf, "0");
811    if (propBuf[0] == '1') {
812        addOption("-Xprofile-start-immediately");
813    }
814
815    // Number of seconds during profile runs.
816    parseRuntimeOption("dalvik.vm.profile.period-secs", profilePeriod, "-Xprofile-period:");
817
818    // Length of each profile run (seconds).
819    parseRuntimeOption("dalvik.vm.profile.duration-secs",
820                       profileDuration,
821                       "-Xprofile-duration:");
822
823    // Polling interval during profile run (microseconds).
824    parseRuntimeOption("dalvik.vm.profile.interval-us", profileInterval, "-Xprofile-interval:");
825
826    // Coefficient for period backoff.  The the period is multiplied
827    // by this value after each profile run.
828    parseRuntimeOption("dalvik.vm.profile.backoff-coeff", profileBackoff, "-Xprofile-backoff:");
829
830    // Top K% of samples that are considered relevant when
831    // deciding if the app should be recompiled.
832    parseRuntimeOption("dalvik.vm.profile.top-k-thr",
833                       profileTopKThreshold,
834                       "-Xprofile-top-k-threshold:");
835
836    // The threshold after which a change in the structure of the
837    // top K% profiled samples becomes significant and triggers
838    // recompilation. A change in profile is considered
839    // significant if X% (top-k-change-threshold) of the top K%
840    // (top-k-threshold property) samples has changed.
841    parseRuntimeOption("dalvik.vm.profile.top-k-ch-thr",
842                       profileTopKChangeThreshold,
843                       "-Xprofile-top-k-change-threshold:");
844
845    // Type of profile data.
846    parseRuntimeOption("dalvik.vm.profiler.type", profileType, "-Xprofile-type:");
847
848    // Depth of bounded stack data
849    parseRuntimeOption("dalvik.vm.profile.stack-depth",
850                       profileMaxStackDepth,
851                       "-Xprofile-max-stack-depth:");
852
853    /*
854     * Tracing options.
855     */
856    property_get("dalvik.vm.method-trace", propBuf, "false");
857    if (strcmp(propBuf, "true") == 0) {
858        addOption("-Xmethod-trace");
859        parseRuntimeOption("dalvik.vm.method-trace-file",
860                           methodTraceFileBuf,
861                           "-Xmethod-trace-file:");
862        parseRuntimeOption("dalvik.vm.method-trace-file-siz",
863                           methodTraceFileSizeBuf,
864                           "-Xmethod-trace-file-size:");
865        property_get("dalvik.vm.method-trace-stream", propBuf, "false");
866        if (strcmp(propBuf, "true") == 0) {
867            addOption("-Xmethod-trace-stream");
868        }
869    }
870
871    // Native bridge library. "0" means that native bridge is disabled.
872    property_get("ro.dalvik.vm.native.bridge", propBuf, "");
873    if (propBuf[0] == '\0') {
874        ALOGW("ro.dalvik.vm.native.bridge is not expected to be empty");
875    } else if (strcmp(propBuf, "0") != 0) {
876        snprintf(nativeBridgeLibrary, sizeof("-XX:NativeBridge=") + PROPERTY_VALUE_MAX,
877                 "-XX:NativeBridge=%s", propBuf);
878        addOption(nativeBridgeLibrary);
879    }
880
881#if defined(__LP64__)
882    const char* cpu_abilist_property_name = "ro.product.cpu.abilist64";
883#else
884    const char* cpu_abilist_property_name = "ro.product.cpu.abilist32";
885#endif  // defined(__LP64__)
886    property_get(cpu_abilist_property_name, propBuf, "");
887    if (propBuf[0] == '\0') {
888        ALOGE("%s is not expected to be empty", cpu_abilist_property_name);
889        return -1;
890    }
891    snprintf(cpuAbiListBuf, sizeof(cpuAbiListBuf), "--cpu-abilist=%s", propBuf);
892    addOption(cpuAbiListBuf);
893
894    // Dalvik-cache pruning counter.
895    parseRuntimeOption("dalvik.vm.zygote.max-boot-retry", cachePruneBuf,
896                       "-Xzygote-max-boot-retry=");
897
898    /*
899     * When running with debug.generate-debug-info, add --generate-debug-info to
900     * the compiler options so that the boot image, if it is compiled on device,
901     * will include native debugging information.
902     */
903    property_get("debug.generate-debug-info", propBuf, "");
904    if (strcmp(propBuf, "true") == 0) {
905        addOption("-Xcompiler-option");
906        addOption("--generate-debug-info");
907        addOption("-Ximage-compiler-option");
908        addOption("--generate-debug-info");
909    }
910
911    /*
912     * Retrieve the build fingerprint and provide it to the runtime. That way, ANR dumps will
913     * contain the fingerprint and can be parsed.
914     */
915    parseRuntimeOption("ro.build.fingerprint", fingerprintBuf, "-Xfingerprint:");
916
917    initArgs.version = JNI_VERSION_1_4;
918    initArgs.options = mOptions.editArray();
919    initArgs.nOptions = mOptions.size();
920    initArgs.ignoreUnrecognized = JNI_FALSE;
921
922    /*
923     * Initialize the VM.
924     *
925     * The JavaVM* is essentially per-process, and the JNIEnv* is per-thread.
926     * If this call succeeds, the VM is ready, and we can start issuing
927     * JNI calls.
928     */
929    if (JNI_CreateJavaVM(pJavaVM, pEnv, &initArgs) < 0) {
930        ALOGE("JNI_CreateJavaVM failed\n");
931        return -1;
932    }
933
934    return 0;
935}
936
937char* AndroidRuntime::toSlashClassName(const char* className)
938{
939    char* result = strdup(className);
940    for (char* cp = result; *cp != '\0'; cp++) {
941        if (*cp == '.') {
942            *cp = '/';
943        }
944    }
945    return result;
946}
947
948/** Create a Java string from an ASCII or Latin-1 string */
949jstring AndroidRuntime::NewStringLatin1(JNIEnv* env, const char* bytes) {
950    if (!bytes) return NULL;
951    int length = strlen(bytes);
952    jchar* buffer = (jchar *)alloca(length * sizeof(jchar));
953    if (!buffer) return NULL;
954    jchar* chp = buffer;
955    for (int i = 0; i < length; i++) {
956        *chp++ = *bytes++;
957    }
958    return env->NewString(buffer, length);
959}
960
961
962/*
963 * Start the Android runtime.  This involves starting the virtual machine
964 * and calling the "static void main(String[] args)" method in the class
965 * named by "className".
966 *
967 * Passes the main function two arguments, the class name and the specified
968 * options string.
969 */
970void AndroidRuntime::start(const char* className, const Vector<String8>& options)
971{
972    ALOGD(">>>>>> START %s uid %d <<<<<<\n",
973            className != NULL ? className : "(unknown)", getuid());
974
975    static const String8 startSystemServer("start-system-server");
976
977    /*
978     * 'startSystemServer == true' means runtime is obsolete and not run from
979     * init.rc anymore, so we print out the boot start event here.
980     */
981    for (size_t i = 0; i < options.size(); ++i) {
982        if (options[i] == startSystemServer) {
983           /* track our progress through the boot sequence */
984           const int LOG_BOOT_PROGRESS_START = 3000;
985           LOG_EVENT_LONG(LOG_BOOT_PROGRESS_START,  ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
986        }
987    }
988
989    const char* rootDir = getenv("ANDROID_ROOT");
990    if (rootDir == NULL) {
991        rootDir = "/system";
992        if (!hasDir("/system")) {
993            LOG_FATAL("No root directory specified, and /android does not exist.");
994            return;
995        }
996        setenv("ANDROID_ROOT", rootDir, 1);
997    }
998
999    //const char* kernelHack = getenv("LD_ASSUME_KERNEL");
1000    //ALOGD("Found LD_ASSUME_KERNEL='%s'\n", kernelHack);
1001
1002    /* start the virtual machine */
1003    JniInvocation jni_invocation;
1004    jni_invocation.Init(NULL);
1005    JNIEnv* env;
1006    if (startVm(&mJavaVM, &env) != 0) {
1007        return;
1008    }
1009    onVmCreated(env);
1010
1011    /*
1012     * Register android functions.
1013     */
1014    if (startReg(env) < 0) {
1015        ALOGE("Unable to register all android natives\n");
1016        return;
1017    }
1018
1019    /*
1020     * We want to call main() with a String array with arguments in it.
1021     * At present we have two arguments, the class name and an option string.
1022     * Create an array to hold them.
1023     */
1024    jclass stringClass;
1025    jobjectArray strArray;
1026    jstring classNameStr;
1027
1028    stringClass = env->FindClass("java/lang/String");
1029    assert(stringClass != NULL);
1030    strArray = env->NewObjectArray(options.size() + 1, stringClass, NULL);
1031    assert(strArray != NULL);
1032    classNameStr = env->NewStringUTF(className);
1033    assert(classNameStr != NULL);
1034    env->SetObjectArrayElement(strArray, 0, classNameStr);
1035
1036    for (size_t i = 0; i < options.size(); ++i) {
1037        jstring optionsStr = env->NewStringUTF(options.itemAt(i).string());
1038        assert(optionsStr != NULL);
1039        env->SetObjectArrayElement(strArray, i + 1, optionsStr);
1040    }
1041
1042    /*
1043     * Start VM.  This thread becomes the main thread of the VM, and will
1044     * not return until the VM exits.
1045     */
1046    char* slashClassName = toSlashClassName(className);
1047    jclass startClass = env->FindClass(slashClassName);
1048    if (startClass == NULL) {
1049        ALOGE("JavaVM unable to locate class '%s'\n", slashClassName);
1050        /* keep going */
1051    } else {
1052        jmethodID startMeth = env->GetStaticMethodID(startClass, "main",
1053            "([Ljava/lang/String;)V");
1054        if (startMeth == NULL) {
1055            ALOGE("JavaVM unable to find main() in '%s'\n", className);
1056            /* keep going */
1057        } else {
1058            env->CallStaticVoidMethod(startClass, startMeth, strArray);
1059
1060#if 0
1061            if (env->ExceptionCheck())
1062                threadExitUncaughtException(env);
1063#endif
1064        }
1065    }
1066    free(slashClassName);
1067
1068    ALOGD("Shutting down VM\n");
1069    if (mJavaVM->DetachCurrentThread() != JNI_OK)
1070        ALOGW("Warning: unable to detach main thread\n");
1071    if (mJavaVM->DestroyJavaVM() != 0)
1072        ALOGW("Warning: VM did not shut down cleanly\n");
1073}
1074
1075void AndroidRuntime::exit(int code)
1076{
1077    if (mExitWithoutCleanup) {
1078        ALOGI("VM exiting with result code %d, cleanup skipped.", code);
1079        ::_exit(code);
1080    } else {
1081        ALOGI("VM exiting with result code %d.", code);
1082        onExit(code);
1083        ::exit(code);
1084    }
1085}
1086
1087void AndroidRuntime::onVmCreated(JNIEnv* env)
1088{
1089    // If AndroidRuntime had anything to do here, we'd have done it in 'start'.
1090}
1091
1092/*
1093 * Get the JNIEnv pointer for this thread.
1094 *
1095 * Returns NULL if the slot wasn't allocated or populated.
1096 */
1097/*static*/ JNIEnv* AndroidRuntime::getJNIEnv()
1098{
1099    JNIEnv* env;
1100    JavaVM* vm = AndroidRuntime::getJavaVM();
1101    assert(vm != NULL);
1102
1103    if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK)
1104        return NULL;
1105    return env;
1106}
1107
1108/*
1109 * Makes the current thread visible to the VM.
1110 *
1111 * The JNIEnv pointer returned is only valid for the current thread, and
1112 * thus must be tucked into thread-local storage.
1113 */
1114static int javaAttachThread(const char* threadName, JNIEnv** pEnv)
1115{
1116    JavaVMAttachArgs args;
1117    JavaVM* vm;
1118    jint result;
1119
1120    vm = AndroidRuntime::getJavaVM();
1121    assert(vm != NULL);
1122
1123    args.version = JNI_VERSION_1_4;
1124    args.name = (char*) threadName;
1125    args.group = NULL;
1126
1127    result = vm->AttachCurrentThread(pEnv, (void*) &args);
1128    if (result != JNI_OK)
1129        ALOGI("NOTE: attach of thread '%s' failed\n", threadName);
1130
1131    return result;
1132}
1133
1134/*
1135 * Detach the current thread from the set visible to the VM.
1136 */
1137static int javaDetachThread(void)
1138{
1139    JavaVM* vm;
1140    jint result;
1141
1142    vm = AndroidRuntime::getJavaVM();
1143    assert(vm != NULL);
1144
1145    result = vm->DetachCurrentThread();
1146    if (result != JNI_OK)
1147        ALOGE("ERROR: thread detach failed\n");
1148    return result;
1149}
1150
1151/*
1152 * When starting a native thread that will be visible from the VM, we
1153 * bounce through this to get the right attach/detach action.
1154 * Note that this function calls free(args)
1155 */
1156/*static*/ int AndroidRuntime::javaThreadShell(void* args) {
1157    void* start = ((void**)args)[0];
1158    void* userData = ((void **)args)[1];
1159    char* name = (char*) ((void **)args)[2];        // we own this storage
1160    free(args);
1161    JNIEnv* env;
1162    int result;
1163
1164    /* hook us into the VM */
1165    if (javaAttachThread(name, &env) != JNI_OK)
1166        return -1;
1167
1168    /* start the thread running */
1169    result = (*(android_thread_func_t)start)(userData);
1170
1171    /* unhook us */
1172    javaDetachThread();
1173    free(name);
1174
1175    return result;
1176}
1177
1178/*
1179 * This is invoked from androidCreateThreadEtc() via the callback
1180 * set with androidSetCreateThreadFunc().
1181 *
1182 * We need to create the new thread in such a way that it gets hooked
1183 * into the VM before it really starts executing.
1184 */
1185/*static*/ int AndroidRuntime::javaCreateThreadEtc(
1186                                android_thread_func_t entryFunction,
1187                                void* userData,
1188                                const char* threadName,
1189                                int32_t threadPriority,
1190                                size_t threadStackSize,
1191                                android_thread_id_t* threadId)
1192{
1193    void** args = (void**) malloc(3 * sizeof(void*));   // javaThreadShell must free
1194    int result;
1195
1196    if (!threadName)
1197        threadName = "unnamed thread";
1198
1199    args[0] = (void*) entryFunction;
1200    args[1] = userData;
1201    args[2] = (void*) strdup(threadName);   // javaThreadShell must free
1202
1203    result = androidCreateRawThreadEtc(AndroidRuntime::javaThreadShell, args,
1204        threadName, threadPriority, threadStackSize, threadId);
1205    return result;
1206}
1207
1208/*
1209 * Create a thread that is visible from the VM.
1210 *
1211 * This is called from elsewhere in the library.
1212 */
1213/*static*/ android_thread_id_t AndroidRuntime::createJavaThread(const char* name,
1214    void (*start)(void *), void* arg)
1215{
1216    android_thread_id_t threadId = 0;
1217    javaCreateThreadEtc((android_thread_func_t) start, arg, name,
1218        ANDROID_PRIORITY_DEFAULT, 0, &threadId);
1219    return threadId;
1220}
1221
1222#if 0
1223static void quickTest(void* arg)
1224{
1225    const char* str = (const char*) arg;
1226
1227    printf("In quickTest: %s\n", str);
1228}
1229#endif
1230
1231#ifdef NDEBUG
1232    #define REG_JNI(name)      { name }
1233    struct RegJNIRec {
1234        int (*mProc)(JNIEnv*);
1235    };
1236#else
1237    #define REG_JNI(name)      { name, #name }
1238    struct RegJNIRec {
1239        int (*mProc)(JNIEnv*);
1240        const char* mName;
1241    };
1242#endif
1243
1244typedef void (*RegJAMProc)();
1245
1246static int register_jni_procs(const RegJNIRec array[], size_t count, JNIEnv* env)
1247{
1248    for (size_t i = 0; i < count; i++) {
1249        if (array[i].mProc(env) < 0) {
1250#ifndef NDEBUG
1251            ALOGD("----------!!! %s failed to load\n", array[i].mName);
1252#endif
1253            return -1;
1254        }
1255    }
1256    return 0;
1257}
1258
1259static const RegJNIRec gRegJNI[] = {
1260    REG_JNI(register_com_android_internal_os_RuntimeInit),
1261    REG_JNI(register_android_os_SystemClock),
1262    REG_JNI(register_android_util_EventLog),
1263    REG_JNI(register_android_util_Log),
1264    REG_JNI(register_android_content_AssetManager),
1265    REG_JNI(register_android_content_StringBlock),
1266    REG_JNI(register_android_content_XmlBlock),
1267    REG_JNI(register_android_text_AndroidCharacter),
1268    REG_JNI(register_android_text_StaticLayout),
1269    REG_JNI(register_android_text_AndroidBidi),
1270    REG_JNI(register_android_view_InputDevice),
1271    REG_JNI(register_android_view_KeyCharacterMap),
1272    REG_JNI(register_android_os_Process),
1273    REG_JNI(register_android_os_SystemProperties),
1274    REG_JNI(register_android_os_Binder),
1275    REG_JNI(register_android_os_Parcel),
1276    REG_JNI(register_android_nio_utils),
1277    REG_JNI(register_android_graphics_Graphics),
1278    REG_JNI(register_android_view_DisplayEventReceiver),
1279    REG_JNI(register_android_view_RenderNode),
1280    REG_JNI(register_android_view_RenderNodeAnimator),
1281    REG_JNI(register_android_view_GraphicBuffer),
1282    REG_JNI(register_android_view_DisplayListCanvas),
1283    REG_JNI(register_android_view_HardwareLayer),
1284    REG_JNI(register_android_view_ThreadedRenderer),
1285    REG_JNI(register_android_view_Surface),
1286    REG_JNI(register_android_view_SurfaceControl),
1287    REG_JNI(register_android_view_SurfaceSession),
1288    REG_JNI(register_android_view_TextureView),
1289    REG_JNI(register_com_android_internal_view_animation_NativeInterpolatorFactoryHelper),
1290    REG_JNI(register_com_google_android_gles_jni_EGLImpl),
1291    REG_JNI(register_com_google_android_gles_jni_GLImpl),
1292    REG_JNI(register_android_opengl_jni_EGL14),
1293    REG_JNI(register_android_opengl_jni_EGLExt),
1294    REG_JNI(register_android_opengl_jni_GLES10),
1295    REG_JNI(register_android_opengl_jni_GLES10Ext),
1296    REG_JNI(register_android_opengl_jni_GLES11),
1297    REG_JNI(register_android_opengl_jni_GLES11Ext),
1298    REG_JNI(register_android_opengl_jni_GLES20),
1299    REG_JNI(register_android_opengl_jni_GLES30),
1300    REG_JNI(register_android_opengl_jni_GLES31),
1301    REG_JNI(register_android_opengl_jni_GLES31Ext),
1302
1303    REG_JNI(register_android_graphics_Bitmap),
1304    REG_JNI(register_android_graphics_BitmapFactory),
1305    REG_JNI(register_android_graphics_BitmapRegionDecoder),
1306    REG_JNI(register_android_graphics_Camera),
1307    REG_JNI(register_android_graphics_CreateJavaOutputStreamAdaptor),
1308    REG_JNI(register_android_graphics_Canvas),
1309    REG_JNI(register_android_graphics_CanvasProperty),
1310    REG_JNI(register_android_graphics_ColorFilter),
1311    REG_JNI(register_android_graphics_DrawFilter),
1312    REG_JNI(register_android_graphics_FontFamily),
1313    REG_JNI(register_android_graphics_Interpolator),
1314    REG_JNI(register_android_graphics_LayerRasterizer),
1315    REG_JNI(register_android_graphics_MaskFilter),
1316    REG_JNI(register_android_graphics_Matrix),
1317    REG_JNI(register_android_graphics_Movie),
1318    REG_JNI(register_android_graphics_NinePatch),
1319    REG_JNI(register_android_graphics_Paint),
1320    REG_JNI(register_android_graphics_Path),
1321    REG_JNI(register_android_graphics_PathMeasure),
1322    REG_JNI(register_android_graphics_PathEffect),
1323    REG_JNI(register_android_graphics_Picture),
1324    REG_JNI(register_android_graphics_PorterDuff),
1325    REG_JNI(register_android_graphics_Rasterizer),
1326    REG_JNI(register_android_graphics_Region),
1327    REG_JNI(register_android_graphics_Shader),
1328    REG_JNI(register_android_graphics_SurfaceTexture),
1329    REG_JNI(register_android_graphics_Typeface),
1330    REG_JNI(register_android_graphics_Xfermode),
1331    REG_JNI(register_android_graphics_YuvImage),
1332    REG_JNI(register_android_graphics_pdf_PdfDocument),
1333    REG_JNI(register_android_graphics_pdf_PdfEditor),
1334    REG_JNI(register_android_graphics_pdf_PdfRenderer),
1335
1336    REG_JNI(register_android_database_CursorWindow),
1337    REG_JNI(register_android_database_SQLiteConnection),
1338    REG_JNI(register_android_database_SQLiteGlobal),
1339    REG_JNI(register_android_database_SQLiteDebug),
1340    REG_JNI(register_android_os_Debug),
1341    REG_JNI(register_android_os_FileObserver),
1342    REG_JNI(register_android_os_MessageQueue),
1343    REG_JNI(register_android_os_SELinux),
1344    REG_JNI(register_android_os_Trace),
1345    REG_JNI(register_android_os_UEventObserver),
1346    REG_JNI(register_android_net_LocalSocketImpl),
1347    REG_JNI(register_android_net_NetworkUtils),
1348    REG_JNI(register_android_net_TrafficStats),
1349    REG_JNI(register_android_os_MemoryFile),
1350    REG_JNI(register_com_android_internal_os_Zygote),
1351    REG_JNI(register_com_android_internal_util_VirtualRefBasePtr),
1352    REG_JNI(register_android_hardware_Camera),
1353    REG_JNI(register_android_hardware_camera2_CameraMetadata),
1354    REG_JNI(register_android_hardware_camera2_legacy_LegacyCameraDevice),
1355    REG_JNI(register_android_hardware_camera2_legacy_PerfMeasurement),
1356    REG_JNI(register_android_hardware_camera2_DngCreator),
1357    REG_JNI(register_android_hardware_Radio),
1358    REG_JNI(register_android_hardware_SensorManager),
1359    REG_JNI(register_android_hardware_SerialPort),
1360    REG_JNI(register_android_hardware_SoundTrigger),
1361    REG_JNI(register_android_hardware_UsbDevice),
1362    REG_JNI(register_android_hardware_UsbDeviceConnection),
1363    REG_JNI(register_android_hardware_UsbRequest),
1364    REG_JNI(register_android_hardware_location_ActivityRecognitionHardware),
1365    REG_JNI(register_android_media_AudioRecord),
1366    REG_JNI(register_android_media_AudioSystem),
1367    REG_JNI(register_android_media_AudioTrack),
1368    REG_JNI(register_android_media_JetPlayer),
1369    REG_JNI(register_android_media_RemoteDisplay),
1370    REG_JNI(register_android_media_ToneGenerator),
1371
1372    REG_JNI(register_android_opengl_classes),
1373    REG_JNI(register_android_server_NetworkManagementSocketTagger),
1374    REG_JNI(register_android_ddm_DdmHandleNativeHeap),
1375    REG_JNI(register_android_backup_BackupDataInput),
1376    REG_JNI(register_android_backup_BackupDataOutput),
1377    REG_JNI(register_android_backup_FileBackupHelperBase),
1378    REG_JNI(register_android_backup_BackupHelperDispatcher),
1379    REG_JNI(register_android_app_backup_FullBackup),
1380    REG_JNI(register_android_app_ActivityThread),
1381    REG_JNI(register_android_app_NativeActivity),
1382    REG_JNI(register_android_view_InputChannel),
1383    REG_JNI(register_android_view_InputEventReceiver),
1384    REG_JNI(register_android_view_InputEventSender),
1385    REG_JNI(register_android_view_InputQueue),
1386    REG_JNI(register_android_view_KeyEvent),
1387    REG_JNI(register_android_view_MotionEvent),
1388    REG_JNI(register_android_view_PointerIcon),
1389    REG_JNI(register_android_view_VelocityTracker),
1390
1391    REG_JNI(register_android_content_res_ObbScanner),
1392    REG_JNI(register_android_content_res_Configuration),
1393
1394    REG_JNI(register_android_animation_PropertyValuesHolder),
1395    REG_JNI(register_com_android_internal_content_NativeLibraryHelper),
1396    REG_JNI(register_com_android_internal_net_NetworkStatsFactory),
1397};
1398
1399/*
1400 * Register android native functions with the VM.
1401 */
1402/*static*/ int AndroidRuntime::startReg(JNIEnv* env)
1403{
1404    /*
1405     * This hook causes all future threads created in this process to be
1406     * attached to the JavaVM.  (This needs to go away in favor of JNI
1407     * Attach calls.)
1408     */
1409    androidSetCreateThreadFunc((android_create_thread_fn) javaCreateThreadEtc);
1410
1411    ALOGV("--- registering native functions ---\n");
1412
1413    /*
1414     * Every "register" function calls one or more things that return
1415     * a local reference (e.g. FindClass).  Because we haven't really
1416     * started the VM yet, they're all getting stored in the base frame
1417     * and never released.  Use Push/Pop to manage the storage.
1418     */
1419    env->PushLocalFrame(200);
1420
1421    if (register_jni_procs(gRegJNI, NELEM(gRegJNI), env) < 0) {
1422        env->PopLocalFrame(NULL);
1423        return -1;
1424    }
1425    env->PopLocalFrame(NULL);
1426
1427    //createJavaThread("fubar", quickTest, (void*) "hello");
1428
1429    return 0;
1430}
1431
1432AndroidRuntime* AndroidRuntime::getRuntime()
1433{
1434    return gCurRuntime;
1435}
1436
1437/**
1438 * Used by surface flinger's DdmConnection to register native methods from
1439 * the framework.
1440 */
1441extern "C" jint registerFrameworkNatives(JNIEnv* env) {
1442    return register_jni_procs(gRegJNI, NELEM(gRegJNI), env);
1443}
1444}   // namespace android
1445