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