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