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