AndroidRuntime.cpp revision 7de699fb68a5219f6801bf0c978fb9f739e54d3f
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 profile_type[sizeof("-Xprofile-type:") + PROPERTY_VALUE_MAX];
498    char profile_max_stack_depth[sizeof("-Xprofile-max-stack-depth:")+PROPERTY_VALUE_MAX];
499    char langOption[sizeof("-Duser.language=") + 3];
500    char regionOption[sizeof("-Duser.region=") + 3];
501    char lockProfThresholdBuf[sizeof("-Xlockprofthreshold:") + sizeof(propBuf)];
502    char jitOpBuf[sizeof("-Xjitop:") + PROPERTY_VALUE_MAX];
503    char jitMethodBuf[sizeof("-Xjitmethod:") + PROPERTY_VALUE_MAX];
504
505    property_get("dalvik.vm.checkjni", propBuf, "");
506    if (strcmp(propBuf, "true") == 0) {
507        checkJni = true;
508    } else if (strcmp(propBuf, "false") != 0) {
509        /* property is neither true nor false; fall back on kernel parameter */
510        property_get("ro.kernel.android.checkjni", propBuf, "");
511        if (propBuf[0] == '1') {
512            checkJni = true;
513        }
514    }
515
516    property_get("dalvik.vm.execution-mode", propBuf, "");
517    if (strcmp(propBuf, "int:portable") == 0) {
518        executionMode = kEMIntPortable;
519    } else if (strcmp(propBuf, "int:fast") == 0) {
520        executionMode = kEMIntFast;
521    } else if (strcmp(propBuf, "int:jit") == 0) {
522        executionMode = kEMJitCompiler;
523    }
524
525    property_get("dalvik.vm.stack-trace-file", stackTraceFileBuf, "");
526
527    property_get("dalvik.vm.check-dex-sum", propBuf, "");
528    if (strcmp(propBuf, "true") == 0) {
529        checkDexSum = true;
530    }
531
532    property_get("log.redirect-stdio", propBuf, "");
533    if (strcmp(propBuf, "true") == 0) {
534        logStdio = true;
535    }
536
537    strcpy(enableAssertBuf, "-ea:");
538    property_get("dalvik.vm.enableassertions", enableAssertBuf+4, "");
539
540    strcpy(jniOptsBuf, "-Xjniopts:");
541    property_get("dalvik.vm.jniopts", jniOptsBuf+10, "");
542
543    /* route exit() to our handler */
544    opt.extraInfo = (void*) runtime_exit;
545    opt.optionString = "exit";
546    mOptions.add(opt);
547
548    /* route fprintf() to our handler */
549    opt.extraInfo = (void*) runtime_vfprintf;
550    opt.optionString = "vfprintf";
551    mOptions.add(opt);
552
553    /* register the framework-specific "is sensitive thread" hook */
554    opt.extraInfo = (void*) runtime_isSensitiveThread;
555    opt.optionString = "sensitiveThread";
556    mOptions.add(opt);
557
558    opt.extraInfo = NULL;
559
560    /* enable verbose; standard options are { jni, gc, class } */
561    //options[curOpt++].optionString = "-verbose:jni";
562    opt.optionString = "-verbose:gc";
563    mOptions.add(opt);
564    //options[curOpt++].optionString = "-verbose:class";
565
566    /*
567     * The default starting and maximum size of the heap.  Larger
568     * values should be specified in a product property override.
569     */
570    strcpy(heapstartsizeOptsBuf, "-Xms");
571    property_get("dalvik.vm.heapstartsize", heapstartsizeOptsBuf+4, "4m");
572    opt.optionString = heapstartsizeOptsBuf;
573    mOptions.add(opt);
574    strcpy(heapsizeOptsBuf, "-Xmx");
575    property_get("dalvik.vm.heapsize", heapsizeOptsBuf+4, "16m");
576    opt.optionString = heapsizeOptsBuf;
577    mOptions.add(opt);
578
579    // Increase the main thread's interpreter stack size for bug 6315322.
580    opt.optionString = "-XX:mainThreadStackSize=24K";
581    mOptions.add(opt);
582
583    // Set the max jit code cache size.  Note: size of 0 will disable the JIT.
584    strcpy(jitcodecachesizeOptsBuf, "-Xjitcodecachesize:");
585    property_get("dalvik.vm.jit.codecachesize", jitcodecachesizeOptsBuf+19,  NULL);
586    if (jitcodecachesizeOptsBuf[19] != '\0') {
587      opt.optionString = jitcodecachesizeOptsBuf;
588      mOptions.add(opt);
589    }
590
591    strcpy(heapgrowthlimitOptsBuf, "-XX:HeapGrowthLimit=");
592    property_get("dalvik.vm.heapgrowthlimit", heapgrowthlimitOptsBuf+20, "");
593    if (heapgrowthlimitOptsBuf[20] != '\0') {
594        opt.optionString = heapgrowthlimitOptsBuf;
595        mOptions.add(opt);
596    }
597
598    strcpy(heapminfreeOptsBuf, "-XX:HeapMinFree=");
599    property_get("dalvik.vm.heapminfree", heapminfreeOptsBuf+16, "");
600    if (heapminfreeOptsBuf[16] != '\0') {
601        opt.optionString = heapminfreeOptsBuf;
602        mOptions.add(opt);
603    }
604
605    strcpy(heapmaxfreeOptsBuf, "-XX:HeapMaxFree=");
606    property_get("dalvik.vm.heapmaxfree", heapmaxfreeOptsBuf+16, "");
607    if (heapmaxfreeOptsBuf[16] != '\0') {
608        opt.optionString = heapmaxfreeOptsBuf;
609        mOptions.add(opt);
610    }
611
612    strcpy(heaptargetutilizationOptsBuf, "-XX:HeapTargetUtilization=");
613    property_get("dalvik.vm.heaptargetutilization", heaptargetutilizationOptsBuf+26, "");
614    if (heaptargetutilizationOptsBuf[26] != '\0') {
615        opt.optionString = heaptargetutilizationOptsBuf;
616        mOptions.add(opt);
617    }
618
619    property_get("ro.config.low_ram", propBuf, "");
620    if (strcmp(propBuf, "true") == 0) {
621      opt.optionString = "-XX:LowMemoryMode";
622      mOptions.add(opt);
623    }
624
625    strcpy(gctypeOptsBuf, "-Xgc:");
626    property_get("dalvik.vm.gctype", gctypeOptsBuf+5, "");
627    if (gctypeOptsBuf[5] != '\0') {
628        opt.optionString = gctypeOptsBuf;
629        mOptions.add(opt);
630    }
631
632    strcpy(backgroundgcOptsBuf, "-XX:BackgroundGC=");
633    property_get("dalvik.vm.backgroundgctype", backgroundgcOptsBuf+sizeof("-XX:BackgroundGC=")-1, "");
634    if (backgroundgcOptsBuf[sizeof("-XX:BackgroundGC=")-1] != '\0') {
635        opt.optionString = backgroundgcOptsBuf;
636        mOptions.add(opt);
637    }
638
639    /*
640     * Enable or disable dexopt features, such as bytecode verification and
641     * calculation of register maps for precise GC.
642     */
643    property_get("dalvik.vm.dexopt-flags", dexoptFlagsBuf, "");
644    if (dexoptFlagsBuf[0] != '\0') {
645        const char* opc;
646        const char* val;
647
648        opc = strstr(dexoptFlagsBuf, "v=");     /* verification */
649        if (opc != NULL) {
650            switch (*(opc+2)) {
651            case 'n':   val = "-Xverify:none";      break;
652            case 'r':   val = "-Xverify:remote";    break;
653            case 'a':   val = "-Xverify:all";       break;
654            default:    val = NULL;                 break;
655            }
656
657            if (val != NULL) {
658                opt.optionString = val;
659                mOptions.add(opt);
660            }
661        }
662
663        opc = strstr(dexoptFlagsBuf, "o=");     /* optimization */
664        if (opc != NULL) {
665            switch (*(opc+2)) {
666            case 'n':   val = "-Xdexopt:none";      break;
667            case 'v':   val = "-Xdexopt:verified";  break;
668            case 'a':   val = "-Xdexopt:all";       break;
669            case 'f':   val = "-Xdexopt:full";      break;
670            default:    val = NULL;                 break;
671            }
672
673            if (val != NULL) {
674                opt.optionString = val;
675                mOptions.add(opt);
676            }
677        }
678
679        opc = strstr(dexoptFlagsBuf, "m=y");    /* register map */
680        if (opc != NULL) {
681            opt.optionString = "-Xgenregmap";
682            mOptions.add(opt);
683
684            /* turn on precise GC while we're at it */
685            opt.optionString = "-Xgc:precise";
686            mOptions.add(opt);
687        }
688    }
689
690    /* enable debugging; set suspend=y to pause during VM init */
691    /* use android ADB transport */
692    opt.optionString =
693        "-agentlib:jdwp=transport=dt_android_adb,suspend=n,server=y";
694    mOptions.add(opt);
695
696    ALOGD("CheckJNI is %s\n", checkJni ? "ON" : "OFF");
697    if (checkJni) {
698        /* extended JNI checking */
699        opt.optionString = "-Xcheck:jni";
700        mOptions.add(opt);
701
702        /* set a cap on JNI global references */
703        opt.optionString = "-Xjnigreflimit:2000";
704        mOptions.add(opt);
705
706        /* with -Xcheck:jni, this provides a JNI function call trace */
707        //opt.optionString = "-verbose:jni";
708        //mOptions.add(opt);
709    }
710
711    property_get("dalvik.vm.lockprof.threshold", propBuf, "");
712    if (strlen(propBuf) > 0) {
713      strcpy(lockProfThresholdBuf, "-Xlockprofthreshold:");
714      strcat(lockProfThresholdBuf, propBuf);
715      opt.optionString = lockProfThresholdBuf;
716      mOptions.add(opt);
717    }
718
719    /* Force interpreter-only mode for selected opcodes. Eg "1-0a,3c,f1-ff" */
720    property_get("dalvik.vm.jit.op", propBuf, "");
721    if (strlen(propBuf) > 0) {
722        strcpy(jitOpBuf, "-Xjitop:");
723        strcat(jitOpBuf, propBuf);
724        opt.optionString = jitOpBuf;
725        mOptions.add(opt);
726    }
727
728    /* Force interpreter-only mode for selected methods */
729    property_get("dalvik.vm.jit.method", propBuf, "");
730    if (strlen(propBuf) > 0) {
731        strcpy(jitMethodBuf, "-Xjitmethod:");
732        strcat(jitMethodBuf, propBuf);
733        opt.optionString = jitMethodBuf;
734        mOptions.add(opt);
735    }
736
737    if (executionMode == kEMIntPortable) {
738        opt.optionString = "-Xint:portable";
739        mOptions.add(opt);
740    } else if (executionMode == kEMIntFast) {
741        opt.optionString = "-Xint:fast";
742        mOptions.add(opt);
743    } else if (executionMode == kEMJitCompiler) {
744        opt.optionString = "-Xint:jit";
745        mOptions.add(opt);
746    }
747
748    if (checkDexSum) {
749        /* perform additional DEX checksum tests */
750        opt.optionString = "-Xcheckdexsum";
751        mOptions.add(opt);
752    }
753
754    if (logStdio) {
755        /* convert stdout/stderr to log messages */
756        opt.optionString = "-Xlog-stdio";
757        mOptions.add(opt);
758    }
759
760    if (enableAssertBuf[4] != '\0') {
761        /* accept "all" to mean "all classes and packages" */
762        if (strcmp(enableAssertBuf+4, "all") == 0)
763            enableAssertBuf[3] = '\0';
764        ALOGI("Assertions enabled: '%s'\n", enableAssertBuf);
765        opt.optionString = enableAssertBuf;
766        mOptions.add(opt);
767    } else {
768        ALOGV("Assertions disabled\n");
769    }
770
771    if (jniOptsBuf[10] != '\0') {
772        ALOGI("JNI options: '%s'\n", jniOptsBuf);
773        opt.optionString = jniOptsBuf;
774        mOptions.add(opt);
775    }
776
777    if (stackTraceFileBuf[0] != '\0') {
778        static const char* stfOptName = "-Xstacktracefile:";
779
780        stackTraceFile = (char*) malloc(strlen(stfOptName) +
781            strlen(stackTraceFileBuf) +1);
782        strcpy(stackTraceFile, stfOptName);
783        strcat(stackTraceFile, stackTraceFileBuf);
784        opt.optionString = stackTraceFile;
785        mOptions.add(opt);
786    }
787
788    // libart tolerates libdvm flags, but not vice versa, so only pass some options if libart.
789    property_get("persist.sys.dalvik.vm.lib.2", dalvikVmLibBuf, "libart.so");
790    bool libart = (strncmp(dalvikVmLibBuf, "libart", 6) == 0);
791
792    if (libart) {
793        // Extra options for DexClassLoader.
794        property_get("dalvik.vm.dex2oat-flags", dex2oatFlagsBuf, "");
795        parseExtraOpts(dex2oatFlagsBuf, "-Xcompiler-option");
796
797        // Extra options for boot.art/boot.oat image generation.
798        property_get("dalvik.vm.image-dex2oat-flags", dex2oatImageFlagsBuf, "");
799        parseExtraOpts(dex2oatImageFlagsBuf, "-Ximage-compiler-option");
800    }
801
802    /* extra options; parse this late so it overrides others */
803    property_get("dalvik.vm.extra-opts", extraOptsBuf, "");
804    parseExtraOpts(extraOptsBuf, NULL);
805
806    /* Set the properties for locale */
807    {
808        strcpy(langOption, "-Duser.language=");
809        strcpy(regionOption, "-Duser.region=");
810        readLocale(langOption, regionOption);
811        opt.extraInfo = NULL;
812        opt.optionString = langOption;
813        mOptions.add(opt);
814        opt.optionString = regionOption;
815        mOptions.add(opt);
816    }
817
818    /*
819     * Set profiler options
820     */
821    if (libart) {
822        // Whether or not the profiler should be enabled.
823        property_get("dalvik.vm.profiler", propBuf, "0");
824        if (propBuf[0] == '1') {
825            opt.optionString = "-Xenable-profiler";
826            mOptions.add(opt);
827        }
828
829        // Whether the profile should start upon app startup or be delayed by some random offset
830        // (in seconds) that is bound between 0 and a fixed value.
831        property_get("dalvik.vm.profile.start-immed", propBuf, "0");
832        if (propBuf[0] == '1') {
833            opt.optionString = "-Xprofile-start-immediately";
834            mOptions.add(opt);
835        }
836
837        // Number of seconds during profile runs.
838        strcpy(profile_period, "-Xprofile-period:");
839        if (property_get("dalvik.vm.profile.period-secs", profile_period+17, NULL) > 0) {
840           opt.optionString = profile_period;
841           mOptions.add(opt);
842        }
843
844        // Length of each profile run (seconds).
845        strcpy(profile_duration, "-Xprofile-duration:");
846        if (property_get("dalvik.vm.profile.duration-secs", profile_duration+19, NULL) > 0) {
847            opt.optionString = profile_duration;
848            mOptions.add(opt);
849        }
850
851        // Polling interval during profile run (microseconds).
852        strcpy(profile_interval, "-Xprofile-interval:");
853        if (property_get("dalvik.vm.profile.interval-us", profile_interval+19, NULL) > 0) {
854            opt.optionString = profile_interval;
855            mOptions.add(opt);
856        }
857
858        // Coefficient for period backoff.  The the period is multiplied
859        // by this value after each profile run.
860        strcpy(profile_backoff, "-Xprofile-backoff:");
861        if (property_get("dalvik.vm.profile.backoff-coeff", profile_backoff+18, NULL) > 0) {
862            opt.optionString = profile_backoff;
863            mOptions.add(opt);
864        }
865
866        // Top K% of samples that are considered relevant when deciding if the app should be recompiled.
867        strcpy(profile_top_k_threshold, "-Xprofile-top-k-threshold:");
868        if (property_get("dalvik.vm.profile.top-k-thr", profile_top_k_threshold+26, NULL) > 0) {
869            opt.optionString = profile_top_k_threshold;
870            mOptions.add(opt);
871        }
872
873        // The threshold after which a change in the structure of the top K% profiled samples becomes significant
874        // and triggers recompilation. A change in profile is considered significant if X% (top-k-change-threshold)
875        // of the top K% (top-k-threshold property) samples has changed.
876        strcpy(profile_top_k_change_threshold, "-Xprofile-top-k-change-threshold:");
877        if (property_get("dalvik.vm.profile.top-k-ch-thr", profile_top_k_change_threshold+33, NULL) > 0) {
878            opt.optionString = profile_top_k_change_threshold;
879            mOptions.add(opt);
880        }
881
882        // Type of profile data.
883        strcpy(profile_type, "-Xprofile-type:");
884        if (property_get("dalvik.vm.profiler.type", profile_type+15, NULL) > 0) {
885            opt.optionString = profile_type;
886            mOptions.add(opt);
887        }
888
889        // Depth of bounded stack data
890        strcpy(profile_max_stack_depth, "-Xprofile-max-stack-depth:");
891        if (property_get("dalvik.vm.profile.max-stack-depth", profile_max_stack_depth+26, NULL) > 0) {
892           opt.optionString = profile_max_stack_depth;
893           mOptions.add(opt);
894        }
895    }
896
897    initArgs.version = JNI_VERSION_1_4;
898    initArgs.options = mOptions.editArray();
899    initArgs.nOptions = mOptions.size();
900    initArgs.ignoreUnrecognized = JNI_FALSE;
901
902    /*
903     * Initialize the VM.
904     *
905     * The JavaVM* is essentially per-process, and the JNIEnv* is per-thread.
906     * If this call succeeds, the VM is ready, and we can start issuing
907     * JNI calls.
908     */
909    if (JNI_CreateJavaVM(pJavaVM, pEnv, &initArgs) < 0) {
910        ALOGE("JNI_CreateJavaVM failed\n");
911        goto bail;
912    }
913
914    result = 0;
915
916bail:
917    free(stackTraceFile);
918    return result;
919}
920
921char* AndroidRuntime::toSlashClassName(const char* className)
922{
923    char* result = strdup(className);
924    for (char* cp = result; *cp != '\0'; cp++) {
925        if (*cp == '.') {
926            *cp = '/';
927        }
928    }
929    return result;
930}
931
932/*
933 * Start the Android runtime.  This involves starting the virtual machine
934 * and calling the "static void main(String[] args)" method in the class
935 * named by "className".
936 *
937 * Passes the main function two arguments, the class name and the specified
938 * options string.
939 */
940void AndroidRuntime::start(const char* className, const Vector<String8>& options)
941{
942    ALOGD("\n>>>>>> AndroidRuntime START %s <<<<<<\n",
943            className != NULL ? className : "(unknown)");
944
945    static const String8 startSystemServer("start-system-server");
946
947    /*
948     * 'startSystemServer == true' means runtime is obsolete and not run from
949     * init.rc anymore, so we print out the boot start event here.
950     */
951    for (size_t i = 0; i < options.size(); ++i) {
952        if (options[i] == startSystemServer) {
953           /* track our progress through the boot sequence */
954           const int LOG_BOOT_PROGRESS_START = 3000;
955           LOG_EVENT_LONG(LOG_BOOT_PROGRESS_START,  ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
956        }
957    }
958
959    const char* rootDir = getenv("ANDROID_ROOT");
960    if (rootDir == NULL) {
961        rootDir = "/system";
962        if (!hasDir("/system")) {
963            LOG_FATAL("No root directory specified, and /android does not exist.");
964            return;
965        }
966        setenv("ANDROID_ROOT", rootDir, 1);
967    }
968
969    //const char* kernelHack = getenv("LD_ASSUME_KERNEL");
970    //ALOGD("Found LD_ASSUME_KERNEL='%s'\n", kernelHack);
971
972    /* start the virtual machine */
973    JniInvocation jni_invocation;
974    jni_invocation.Init(NULL);
975    JNIEnv* env;
976    if (startVm(&mJavaVM, &env) != 0) {
977        return;
978    }
979    onVmCreated(env);
980
981    /*
982     * Register android functions.
983     */
984    if (startReg(env) < 0) {
985        ALOGE("Unable to register all android natives\n");
986        return;
987    }
988
989    /*
990     * We want to call main() with a String array with arguments in it.
991     * At present we have two arguments, the class name and an option string.
992     * Create an array to hold them.
993     */
994    jclass stringClass;
995    jobjectArray strArray;
996    jstring classNameStr;
997
998    stringClass = env->FindClass("java/lang/String");
999    assert(stringClass != NULL);
1000    strArray = env->NewObjectArray(options.size() + 1, stringClass, NULL);
1001    assert(strArray != NULL);
1002    classNameStr = env->NewStringUTF(className);
1003    assert(classNameStr != NULL);
1004    env->SetObjectArrayElement(strArray, 0, classNameStr);
1005
1006    for (size_t i = 0; i < options.size(); ++i) {
1007        jstring optionsStr = env->NewStringUTF(options.itemAt(i).string());
1008        assert(optionsStr != NULL);
1009        env->SetObjectArrayElement(strArray, i + 1, optionsStr);
1010    }
1011
1012    /*
1013     * Start VM.  This thread becomes the main thread of the VM, and will
1014     * not return until the VM exits.
1015     */
1016    char* slashClassName = toSlashClassName(className);
1017    jclass startClass = env->FindClass(slashClassName);
1018    if (startClass == NULL) {
1019        ALOGE("JavaVM unable to locate class '%s'\n", slashClassName);
1020        /* keep going */
1021    } else {
1022        jmethodID startMeth = env->GetStaticMethodID(startClass, "main",
1023            "([Ljava/lang/String;)V");
1024        if (startMeth == NULL) {
1025            ALOGE("JavaVM unable to find main() in '%s'\n", className);
1026            /* keep going */
1027        } else {
1028            env->CallStaticVoidMethod(startClass, startMeth, strArray);
1029
1030#if 0
1031            if (env->ExceptionCheck())
1032                threadExitUncaughtException(env);
1033#endif
1034        }
1035    }
1036    free(slashClassName);
1037
1038    ALOGD("Shutting down VM\n");
1039    if (mJavaVM->DetachCurrentThread() != JNI_OK)
1040        ALOGW("Warning: unable to detach main thread\n");
1041    if (mJavaVM->DestroyJavaVM() != 0)
1042        ALOGW("Warning: VM did not shut down cleanly\n");
1043}
1044
1045void AndroidRuntime::exit(int code)
1046{
1047    if (mExitWithoutCleanup) {
1048        ALOGI("VM exiting with result code %d, cleanup skipped.", code);
1049        ::_exit(code);
1050    } else {
1051        ALOGI("VM exiting with result code %d.", code);
1052        onExit(code);
1053        ::exit(code);
1054    }
1055}
1056
1057void AndroidRuntime::onVmCreated(JNIEnv* env)
1058{
1059    // If AndroidRuntime had anything to do here, we'd have done it in 'start'.
1060}
1061
1062/*
1063 * Get the JNIEnv pointer for this thread.
1064 *
1065 * Returns NULL if the slot wasn't allocated or populated.
1066 */
1067/*static*/ JNIEnv* AndroidRuntime::getJNIEnv()
1068{
1069    JNIEnv* env;
1070    JavaVM* vm = AndroidRuntime::getJavaVM();
1071    assert(vm != NULL);
1072
1073    if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK)
1074        return NULL;
1075    return env;
1076}
1077
1078/*
1079 * Makes the current thread visible to the VM.
1080 *
1081 * The JNIEnv pointer returned is only valid for the current thread, and
1082 * thus must be tucked into thread-local storage.
1083 */
1084static int javaAttachThread(const char* threadName, JNIEnv** pEnv)
1085{
1086    JavaVMAttachArgs args;
1087    JavaVM* vm;
1088    jint result;
1089
1090    vm = AndroidRuntime::getJavaVM();
1091    assert(vm != NULL);
1092
1093    args.version = JNI_VERSION_1_4;
1094    args.name = (char*) threadName;
1095    args.group = NULL;
1096
1097    result = vm->AttachCurrentThread(pEnv, (void*) &args);
1098    if (result != JNI_OK)
1099        ALOGI("NOTE: attach of thread '%s' failed\n", threadName);
1100
1101    return result;
1102}
1103
1104/*
1105 * Detach the current thread from the set visible to the VM.
1106 */
1107static int javaDetachThread(void)
1108{
1109    JavaVM* vm;
1110    jint result;
1111
1112    vm = AndroidRuntime::getJavaVM();
1113    assert(vm != NULL);
1114
1115    result = vm->DetachCurrentThread();
1116    if (result != JNI_OK)
1117        ALOGE("ERROR: thread detach failed\n");
1118    return result;
1119}
1120
1121/*
1122 * When starting a native thread that will be visible from the VM, we
1123 * bounce through this to get the right attach/detach action.
1124 * Note that this function calls free(args)
1125 */
1126/*static*/ int AndroidRuntime::javaThreadShell(void* args) {
1127    void* start = ((void**)args)[0];
1128    void* userData = ((void **)args)[1];
1129    char* name = (char*) ((void **)args)[2];        // we own this storage
1130    free(args);
1131    JNIEnv* env;
1132    int result;
1133
1134    /* hook us into the VM */
1135    if (javaAttachThread(name, &env) != JNI_OK)
1136        return -1;
1137
1138    /* start the thread running */
1139    result = (*(android_thread_func_t)start)(userData);
1140
1141    /* unhook us */
1142    javaDetachThread();
1143    free(name);
1144
1145    return result;
1146}
1147
1148/*
1149 * This is invoked from androidCreateThreadEtc() via the callback
1150 * set with androidSetCreateThreadFunc().
1151 *
1152 * We need to create the new thread in such a way that it gets hooked
1153 * into the VM before it really starts executing.
1154 */
1155/*static*/ int AndroidRuntime::javaCreateThreadEtc(
1156                                android_thread_func_t entryFunction,
1157                                void* userData,
1158                                const char* threadName,
1159                                int32_t threadPriority,
1160                                size_t threadStackSize,
1161                                android_thread_id_t* threadId)
1162{
1163    void** args = (void**) malloc(3 * sizeof(void*));   // javaThreadShell must free
1164    int result;
1165
1166    if (!threadName)
1167        threadName = "unnamed thread";
1168
1169    args[0] = (void*) entryFunction;
1170    args[1] = userData;
1171    args[2] = (void*) strdup(threadName);   // javaThreadShell must free
1172
1173    result = androidCreateRawThreadEtc(AndroidRuntime::javaThreadShell, args,
1174        threadName, threadPriority, threadStackSize, threadId);
1175    return result;
1176}
1177
1178/*
1179 * Create a thread that is visible from the VM.
1180 *
1181 * This is called from elsewhere in the library.
1182 */
1183/*static*/ android_thread_id_t AndroidRuntime::createJavaThread(const char* name,
1184    void (*start)(void *), void* arg)
1185{
1186    android_thread_id_t threadId = 0;
1187    javaCreateThreadEtc((android_thread_func_t) start, arg, name,
1188        ANDROID_PRIORITY_DEFAULT, 0, &threadId);
1189    return threadId;
1190}
1191
1192#if 0
1193static void quickTest(void* arg)
1194{
1195    const char* str = (const char*) arg;
1196
1197    printf("In quickTest: %s\n", str);
1198}
1199#endif
1200
1201#ifdef NDEBUG
1202    #define REG_JNI(name)      { name }
1203    struct RegJNIRec {
1204        int (*mProc)(JNIEnv*);
1205    };
1206#else
1207    #define REG_JNI(name)      { name, #name }
1208    struct RegJNIRec {
1209        int (*mProc)(JNIEnv*);
1210        const char* mName;
1211    };
1212#endif
1213
1214typedef void (*RegJAMProc)();
1215
1216static int register_jni_procs(const RegJNIRec array[], size_t count, JNIEnv* env)
1217{
1218    for (size_t i = 0; i < count; i++) {
1219        if (array[i].mProc(env) < 0) {
1220#ifndef NDEBUG
1221            ALOGD("----------!!! %s failed to load\n", array[i].mName);
1222#endif
1223            return -1;
1224        }
1225    }
1226    return 0;
1227}
1228
1229static void register_jam_procs(const RegJAMProc array[], size_t count)
1230{
1231    for (size_t i = 0; i < count; i++) {
1232        array[i]();
1233    }
1234}
1235
1236static const RegJNIRec gRegJNI[] = {
1237    REG_JNI(register_com_android_internal_os_RuntimeInit),
1238    REG_JNI(register_android_os_SystemClock),
1239    REG_JNI(register_android_util_EventLog),
1240    REG_JNI(register_android_util_Log),
1241    REG_JNI(register_android_util_FloatMath),
1242    REG_JNI(register_android_text_format_Time),
1243    REG_JNI(register_android_content_AssetManager),
1244    REG_JNI(register_android_content_StringBlock),
1245    REG_JNI(register_android_content_XmlBlock),
1246    REG_JNI(register_android_emoji_EmojiFactory),
1247    REG_JNI(register_android_text_AndroidCharacter),
1248    REG_JNI(register_android_text_StaticLayout),
1249    REG_JNI(register_android_text_AndroidBidi),
1250    REG_JNI(register_android_view_InputDevice),
1251    REG_JNI(register_android_view_KeyCharacterMap),
1252    REG_JNI(register_android_os_Process),
1253    REG_JNI(register_android_os_SystemProperties),
1254    REG_JNI(register_android_os_Binder),
1255    REG_JNI(register_android_os_Parcel),
1256    REG_JNI(register_android_nio_utils),
1257    REG_JNI(register_android_graphics_Graphics),
1258    REG_JNI(register_android_view_DisplayEventReceiver),
1259    REG_JNI(register_android_view_RenderNode),
1260    REG_JNI(register_android_view_RenderNodeAnimator),
1261    REG_JNI(register_android_view_GraphicBuffer),
1262    REG_JNI(register_android_view_GLES20Canvas),
1263    REG_JNI(register_android_view_HardwareLayer),
1264    REG_JNI(register_android_view_ThreadedRenderer),
1265    REG_JNI(register_android_view_Surface),
1266    REG_JNI(register_android_view_SurfaceControl),
1267    REG_JNI(register_android_view_SurfaceSession),
1268    REG_JNI(register_android_view_TextureView),
1269    REG_JNI(register_com_android_internal_view_animation_NativeInterpolatorFactoryHelper),
1270    REG_JNI(register_com_google_android_gles_jni_EGLImpl),
1271    REG_JNI(register_com_google_android_gles_jni_GLImpl),
1272    REG_JNI(register_android_opengl_jni_EGL14),
1273    REG_JNI(register_android_opengl_jni_EGLExt),
1274    REG_JNI(register_android_opengl_jni_GLES10),
1275    REG_JNI(register_android_opengl_jni_GLES10Ext),
1276    REG_JNI(register_android_opengl_jni_GLES11),
1277    REG_JNI(register_android_opengl_jni_GLES11Ext),
1278    REG_JNI(register_android_opengl_jni_GLES20),
1279    REG_JNI(register_android_opengl_jni_GLES30),
1280    REG_JNI(register_android_opengl_jni_GLES31),
1281    REG_JNI(register_android_opengl_jni_GLES31Ext),
1282
1283    REG_JNI(register_android_graphics_Bitmap),
1284    REG_JNI(register_android_graphics_BitmapFactory),
1285    REG_JNI(register_android_graphics_BitmapRegionDecoder),
1286    REG_JNI(register_android_graphics_Camera),
1287    REG_JNI(register_android_graphics_CreateJavaOutputStreamAdaptor),
1288    REG_JNI(register_android_graphics_Canvas),
1289    REG_JNI(register_android_graphics_CanvasProperty),
1290    REG_JNI(register_android_graphics_ColorFilter),
1291    REG_JNI(register_android_graphics_DrawFilter),
1292    REG_JNI(register_android_graphics_FontFamily),
1293    REG_JNI(register_android_graphics_Interpolator),
1294    REG_JNI(register_android_graphics_LayerRasterizer),
1295    REG_JNI(register_android_graphics_MaskFilter),
1296    REG_JNI(register_android_graphics_Matrix),
1297    REG_JNI(register_android_graphics_Movie),
1298    REG_JNI(register_android_graphics_NinePatch),
1299    REG_JNI(register_android_graphics_Paint),
1300    REG_JNI(register_android_graphics_Path),
1301    REG_JNI(register_android_graphics_PathMeasure),
1302    REG_JNI(register_android_graphics_PathEffect),
1303    REG_JNI(register_android_graphics_Picture),
1304    REG_JNI(register_android_graphics_PorterDuff),
1305    REG_JNI(register_android_graphics_Rasterizer),
1306    REG_JNI(register_android_graphics_Region),
1307    REG_JNI(register_android_graphics_Shader),
1308    REG_JNI(register_android_graphics_SurfaceTexture),
1309    REG_JNI(register_android_graphics_Typeface),
1310    REG_JNI(register_android_graphics_Xfermode),
1311    REG_JNI(register_android_graphics_YuvImage),
1312    REG_JNI(register_android_graphics_pdf_PdfDocument),
1313    REG_JNI(register_android_graphics_pdf_PdfRenderer),
1314
1315    REG_JNI(register_android_database_CursorWindow),
1316    REG_JNI(register_android_database_SQLiteConnection),
1317    REG_JNI(register_android_database_SQLiteGlobal),
1318    REG_JNI(register_android_database_SQLiteDebug),
1319    REG_JNI(register_android_os_Debug),
1320    REG_JNI(register_android_os_FileObserver),
1321    REG_JNI(register_android_os_MessageQueue),
1322    REG_JNI(register_android_os_SELinux),
1323    REG_JNI(register_android_os_Trace),
1324    REG_JNI(register_android_os_UEventObserver),
1325    REG_JNI(register_android_net_LocalSocketImpl),
1326    REG_JNI(register_android_net_NetworkUtils),
1327    REG_JNI(register_android_net_TrafficStats),
1328    REG_JNI(register_android_os_MemoryFile),
1329    REG_JNI(register_com_android_internal_os_ZygoteInit),
1330    REG_JNI(register_com_android_internal_os_Zygote),
1331    REG_JNI(register_com_android_internal_util_VirtualRefBasePtr),
1332    REG_JNI(register_android_hardware_Camera),
1333    REG_JNI(register_android_hardware_camera2_CameraMetadata),
1334    REG_JNI(register_android_hardware_camera2_legacy_LegacyCameraDevice),
1335    REG_JNI(register_android_hardware_camera2_DngCreator),
1336    REG_JNI(register_android_hardware_SensorManager),
1337    REG_JNI(register_android_hardware_SerialPort),
1338    REG_JNI(register_android_hardware_SoundTrigger),
1339    REG_JNI(register_android_hardware_UsbDevice),
1340    REG_JNI(register_android_hardware_UsbDeviceConnection),
1341    REG_JNI(register_android_hardware_UsbRequest),
1342    REG_JNI(register_android_media_AudioRecord),
1343    REG_JNI(register_android_media_AudioSystem),
1344    REG_JNI(register_android_media_AudioTrack),
1345    REG_JNI(register_android_media_JetPlayer),
1346    REG_JNI(register_android_media_RemoteDisplay),
1347    REG_JNI(register_android_media_ToneGenerator),
1348
1349    REG_JNI(register_android_opengl_classes),
1350	REG_JNI(register_android_server_fingerprint_FingerprintService),
1351    REG_JNI(register_android_server_NetworkManagementSocketTagger),
1352    REG_JNI(register_android_server_Watchdog),
1353    REG_JNI(register_android_ddm_DdmHandleNativeHeap),
1354    REG_JNI(register_android_backup_BackupDataInput),
1355    REG_JNI(register_android_backup_BackupDataOutput),
1356    REG_JNI(register_android_backup_FileBackupHelperBase),
1357    REG_JNI(register_android_backup_BackupHelperDispatcher),
1358    REG_JNI(register_android_app_backup_FullBackup),
1359    REG_JNI(register_android_app_ActivityThread),
1360    REG_JNI(register_android_app_NativeActivity),
1361    REG_JNI(register_android_view_InputChannel),
1362    REG_JNI(register_android_view_InputEventReceiver),
1363    REG_JNI(register_android_view_InputEventSender),
1364    REG_JNI(register_android_view_InputQueue),
1365    REG_JNI(register_android_view_KeyEvent),
1366    REG_JNI(register_android_view_MotionEvent),
1367    REG_JNI(register_android_view_PointerIcon),
1368    REG_JNI(register_android_view_VelocityTracker),
1369
1370    REG_JNI(register_android_content_res_ObbScanner),
1371    REG_JNI(register_android_content_res_Configuration),
1372
1373    REG_JNI(register_android_animation_PropertyValuesHolder),
1374    REG_JNI(register_com_android_internal_content_NativeLibraryHelper),
1375    REG_JNI(register_com_android_internal_net_NetworkStatsFactory),
1376};
1377
1378/*
1379 * Register android native functions with the VM.
1380 */
1381/*static*/ int AndroidRuntime::startReg(JNIEnv* env)
1382{
1383    /*
1384     * This hook causes all future threads created in this process to be
1385     * attached to the JavaVM.  (This needs to go away in favor of JNI
1386     * Attach calls.)
1387     */
1388    androidSetCreateThreadFunc((android_create_thread_fn) javaCreateThreadEtc);
1389
1390    ALOGV("--- registering native functions ---\n");
1391
1392    /*
1393     * Every "register" function calls one or more things that return
1394     * a local reference (e.g. FindClass).  Because we haven't really
1395     * started the VM yet, they're all getting stored in the base frame
1396     * and never released.  Use Push/Pop to manage the storage.
1397     */
1398    env->PushLocalFrame(200);
1399
1400    if (register_jni_procs(gRegJNI, NELEM(gRegJNI), env) < 0) {
1401        env->PopLocalFrame(NULL);
1402        return -1;
1403    }
1404    env->PopLocalFrame(NULL);
1405
1406    //createJavaThread("fubar", quickTest, (void*) "hello");
1407
1408    return 0;
1409}
1410
1411AndroidRuntime* AndroidRuntime::getRuntime()
1412{
1413    return gCurRuntime;
1414}
1415
1416/**
1417 * Used by WithFramework to register native functions.
1418 */
1419extern "C"
1420jint Java_com_android_internal_util_WithFramework_registerNatives(
1421        JNIEnv* env, jclass clazz) {
1422    return register_jni_procs(gRegJNI, NELEM(gRegJNI), env);
1423}
1424
1425/**
1426 * Used by LoadClass to register native functions.
1427 */
1428extern "C"
1429jint Java_LoadClass_registerNatives(JNIEnv* env, jclass clazz) {
1430    return register_jni_procs(gRegJNI, NELEM(gRegJNI), env);
1431}
1432
1433}   // namespace android
1434