AndroidRuntime.cpp revision 62ce332c141cf7bc7200c4c87d63e395874fc3ec
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "AndroidRuntime"
18//#define LOG_NDEBUG 0
19
20#include <android_runtime/AndroidRuntime.h>
21#include <binder/IBinder.h>
22#include <binder/IPCThreadState.h>
23#include <binder/IServiceManager.h>
24#include <utils/Log.h>
25#include <utils/misc.h>
26#include <binder/Parcel.h>
27#include <utils/threads.h>
28#include <cutils/properties.h>
29
30#include <SkGraphics.h>
31#include <SkImageDecoder.h>
32
33#include "jni.h"
34#include "JNIHelp.h"
35#include "JniInvocation.h"
36#include "android_util_Binder.h"
37
38#include <stdio.h>
39#include <signal.h>
40#include <sys/stat.h>
41#include <sys/types.h>
42#include <signal.h>
43#include <dirent.h>
44#include <assert.h>
45
46
47using namespace android;
48
49extern int register_android_os_Binder(JNIEnv* env);
50extern int register_android_os_Process(JNIEnv* env);
51extern int register_android_graphics_Bitmap(JNIEnv*);
52extern int register_android_graphics_BitmapFactory(JNIEnv*);
53extern int register_android_graphics_BitmapRegionDecoder(JNIEnv*);
54extern int register_android_graphics_Camera(JNIEnv* env);
55extern int register_android_graphics_CreateJavaOutputStreamAdaptor(JNIEnv* env);
56extern int register_android_graphics_Graphics(JNIEnv* env);
57extern int register_android_graphics_Interpolator(JNIEnv* env);
58extern int register_android_graphics_MaskFilter(JNIEnv* env);
59extern int register_android_graphics_Movie(JNIEnv* env);
60extern int register_android_graphics_NinePatch(JNIEnv*);
61extern int register_android_graphics_PathEffect(JNIEnv* env);
62extern int register_android_graphics_Shader(JNIEnv* env);
63extern int register_android_graphics_Typeface(JNIEnv* env);
64extern int register_android_graphics_YuvImage(JNIEnv* env);
65
66extern int register_com_google_android_gles_jni_EGLImpl(JNIEnv* env);
67extern int register_com_google_android_gles_jni_GLImpl(JNIEnv* env);
68extern int register_android_opengl_jni_EGL14(JNIEnv* env);
69extern int register_android_opengl_jni_EGLExt(JNIEnv* env);
70extern int register_android_opengl_jni_GLES10(JNIEnv* env);
71extern int register_android_opengl_jni_GLES10Ext(JNIEnv* env);
72extern int register_android_opengl_jni_GLES11(JNIEnv* env);
73extern int register_android_opengl_jni_GLES11Ext(JNIEnv* env);
74extern int register_android_opengl_jni_GLES20(JNIEnv* env);
75extern int register_android_opengl_jni_GLES30(JNIEnv* env);
76extern int register_android_opengl_jni_GLES31(JNIEnv* env);
77extern int register_android_opengl_jni_GLES31Ext(JNIEnv* env);
78
79extern int register_android_hardware_Camera(JNIEnv *env);
80extern int register_android_hardware_camera2_CameraMetadata(JNIEnv *env);
81extern int register_android_hardware_camera2_legacy_LegacyCameraDevice(JNIEnv *env);
82extern int register_android_hardware_camera2_legacy_PerfMeasurement(JNIEnv *env);
83extern int register_android_hardware_camera2_DngCreator(JNIEnv *env);
84extern int register_android_hardware_SensorManager(JNIEnv *env);
85extern int register_android_hardware_SerialPort(JNIEnv *env);
86extern int register_android_hardware_SoundTrigger(JNIEnv *env);
87extern int register_android_hardware_UsbDevice(JNIEnv *env);
88extern int register_android_hardware_UsbDeviceConnection(JNIEnv *env);
89extern int register_android_hardware_UsbRequest(JNIEnv *env);
90extern int register_android_hardware_location_ActivityRecognitionHardware(JNIEnv* env);
91
92extern int register_android_media_AudioRecord(JNIEnv *env);
93extern int register_android_media_AudioSystem(JNIEnv *env);
94extern int register_android_media_AudioTrack(JNIEnv *env);
95extern int register_android_media_JetPlayer(JNIEnv *env);
96extern int register_android_media_ToneGenerator(JNIEnv *env);
97
98extern int register_android_util_FloatMath(JNIEnv* env);
99
100namespace android {
101
102/*
103 * JNI-based registration functions.  Note these are properly contained in
104 * namespace android.
105 */
106extern int register_android_content_AssetManager(JNIEnv* env);
107extern int register_android_util_EventLog(JNIEnv* env);
108extern int register_android_util_Log(JNIEnv* env);
109extern int register_android_content_StringBlock(JNIEnv* env);
110extern int register_android_content_XmlBlock(JNIEnv* env);
111extern int register_android_emoji_EmojiFactory(JNIEnv* env);
112extern int register_android_graphics_Canvas(JNIEnv* env);
113extern int register_android_graphics_CanvasProperty(JNIEnv* env);
114extern int register_android_graphics_ColorFilter(JNIEnv* env);
115extern int register_android_graphics_DrawFilter(JNIEnv* env);
116extern int register_android_graphics_FontFamily(JNIEnv* env);
117extern int register_android_graphics_LayerRasterizer(JNIEnv*);
118extern int register_android_graphics_Matrix(JNIEnv* env);
119extern int register_android_graphics_Paint(JNIEnv* env);
120extern int register_android_graphics_Path(JNIEnv* env);
121extern int register_android_graphics_PathMeasure(JNIEnv* env);
122extern int register_android_graphics_Picture(JNIEnv*);
123extern int register_android_graphics_PorterDuff(JNIEnv* env);
124extern int register_android_graphics_Rasterizer(JNIEnv* env);
125extern int register_android_graphics_Region(JNIEnv* env);
126extern int register_android_graphics_SurfaceTexture(JNIEnv* env);
127extern int register_android_graphics_Xfermode(JNIEnv* env);
128extern int register_android_graphics_pdf_PdfDocument(JNIEnv* env);
129extern int register_android_graphics_pdf_PdfEditor(JNIEnv* env);
130extern int register_android_graphics_pdf_PdfRenderer(JNIEnv* env);
131extern int register_android_view_DisplayEventReceiver(JNIEnv* env);
132extern int register_android_view_RenderNode(JNIEnv* env);
133extern int register_android_view_RenderNodeAnimator(JNIEnv* env);
134extern int register_android_view_GraphicBuffer(JNIEnv* env);
135extern int register_android_view_GLES20Canvas(JNIEnv* env);
136extern int register_android_view_HardwareLayer(JNIEnv* env);
137extern int register_android_view_ThreadedRenderer(JNIEnv* env);
138extern int register_android_view_Surface(JNIEnv* env);
139extern int register_android_view_SurfaceControl(JNIEnv* env);
140extern int register_android_view_SurfaceSession(JNIEnv* env);
141extern int register_android_view_TextureView(JNIEnv* env);
142extern int register_com_android_internal_view_animation_NativeInterpolatorFactoryHelper(JNIEnv *env);
143extern int register_android_database_CursorWindow(JNIEnv* env);
144extern int register_android_database_SQLiteConnection(JNIEnv* env);
145extern int register_android_database_SQLiteGlobal(JNIEnv* env);
146extern int register_android_database_SQLiteDebug(JNIEnv* env);
147extern int register_android_nio_utils(JNIEnv* env);
148extern int register_android_os_Debug(JNIEnv* env);
149extern int register_android_os_MessageQueue(JNIEnv* env);
150extern int register_android_os_Parcel(JNIEnv* env);
151extern int register_android_os_SELinux(JNIEnv* env);
152extern int register_android_os_SystemProperties(JNIEnv *env);
153extern int register_android_os_SystemClock(JNIEnv* env);
154extern int register_android_os_Trace(JNIEnv* env);
155extern int register_android_os_FileObserver(JNIEnv *env);
156extern int register_android_os_UEventObserver(JNIEnv* env);
157extern int register_android_os_MemoryFile(JNIEnv* env);
158extern int register_android_net_LocalSocketImpl(JNIEnv* env);
159extern int register_android_net_NetworkUtils(JNIEnv* env);
160extern int register_android_net_TrafficStats(JNIEnv* env);
161extern int register_android_text_AndroidCharacter(JNIEnv *env);
162extern int register_android_text_StaticLayout(JNIEnv *env);
163extern int register_android_text_AndroidBidi(JNIEnv *env);
164extern int register_android_opengl_classes(JNIEnv *env);
165extern int register_android_ddm_DdmHandleNativeHeap(JNIEnv *env);
166extern int register_android_server_NetworkManagementSocketTagger(JNIEnv* env);
167extern int register_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        addOption(argv[i]);
366    }
367    return i;
368}
369
370static int hasDir(const char* dir)
371{
372    struct stat s;
373    int res = stat(dir, &s);
374    if (res == 0) {
375        return S_ISDIR(s.st_mode);
376    }
377    return 0;
378}
379
380/*
381 * Read the persistent locale.
382 */
383static void readLocale(char* language, char* region)
384{
385    char propLang[PROPERTY_VALUE_MAX], propRegn[PROPERTY_VALUE_MAX];
386
387    property_get("persist.sys.language", propLang, "");
388    property_get("persist.sys.country", propRegn, "");
389    if (*propLang == 0 && *propRegn == 0) {
390        /* Set to ro properties, default is en_US */
391        property_get("ro.product.locale.language", propLang, "en");
392        property_get("ro.product.locale.region", propRegn, "US");
393    }
394    strncat(language, propLang, 3);
395    strncat(region, propRegn, 3);
396    //ALOGD("language=%s region=%s\n", language, region);
397}
398
399void AndroidRuntime::addOption(const char* optionString, void* extraInfo)
400{
401    JavaVMOption opt;
402    opt.optionString = optionString;
403    opt.extraInfo = extraInfo;
404    mOptions.add(opt);
405}
406
407/*
408 * Parse a property containing space-separated options that should be
409 * passed directly to the VM, e.g. "-Xmx32m -verbose:gc -Xregenmap".
410 *
411 * This will cut up "extraOptsBuf" as we chop it into individual options.
412 *
413 * If "quotingArg" is non-null, it is passed before each extra option in mOptions.
414 *
415 * Adds the strings, if any, to mOptions.
416 */
417void AndroidRuntime::parseExtraOpts(char* extraOptsBuf, const char* quotingArg)
418{
419    char* start = extraOptsBuf;
420    char* end = NULL;
421    while (*start != '\0') {
422        while (*start == ' ')                   /* skip leading whitespace */
423            start++;
424        if (*start == '\0')                     /* was trailing ws, bail */
425            break;
426
427        end = start+1;
428        while (*end != ' ' && *end != '\0')     /* find end of token */
429            end++;
430        if (*end == ' ')
431            *end++ = '\0';          /* mark end, advance to indicate more */
432
433        if (quotingArg != NULL) {
434            addOption(quotingArg);
435        }
436        addOption(start);
437        start = end;
438    }
439}
440
441/*
442 * Reads a "property" into "buffer" with a default of "defaultArg". If
443 * the property is non-empty, it is treated as a runtime option such
444 * as "-Xmx32m".
445 *
446 * The "runtimeArg" is a prefix for the option such as "-Xms" or "-Xmx".
447 *
448 * If an argument is found, it is added to mOptions.
449 *
450 * If an option is found, it is added to mOptions and true is
451 * returned. Otherwise false is returned.
452 */
453bool AndroidRuntime::parseRuntimeOption(const char* property,
454                                        char* buffer,
455                                        const char* runtimeArg,
456                                        const char* defaultArg)
457{
458    strcpy(buffer, runtimeArg);
459    size_t runtimeArgLen = strlen(runtimeArg);
460    property_get(property, buffer+runtimeArgLen, defaultArg);
461    if (buffer[runtimeArgLen] == '\0') {
462        return false;
463    }
464    addOption(buffer);
465    return true;
466}
467
468/*
469 * Reads a "property" into "buffer". If the property is non-empty, it
470 * is treated as a dex2oat compiler option that should be
471 * passed as a quoted option, e.g. "-Ximage-compiler-option --compiler-filter=verify-none".
472 *
473 * The "compilerArg" is a prefix for the option such as "--compiler-filter=".
474 *
475 * The "quotingArg" should be "-Ximage-compiler-option" or "-Xcompiler-option".
476 *
477 * If an option is found, it is added to mOptions and true is
478 * returned. Otherwise false is returned.
479 */
480bool AndroidRuntime::parseCompilerOption(const char* property,
481                                         char* buffer,
482                                         const char* compilerArg,
483                                         const char* quotingArg)
484{
485    strcpy(buffer, compilerArg);
486    size_t compilerArgLen = strlen(compilerArg);
487    property_get(property, buffer+compilerArgLen, "");
488    if (buffer[compilerArgLen] == '\0') {
489        return false;
490    }
491    addOption(quotingArg);
492    addOption(buffer);
493    return true;
494}
495
496/*
497 * Reads a "property" into "buffer". If the property is non-empty, it
498 * is treated as a dex2oat compiler runtime option that should be
499 * passed as a quoted option, e.g. "-Ximage-compiler-option
500 * --runtime-arg -Ximage-compiler-option -Xmx32m".
501 *
502 * The "runtimeArg" is a prefix for the option such as "-Xms" or "-Xmx".
503 *
504 * The "quotingArg" should be "-Ximage-compiler-option" or "-Xcompiler-option".
505 *
506 * If an option is found, it is added to mOptions and true is
507 * returned. Otherwise false is returned.
508 */
509bool AndroidRuntime::parseCompilerRuntimeOption(const char* property,
510                                                char* buffer,
511                                                const char* runtimeArg,
512                                                const char* quotingArg)
513{
514    strcpy(buffer, runtimeArg);
515    size_t runtimeArgLen = strlen(runtimeArg);
516    property_get(property, buffer+runtimeArgLen, "");
517    if (buffer[runtimeArgLen] == '\0') {
518        return false;
519    }
520    addOption(quotingArg);
521    addOption("--runtime-arg");
522    addOption(quotingArg);
523    addOption(buffer);
524    return true;
525}
526
527/*
528 * Start the Dalvik Virtual Machine.
529 *
530 * Various arguments, most determined by system properties, are passed in.
531 * The "mOptions" vector is updated.
532 *
533 * CAUTION: when adding options in here, be careful not to put the
534 * char buffer inside a nested scope.  Adding the buffer to the
535 * options using mOptions.add() does not copy the buffer, so if the
536 * buffer goes out of scope the option may be overwritten.  It's best
537 * to put the buffer at the top of the function so that it is more
538 * unlikely that someone will surround it in a scope at a later time
539 * and thus introduce a bug.
540 *
541 * Returns 0 on success.
542 */
543int AndroidRuntime::startVm(JavaVM** pJavaVM, JNIEnv** pEnv)
544{
545    int result = -1;
546    JavaVMInitArgs initArgs;
547    char propBuf[PROPERTY_VALUE_MAX];
548    char stackTraceFileBuf[sizeof("-Xstacktracefile:")-1 + PROPERTY_VALUE_MAX];
549    char dexoptFlagsBuf[PROPERTY_VALUE_MAX];
550    char enableAssertBuf[sizeof("-ea:")-1 + PROPERTY_VALUE_MAX];
551    char jniOptsBuf[sizeof("-Xjniopts:")-1 + PROPERTY_VALUE_MAX];
552    char heapstartsizeOptsBuf[sizeof("-Xms")-1 + PROPERTY_VALUE_MAX];
553    char heapsizeOptsBuf[sizeof("-Xmx")-1 + PROPERTY_VALUE_MAX];
554    char heapgrowthlimitOptsBuf[sizeof("-XX:HeapGrowthLimit=")-1 + PROPERTY_VALUE_MAX];
555    char heapminfreeOptsBuf[sizeof("-XX:HeapMinFree=")-1 + PROPERTY_VALUE_MAX];
556    char heapmaxfreeOptsBuf[sizeof("-XX:HeapMaxFree=")-1 + PROPERTY_VALUE_MAX];
557    char gctypeOptsBuf[sizeof("-Xgc:")-1 + PROPERTY_VALUE_MAX];
558    char backgroundgcOptsBuf[sizeof("-XX:BackgroundGC=")-1 + PROPERTY_VALUE_MAX];
559    char heaptargetutilizationOptsBuf[sizeof("-XX:HeapTargetUtilization=")-1 + PROPERTY_VALUE_MAX];
560    char jitcodecachesizeOptsBuf[sizeof("-Xjitcodecachesize:")-1 + PROPERTY_VALUE_MAX];
561    char dalvikVmLibBuf[PROPERTY_VALUE_MAX];
562    char dex2oatXmsImageFlagsBuf[sizeof("-Xms")-1 + PROPERTY_VALUE_MAX];
563    char dex2oatXmxImageFlagsBuf[sizeof("-Xmx")-1 + PROPERTY_VALUE_MAX];
564    char dex2oatXmsFlagsBuf[sizeof("-Xms")-1 + PROPERTY_VALUE_MAX];
565    char dex2oatXmxFlagsBuf[sizeof("-Xmx")-1 + PROPERTY_VALUE_MAX];
566    char dex2oatCompilerFilterBuf[sizeof("--compiler-filter=")-1 + PROPERTY_VALUE_MAX];
567    char dex2oatImageCompilerFilterBuf[sizeof("--compiler-filter=")-1 + PROPERTY_VALUE_MAX];
568    char dex2oatFlagsBuf[PROPERTY_VALUE_MAX];
569    char dex2oatImageFlagsBuf[PROPERTY_VALUE_MAX];
570    char extraOptsBuf[PROPERTY_VALUE_MAX];
571    char voldDecryptBuf[PROPERTY_VALUE_MAX];
572    enum {
573      kEMDefault,
574      kEMIntPortable,
575      kEMIntFast,
576      kEMJitCompiler,
577    } executionMode = kEMDefault;
578    char profilePeriod[sizeof("-Xprofile-period:")-1 + PROPERTY_VALUE_MAX];
579    char profileDuration[sizeof("-Xprofile-duration:")-1 + PROPERTY_VALUE_MAX];
580    char profileInterval[sizeof("-Xprofile-interval:")-1 + PROPERTY_VALUE_MAX];
581    char profileBackoff[sizeof("-Xprofile-backoff:")-1 + PROPERTY_VALUE_MAX];
582    char profileTopKThreshold[sizeof("-Xprofile-top-k-threshold:")-1 + PROPERTY_VALUE_MAX];
583    char profileTopKChangeThreshold[sizeof("-Xprofile-top-k-change-threshold:")-1 +
584                                    PROPERTY_VALUE_MAX];
585    char profileType[sizeof("-Xprofile-type:")-1 + PROPERTY_VALUE_MAX];
586    char profileMaxStackDepth[sizeof("-Xprofile-max-stack-depth:")-1 + PROPERTY_VALUE_MAX];
587    char langOption[sizeof("-Duser.language=") + 3];
588    char regionOption[sizeof("-Duser.region=") + 3];
589    char lockProfThresholdBuf[sizeof("-Xlockprofthreshold:")-1 + PROPERTY_VALUE_MAX];
590    char jitOpBuf[sizeof("-Xjitop:")-1 + PROPERTY_VALUE_MAX];
591    char jitMethodBuf[sizeof("-Xjitmethod:")-1 + PROPERTY_VALUE_MAX];
592    char nativeBridgeLibrary[sizeof("-XX:NativeBridge=") + PROPERTY_VALUE_MAX];
593
594    bool checkJni = false;
595    property_get("dalvik.vm.checkjni", propBuf, "");
596    if (strcmp(propBuf, "true") == 0) {
597        checkJni = true;
598    } else if (strcmp(propBuf, "false") != 0) {
599        /* property is neither true nor false; fall back on kernel parameter */
600        property_get("ro.kernel.android.checkjni", propBuf, "");
601        if (propBuf[0] == '1') {
602            checkJni = true;
603        }
604    }
605    ALOGD("CheckJNI is %s\n", checkJni ? "ON" : "OFF");
606    if (checkJni) {
607        /* extended JNI checking */
608        addOption("-Xcheck:jni");
609
610        /* set a cap on JNI global references */
611        addOption("-Xjnigreflimit:2000");
612
613        /* with -Xcheck:jni, this provides a JNI function call trace */
614        //addOption("-verbose:jni");
615    }
616
617    property_get("dalvik.vm.execution-mode", propBuf, "");
618    if (strcmp(propBuf, "int:portable") == 0) {
619        executionMode = kEMIntPortable;
620    } else if (strcmp(propBuf, "int:fast") == 0) {
621        executionMode = kEMIntFast;
622    } else if (strcmp(propBuf, "int:jit") == 0) {
623        executionMode = kEMJitCompiler;
624    }
625
626    parseRuntimeOption("dalvik.vm.stack-trace-file", stackTraceFileBuf, "-Xstacktracefile:");
627
628    property_get("dalvik.vm.check-dex-sum", propBuf, "");
629    if (strcmp(propBuf, "true") == 0) {
630        /* perform additional DEX checksum tests */
631        addOption("-Xcheckdexsum");
632    }
633
634    property_get("log.redirect-stdio", propBuf, "");
635    if (strcmp(propBuf, "true") == 0) {
636        /* convert stdout/stderr to log messages */
637        addOption("-Xlog-stdio");
638    }
639
640    strcpy(enableAssertBuf, "-ea:");
641    property_get("dalvik.vm.enableassertions", enableAssertBuf+sizeof("-ea:")-1, "");
642    if (enableAssertBuf[sizeof("-ea:")-1] != '\0') {
643        /* accept "all" to mean "all classes and packages" */
644        if (strcmp(enableAssertBuf+sizeof("-ea:")-1, "all") == 0)
645            enableAssertBuf[3] = '\0'; // truncate to "-ea"
646        ALOGI("Assertions enabled: '%s'\n", enableAssertBuf);
647        addOption(enableAssertBuf);
648    } else {
649        ALOGV("Assertions disabled\n");
650    }
651
652    strcpy(jniOptsBuf, "-Xjniopts:");
653    if (parseRuntimeOption("dalvik.vm.jniopts", jniOptsBuf, "-Xjniopts:")) {
654        ALOGI("JNI options: '%s'\n", jniOptsBuf);
655    }
656
657    /* route exit() to our handler */
658    addOption("exit", (void*) runtime_exit);
659
660    /* route fprintf() to our handler */
661    addOption("vfprintf", (void*) runtime_vfprintf);
662
663    /* register the framework-specific "is sensitive thread" hook */
664    addOption("sensitiveThread", (void*) runtime_isSensitiveThread);
665
666    /* enable verbose; standard options are { jni, gc, class } */
667    //addOption("-verbose:jni");
668    addOption("-verbose:gc");
669    //addOption("-verbose:class");
670
671    /*
672     * The default starting and maximum size of the heap.  Larger
673     * values should be specified in a product property override.
674     */
675    parseRuntimeOption("dalvik.vm.heapstartsize", heapstartsizeOptsBuf, "-Xms", "4m");
676    parseRuntimeOption("dalvik.vm.heapsize", heapsizeOptsBuf, "-Xmx", "16m");
677
678    // Increase the main thread's interpreter stack size for bug 6315322.
679    addOption("-XX:mainThreadStackSize=24K");
680
681    // Set the max jit code cache size.  Note: size of 0 will disable the JIT.
682    parseRuntimeOption("dalvik.vm.jit.codecachesize",
683                       jitcodecachesizeOptsBuf,
684                       "-Xjitcodecachesize:");
685
686    parseRuntimeOption("dalvik.vm.heapgrowthlimit", heapgrowthlimitOptsBuf, "-XX:HeapGrowthLimit=");
687    parseRuntimeOption("dalvik.vm.heapminfree", heapminfreeOptsBuf, "-XX:HeapMinFree=");
688    parseRuntimeOption("dalvik.vm.heapmaxfree", heapmaxfreeOptsBuf, "-XX:HeapMaxFree=");
689    parseRuntimeOption("dalvik.vm.heaptargetutilization",
690                       heaptargetutilizationOptsBuf,
691                       "-XX:HeapTargetUtilization=");
692
693    property_get("ro.config.low_ram", propBuf, "");
694    if (strcmp(propBuf, "true") == 0) {
695      addOption("-XX:LowMemoryMode");
696    }
697
698    parseRuntimeOption("dalvik.vm.gctype", gctypeOptsBuf, "-Xgc:");
699    parseRuntimeOption("dalvik.vm.backgroundgctype", backgroundgcOptsBuf, "-XX:BackgroundGC=");
700
701    /*
702     * Enable or disable dexopt features, such as bytecode verification and
703     * calculation of register maps for precise GC.
704     */
705    property_get("dalvik.vm.dexopt-flags", dexoptFlagsBuf, "");
706    if (dexoptFlagsBuf[0] != '\0') {
707        const char* opc;
708        const char* val;
709
710        opc = strstr(dexoptFlagsBuf, "v=");     /* verification */
711        if (opc != NULL) {
712            switch (*(opc+2)) {
713            case 'n':   val = "-Xverify:none";      break;
714            case 'r':   val = "-Xverify:remote";    break;
715            case 'a':   val = "-Xverify:all";       break;
716            default:    val = NULL;                 break;
717            }
718
719            if (val != NULL) {
720                addOption(val);
721            }
722        }
723
724        opc = strstr(dexoptFlagsBuf, "o=");     /* optimization */
725        if (opc != NULL) {
726            switch (*(opc+2)) {
727            case 'n':   val = "-Xdexopt:none";      break;
728            case 'v':   val = "-Xdexopt:verified";  break;
729            case 'a':   val = "-Xdexopt:all";       break;
730            case 'f':   val = "-Xdexopt:full";      break;
731            default:    val = NULL;                 break;
732            }
733
734            if (val != NULL) {
735                addOption(val);
736            }
737        }
738
739        opc = strstr(dexoptFlagsBuf, "m=y");    /* register map */
740        if (opc != NULL) {
741            addOption("-Xgenregmap");
742
743            /* turn on precise GC while we're at it */
744            addOption("-Xgc:precise");
745        }
746    }
747
748    /* enable debugging; set suspend=y to pause during VM init */
749    /* use android ADB transport */
750    addOption("-agentlib:jdwp=transport=dt_android_adb,suspend=n,server=y");
751
752    parseRuntimeOption("dalvik.vm.lockprof.threshold",
753                       lockProfThresholdBuf,
754                       "-Xlockprofthreshold:");
755
756    /* Force interpreter-only mode for selected opcodes. Eg "1-0a,3c,f1-ff" */
757    parseRuntimeOption("dalvik.vm.jit.op", jitOpBuf, "-Xjitop:");
758
759    /* Force interpreter-only mode for selected methods */
760    parseRuntimeOption("dalvik.vm.jit.method", jitMethodBuf, "-Xjitmethod:");
761
762    if (executionMode == kEMIntPortable) {
763        addOption("-Xint:portable");
764    } else if (executionMode == kEMIntFast) {
765        addOption("-Xint:fast");
766    } else if (executionMode == kEMJitCompiler) {
767        addOption("-Xint:jit");
768    }
769
770    // libart tolerates libdvm flags, but not vice versa, so only pass some options if libart.
771    property_get("persist.sys.dalvik.vm.lib.2", dalvikVmLibBuf, "libart.so");
772    bool libart = (strncmp(dalvikVmLibBuf, "libart", 6) == 0);
773
774    if (libart) {
775        // If we booting without the real /data, don't spend time compiling.
776        property_get("vold.decrypt", voldDecryptBuf, "");
777        bool skip_compilation = ((strcmp(voldDecryptBuf, "trigger_restart_min_framework") == 0) ||
778                                 (strcmp(voldDecryptBuf, "1") == 0));
779
780        // Extra options for boot.art/boot.oat image generation.
781        parseCompilerRuntimeOption("dalvik.vm.image-dex2oat-Xms", dex2oatXmsImageFlagsBuf,
782                                   "-Xms", "-Ximage-compiler-option");
783        parseCompilerRuntimeOption("dalvik.vm.image-dex2oat-Xmx", dex2oatXmxImageFlagsBuf,
784                                   "-Xmx", "-Ximage-compiler-option");
785        if (skip_compilation) {
786            addOption("-Ximage-compiler-option");
787            addOption("--compiler-filter=verify-none");
788        } else {
789            parseCompilerOption("dalvik.vm.image-dex2oat-filter", dex2oatImageCompilerFilterBuf,
790                                "--compiler-filter=", "-Ximage-compiler-option");
791        }
792        addOption("-Ximage-compiler-option");
793        addOption("--image-classes-zip=/system/framework/framework.jar");
794        addOption("-Ximage-compiler-option");
795        addOption("--image-classes=preloaded-classes");
796        property_get("dalvik.vm.image-dex2oat-flags", dex2oatImageFlagsBuf, "");
797        parseExtraOpts(dex2oatImageFlagsBuf, "-Ximage-compiler-option");
798
799        // Extra options for DexClassLoader.
800        parseCompilerRuntimeOption("dalvik.vm.dex2oat-Xms", dex2oatXmsFlagsBuf,
801                                   "-Xms", "-Xcompiler-option");
802        parseCompilerRuntimeOption("dalvik.vm.dex2oat-Xmx", dex2oatXmxFlagsBuf,
803                                   "-Xmx", "-Xcompiler-option");
804        if (skip_compilation) {
805            addOption("-Xcompiler-option");
806            addOption("--compiler-filter=verify-none");
807        } else {
808            parseCompilerOption("dalvik.vm.dex2oat-filter", dex2oatCompilerFilterBuf,
809                                "--compiler-filter=", "-Xcompiler-option");
810        }
811        property_get("dalvik.vm.dex2oat-flags", dex2oatFlagsBuf, "");
812        parseExtraOpts(dex2oatFlagsBuf, "-Xcompiler-option");
813
814    }
815
816    /* extra options; parse this late so it overrides others */
817    property_get("dalvik.vm.extra-opts", extraOptsBuf, "");
818    parseExtraOpts(extraOptsBuf, NULL);
819
820    /* Set the properties for locale */
821    {
822        strcpy(langOption, "-Duser.language=");
823        strcpy(regionOption, "-Duser.region=");
824        readLocale(langOption, regionOption);
825        addOption(langOption);
826        addOption(regionOption);
827    }
828
829    /*
830     * Set profiler options
831     */
832    if (libart) {
833        // Whether or not the profiler should be enabled.
834        property_get("dalvik.vm.profiler", propBuf, "0");
835        if (propBuf[0] == '1') {
836            addOption("-Xenable-profiler");
837        }
838
839        // Whether the profile should start upon app startup or be delayed by some random offset
840        // (in seconds) that is bound between 0 and a fixed value.
841        property_get("dalvik.vm.profile.start-immed", propBuf, "0");
842        if (propBuf[0] == '1') {
843            addOption("-Xprofile-start-immediately");
844        }
845
846        // Number of seconds during profile runs.
847        parseRuntimeOption("dalvik.vm.profile.period-secs", profilePeriod, "-Xprofile-period:");
848
849        // Length of each profile run (seconds).
850        parseRuntimeOption("dalvik.vm.profile.duration-secs",
851                           profileDuration,
852                           "-Xprofile-duration:");
853
854        // Polling interval during profile run (microseconds).
855        parseRuntimeOption("dalvik.vm.profile.interval-us", profileInterval, "-Xprofile-interval:");
856
857        // Coefficient for period backoff.  The the period is multiplied
858        // by this value after each profile run.
859        parseRuntimeOption("dalvik.vm.profile.backoff-coeff", profileBackoff, "-Xprofile-backoff:");
860
861        // Top K% of samples that are considered relevant when
862        // deciding if the app should be recompiled.
863        parseRuntimeOption("dalvik.vm.profile.top-k-thr",
864                           profileTopKThreshold,
865                           "-Xprofile-top-k-threshold:");
866
867        // The threshold after which a change in the structure of the
868        // top K% profiled samples becomes significant and triggers
869        // recompilation. A change in profile is considered
870        // significant if X% (top-k-change-threshold) of the top K%
871        // (top-k-threshold property) samples has changed.
872        parseRuntimeOption("dalvik.vm.profile.top-k-ch-thr",
873                           profileTopKChangeThreshold,
874                           "-Xprofile-top-k-change-threshold:");
875
876        // Type of profile data.
877        parseRuntimeOption("dalvik.vm.profiler.type", profileType, "-Xprofile-type:");
878
879        // Depth of bounded stack data
880        parseRuntimeOption("dalvik.vm.profile.max-stack-depth",
881                           profileMaxStackDepth,
882                           "-Xprofile-max-stack-depth:");
883
884        // Native bridge library. "0" means that native bridge is disabled.
885        property_get("ro.dalvik.vm.native.bridge", propBuf, "");
886        if (propBuf[0] == '\0') {
887            ALOGW("ro.dalvik.vm.native.bridge is not expected to be empty");
888        } else if (strcmp(propBuf, "0") != 0) {
889            snprintf(nativeBridgeLibrary, sizeof("-XX:NativeBridge=") + PROPERTY_VALUE_MAX,
890                     "-XX:NativeBridge=%s", propBuf);
891            addOption(nativeBridgeLibrary);
892        }
893    }
894
895    initArgs.version = JNI_VERSION_1_4;
896    initArgs.options = mOptions.editArray();
897    initArgs.nOptions = mOptions.size();
898    initArgs.ignoreUnrecognized = JNI_FALSE;
899
900    /*
901     * Initialize the VM.
902     *
903     * The JavaVM* is essentially per-process, and the JNIEnv* is per-thread.
904     * If this call succeeds, the VM is ready, and we can start issuing
905     * JNI calls.
906     */
907    if (JNI_CreateJavaVM(pJavaVM, pEnv, &initArgs) < 0) {
908        ALOGE("JNI_CreateJavaVM failed\n");
909        goto bail;
910    }
911
912    result = 0;
913
914bail:
915    return result;
916}
917
918char* AndroidRuntime::toSlashClassName(const char* className)
919{
920    char* result = strdup(className);
921    for (char* cp = result; *cp != '\0'; cp++) {
922        if (*cp == '.') {
923            *cp = '/';
924        }
925    }
926    return result;
927}
928
929/*
930 * Start the Android runtime.  This involves starting the virtual machine
931 * and calling the "static void main(String[] args)" method in the class
932 * named by "className".
933 *
934 * Passes the main function two arguments, the class name and the specified
935 * options string.
936 */
937void AndroidRuntime::start(const char* className, const Vector<String8>& options)
938{
939    ALOGD("\n>>>>>> AndroidRuntime START %s <<<<<<\n",
940            className != NULL ? className : "(unknown)");
941
942    static const String8 startSystemServer("start-system-server");
943
944    /*
945     * 'startSystemServer == true' means runtime is obsolete and not run from
946     * init.rc anymore, so we print out the boot start event here.
947     */
948    for (size_t i = 0; i < options.size(); ++i) {
949        if (options[i] == startSystemServer) {
950           /* track our progress through the boot sequence */
951           const int LOG_BOOT_PROGRESS_START = 3000;
952           LOG_EVENT_LONG(LOG_BOOT_PROGRESS_START,  ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
953        }
954    }
955
956    const char* rootDir = getenv("ANDROID_ROOT");
957    if (rootDir == NULL) {
958        rootDir = "/system";
959        if (!hasDir("/system")) {
960            LOG_FATAL("No root directory specified, and /android does not exist.");
961            return;
962        }
963        setenv("ANDROID_ROOT", rootDir, 1);
964    }
965
966    //const char* kernelHack = getenv("LD_ASSUME_KERNEL");
967    //ALOGD("Found LD_ASSUME_KERNEL='%s'\n", kernelHack);
968
969    /* start the virtual machine */
970    JniInvocation jni_invocation;
971    jni_invocation.Init(NULL);
972    JNIEnv* env;
973    if (startVm(&mJavaVM, &env) != 0) {
974        return;
975    }
976    onVmCreated(env);
977
978    /*
979     * Register android functions.
980     */
981    if (startReg(env) < 0) {
982        ALOGE("Unable to register all android natives\n");
983        return;
984    }
985
986    /*
987     * We want to call main() with a String array with arguments in it.
988     * At present we have two arguments, the class name and an option string.
989     * Create an array to hold them.
990     */
991    jclass stringClass;
992    jobjectArray strArray;
993    jstring classNameStr;
994
995    stringClass = env->FindClass("java/lang/String");
996    assert(stringClass != NULL);
997    strArray = env->NewObjectArray(options.size() + 1, stringClass, NULL);
998    assert(strArray != NULL);
999    classNameStr = env->NewStringUTF(className);
1000    assert(classNameStr != NULL);
1001    env->SetObjectArrayElement(strArray, 0, classNameStr);
1002
1003    for (size_t i = 0; i < options.size(); ++i) {
1004        jstring optionsStr = env->NewStringUTF(options.itemAt(i).string());
1005        assert(optionsStr != NULL);
1006        env->SetObjectArrayElement(strArray, i + 1, optionsStr);
1007    }
1008
1009    /*
1010     * Start VM.  This thread becomes the main thread of the VM, and will
1011     * not return until the VM exits.
1012     */
1013    char* slashClassName = toSlashClassName(className);
1014    jclass startClass = env->FindClass(slashClassName);
1015    if (startClass == NULL) {
1016        ALOGE("JavaVM unable to locate class '%s'\n", slashClassName);
1017        /* keep going */
1018    } else {
1019        jmethodID startMeth = env->GetStaticMethodID(startClass, "main",
1020            "([Ljava/lang/String;)V");
1021        if (startMeth == NULL) {
1022            ALOGE("JavaVM unable to find main() in '%s'\n", className);
1023            /* keep going */
1024        } else {
1025            env->CallStaticVoidMethod(startClass, startMeth, strArray);
1026
1027#if 0
1028            if (env->ExceptionCheck())
1029                threadExitUncaughtException(env);
1030#endif
1031        }
1032    }
1033    free(slashClassName);
1034
1035    ALOGD("Shutting down VM\n");
1036    if (mJavaVM->DetachCurrentThread() != JNI_OK)
1037        ALOGW("Warning: unable to detach main thread\n");
1038    if (mJavaVM->DestroyJavaVM() != 0)
1039        ALOGW("Warning: VM did not shut down cleanly\n");
1040}
1041
1042void AndroidRuntime::exit(int code)
1043{
1044    if (mExitWithoutCleanup) {
1045        ALOGI("VM exiting with result code %d, cleanup skipped.", code);
1046        ::_exit(code);
1047    } else {
1048        ALOGI("VM exiting with result code %d.", code);
1049        onExit(code);
1050        ::exit(code);
1051    }
1052}
1053
1054void AndroidRuntime::onVmCreated(JNIEnv* env)
1055{
1056    // If AndroidRuntime had anything to do here, we'd have done it in 'start'.
1057}
1058
1059/*
1060 * Get the JNIEnv pointer for this thread.
1061 *
1062 * Returns NULL if the slot wasn't allocated or populated.
1063 */
1064/*static*/ JNIEnv* AndroidRuntime::getJNIEnv()
1065{
1066    JNIEnv* env;
1067    JavaVM* vm = AndroidRuntime::getJavaVM();
1068    assert(vm != NULL);
1069
1070    if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK)
1071        return NULL;
1072    return env;
1073}
1074
1075/*
1076 * Makes the current thread visible to the VM.
1077 *
1078 * The JNIEnv pointer returned is only valid for the current thread, and
1079 * thus must be tucked into thread-local storage.
1080 */
1081static int javaAttachThread(const char* threadName, JNIEnv** pEnv)
1082{
1083    JavaVMAttachArgs args;
1084    JavaVM* vm;
1085    jint result;
1086
1087    vm = AndroidRuntime::getJavaVM();
1088    assert(vm != NULL);
1089
1090    args.version = JNI_VERSION_1_4;
1091    args.name = (char*) threadName;
1092    args.group = NULL;
1093
1094    result = vm->AttachCurrentThread(pEnv, (void*) &args);
1095    if (result != JNI_OK)
1096        ALOGI("NOTE: attach of thread '%s' failed\n", threadName);
1097
1098    return result;
1099}
1100
1101/*
1102 * Detach the current thread from the set visible to the VM.
1103 */
1104static int javaDetachThread(void)
1105{
1106    JavaVM* vm;
1107    jint result;
1108
1109    vm = AndroidRuntime::getJavaVM();
1110    assert(vm != NULL);
1111
1112    result = vm->DetachCurrentThread();
1113    if (result != JNI_OK)
1114        ALOGE("ERROR: thread detach failed\n");
1115    return result;
1116}
1117
1118/*
1119 * When starting a native thread that will be visible from the VM, we
1120 * bounce through this to get the right attach/detach action.
1121 * Note that this function calls free(args)
1122 */
1123/*static*/ int AndroidRuntime::javaThreadShell(void* args) {
1124    void* start = ((void**)args)[0];
1125    void* userData = ((void **)args)[1];
1126    char* name = (char*) ((void **)args)[2];        // we own this storage
1127    free(args);
1128    JNIEnv* env;
1129    int result;
1130
1131    /* hook us into the VM */
1132    if (javaAttachThread(name, &env) != JNI_OK)
1133        return -1;
1134
1135    /* start the thread running */
1136    result = (*(android_thread_func_t)start)(userData);
1137
1138    /* unhook us */
1139    javaDetachThread();
1140    free(name);
1141
1142    return result;
1143}
1144
1145/*
1146 * This is invoked from androidCreateThreadEtc() via the callback
1147 * set with androidSetCreateThreadFunc().
1148 *
1149 * We need to create the new thread in such a way that it gets hooked
1150 * into the VM before it really starts executing.
1151 */
1152/*static*/ int AndroidRuntime::javaCreateThreadEtc(
1153                                android_thread_func_t entryFunction,
1154                                void* userData,
1155                                const char* threadName,
1156                                int32_t threadPriority,
1157                                size_t threadStackSize,
1158                                android_thread_id_t* threadId)
1159{
1160    void** args = (void**) malloc(3 * sizeof(void*));   // javaThreadShell must free
1161    int result;
1162
1163    if (!threadName)
1164        threadName = "unnamed thread";
1165
1166    args[0] = (void*) entryFunction;
1167    args[1] = userData;
1168    args[2] = (void*) strdup(threadName);   // javaThreadShell must free
1169
1170    result = androidCreateRawThreadEtc(AndroidRuntime::javaThreadShell, args,
1171        threadName, threadPriority, threadStackSize, threadId);
1172    return result;
1173}
1174
1175/*
1176 * Create a thread that is visible from the VM.
1177 *
1178 * This is called from elsewhere in the library.
1179 */
1180/*static*/ android_thread_id_t AndroidRuntime::createJavaThread(const char* name,
1181    void (*start)(void *), void* arg)
1182{
1183    android_thread_id_t threadId = 0;
1184    javaCreateThreadEtc((android_thread_func_t) start, arg, name,
1185        ANDROID_PRIORITY_DEFAULT, 0, &threadId);
1186    return threadId;
1187}
1188
1189#if 0
1190static void quickTest(void* arg)
1191{
1192    const char* str = (const char*) arg;
1193
1194    printf("In quickTest: %s\n", str);
1195}
1196#endif
1197
1198#ifdef NDEBUG
1199    #define REG_JNI(name)      { name }
1200    struct RegJNIRec {
1201        int (*mProc)(JNIEnv*);
1202    };
1203#else
1204    #define REG_JNI(name)      { name, #name }
1205    struct RegJNIRec {
1206        int (*mProc)(JNIEnv*);
1207        const char* mName;
1208    };
1209#endif
1210
1211typedef void (*RegJAMProc)();
1212
1213static int register_jni_procs(const RegJNIRec array[], size_t count, JNIEnv* env)
1214{
1215    for (size_t i = 0; i < count; i++) {
1216        if (array[i].mProc(env) < 0) {
1217#ifndef NDEBUG
1218            ALOGD("----------!!! %s failed to load\n", array[i].mName);
1219#endif
1220            return -1;
1221        }
1222    }
1223    return 0;
1224}
1225
1226static void register_jam_procs(const RegJAMProc array[], size_t count)
1227{
1228    for (size_t i = 0; i < count; i++) {
1229        array[i]();
1230    }
1231}
1232
1233static const RegJNIRec gRegJNI[] = {
1234    REG_JNI(register_com_android_internal_os_RuntimeInit),
1235    REG_JNI(register_android_os_SystemClock),
1236    REG_JNI(register_android_util_EventLog),
1237    REG_JNI(register_android_util_Log),
1238    REG_JNI(register_android_util_FloatMath),
1239    REG_JNI(register_android_content_AssetManager),
1240    REG_JNI(register_android_content_StringBlock),
1241    REG_JNI(register_android_content_XmlBlock),
1242    REG_JNI(register_android_emoji_EmojiFactory),
1243    REG_JNI(register_android_text_AndroidCharacter),
1244    REG_JNI(register_android_text_StaticLayout),
1245    REG_JNI(register_android_text_AndroidBidi),
1246    REG_JNI(register_android_view_InputDevice),
1247    REG_JNI(register_android_view_KeyCharacterMap),
1248    REG_JNI(register_android_os_Process),
1249    REG_JNI(register_android_os_SystemProperties),
1250    REG_JNI(register_android_os_Binder),
1251    REG_JNI(register_android_os_Parcel),
1252    REG_JNI(register_android_nio_utils),
1253    REG_JNI(register_android_graphics_Graphics),
1254    REG_JNI(register_android_view_DisplayEventReceiver),
1255    REG_JNI(register_android_view_RenderNode),
1256    REG_JNI(register_android_view_RenderNodeAnimator),
1257    REG_JNI(register_android_view_GraphicBuffer),
1258    REG_JNI(register_android_view_GLES20Canvas),
1259    REG_JNI(register_android_view_HardwareLayer),
1260    REG_JNI(register_android_view_ThreadedRenderer),
1261    REG_JNI(register_android_view_Surface),
1262    REG_JNI(register_android_view_SurfaceControl),
1263    REG_JNI(register_android_view_SurfaceSession),
1264    REG_JNI(register_android_view_TextureView),
1265    REG_JNI(register_com_android_internal_view_animation_NativeInterpolatorFactoryHelper),
1266    REG_JNI(register_com_google_android_gles_jni_EGLImpl),
1267    REG_JNI(register_com_google_android_gles_jni_GLImpl),
1268    REG_JNI(register_android_opengl_jni_EGL14),
1269    REG_JNI(register_android_opengl_jni_EGLExt),
1270    REG_JNI(register_android_opengl_jni_GLES10),
1271    REG_JNI(register_android_opengl_jni_GLES10Ext),
1272    REG_JNI(register_android_opengl_jni_GLES11),
1273    REG_JNI(register_android_opengl_jni_GLES11Ext),
1274    REG_JNI(register_android_opengl_jni_GLES20),
1275    REG_JNI(register_android_opengl_jni_GLES30),
1276    REG_JNI(register_android_opengl_jni_GLES31),
1277    REG_JNI(register_android_opengl_jni_GLES31Ext),
1278
1279    REG_JNI(register_android_graphics_Bitmap),
1280    REG_JNI(register_android_graphics_BitmapFactory),
1281    REG_JNI(register_android_graphics_BitmapRegionDecoder),
1282    REG_JNI(register_android_graphics_Camera),
1283    REG_JNI(register_android_graphics_CreateJavaOutputStreamAdaptor),
1284    REG_JNI(register_android_graphics_Canvas),
1285    REG_JNI(register_android_graphics_CanvasProperty),
1286    REG_JNI(register_android_graphics_ColorFilter),
1287    REG_JNI(register_android_graphics_DrawFilter),
1288    REG_JNI(register_android_graphics_FontFamily),
1289    REG_JNI(register_android_graphics_Interpolator),
1290    REG_JNI(register_android_graphics_LayerRasterizer),
1291    REG_JNI(register_android_graphics_MaskFilter),
1292    REG_JNI(register_android_graphics_Matrix),
1293    REG_JNI(register_android_graphics_Movie),
1294    REG_JNI(register_android_graphics_NinePatch),
1295    REG_JNI(register_android_graphics_Paint),
1296    REG_JNI(register_android_graphics_Path),
1297    REG_JNI(register_android_graphics_PathMeasure),
1298    REG_JNI(register_android_graphics_PathEffect),
1299    REG_JNI(register_android_graphics_Picture),
1300    REG_JNI(register_android_graphics_PorterDuff),
1301    REG_JNI(register_android_graphics_Rasterizer),
1302    REG_JNI(register_android_graphics_Region),
1303    REG_JNI(register_android_graphics_Shader),
1304    REG_JNI(register_android_graphics_SurfaceTexture),
1305    REG_JNI(register_android_graphics_Typeface),
1306    REG_JNI(register_android_graphics_Xfermode),
1307    REG_JNI(register_android_graphics_YuvImage),
1308    REG_JNI(register_android_graphics_pdf_PdfDocument),
1309    REG_JNI(register_android_graphics_pdf_PdfEditor),
1310    REG_JNI(register_android_graphics_pdf_PdfRenderer),
1311
1312    REG_JNI(register_android_database_CursorWindow),
1313    REG_JNI(register_android_database_SQLiteConnection),
1314    REG_JNI(register_android_database_SQLiteGlobal),
1315    REG_JNI(register_android_database_SQLiteDebug),
1316    REG_JNI(register_android_os_Debug),
1317    REG_JNI(register_android_os_FileObserver),
1318    REG_JNI(register_android_os_MessageQueue),
1319    REG_JNI(register_android_os_SELinux),
1320    REG_JNI(register_android_os_Trace),
1321    REG_JNI(register_android_os_UEventObserver),
1322    REG_JNI(register_android_net_LocalSocketImpl),
1323    REG_JNI(register_android_net_NetworkUtils),
1324    REG_JNI(register_android_net_TrafficStats),
1325    REG_JNI(register_android_os_MemoryFile),
1326    REG_JNI(register_com_android_internal_os_ZygoteInit),
1327    REG_JNI(register_com_android_internal_os_Zygote),
1328    REG_JNI(register_com_android_internal_util_VirtualRefBasePtr),
1329    REG_JNI(register_android_hardware_Camera),
1330    REG_JNI(register_android_hardware_camera2_CameraMetadata),
1331    REG_JNI(register_android_hardware_camera2_legacy_LegacyCameraDevice),
1332    REG_JNI(register_android_hardware_camera2_legacy_PerfMeasurement),
1333    REG_JNI(register_android_hardware_camera2_DngCreator),
1334    REG_JNI(register_android_hardware_SensorManager),
1335    REG_JNI(register_android_hardware_SerialPort),
1336    REG_JNI(register_android_hardware_SoundTrigger),
1337    REG_JNI(register_android_hardware_UsbDevice),
1338    REG_JNI(register_android_hardware_UsbDeviceConnection),
1339    REG_JNI(register_android_hardware_UsbRequest),
1340    REG_JNI(register_android_hardware_location_ActivityRecognitionHardware),
1341    REG_JNI(register_android_media_AudioRecord),
1342    REG_JNI(register_android_media_AudioSystem),
1343    REG_JNI(register_android_media_AudioTrack),
1344    REG_JNI(register_android_media_JetPlayer),
1345    REG_JNI(register_android_media_RemoteDisplay),
1346    REG_JNI(register_android_media_ToneGenerator),
1347
1348    REG_JNI(register_android_opengl_classes),
1349    REG_JNI(register_android_server_NetworkManagementSocketTagger),
1350    REG_JNI(register_android_ddm_DdmHandleNativeHeap),
1351    REG_JNI(register_android_backup_BackupDataInput),
1352    REG_JNI(register_android_backup_BackupDataOutput),
1353    REG_JNI(register_android_backup_FileBackupHelperBase),
1354    REG_JNI(register_android_backup_BackupHelperDispatcher),
1355    REG_JNI(register_android_app_backup_FullBackup),
1356    REG_JNI(register_android_app_ActivityThread),
1357    REG_JNI(register_android_app_NativeActivity),
1358    REG_JNI(register_android_view_InputChannel),
1359    REG_JNI(register_android_view_InputEventReceiver),
1360    REG_JNI(register_android_view_InputEventSender),
1361    REG_JNI(register_android_view_InputQueue),
1362    REG_JNI(register_android_view_KeyEvent),
1363    REG_JNI(register_android_view_MotionEvent),
1364    REG_JNI(register_android_view_PointerIcon),
1365    REG_JNI(register_android_view_VelocityTracker),
1366
1367    REG_JNI(register_android_content_res_ObbScanner),
1368    REG_JNI(register_android_content_res_Configuration),
1369
1370    REG_JNI(register_android_animation_PropertyValuesHolder),
1371    REG_JNI(register_com_android_internal_content_NativeLibraryHelper),
1372    REG_JNI(register_com_android_internal_net_NetworkStatsFactory),
1373};
1374
1375/*
1376 * Register android native functions with the VM.
1377 */
1378/*static*/ int AndroidRuntime::startReg(JNIEnv* env)
1379{
1380    /*
1381     * This hook causes all future threads created in this process to be
1382     * attached to the JavaVM.  (This needs to go away in favor of JNI
1383     * Attach calls.)
1384     */
1385    androidSetCreateThreadFunc((android_create_thread_fn) javaCreateThreadEtc);
1386
1387    ALOGV("--- registering native functions ---\n");
1388
1389    /*
1390     * Every "register" function calls one or more things that return
1391     * a local reference (e.g. FindClass).  Because we haven't really
1392     * started the VM yet, they're all getting stored in the base frame
1393     * and never released.  Use Push/Pop to manage the storage.
1394     */
1395    env->PushLocalFrame(200);
1396
1397    if (register_jni_procs(gRegJNI, NELEM(gRegJNI), env) < 0) {
1398        env->PopLocalFrame(NULL);
1399        return -1;
1400    }
1401    env->PopLocalFrame(NULL);
1402
1403    //createJavaThread("fubar", quickTest, (void*) "hello");
1404
1405    return 0;
1406}
1407
1408AndroidRuntime* AndroidRuntime::getRuntime()
1409{
1410    return gCurRuntime;
1411}
1412
1413/**
1414 * Used by WithFramework to register native functions.
1415 */
1416extern "C"
1417jint Java_com_android_internal_util_WithFramework_registerNatives(
1418        JNIEnv* env, jclass clazz) {
1419    return register_jni_procs(gRegJNI, NELEM(gRegJNI), env);
1420}
1421
1422/**
1423 * Used by LoadClass to register native functions.
1424 */
1425extern "C"
1426jint Java_LoadClass_registerNatives(JNIEnv* env, jclass clazz) {
1427    return register_jni_procs(gRegJNI, NELEM(gRegJNI), env);
1428}
1429
1430}   // namespace android
1431