• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
doThrow(JNIEnv * env,const char * exc,const char * msg=NULL)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  */
com_android_internal_os_RuntimeInit_nativeFinishInit(JNIEnv * env,jobject clazz)205 static void com_android_internal_os_RuntimeInit_nativeFinishInit(JNIEnv* env, jobject clazz)
206 {
207     gCurRuntime->onStarted();
208 }
209 
com_android_internal_os_RuntimeInit_nativeZygoteInit(JNIEnv * env,jobject clazz)210 static void com_android_internal_os_RuntimeInit_nativeZygoteInit(JNIEnv* env, jobject clazz)
211 {
212     gCurRuntime->onZygoteInit();
213 }
214 
com_android_internal_os_RuntimeInit_nativeSetExitWithoutCleanup(JNIEnv * env,jobject clazz,jboolean exitWithoutCleanup)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 
register_com_android_internal_os_RuntimeInit(JNIEnv * env)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 
AndroidRuntime(char * argBlockStart,const size_t argBlockLength)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 
~AndroidRuntime()259 AndroidRuntime::~AndroidRuntime()
260 {
261     SkGraphics::Term();
262 }
263 
264 /*
265  * Register native methods using JNI.
266  */
registerNativeMethods(JNIEnv * env,const char * className,const JNINativeMethod * gMethods,int numMethods)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 
setArgv0(const char * argv0)273 void AndroidRuntime::setArgv0(const char* argv0) {
274     memset(mArgBlockStart, 0, mArgBlockLength);
275     strlcpy(mArgBlockStart, argv0, mArgBlockLength);
276 }
277 
callMain(const String8 & className,jclass clazz,const Vector<String8> & args)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  */
runtime_exit(int code)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  */
runtime_vfprintf(FILE * fp,const char * format,va_list ap)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  */
runtime_isSensitiveThread()344 static bool runtime_isSensitiveThread() {
345     IPCThreadState* state = IPCThreadState::selfOrNull();
346     return state && state->getStrictModePolicy() != 0;
347 }
348 
hasDir(const char * dir)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 
hasFile(const char * file)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  */
readLocale(char * language,char * region)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 
addOption(const char * optionString,void * extraInfo)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  */
parseExtraOpts(char * extraOptsBuf,const char * quotingArg)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  */
parseRuntimeOption(const char * property,char * buffer,const char * runtimeArg,const char * defaultArg)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  */
parseCompilerOption(const char * property,char * buffer,const char * compilerArg,const char * quotingArg)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  */
parseCompilerRuntimeOption(const char * property,char * buffer,const char * runtimeArg,const char * quotingArg)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  */
startVm(JavaVM ** pJavaVM,JNIEnv ** pEnv,bool zygote)531 int AndroidRuntime::startVm(JavaVM** pJavaVM, JNIEnv** pEnv, bool zygote)
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     /*
737      * Enable debugging only for apps forked from zygote.
738      * Set suspend=y to pause during VM init and use android ADB transport.
739      */
740     if (zygote) {
741       addOption("-agentlib:jdwp=transport=dt_android_adb,suspend=n,server=y");
742     }
743 
744     parseRuntimeOption("dalvik.vm.lockprof.threshold",
745                        lockProfThresholdBuf,
746                        "-Xlockprofthreshold:");
747 
748     /* Force interpreter-only mode for selected opcodes. Eg "1-0a,3c,f1-ff" */
749     parseRuntimeOption("dalvik.vm.jit.op", jitOpBuf, "-Xjitop:");
750 
751     /* Force interpreter-only mode for selected methods */
752     parseRuntimeOption("dalvik.vm.jit.method", jitMethodBuf, "-Xjitmethod:");
753 
754     if (executionMode == kEMIntPortable) {
755         addOption("-Xint:portable");
756     } else if (executionMode == kEMIntFast) {
757         addOption("-Xint:fast");
758     } else if (executionMode == kEMJitCompiler) {
759         addOption("-Xint:jit");
760     }
761 
762     // libart tolerates libdvm flags, but not vice versa, so only pass some options if libart.
763     property_get("persist.sys.dalvik.vm.lib.2", dalvikVmLibBuf, "libart.so");
764     bool libart = (strncmp(dalvikVmLibBuf, "libart", 6) == 0);
765 
766     if (libart) {
767         // If we booting without the real /data, don't spend time compiling.
768         property_get("vold.decrypt", voldDecryptBuf, "");
769         bool skip_compilation = ((strcmp(voldDecryptBuf, "trigger_restart_min_framework") == 0) ||
770                                  (strcmp(voldDecryptBuf, "1") == 0));
771 
772         // Extra options for boot.art/boot.oat image generation.
773         parseCompilerRuntimeOption("dalvik.vm.image-dex2oat-Xms", dex2oatXmsImageFlagsBuf,
774                                    "-Xms", "-Ximage-compiler-option");
775         parseCompilerRuntimeOption("dalvik.vm.image-dex2oat-Xmx", dex2oatXmxImageFlagsBuf,
776                                    "-Xmx", "-Ximage-compiler-option");
777         if (skip_compilation) {
778             addOption("-Ximage-compiler-option");
779             addOption("--compiler-filter=verify-none");
780         } else {
781             parseCompilerOption("dalvik.vm.image-dex2oat-filter", dex2oatImageCompilerFilterBuf,
782                                 "--compiler-filter=", "-Ximage-compiler-option");
783         }
784 
785         // Make sure there is a preloaded-classes file.
786         if (!hasFile("/system/etc/preloaded-classes")) {
787             ALOGE("Missing preloaded-classes file, /system/etc/preloaded-classes not found: %s\n",
788                   strerror(errno));
789             goto bail;
790         }
791         addOption("-Ximage-compiler-option");
792         addOption("--image-classes=/system/etc/preloaded-classes");
793 
794         // If there is a compiled-classes file, push it.
795         if (hasFile("/system/etc/compiled-classes")) {
796             addOption("-Ximage-compiler-option");
797             addOption("--compiled-classes=/system/etc/compiled-classes");
798         }
799 
800         property_get("dalvik.vm.image-dex2oat-flags", dex2oatImageFlagsBuf, "");
801         parseExtraOpts(dex2oatImageFlagsBuf, "-Ximage-compiler-option");
802 
803         // Extra options for DexClassLoader.
804         parseCompilerRuntimeOption("dalvik.vm.dex2oat-Xms", dex2oatXmsFlagsBuf,
805                                    "-Xms", "-Xcompiler-option");
806         parseCompilerRuntimeOption("dalvik.vm.dex2oat-Xmx", dex2oatXmxFlagsBuf,
807                                    "-Xmx", "-Xcompiler-option");
808         if (skip_compilation) {
809             addOption("-Xcompiler-option");
810             addOption("--compiler-filter=verify-none");
811         } else {
812             parseCompilerOption("dalvik.vm.dex2oat-filter", dex2oatCompilerFilterBuf,
813                                 "--compiler-filter=", "-Xcompiler-option");
814         }
815         property_get("dalvik.vm.dex2oat-flags", dex2oatFlagsBuf, "");
816         parseExtraOpts(dex2oatFlagsBuf, "-Xcompiler-option");
817 
818     }
819 
820     /* extra options; parse this late so it overrides others */
821     property_get("dalvik.vm.extra-opts", extraOptsBuf, "");
822     parseExtraOpts(extraOptsBuf, NULL);
823 
824     /* Set the properties for locale */
825     {
826         strcpy(langOption, "-Duser.language=");
827         strcpy(regionOption, "-Duser.region=");
828         readLocale(langOption, regionOption);
829         addOption(langOption);
830         addOption(regionOption);
831     }
832 
833     /*
834      * Set profiler options
835      */
836     if (libart) {
837         // Whether or not the profiler should be enabled.
838         property_get("dalvik.vm.profiler", propBuf, "0");
839         if (propBuf[0] == '1') {
840             addOption("-Xenable-profiler");
841         }
842 
843         // Whether the profile should start upon app startup or be delayed by some random offset
844         // (in seconds) that is bound between 0 and a fixed value.
845         property_get("dalvik.vm.profile.start-immed", propBuf, "0");
846         if (propBuf[0] == '1') {
847             addOption("-Xprofile-start-immediately");
848         }
849 
850         // Number of seconds during profile runs.
851         parseRuntimeOption("dalvik.vm.profile.period-secs", profilePeriod, "-Xprofile-period:");
852 
853         // Length of each profile run (seconds).
854         parseRuntimeOption("dalvik.vm.profile.duration-secs",
855                            profileDuration,
856                            "-Xprofile-duration:");
857 
858         // Polling interval during profile run (microseconds).
859         parseRuntimeOption("dalvik.vm.profile.interval-us", profileInterval, "-Xprofile-interval:");
860 
861         // Coefficient for period backoff.  The the period is multiplied
862         // by this value after each profile run.
863         parseRuntimeOption("dalvik.vm.profile.backoff-coeff", profileBackoff, "-Xprofile-backoff:");
864 
865         // Top K% of samples that are considered relevant when
866         // deciding if the app should be recompiled.
867         parseRuntimeOption("dalvik.vm.profile.top-k-thr",
868                            profileTopKThreshold,
869                            "-Xprofile-top-k-threshold:");
870 
871         // The threshold after which a change in the structure of the
872         // top K% profiled samples becomes significant and triggers
873         // recompilation. A change in profile is considered
874         // significant if X% (top-k-change-threshold) of the top K%
875         // (top-k-threshold property) samples has changed.
876         parseRuntimeOption("dalvik.vm.profile.top-k-ch-thr",
877                            profileTopKChangeThreshold,
878                            "-Xprofile-top-k-change-threshold:");
879 
880         // Type of profile data.
881         parseRuntimeOption("dalvik.vm.profiler.type", profileType, "-Xprofile-type:");
882 
883         // Depth of bounded stack data
884         parseRuntimeOption("dalvik.vm.profile.stack-depth",
885                            profileMaxStackDepth,
886                            "-Xprofile-max-stack-depth:");
887 
888         // Native bridge library. "0" means that native bridge is disabled.
889         property_get("ro.dalvik.vm.native.bridge", propBuf, "");
890         if (propBuf[0] == '\0') {
891             ALOGW("ro.dalvik.vm.native.bridge is not expected to be empty");
892         } else if (strcmp(propBuf, "0") != 0) {
893             snprintf(nativeBridgeLibrary, sizeof("-XX:NativeBridge=") + PROPERTY_VALUE_MAX,
894                      "-XX:NativeBridge=%s", propBuf);
895             addOption(nativeBridgeLibrary);
896         }
897     }
898 
899     initArgs.version = JNI_VERSION_1_4;
900     initArgs.options = mOptions.editArray();
901     initArgs.nOptions = mOptions.size();
902     initArgs.ignoreUnrecognized = JNI_FALSE;
903 
904     /*
905      * Initialize the VM.
906      *
907      * The JavaVM* is essentially per-process, and the JNIEnv* is per-thread.
908      * If this call succeeds, the VM is ready, and we can start issuing
909      * JNI calls.
910      */
911     if (JNI_CreateJavaVM(pJavaVM, pEnv, &initArgs) < 0) {
912         ALOGE("JNI_CreateJavaVM failed\n");
913         goto bail;
914     }
915 
916     result = 0;
917 
918 bail:
919     return result;
920 }
921 
toSlashClassName(const char * className)922 char* AndroidRuntime::toSlashClassName(const char* className)
923 {
924     char* result = strdup(className);
925     for (char* cp = result; *cp != '\0'; cp++) {
926         if (*cp == '.') {
927             *cp = '/';
928         }
929     }
930     return result;
931 }
932 
933 /** Create a Java string from an ASCII or Latin-1 string */
NewStringLatin1(JNIEnv * env,const char * bytes)934 jstring AndroidRuntime::NewStringLatin1(JNIEnv* env, const char* bytes) {
935     if (!bytes) return NULL;
936     int length = strlen(bytes);
937     jchar* buffer = (jchar *)alloca(length * sizeof(jchar));
938     if (!buffer) return NULL;
939     jchar* chp = buffer;
940     for (int i = 0; i < length; i++) {
941         *chp++ = *bytes++;
942     }
943     return env->NewString(buffer, length);
944 }
945 
946 
947 /*
948  * Start the Android runtime.  This involves starting the virtual machine
949  * and calling the "static void main(String[] args)" method in the class
950  * named by "className".
951  *
952  * Passes the main function two arguments, the class name and the specified
953  * options string.
954  */
start(const char * className,const Vector<String8> & options,bool zygote)955 void AndroidRuntime::start(const char* className, const Vector<String8>& options, bool zygote)
956 {
957     ALOGD(">>>>>> START %s uid %d <<<<<<\n",
958             className != NULL ? className : "(unknown)", getuid());
959 
960     static const String8 startSystemServer("start-system-server");
961 
962     /*
963      * 'startSystemServer == true' means runtime is obsolete and not run from
964      * init.rc anymore, so we print out the boot start event here.
965      */
966     for (size_t i = 0; i < options.size(); ++i) {
967         if (options[i] == startSystemServer) {
968            /* track our progress through the boot sequence */
969            const int LOG_BOOT_PROGRESS_START = 3000;
970            LOG_EVENT_LONG(LOG_BOOT_PROGRESS_START,  ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
971         }
972     }
973 
974     const char* rootDir = getenv("ANDROID_ROOT");
975     if (rootDir == NULL) {
976         rootDir = "/system";
977         if (!hasDir("/system")) {
978             LOG_FATAL("No root directory specified, and /android does not exist.");
979             return;
980         }
981         setenv("ANDROID_ROOT", rootDir, 1);
982     }
983 
984     //const char* kernelHack = getenv("LD_ASSUME_KERNEL");
985     //ALOGD("Found LD_ASSUME_KERNEL='%s'\n", kernelHack);
986 
987     /* start the virtual machine */
988     JniInvocation jni_invocation;
989     jni_invocation.Init(NULL);
990     JNIEnv* env;
991     if (startVm(&mJavaVM, &env, zygote) != 0) {
992         return;
993     }
994     onVmCreated(env);
995 
996     /*
997      * Register android functions.
998      */
999     if (startReg(env) < 0) {
1000         ALOGE("Unable to register all android natives\n");
1001         return;
1002     }
1003 
1004     /*
1005      * We want to call main() with a String array with arguments in it.
1006      * At present we have two arguments, the class name and an option string.
1007      * Create an array to hold them.
1008      */
1009     jclass stringClass;
1010     jobjectArray strArray;
1011     jstring classNameStr;
1012 
1013     stringClass = env->FindClass("java/lang/String");
1014     assert(stringClass != NULL);
1015     strArray = env->NewObjectArray(options.size() + 1, stringClass, NULL);
1016     assert(strArray != NULL);
1017     classNameStr = env->NewStringUTF(className);
1018     assert(classNameStr != NULL);
1019     env->SetObjectArrayElement(strArray, 0, classNameStr);
1020 
1021     for (size_t i = 0; i < options.size(); ++i) {
1022         jstring optionsStr = env->NewStringUTF(options.itemAt(i).string());
1023         assert(optionsStr != NULL);
1024         env->SetObjectArrayElement(strArray, i + 1, optionsStr);
1025     }
1026 
1027     /*
1028      * Start VM.  This thread becomes the main thread of the VM, and will
1029      * not return until the VM exits.
1030      */
1031     char* slashClassName = toSlashClassName(className);
1032     jclass startClass = env->FindClass(slashClassName);
1033     if (startClass == NULL) {
1034         ALOGE("JavaVM unable to locate class '%s'\n", slashClassName);
1035         /* keep going */
1036     } else {
1037         jmethodID startMeth = env->GetStaticMethodID(startClass, "main",
1038             "([Ljava/lang/String;)V");
1039         if (startMeth == NULL) {
1040             ALOGE("JavaVM unable to find main() in '%s'\n", className);
1041             /* keep going */
1042         } else {
1043             env->CallStaticVoidMethod(startClass, startMeth, strArray);
1044 
1045 #if 0
1046             if (env->ExceptionCheck())
1047                 threadExitUncaughtException(env);
1048 #endif
1049         }
1050     }
1051     free(slashClassName);
1052 
1053     ALOGD("Shutting down VM\n");
1054     if (mJavaVM->DetachCurrentThread() != JNI_OK)
1055         ALOGW("Warning: unable to detach main thread\n");
1056     if (mJavaVM->DestroyJavaVM() != 0)
1057         ALOGW("Warning: VM did not shut down cleanly\n");
1058 }
1059 
exit(int code)1060 void AndroidRuntime::exit(int code)
1061 {
1062     if (mExitWithoutCleanup) {
1063         ALOGI("VM exiting with result code %d, cleanup skipped.", code);
1064         ::_exit(code);
1065     } else {
1066         ALOGI("VM exiting with result code %d.", code);
1067         onExit(code);
1068         ::exit(code);
1069     }
1070 }
1071 
onVmCreated(JNIEnv * env)1072 void AndroidRuntime::onVmCreated(JNIEnv* env)
1073 {
1074     // If AndroidRuntime had anything to do here, we'd have done it in 'start'.
1075 }
1076 
1077 /*
1078  * Get the JNIEnv pointer for this thread.
1079  *
1080  * Returns NULL if the slot wasn't allocated or populated.
1081  */
getJNIEnv()1082 /*static*/ JNIEnv* AndroidRuntime::getJNIEnv()
1083 {
1084     JNIEnv* env;
1085     JavaVM* vm = AndroidRuntime::getJavaVM();
1086     assert(vm != NULL);
1087 
1088     if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK)
1089         return NULL;
1090     return env;
1091 }
1092 
1093 /*
1094  * Makes the current thread visible to the VM.
1095  *
1096  * The JNIEnv pointer returned is only valid for the current thread, and
1097  * thus must be tucked into thread-local storage.
1098  */
javaAttachThread(const char * threadName,JNIEnv ** pEnv)1099 static int javaAttachThread(const char* threadName, JNIEnv** pEnv)
1100 {
1101     JavaVMAttachArgs args;
1102     JavaVM* vm;
1103     jint result;
1104 
1105     vm = AndroidRuntime::getJavaVM();
1106     assert(vm != NULL);
1107 
1108     args.version = JNI_VERSION_1_4;
1109     args.name = (char*) threadName;
1110     args.group = NULL;
1111 
1112     result = vm->AttachCurrentThread(pEnv, (void*) &args);
1113     if (result != JNI_OK)
1114         ALOGI("NOTE: attach of thread '%s' failed\n", threadName);
1115 
1116     return result;
1117 }
1118 
1119 /*
1120  * Detach the current thread from the set visible to the VM.
1121  */
javaDetachThread(void)1122 static int javaDetachThread(void)
1123 {
1124     JavaVM* vm;
1125     jint result;
1126 
1127     vm = AndroidRuntime::getJavaVM();
1128     assert(vm != NULL);
1129 
1130     result = vm->DetachCurrentThread();
1131     if (result != JNI_OK)
1132         ALOGE("ERROR: thread detach failed\n");
1133     return result;
1134 }
1135 
1136 /*
1137  * When starting a native thread that will be visible from the VM, we
1138  * bounce through this to get the right attach/detach action.
1139  * Note that this function calls free(args)
1140  */
javaThreadShell(void * args)1141 /*static*/ int AndroidRuntime::javaThreadShell(void* args) {
1142     void* start = ((void**)args)[0];
1143     void* userData = ((void **)args)[1];
1144     char* name = (char*) ((void **)args)[2];        // we own this storage
1145     free(args);
1146     JNIEnv* env;
1147     int result;
1148 
1149     /* hook us into the VM */
1150     if (javaAttachThread(name, &env) != JNI_OK)
1151         return -1;
1152 
1153     /* start the thread running */
1154     result = (*(android_thread_func_t)start)(userData);
1155 
1156     /* unhook us */
1157     javaDetachThread();
1158     free(name);
1159 
1160     return result;
1161 }
1162 
1163 /*
1164  * This is invoked from androidCreateThreadEtc() via the callback
1165  * set with androidSetCreateThreadFunc().
1166  *
1167  * We need to create the new thread in such a way that it gets hooked
1168  * into the VM before it really starts executing.
1169  */
javaCreateThreadEtc(android_thread_func_t entryFunction,void * userData,const char * threadName,int32_t threadPriority,size_t threadStackSize,android_thread_id_t * threadId)1170 /*static*/ int AndroidRuntime::javaCreateThreadEtc(
1171                                 android_thread_func_t entryFunction,
1172                                 void* userData,
1173                                 const char* threadName,
1174                                 int32_t threadPriority,
1175                                 size_t threadStackSize,
1176                                 android_thread_id_t* threadId)
1177 {
1178     void** args = (void**) malloc(3 * sizeof(void*));   // javaThreadShell must free
1179     int result;
1180 
1181     if (!threadName)
1182         threadName = "unnamed thread";
1183 
1184     args[0] = (void*) entryFunction;
1185     args[1] = userData;
1186     args[2] = (void*) strdup(threadName);   // javaThreadShell must free
1187 
1188     result = androidCreateRawThreadEtc(AndroidRuntime::javaThreadShell, args,
1189         threadName, threadPriority, threadStackSize, threadId);
1190     return result;
1191 }
1192 
1193 /*
1194  * Create a thread that is visible from the VM.
1195  *
1196  * This is called from elsewhere in the library.
1197  */
createJavaThread(const char * name,void (* start)(void *),void * arg)1198 /*static*/ android_thread_id_t AndroidRuntime::createJavaThread(const char* name,
1199     void (*start)(void *), void* arg)
1200 {
1201     android_thread_id_t threadId = 0;
1202     javaCreateThreadEtc((android_thread_func_t) start, arg, name,
1203         ANDROID_PRIORITY_DEFAULT, 0, &threadId);
1204     return threadId;
1205 }
1206 
1207 #if 0
1208 static void quickTest(void* arg)
1209 {
1210     const char* str = (const char*) arg;
1211 
1212     printf("In quickTest: %s\n", str);
1213 }
1214 #endif
1215 
1216 #ifdef NDEBUG
1217     #define REG_JNI(name)      { name }
1218     struct RegJNIRec {
1219         int (*mProc)(JNIEnv*);
1220     };
1221 #else
1222     #define REG_JNI(name)      { name, #name }
1223     struct RegJNIRec {
1224         int (*mProc)(JNIEnv*);
1225         const char* mName;
1226     };
1227 #endif
1228 
1229 typedef void (*RegJAMProc)();
1230 
register_jni_procs(const RegJNIRec array[],size_t count,JNIEnv * env)1231 static int register_jni_procs(const RegJNIRec array[], size_t count, JNIEnv* env)
1232 {
1233     for (size_t i = 0; i < count; i++) {
1234         if (array[i].mProc(env) < 0) {
1235 #ifndef NDEBUG
1236             ALOGD("----------!!! %s failed to load\n", array[i].mName);
1237 #endif
1238             return -1;
1239         }
1240     }
1241     return 0;
1242 }
1243 
register_jam_procs(const RegJAMProc array[],size_t count)1244 static void register_jam_procs(const RegJAMProc array[], size_t count)
1245 {
1246     for (size_t i = 0; i < count; i++) {
1247         array[i]();
1248     }
1249 }
1250 
1251 static const RegJNIRec gRegJNI[] = {
1252     REG_JNI(register_com_android_internal_os_RuntimeInit),
1253     REG_JNI(register_android_os_SystemClock),
1254     REG_JNI(register_android_util_EventLog),
1255     REG_JNI(register_android_util_Log),
1256     REG_JNI(register_android_util_FloatMath),
1257     REG_JNI(register_android_content_AssetManager),
1258     REG_JNI(register_android_content_StringBlock),
1259     REG_JNI(register_android_content_XmlBlock),
1260     REG_JNI(register_android_emoji_EmojiFactory),
1261     REG_JNI(register_android_text_AndroidCharacter),
1262     REG_JNI(register_android_text_StaticLayout),
1263     REG_JNI(register_android_text_AndroidBidi),
1264     REG_JNI(register_android_view_InputDevice),
1265     REG_JNI(register_android_view_KeyCharacterMap),
1266     REG_JNI(register_android_os_Process),
1267     REG_JNI(register_android_os_SystemProperties),
1268     REG_JNI(register_android_os_Binder),
1269     REG_JNI(register_android_os_Parcel),
1270     REG_JNI(register_android_nio_utils),
1271     REG_JNI(register_android_graphics_Graphics),
1272     REG_JNI(register_android_view_DisplayEventReceiver),
1273     REG_JNI(register_android_view_RenderNode),
1274     REG_JNI(register_android_view_RenderNodeAnimator),
1275     REG_JNI(register_android_view_GraphicBuffer),
1276     REG_JNI(register_android_view_GLES20Canvas),
1277     REG_JNI(register_android_view_HardwareLayer),
1278     REG_JNI(register_android_view_ThreadedRenderer),
1279     REG_JNI(register_android_view_Surface),
1280     REG_JNI(register_android_view_SurfaceControl),
1281     REG_JNI(register_android_view_SurfaceSession),
1282     REG_JNI(register_android_view_TextureView),
1283     REG_JNI(register_com_android_internal_view_animation_NativeInterpolatorFactoryHelper),
1284     REG_JNI(register_com_google_android_gles_jni_EGLImpl),
1285     REG_JNI(register_com_google_android_gles_jni_GLImpl),
1286     REG_JNI(register_android_opengl_jni_EGL14),
1287     REG_JNI(register_android_opengl_jni_EGLExt),
1288     REG_JNI(register_android_opengl_jni_GLES10),
1289     REG_JNI(register_android_opengl_jni_GLES10Ext),
1290     REG_JNI(register_android_opengl_jni_GLES11),
1291     REG_JNI(register_android_opengl_jni_GLES11Ext),
1292     REG_JNI(register_android_opengl_jni_GLES20),
1293     REG_JNI(register_android_opengl_jni_GLES30),
1294     REG_JNI(register_android_opengl_jni_GLES31),
1295     REG_JNI(register_android_opengl_jni_GLES31Ext),
1296 
1297     REG_JNI(register_android_graphics_Bitmap),
1298     REG_JNI(register_android_graphics_BitmapFactory),
1299     REG_JNI(register_android_graphics_BitmapRegionDecoder),
1300     REG_JNI(register_android_graphics_Camera),
1301     REG_JNI(register_android_graphics_CreateJavaOutputStreamAdaptor),
1302     REG_JNI(register_android_graphics_Canvas),
1303     REG_JNI(register_android_graphics_CanvasProperty),
1304     REG_JNI(register_android_graphics_ColorFilter),
1305     REG_JNI(register_android_graphics_DrawFilter),
1306     REG_JNI(register_android_graphics_FontFamily),
1307     REG_JNI(register_android_graphics_Interpolator),
1308     REG_JNI(register_android_graphics_LayerRasterizer),
1309     REG_JNI(register_android_graphics_MaskFilter),
1310     REG_JNI(register_android_graphics_Matrix),
1311     REG_JNI(register_android_graphics_Movie),
1312     REG_JNI(register_android_graphics_NinePatch),
1313     REG_JNI(register_android_graphics_Paint),
1314     REG_JNI(register_android_graphics_Path),
1315     REG_JNI(register_android_graphics_PathMeasure),
1316     REG_JNI(register_android_graphics_PathEffect),
1317     REG_JNI(register_android_graphics_Picture),
1318     REG_JNI(register_android_graphics_PorterDuff),
1319     REG_JNI(register_android_graphics_Rasterizer),
1320     REG_JNI(register_android_graphics_Region),
1321     REG_JNI(register_android_graphics_Shader),
1322     REG_JNI(register_android_graphics_SurfaceTexture),
1323     REG_JNI(register_android_graphics_Typeface),
1324     REG_JNI(register_android_graphics_Xfermode),
1325     REG_JNI(register_android_graphics_YuvImage),
1326     REG_JNI(register_android_graphics_pdf_PdfDocument),
1327     REG_JNI(register_android_graphics_pdf_PdfEditor),
1328     REG_JNI(register_android_graphics_pdf_PdfRenderer),
1329 
1330     REG_JNI(register_android_database_CursorWindow),
1331     REG_JNI(register_android_database_SQLiteConnection),
1332     REG_JNI(register_android_database_SQLiteGlobal),
1333     REG_JNI(register_android_database_SQLiteDebug),
1334     REG_JNI(register_android_os_Debug),
1335     REG_JNI(register_android_os_FileObserver),
1336     REG_JNI(register_android_os_MessageQueue),
1337     REG_JNI(register_android_os_SELinux),
1338     REG_JNI(register_android_os_Trace),
1339     REG_JNI(register_android_os_UEventObserver),
1340     REG_JNI(register_android_net_LocalSocketImpl),
1341     REG_JNI(register_android_net_NetworkUtils),
1342     REG_JNI(register_android_net_TrafficStats),
1343     REG_JNI(register_android_os_MemoryFile),
1344     REG_JNI(register_com_android_internal_os_ZygoteInit),
1345     REG_JNI(register_com_android_internal_os_Zygote),
1346     REG_JNI(register_com_android_internal_util_VirtualRefBasePtr),
1347     REG_JNI(register_android_hardware_Camera),
1348     REG_JNI(register_android_hardware_camera2_CameraMetadata),
1349     REG_JNI(register_android_hardware_camera2_legacy_LegacyCameraDevice),
1350     REG_JNI(register_android_hardware_camera2_legacy_PerfMeasurement),
1351     REG_JNI(register_android_hardware_camera2_DngCreator),
1352     REG_JNI(register_android_hardware_SensorManager),
1353     REG_JNI(register_android_hardware_SerialPort),
1354     REG_JNI(register_android_hardware_SoundTrigger),
1355     REG_JNI(register_android_hardware_UsbDevice),
1356     REG_JNI(register_android_hardware_UsbDeviceConnection),
1357     REG_JNI(register_android_hardware_UsbRequest),
1358     REG_JNI(register_android_hardware_location_ActivityRecognitionHardware),
1359     REG_JNI(register_android_media_AudioRecord),
1360     REG_JNI(register_android_media_AudioSystem),
1361     REG_JNI(register_android_media_AudioTrack),
1362     REG_JNI(register_android_media_JetPlayer),
1363     REG_JNI(register_android_media_RemoteDisplay),
1364     REG_JNI(register_android_media_ToneGenerator),
1365 
1366     REG_JNI(register_android_opengl_classes),
1367     REG_JNI(register_android_server_NetworkManagementSocketTagger),
1368     REG_JNI(register_android_ddm_DdmHandleNativeHeap),
1369     REG_JNI(register_android_backup_BackupDataInput),
1370     REG_JNI(register_android_backup_BackupDataOutput),
1371     REG_JNI(register_android_backup_FileBackupHelperBase),
1372     REG_JNI(register_android_backup_BackupHelperDispatcher),
1373     REG_JNI(register_android_app_backup_FullBackup),
1374     REG_JNI(register_android_app_ActivityThread),
1375     REG_JNI(register_android_app_NativeActivity),
1376     REG_JNI(register_android_view_InputChannel),
1377     REG_JNI(register_android_view_InputEventReceiver),
1378     REG_JNI(register_android_view_InputEventSender),
1379     REG_JNI(register_android_view_InputQueue),
1380     REG_JNI(register_android_view_KeyEvent),
1381     REG_JNI(register_android_view_MotionEvent),
1382     REG_JNI(register_android_view_PointerIcon),
1383     REG_JNI(register_android_view_VelocityTracker),
1384 
1385     REG_JNI(register_android_content_res_ObbScanner),
1386     REG_JNI(register_android_content_res_Configuration),
1387 
1388     REG_JNI(register_android_animation_PropertyValuesHolder),
1389     REG_JNI(register_com_android_internal_content_NativeLibraryHelper),
1390     REG_JNI(register_com_android_internal_net_NetworkStatsFactory),
1391 };
1392 
1393 /*
1394  * Register android native functions with the VM.
1395  */
startReg(JNIEnv * env)1396 /*static*/ int AndroidRuntime::startReg(JNIEnv* env)
1397 {
1398     /*
1399      * This hook causes all future threads created in this process to be
1400      * attached to the JavaVM.  (This needs to go away in favor of JNI
1401      * Attach calls.)
1402      */
1403     androidSetCreateThreadFunc((android_create_thread_fn) javaCreateThreadEtc);
1404 
1405     ALOGV("--- registering native functions ---\n");
1406 
1407     /*
1408      * Every "register" function calls one or more things that return
1409      * a local reference (e.g. FindClass).  Because we haven't really
1410      * started the VM yet, they're all getting stored in the base frame
1411      * and never released.  Use Push/Pop to manage the storage.
1412      */
1413     env->PushLocalFrame(200);
1414 
1415     if (register_jni_procs(gRegJNI, NELEM(gRegJNI), env) < 0) {
1416         env->PopLocalFrame(NULL);
1417         return -1;
1418     }
1419     env->PopLocalFrame(NULL);
1420 
1421     //createJavaThread("fubar", quickTest, (void*) "hello");
1422 
1423     return 0;
1424 }
1425 
getRuntime()1426 AndroidRuntime* AndroidRuntime::getRuntime()
1427 {
1428     return gCurRuntime;
1429 }
1430 
1431 /**
1432  * Used by WithFramework to register native functions.
1433  */
1434 extern "C"
Java_com_android_internal_util_WithFramework_registerNatives(JNIEnv * env,jclass clazz)1435 jint Java_com_android_internal_util_WithFramework_registerNatives(
1436         JNIEnv* env, jclass clazz) {
1437     return register_jni_procs(gRegJNI, NELEM(gRegJNI), env);
1438 }
1439 
1440 /**
1441  * Used by LoadClass to register native functions.
1442  */
1443 extern "C"
Java_LoadClass_registerNatives(JNIEnv * env,jclass clazz)1444 jint Java_LoadClass_registerNatives(JNIEnv* env, jclass clazz) {
1445     return register_jni_procs(gRegJNI, NELEM(gRegJNI), env);
1446 }
1447 
1448 }   // namespace android
1449