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