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