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 ATRACE_TAG ATRACE_TAG_DALVIK
18 #define LOG_TAG "AndroidRuntime"
19 #define LOG_NDEBUG 1
20 
21 #include <android_runtime/AndroidRuntime.h>
22 #include <binder/IBinder.h>
23 #include <binder/IPCThreadState.h>
24 #include <binder/IServiceManager.h>
25 #include <utils/Log.h>
26 #include <utils/misc.h>
27 #include <utils/Trace.h>
28 #include <binder/Parcel.h>
29 #include <utils/threads.h>
30 #include <cutils/properties.h>
31 
32 #include <SkGraphics.h>
33 
34 #include "jni.h"
35 #include "JNIHelp.h"
36 #include "JniInvocation.h"
37 #include "android_util_Binder.h"
38 
39 #include <stdio.h>
40 #include <signal.h>
41 #include <sys/stat.h>
42 #include <sys/types.h>
43 #include <signal.h>
44 #include <dirent.h>
45 #include <assert.h>
46 
47 #include <string>
48 #include <vector>
49 
50 
51 using namespace android;
52 
53 extern int register_android_os_Binder(JNIEnv* env);
54 extern int register_android_os_Process(JNIEnv* env);
55 extern int register_android_graphics_Bitmap(JNIEnv*);
56 extern int register_android_graphics_BitmapFactory(JNIEnv*);
57 extern int register_android_graphics_BitmapRegionDecoder(JNIEnv*);
58 extern int register_android_graphics_Camera(JNIEnv* env);
59 extern int register_android_graphics_CreateJavaOutputStreamAdaptor(JNIEnv* env);
60 extern int register_android_graphics_GraphicBuffer(JNIEnv* env);
61 extern int register_android_graphics_Graphics(JNIEnv* env);
62 extern int register_android_graphics_Interpolator(JNIEnv* env);
63 extern int register_android_graphics_MaskFilter(JNIEnv* env);
64 extern int register_android_graphics_Movie(JNIEnv* env);
65 extern int register_android_graphics_NinePatch(JNIEnv*);
66 extern int register_android_graphics_PathEffect(JNIEnv* env);
67 extern int register_android_graphics_Shader(JNIEnv* env);
68 extern int register_android_graphics_Typeface(JNIEnv* env);
69 extern int register_android_graphics_YuvImage(JNIEnv* env);
70 
71 extern int register_com_google_android_gles_jni_EGLImpl(JNIEnv* env);
72 extern int register_com_google_android_gles_jni_GLImpl(JNIEnv* env);
73 extern int register_android_opengl_jni_EGL14(JNIEnv* env);
74 extern int register_android_opengl_jni_EGLExt(JNIEnv* env);
75 extern int register_android_opengl_jni_GLES10(JNIEnv* env);
76 extern int register_android_opengl_jni_GLES10Ext(JNIEnv* env);
77 extern int register_android_opengl_jni_GLES11(JNIEnv* env);
78 extern int register_android_opengl_jni_GLES11Ext(JNIEnv* env);
79 extern int register_android_opengl_jni_GLES20(JNIEnv* env);
80 extern int register_android_opengl_jni_GLES30(JNIEnv* env);
81 extern int register_android_opengl_jni_GLES31(JNIEnv* env);
82 extern int register_android_opengl_jni_GLES31Ext(JNIEnv* env);
83 extern int register_android_opengl_jni_GLES32(JNIEnv* env);
84 
85 extern int register_android_hardware_Camera(JNIEnv *env);
86 extern int register_android_hardware_camera2_CameraMetadata(JNIEnv *env);
87 extern int register_android_hardware_camera2_legacy_LegacyCameraDevice(JNIEnv *env);
88 extern int register_android_hardware_camera2_legacy_PerfMeasurement(JNIEnv *env);
89 extern int register_android_hardware_camera2_DngCreator(JNIEnv *env);
90 extern int register_android_hardware_HardwareBuffer(JNIEnv *env);
91 extern int register_android_hardware_Radio(JNIEnv *env);
92 extern int register_android_hardware_SensorManager(JNIEnv *env);
93 extern int register_android_hardware_SerialPort(JNIEnv *env);
94 extern int register_android_hardware_SoundTrigger(JNIEnv *env);
95 extern int register_android_hardware_UsbDevice(JNIEnv *env);
96 extern int register_android_hardware_UsbDeviceConnection(JNIEnv *env);
97 extern int register_android_hardware_UsbRequest(JNIEnv *env);
98 extern int register_android_hardware_location_ActivityRecognitionHardware(JNIEnv* env);
99 
100 extern int register_android_media_AudioRecord(JNIEnv *env);
101 extern int register_android_media_AudioSystem(JNIEnv *env);
102 extern int register_android_media_AudioTrack(JNIEnv *env);
103 extern int register_android_media_JetPlayer(JNIEnv *env);
104 extern int register_android_media_ToneGenerator(JNIEnv *env);
105 
106 namespace android {
107 
108 /*
109  * JNI-based registration functions.  Note these are properly contained in
110  * namespace android.
111  */
112 extern int register_android_app_admin_SecurityLog(JNIEnv* env);
113 extern int register_android_content_AssetManager(JNIEnv* env);
114 extern int register_android_util_EventLog(JNIEnv* env);
115 extern int register_android_util_Log(JNIEnv* env);
116 extern int register_android_util_MemoryIntArray(JNIEnv* env);
117 extern int register_android_util_PathParser(JNIEnv* env);
118 extern int register_android_content_StringBlock(JNIEnv* env);
119 extern int register_android_content_XmlBlock(JNIEnv* env);
120 extern int register_android_graphics_Canvas(JNIEnv* env);
121 extern int register_android_graphics_CanvasProperty(JNIEnv* env);
122 extern int register_android_graphics_ColorFilter(JNIEnv* env);
123 extern int register_android_graphics_DrawFilter(JNIEnv* env);
124 extern int register_android_graphics_FontFamily(JNIEnv* env);
125 extern int register_android_graphics_Matrix(JNIEnv* env);
126 extern int register_android_graphics_Paint(JNIEnv* env);
127 extern int register_android_graphics_Path(JNIEnv* env);
128 extern int register_android_graphics_PathMeasure(JNIEnv* env);
129 extern int register_android_graphics_Picture(JNIEnv*);
130 extern int register_android_graphics_Region(JNIEnv* env);
131 extern int register_android_graphics_SurfaceTexture(JNIEnv* env);
132 extern int register_android_graphics_drawable_AnimatedVectorDrawable(JNIEnv* env);
133 extern int register_android_graphics_drawable_VectorDrawable(JNIEnv* env);
134 extern int register_android_graphics_pdf_PdfDocument(JNIEnv* env);
135 extern int register_android_graphics_pdf_PdfEditor(JNIEnv* env);
136 extern int register_android_graphics_pdf_PdfRenderer(JNIEnv* env);
137 extern int register_android_view_DisplayEventReceiver(JNIEnv* env);
138 extern int register_android_view_DisplayListCanvas(JNIEnv* env);
139 extern int register_android_view_HardwareLayer(JNIEnv* env);
140 extern int register_android_view_RenderNode(JNIEnv* env);
141 extern int register_android_view_RenderNodeAnimator(JNIEnv* env);
142 extern int register_android_view_Surface(JNIEnv* env);
143 extern int register_android_view_SurfaceControl(JNIEnv* env);
144 extern int register_android_view_SurfaceSession(JNIEnv* env);
145 extern int register_android_view_TextureView(JNIEnv* env);
146 extern int register_android_view_ThreadedRenderer(JNIEnv* env);
147 extern int register_com_android_internal_view_animation_NativeInterpolatorFactoryHelper(JNIEnv *env);
148 extern int register_android_database_CursorWindow(JNIEnv* env);
149 extern int register_android_database_SQLiteConnection(JNIEnv* env);
150 extern int register_android_database_SQLiteGlobal(JNIEnv* env);
151 extern int register_android_database_SQLiteDebug(JNIEnv* env);
152 extern int register_android_nio_utils(JNIEnv* env);
153 extern int register_android_os_Debug(JNIEnv* env);
154 extern int register_android_os_GraphicsEnvironment(JNIEnv* env);
155 extern int register_android_os_HwBinder(JNIEnv *env);
156 extern int register_android_os_HwBlob(JNIEnv *env);
157 extern int register_android_os_HwParcel(JNIEnv *env);
158 extern int register_android_os_HwRemoteBinder(JNIEnv *env);
159 extern int register_android_os_MessageQueue(JNIEnv* env);
160 extern int register_android_os_Parcel(JNIEnv* env);
161 extern int register_android_os_SELinux(JNIEnv* env);
162 extern int register_android_os_VintfObject(JNIEnv *env);
163 extern int register_android_os_VintfRuntimeInfo(JNIEnv *env);
164 extern int register_android_os_seccomp(JNIEnv* env);
165 extern int register_android_os_SystemProperties(JNIEnv *env);
166 extern int register_android_os_SystemClock(JNIEnv* env);
167 extern int register_android_os_Trace(JNIEnv* env);
168 extern int register_android_os_FileObserver(JNIEnv *env);
169 extern int register_android_os_UEventObserver(JNIEnv* env);
170 extern int register_android_os_MemoryFile(JNIEnv* env);
171 extern int register_android_net_LocalSocketImpl(JNIEnv* env);
172 extern int register_android_net_NetworkUtils(JNIEnv* env);
173 extern int register_android_net_TrafficStats(JNIEnv* env);
174 extern int register_android_text_AndroidCharacter(JNIEnv *env);
175 extern int register_android_text_StaticLayout(JNIEnv *env);
176 extern int register_android_text_AndroidBidi(JNIEnv *env);
177 extern int register_android_opengl_classes(JNIEnv *env);
178 extern int register_android_ddm_DdmHandleNativeHeap(JNIEnv *env);
179 extern int register_android_server_NetworkManagementSocketTagger(JNIEnv* env);
180 extern int register_android_backup_BackupDataInput(JNIEnv *env);
181 extern int register_android_backup_BackupDataOutput(JNIEnv *env);
182 extern int register_android_backup_FileBackupHelperBase(JNIEnv *env);
183 extern int register_android_backup_BackupHelperDispatcher(JNIEnv *env);
184 extern int register_android_app_backup_FullBackup(JNIEnv *env);
185 extern int register_android_app_Activity(JNIEnv *env);
186 extern int register_android_app_ActivityThread(JNIEnv *env);
187 extern int register_android_app_ApplicationLoaders(JNIEnv *env);
188 extern int register_android_app_NativeActivity(JNIEnv *env);
189 extern int register_android_media_RemoteDisplay(JNIEnv *env);
190 extern int register_android_util_jar_StrictJarFile(JNIEnv* env);
191 extern int register_android_view_InputChannel(JNIEnv* env);
192 extern int register_android_view_InputDevice(JNIEnv* env);
193 extern int register_android_view_InputEventReceiver(JNIEnv* env);
194 extern int register_android_view_InputEventSender(JNIEnv* env);
195 extern int register_android_view_InputQueue(JNIEnv* env);
196 extern int register_android_view_KeyCharacterMap(JNIEnv *env);
197 extern int register_android_view_KeyEvent(JNIEnv* env);
198 extern int register_android_view_MotionEvent(JNIEnv* env);
199 extern int register_android_view_PointerIcon(JNIEnv* env);
200 extern int register_android_view_VelocityTracker(JNIEnv* env);
201 extern int register_android_content_res_ObbScanner(JNIEnv* env);
202 extern int register_android_content_res_Configuration(JNIEnv* env);
203 extern int register_android_animation_PropertyValuesHolder(JNIEnv *env);
204 extern int register_com_android_internal_content_NativeLibraryHelper(JNIEnv *env);
205 extern int register_com_android_internal_net_NetworkStatsFactory(JNIEnv *env);
206 extern int register_com_android_internal_os_FuseAppLoop(JNIEnv* env);
207 extern int register_com_android_internal_os_PathClassLoaderFactory(JNIEnv* env);
208 extern int register_com_android_internal_os_Zygote(JNIEnv *env);
209 extern int register_com_android_internal_util_VirtualRefBasePtr(JNIEnv *env);
210 
211 static AndroidRuntime* gCurRuntime = NULL;
212 
213 /*
214  * Code written in the Java Programming Language calls here from main().
215  */
com_android_internal_os_RuntimeInit_nativeFinishInit(JNIEnv * env,jobject clazz)216 static void com_android_internal_os_RuntimeInit_nativeFinishInit(JNIEnv* env, jobject clazz)
217 {
218     gCurRuntime->onStarted();
219 }
220 
com_android_internal_os_ZygoteInit_nativeZygoteInit(JNIEnv * env,jobject clazz)221 static void com_android_internal_os_ZygoteInit_nativeZygoteInit(JNIEnv* env, jobject clazz)
222 {
223     gCurRuntime->onZygoteInit();
224 }
225 
com_android_internal_os_RuntimeInit_nativeSetExitWithoutCleanup(JNIEnv * env,jobject clazz,jboolean exitWithoutCleanup)226 static void com_android_internal_os_RuntimeInit_nativeSetExitWithoutCleanup(JNIEnv* env,
227         jobject clazz, jboolean exitWithoutCleanup)
228 {
229     gCurRuntime->setExitWithoutCleanup(exitWithoutCleanup);
230 }
231 
232 /*
233  * JNI registration.
234  */
235 
register_com_android_internal_os_RuntimeInit(JNIEnv * env)236 int register_com_android_internal_os_RuntimeInit(JNIEnv* env)
237 {
238     const JNINativeMethod methods[] = {
239         { "nativeFinishInit", "()V",
240             (void*) com_android_internal_os_RuntimeInit_nativeFinishInit },
241         { "nativeSetExitWithoutCleanup", "(Z)V",
242             (void*) com_android_internal_os_RuntimeInit_nativeSetExitWithoutCleanup },
243     };
244     return jniRegisterNativeMethods(env, "com/android/internal/os/RuntimeInit",
245         methods, NELEM(methods));
246 }
247 
register_com_android_internal_os_ZygoteInit(JNIEnv * env)248 int register_com_android_internal_os_ZygoteInit(JNIEnv* env)
249 {
250     const JNINativeMethod methods[] = {
251         { "nativeZygoteInit", "()V",
252             (void*) com_android_internal_os_ZygoteInit_nativeZygoteInit },
253     };
254     return jniRegisterNativeMethods(env, "com/android/internal/os/ZygoteInit",
255         methods, NELEM(methods));
256 }
257 
258 // ----------------------------------------------------------------------
259 
260 /*static*/ JavaVM* AndroidRuntime::mJavaVM = NULL;
261 
AndroidRuntime(char * argBlockStart,const size_t argBlockLength)262 AndroidRuntime::AndroidRuntime(char* argBlockStart, const size_t argBlockLength) :
263         mExitWithoutCleanup(false),
264         mArgBlockStart(argBlockStart),
265         mArgBlockLength(argBlockLength)
266 {
267     SkGraphics::Init();
268     // There is also a global font cache, but its budget is specified by
269     // SK_DEFAULT_FONT_CACHE_COUNT_LIMIT and SK_DEFAULT_FONT_CACHE_LIMIT.
270 
271     // Pre-allocate enough space to hold a fair number of options.
272     mOptions.setCapacity(20);
273 
274     assert(gCurRuntime == NULL);        // one per process
275     gCurRuntime = this;
276 }
277 
~AndroidRuntime()278 AndroidRuntime::~AndroidRuntime()
279 {
280     SkGraphics::Term();
281 }
282 
283 /*
284  * Register native methods using JNI.
285  */
registerNativeMethods(JNIEnv * env,const char * className,const JNINativeMethod * gMethods,int numMethods)286 /*static*/ int AndroidRuntime::registerNativeMethods(JNIEnv* env,
287     const char* className, const JNINativeMethod* gMethods, int numMethods)
288 {
289     return jniRegisterNativeMethods(env, className, gMethods, numMethods);
290 }
291 
setArgv0(const char * argv0,bool setProcName)292 void AndroidRuntime::setArgv0(const char* argv0, bool setProcName) {
293     if (setProcName) {
294         int len = strlen(argv0);
295         if (len < 15) {
296             pthread_setname_np(pthread_self(), argv0);
297         } else {
298             pthread_setname_np(pthread_self(), argv0 + len - 15);
299         }
300     }
301     memset(mArgBlockStart, 0, mArgBlockLength);
302     strlcpy(mArgBlockStart, argv0, mArgBlockLength);
303 }
304 
callMain(const String8 & className,jclass clazz,const Vector<String8> & args)305 status_t AndroidRuntime::callMain(const String8& className, jclass clazz,
306     const Vector<String8>& args)
307 {
308     JNIEnv* env;
309     jmethodID methodId;
310 
311     ALOGD("Calling main entry %s", className.string());
312 
313     env = getJNIEnv();
314     if (clazz == NULL || env == NULL) {
315         return UNKNOWN_ERROR;
316     }
317 
318     methodId = env->GetStaticMethodID(clazz, "main", "([Ljava/lang/String;)V");
319     if (methodId == NULL) {
320         ALOGE("ERROR: could not find method %s.main(String[])\n", className.string());
321         return UNKNOWN_ERROR;
322     }
323 
324     /*
325      * We want to call main() with a String array with our arguments in it.
326      * Create an array and populate it.
327      */
328     jclass stringClass;
329     jobjectArray strArray;
330 
331     const size_t numArgs = args.size();
332     stringClass = env->FindClass("java/lang/String");
333     strArray = env->NewObjectArray(numArgs, stringClass, NULL);
334 
335     for (size_t i = 0; i < numArgs; i++) {
336         jstring argStr = env->NewStringUTF(args[i].string());
337         env->SetObjectArrayElement(strArray, i, argStr);
338     }
339 
340     env->CallStaticVoidMethod(clazz, methodId, strArray);
341     return NO_ERROR;
342 }
343 
344 /*
345  * The VM calls this through the "exit" hook.
346  */
runtime_exit(int code)347 static void runtime_exit(int code)
348 {
349     gCurRuntime->exit(code);
350 }
351 
352 /*
353  * The VM calls this through the "vfprintf" hook.
354  *
355  * We ignore "fp" and just write the results to the log file.
356  */
runtime_vfprintf(FILE * fp,const char * format,va_list ap)357 static void runtime_vfprintf(FILE* fp, const char* format, va_list ap)
358 {
359     LOG_PRI_VA(ANDROID_LOG_INFO, "vm-printf", format, ap);
360 }
361 
362 /**
363  * The VM calls this when mutex contention debugging is enabled to
364  * determine whether or not the blocked thread was a "sensitive thread"
365  * for user responsiveness/smoothess.
366  *
367  * Our policy for this is whether or not we're tracing any StrictMode
368  * events on this thread (which we might've inherited via Binder calls
369  * into us)
370  */
runtime_isSensitiveThread()371 static bool runtime_isSensitiveThread() {
372     IPCThreadState* state = IPCThreadState::selfOrNull();
373     return state && state->getStrictModePolicy() != 0;
374 }
375 
hasDir(const char * dir)376 static int hasDir(const char* dir)
377 {
378     struct stat s;
379     int res = stat(dir, &s);
380     if (res == 0) {
381         return S_ISDIR(s.st_mode);
382     }
383     return 0;
384 }
385 
hasFile(const char * file)386 static bool hasFile(const char* file) {
387     struct stat s;
388     int res = stat(file, &s);
389     if (res == 0) {
390         return S_ISREG(s.st_mode);
391     }
392     return false;
393 }
394 
395 // Convenience wrapper over the property API that returns an
396 // std::string.
getProperty(const char * key,const char * defaultValue)397 std::string getProperty(const char* key, const char* defaultValue) {
398     std::vector<char> temp(PROPERTY_VALUE_MAX);
399     const int len = property_get(key, &temp[0], defaultValue);
400     if (len < 0) {
401         return "";
402     }
403     return std::string(&temp[0], len);
404 }
405 
406 /*
407  * Read the persistent locale. Inspects the following system properties
408  * (in order) and returns the first non-empty property in the list :
409  *
410  * (1) persist.sys.locale
411  * (2) persist.sys.language/country/localevar (country and localevar are
412  * inspected iff. language is non-empty.
413  * (3) ro.product.locale
414  * (4) ro.product.locale.language/region
415  *
416  * Note that we need to inspect persist.sys.language/country/localevar to
417  * preserve language settings for devices that are upgrading from Lollipop
418  * to M. The same goes for ro.product.locale.language/region as well.
419  */
readLocale()420 const std::string readLocale()
421 {
422     const std::string locale = getProperty("persist.sys.locale", "");
423     if (!locale.empty()) {
424         return locale;
425     }
426 
427     const std::string language = getProperty("persist.sys.language", "");
428     if (!language.empty()) {
429         const std::string country = getProperty("persist.sys.country", "");
430         const std::string variant = getProperty("persist.sys.localevar", "");
431 
432         std::string out = language;
433         if (!country.empty()) {
434             out = out + "-" + country;
435         }
436 
437         if (!variant.empty()) {
438             out = out + "-" + variant;
439         }
440 
441         return out;
442     }
443 
444     const std::string productLocale = getProperty("ro.product.locale", "");
445     if (!productLocale.empty()) {
446         return productLocale;
447     }
448 
449     // If persist.sys.locale and ro.product.locale are missing,
450     // construct a locale value from the individual locale components.
451     const std::string productLanguage = getProperty("ro.product.locale.language", "en");
452     const std::string productRegion = getProperty("ro.product.locale.region", "US");
453 
454     return productLanguage + "-" + productRegion;
455 }
456 
addOption(const char * optionString,void * extraInfo)457 void AndroidRuntime::addOption(const char* optionString, void* extraInfo)
458 {
459     JavaVMOption opt;
460     opt.optionString = optionString;
461     opt.extraInfo = extraInfo;
462     mOptions.add(opt);
463 }
464 
465 /*
466  * Parse a property containing space-separated options that should be
467  * passed directly to the VM, e.g. "-Xmx32m -verbose:gc -Xregenmap".
468  *
469  * This will cut up "extraOptsBuf" as we chop it into individual options.
470  *
471  * If "quotingArg" is non-null, it is passed before each extra option in mOptions.
472  *
473  * Adds the strings, if any, to mOptions.
474  */
parseExtraOpts(char * extraOptsBuf,const char * quotingArg)475 void AndroidRuntime::parseExtraOpts(char* extraOptsBuf, const char* quotingArg)
476 {
477     char* start = extraOptsBuf;
478     char* end = NULL;
479     while (*start != '\0') {
480         while (*start == ' ')                   /* skip leading whitespace */
481             start++;
482         if (*start == '\0')                     /* was trailing ws, bail */
483             break;
484 
485         end = start+1;
486         while (*end != ' ' && *end != '\0')     /* find end of token */
487             end++;
488         if (*end == ' ')
489             *end++ = '\0';          /* mark end, advance to indicate more */
490 
491         if (quotingArg != NULL) {
492             addOption(quotingArg);
493         }
494         addOption(start);
495         start = end;
496     }
497 }
498 
499 /*
500  * Reads a "property" into "buffer" with a default of "defaultArg". If
501  * the property is non-empty, it is treated as a runtime option such
502  * as "-Xmx32m".
503  *
504  * The "runtimeArg" is a prefix for the option such as "-Xms" or "-Xmx".
505  *
506  * If an argument is found, it is added to mOptions.
507  *
508  * If an option is found, it is added to mOptions and true is
509  * returned. Otherwise false is returned.
510  */
parseRuntimeOption(const char * property,char * buffer,const char * runtimeArg,const char * defaultArg)511 bool AndroidRuntime::parseRuntimeOption(const char* property,
512                                         char* buffer,
513                                         const char* runtimeArg,
514                                         const char* defaultArg)
515 {
516     strcpy(buffer, runtimeArg);
517     size_t runtimeArgLen = strlen(runtimeArg);
518     property_get(property, buffer+runtimeArgLen, defaultArg);
519     if (buffer[runtimeArgLen] == '\0') {
520         return false;
521     }
522     addOption(buffer);
523     return true;
524 }
525 
526 /*
527  * Reads a "property" into "buffer". If the property is non-empty, it
528  * is treated as a dex2oat compiler option that should be
529  * passed as a quoted option, e.g. "-Ximage-compiler-option --compiler-filter=assume-verified".
530  *
531  * The "compilerArg" is a prefix for the option such as "--compiler-filter=".
532  *
533  * The "quotingArg" should be "-Ximage-compiler-option" or "-Xcompiler-option".
534  *
535  * If an option is found, it is added to mOptions and true is
536  * returned. Otherwise false is returned.
537  */
parseCompilerOption(const char * property,char * buffer,const char * compilerArg,const char * quotingArg)538 bool AndroidRuntime::parseCompilerOption(const char* property,
539                                          char* buffer,
540                                          const char* compilerArg,
541                                          const char* quotingArg)
542 {
543     strcpy(buffer, compilerArg);
544     size_t compilerArgLen = strlen(compilerArg);
545     property_get(property, buffer+compilerArgLen, "");
546     if (buffer[compilerArgLen] == '\0') {
547         return false;
548     }
549     addOption(quotingArg);
550     addOption(buffer);
551     return true;
552 }
553 
554 /*
555  * Reads a "property" into "buffer". If the property is non-empty, it
556  * is treated as a dex2oat compiler runtime option that should be
557  * passed as a quoted option, e.g. "-Ximage-compiler-option
558  * --runtime-arg -Ximage-compiler-option -Xmx32m".
559  *
560  * The "runtimeArg" is a prefix for the option such as "-Xms" or "-Xmx".
561  *
562  * The "quotingArg" should be "-Ximage-compiler-option" or "-Xcompiler-option".
563  *
564  * If an option is found, it is added to mOptions and true is
565  * returned. Otherwise false is returned.
566  */
parseCompilerRuntimeOption(const char * property,char * buffer,const char * runtimeArg,const char * quotingArg)567 bool AndroidRuntime::parseCompilerRuntimeOption(const char* property,
568                                                 char* buffer,
569                                                 const char* runtimeArg,
570                                                 const char* quotingArg)
571 {
572     strcpy(buffer, runtimeArg);
573     size_t runtimeArgLen = strlen(runtimeArg);
574     property_get(property, buffer+runtimeArgLen, "");
575     if (buffer[runtimeArgLen] == '\0') {
576         return false;
577     }
578     addOption(quotingArg);
579     addOption("--runtime-arg");
580     addOption(quotingArg);
581     addOption(buffer);
582     return true;
583 }
584 
585 /*
586  * Start the Dalvik Virtual Machine.
587  *
588  * Various arguments, most determined by system properties, are passed in.
589  * The "mOptions" vector is updated.
590  *
591  * CAUTION: when adding options in here, be careful not to put the
592  * char buffer inside a nested scope.  Adding the buffer to the
593  * options using mOptions.add() does not copy the buffer, so if the
594  * buffer goes out of scope the option may be overwritten.  It's best
595  * to put the buffer at the top of the function so that it is more
596  * unlikely that someone will surround it in a scope at a later time
597  * and thus introduce a bug.
598  *
599  * Returns 0 on success.
600  */
startVm(JavaVM ** pJavaVM,JNIEnv ** pEnv,bool zygote)601 int AndroidRuntime::startVm(JavaVM** pJavaVM, JNIEnv** pEnv, bool zygote)
602 {
603     JavaVMInitArgs initArgs;
604     char propBuf[PROPERTY_VALUE_MAX];
605     char stackTraceFileBuf[sizeof("-Xstacktracefile:")-1 + PROPERTY_VALUE_MAX];
606     char jniOptsBuf[sizeof("-Xjniopts:")-1 + PROPERTY_VALUE_MAX];
607     char heapstartsizeOptsBuf[sizeof("-Xms")-1 + PROPERTY_VALUE_MAX];
608     char heapsizeOptsBuf[sizeof("-Xmx")-1 + PROPERTY_VALUE_MAX];
609     char heapgrowthlimitOptsBuf[sizeof("-XX:HeapGrowthLimit=")-1 + PROPERTY_VALUE_MAX];
610     char heapminfreeOptsBuf[sizeof("-XX:HeapMinFree=")-1 + PROPERTY_VALUE_MAX];
611     char heapmaxfreeOptsBuf[sizeof("-XX:HeapMaxFree=")-1 + PROPERTY_VALUE_MAX];
612     char usejitOptsBuf[sizeof("-Xusejit:")-1 + PROPERTY_VALUE_MAX];
613     char jitmaxsizeOptsBuf[sizeof("-Xjitmaxsize:")-1 + PROPERTY_VALUE_MAX];
614     char jitinitialsizeOptsBuf[sizeof("-Xjitinitialsize:")-1 + PROPERTY_VALUE_MAX];
615     char jitthresholdOptsBuf[sizeof("-Xjitthreshold:")-1 + PROPERTY_VALUE_MAX];
616     char useJitProfilesOptsBuf[sizeof("-Xjitsaveprofilinginfo:")-1 + PROPERTY_VALUE_MAX];
617     char jitprithreadweightOptBuf[sizeof("-Xjitprithreadweight:")-1 + PROPERTY_VALUE_MAX];
618     char jittransitionweightOptBuf[sizeof("-Xjittransitionweight:")-1 + PROPERTY_VALUE_MAX];
619     char gctypeOptsBuf[sizeof("-Xgc:")-1 + PROPERTY_VALUE_MAX];
620     char backgroundgcOptsBuf[sizeof("-XX:BackgroundGC=")-1 + PROPERTY_VALUE_MAX];
621     char heaptargetutilizationOptsBuf[sizeof("-XX:HeapTargetUtilization=")-1 + PROPERTY_VALUE_MAX];
622     char cachePruneBuf[sizeof("-Xzygote-max-boot-retry=")-1 + PROPERTY_VALUE_MAX];
623     char dex2oatXmsImageFlagsBuf[sizeof("-Xms")-1 + PROPERTY_VALUE_MAX];
624     char dex2oatXmxImageFlagsBuf[sizeof("-Xmx")-1 + PROPERTY_VALUE_MAX];
625     char dex2oatXmsFlagsBuf[sizeof("-Xms")-1 + PROPERTY_VALUE_MAX];
626     char dex2oatXmxFlagsBuf[sizeof("-Xmx")-1 + PROPERTY_VALUE_MAX];
627     char dex2oatCompilerFilterBuf[sizeof("--compiler-filter=")-1 + PROPERTY_VALUE_MAX];
628     char dex2oatImageCompilerFilterBuf[sizeof("--compiler-filter=")-1 + PROPERTY_VALUE_MAX];
629     char dex2oatThreadsBuf[sizeof("-j")-1 + PROPERTY_VALUE_MAX];
630     char dex2oatThreadsImageBuf[sizeof("-j")-1 + PROPERTY_VALUE_MAX];
631     char dex2oat_isa_variant_key[PROPERTY_KEY_MAX];
632     char dex2oat_isa_variant[sizeof("--instruction-set-variant=") -1 + PROPERTY_VALUE_MAX];
633     char dex2oat_isa_features_key[PROPERTY_KEY_MAX];
634     char dex2oat_isa_features[sizeof("--instruction-set-features=") -1 + PROPERTY_VALUE_MAX];
635     char dex2oatFlagsBuf[PROPERTY_VALUE_MAX];
636     char dex2oatImageFlagsBuf[PROPERTY_VALUE_MAX];
637     char extraOptsBuf[PROPERTY_VALUE_MAX];
638     char voldDecryptBuf[PROPERTY_VALUE_MAX];
639     enum {
640       kEMDefault,
641       kEMIntPortable,
642       kEMIntFast,
643       kEMJitCompiler,
644     } executionMode = kEMDefault;
645     char localeOption[sizeof("-Duser.locale=") + PROPERTY_VALUE_MAX];
646     char lockProfThresholdBuf[sizeof("-Xlockprofthreshold:")-1 + PROPERTY_VALUE_MAX];
647     char nativeBridgeLibrary[sizeof("-XX:NativeBridge=") + PROPERTY_VALUE_MAX];
648     char cpuAbiListBuf[sizeof("--cpu-abilist=") + PROPERTY_VALUE_MAX];
649     char methodTraceFileBuf[sizeof("-Xmethod-trace-file:") + PROPERTY_VALUE_MAX];
650     char methodTraceFileSizeBuf[sizeof("-Xmethod-trace-file-size:") + PROPERTY_VALUE_MAX];
651     char fingerprintBuf[sizeof("-Xfingerprint:") + PROPERTY_VALUE_MAX];
652 
653     bool checkJni = false;
654     property_get("dalvik.vm.checkjni", propBuf, "");
655     if (strcmp(propBuf, "true") == 0) {
656         checkJni = true;
657     } else if (strcmp(propBuf, "false") != 0) {
658         /* property is neither true nor false; fall back on kernel parameter */
659         property_get("ro.kernel.android.checkjni", propBuf, "");
660         if (propBuf[0] == '1') {
661             checkJni = true;
662         }
663     }
664     ALOGV("CheckJNI is %s\n", checkJni ? "ON" : "OFF");
665     if (checkJni) {
666         /* extended JNI checking */
667         addOption("-Xcheck:jni");
668 
669         /* with -Xcheck:jni, this provides a JNI function call trace */
670         //addOption("-verbose:jni");
671     }
672 
673     property_get("dalvik.vm.execution-mode", propBuf, "");
674     if (strcmp(propBuf, "int:portable") == 0) {
675         executionMode = kEMIntPortable;
676     } else if (strcmp(propBuf, "int:fast") == 0) {
677         executionMode = kEMIntFast;
678     } else if (strcmp(propBuf, "int:jit") == 0) {
679         executionMode = kEMJitCompiler;
680     }
681 
682     parseRuntimeOption("dalvik.vm.stack-trace-file", stackTraceFileBuf, "-Xstacktracefile:");
683 
684     strcpy(jniOptsBuf, "-Xjniopts:");
685     if (parseRuntimeOption("dalvik.vm.jniopts", jniOptsBuf, "-Xjniopts:")) {
686         ALOGI("JNI options: '%s'\n", jniOptsBuf);
687     }
688 
689     /* route exit() to our handler */
690     addOption("exit", (void*) runtime_exit);
691 
692     /* route fprintf() to our handler */
693     addOption("vfprintf", (void*) runtime_vfprintf);
694 
695     /* register the framework-specific "is sensitive thread" hook */
696     addOption("sensitiveThread", (void*) runtime_isSensitiveThread);
697 
698     /* enable verbose; standard options are { jni, gc, class } */
699     //addOption("-verbose:jni");
700     addOption("-verbose:gc");
701     //addOption("-verbose:class");
702 
703     /*
704      * The default starting and maximum size of the heap.  Larger
705      * values should be specified in a product property override.
706      */
707     parseRuntimeOption("dalvik.vm.heapstartsize", heapstartsizeOptsBuf, "-Xms", "4m");
708     parseRuntimeOption("dalvik.vm.heapsize", heapsizeOptsBuf, "-Xmx", "16m");
709 
710     parseRuntimeOption("dalvik.vm.heapgrowthlimit", heapgrowthlimitOptsBuf, "-XX:HeapGrowthLimit=");
711     parseRuntimeOption("dalvik.vm.heapminfree", heapminfreeOptsBuf, "-XX:HeapMinFree=");
712     parseRuntimeOption("dalvik.vm.heapmaxfree", heapmaxfreeOptsBuf, "-XX:HeapMaxFree=");
713     parseRuntimeOption("dalvik.vm.heaptargetutilization",
714                        heaptargetutilizationOptsBuf,
715                        "-XX:HeapTargetUtilization=");
716 
717     /*
718      * JIT related options.
719      */
720     parseRuntimeOption("dalvik.vm.usejit", usejitOptsBuf, "-Xusejit:");
721     parseRuntimeOption("dalvik.vm.jitmaxsize", jitmaxsizeOptsBuf, "-Xjitmaxsize:");
722     parseRuntimeOption("dalvik.vm.jitinitialsize", jitinitialsizeOptsBuf, "-Xjitinitialsize:");
723     parseRuntimeOption("dalvik.vm.jitthreshold", jitthresholdOptsBuf, "-Xjitthreshold:");
724     property_get("dalvik.vm.usejitprofiles", useJitProfilesOptsBuf, "");
725     if (strcmp(useJitProfilesOptsBuf, "true") == 0) {
726         addOption("-Xjitsaveprofilinginfo");
727     }
728 
729     parseRuntimeOption("dalvik.vm.jitprithreadweight",
730                        jitprithreadweightOptBuf,
731                        "-Xjitprithreadweight:");
732 
733     parseRuntimeOption("dalvik.vm.jittransitionweight",
734                        jittransitionweightOptBuf,
735                        "-Xjittransitionweight:");
736 
737     property_get("ro.config.low_ram", propBuf, "");
738     if (strcmp(propBuf, "true") == 0) {
739       addOption("-XX:LowMemoryMode");
740     }
741 
742     parseRuntimeOption("dalvik.vm.gctype", gctypeOptsBuf, "-Xgc:");
743     parseRuntimeOption("dalvik.vm.backgroundgctype", backgroundgcOptsBuf, "-XX:BackgroundGC=");
744 
745     /*
746      * Enable debugging only for apps forked from zygote.
747      * Set suspend=y to pause during VM init and use android ADB transport.
748      */
749     if (zygote) {
750       addOption("-agentlib:jdwp=transport=dt_android_adb,suspend=n,server=y");
751     }
752 
753     parseRuntimeOption("dalvik.vm.lockprof.threshold",
754                        lockProfThresholdBuf,
755                        "-Xlockprofthreshold:");
756 
757     if (executionMode == kEMIntPortable) {
758         addOption("-Xint:portable");
759     } else if (executionMode == kEMIntFast) {
760         addOption("-Xint:fast");
761     } else if (executionMode == kEMJitCompiler) {
762         addOption("-Xint:jit");
763     }
764 
765     // If we are booting without the real /data, don't spend time compiling.
766     property_get("vold.decrypt", voldDecryptBuf, "");
767     bool skip_compilation = ((strcmp(voldDecryptBuf, "trigger_restart_min_framework") == 0) ||
768                              (strcmp(voldDecryptBuf, "1") == 0));
769 
770     // Extra options for boot.art/boot.oat image generation.
771     parseCompilerRuntimeOption("dalvik.vm.image-dex2oat-Xms", dex2oatXmsImageFlagsBuf,
772                                "-Xms", "-Ximage-compiler-option");
773     parseCompilerRuntimeOption("dalvik.vm.image-dex2oat-Xmx", dex2oatXmxImageFlagsBuf,
774                                "-Xmx", "-Ximage-compiler-option");
775     if (skip_compilation) {
776         addOption("-Ximage-compiler-option");
777         addOption("--compiler-filter=assume-verified");
778     } else {
779         parseCompilerOption("dalvik.vm.image-dex2oat-filter", dex2oatImageCompilerFilterBuf,
780                             "--compiler-filter=", "-Ximage-compiler-option");
781     }
782 
783     // Make sure there is a preloaded-classes file.
784     if (!hasFile("/system/etc/preloaded-classes")) {
785         ALOGE("Missing preloaded-classes file, /system/etc/preloaded-classes not found: %s\n",
786               strerror(errno));
787         return -1;
788     }
789     addOption("-Ximage-compiler-option");
790     addOption("--image-classes=/system/etc/preloaded-classes");
791 
792     // If there is a compiled-classes file, push it.
793     if (hasFile("/system/etc/compiled-classes")) {
794         addOption("-Ximage-compiler-option");
795         addOption("--compiled-classes=/system/etc/compiled-classes");
796     }
797 
798     property_get("dalvik.vm.image-dex2oat-flags", dex2oatImageFlagsBuf, "");
799     parseExtraOpts(dex2oatImageFlagsBuf, "-Ximage-compiler-option");
800 
801     // Extra options for DexClassLoader.
802     parseCompilerRuntimeOption("dalvik.vm.dex2oat-Xms", dex2oatXmsFlagsBuf,
803                                "-Xms", "-Xcompiler-option");
804     parseCompilerRuntimeOption("dalvik.vm.dex2oat-Xmx", dex2oatXmxFlagsBuf,
805                                "-Xmx", "-Xcompiler-option");
806     if (skip_compilation) {
807         addOption("-Xcompiler-option");
808         addOption("--compiler-filter=assume-verified");
809 
810         // We skip compilation when a minimal runtime is brought up for decryption. In that case
811         // /data is temporarily backed by a tmpfs, which is usually small.
812         // If the system image contains prebuilts, they will be relocated into the tmpfs. In this
813         // specific situation it is acceptable to *not* relocate and run out of the prebuilts
814         // directly instead.
815         addOption("--runtime-arg");
816         addOption("-Xnorelocate");
817     } else {
818         parseCompilerOption("dalvik.vm.dex2oat-filter", dex2oatCompilerFilterBuf,
819                             "--compiler-filter=", "-Xcompiler-option");
820     }
821     parseCompilerOption("dalvik.vm.dex2oat-threads", dex2oatThreadsBuf, "-j", "-Xcompiler-option");
822     parseCompilerOption("dalvik.vm.image-dex2oat-threads", dex2oatThreadsImageBuf, "-j",
823                         "-Ximage-compiler-option");
824 
825     // The runtime will compile a boot image, when necessary, not using installd. Thus, we need to
826     // pass the instruction-set-features/variant as an image-compiler-option.
827     // TODO: Find a better way for the instruction-set.
828 #if defined(__arm__)
829     constexpr const char* instruction_set = "arm";
830 #elif defined(__aarch64__)
831     constexpr const char* instruction_set = "arm64";
832 #elif defined(__mips__) && !defined(__LP64__)
833     constexpr const char* instruction_set = "mips";
834 #elif defined(__mips__) && defined(__LP64__)
835     constexpr const char* instruction_set = "mips64";
836 #elif defined(__i386__)
837     constexpr const char* instruction_set = "x86";
838 #elif defined(__x86_64__)
839     constexpr const char* instruction_set = "x86_64";
840 #else
841     constexpr const char* instruction_set = "unknown";
842 #endif
843     // Note: it is OK to reuse the buffer, as the values are exactly the same between
844     //       * compiler-option, used for runtime compilation (DexClassLoader)
845     //       * image-compiler-option, used for boot-image compilation on device
846 
847     // Copy the variant.
848     sprintf(dex2oat_isa_variant_key, "dalvik.vm.isa.%s.variant", instruction_set);
849     parseCompilerOption(dex2oat_isa_variant_key, dex2oat_isa_variant,
850                         "--instruction-set-variant=", "-Ximage-compiler-option");
851     parseCompilerOption(dex2oat_isa_variant_key, dex2oat_isa_variant,
852                         "--instruction-set-variant=", "-Xcompiler-option");
853     // Copy the features.
854     sprintf(dex2oat_isa_features_key, "dalvik.vm.isa.%s.features", instruction_set);
855     parseCompilerOption(dex2oat_isa_features_key, dex2oat_isa_features,
856                         "--instruction-set-features=", "-Ximage-compiler-option");
857     parseCompilerOption(dex2oat_isa_features_key, dex2oat_isa_features,
858                         "--instruction-set-features=", "-Xcompiler-option");
859 
860 
861     property_get("dalvik.vm.dex2oat-flags", dex2oatFlagsBuf, "");
862     parseExtraOpts(dex2oatFlagsBuf, "-Xcompiler-option");
863 
864     /* extra options; parse this late so it overrides others */
865     property_get("dalvik.vm.extra-opts", extraOptsBuf, "");
866     parseExtraOpts(extraOptsBuf, NULL);
867 
868     /* Set the properties for locale */
869     {
870         strcpy(localeOption, "-Duser.locale=");
871         const std::string locale = readLocale();
872         strncat(localeOption, locale.c_str(), PROPERTY_VALUE_MAX);
873         addOption(localeOption);
874     }
875 
876     // Trace files are stored in /data/misc/trace which is writable only in debug mode.
877     property_get("ro.debuggable", propBuf, "0");
878     if (strcmp(propBuf, "1") == 0) {
879         property_get("dalvik.vm.method-trace", propBuf, "false");
880         if (strcmp(propBuf, "true") == 0) {
881             addOption("-Xmethod-trace");
882             parseRuntimeOption("dalvik.vm.method-trace-file",
883                                methodTraceFileBuf,
884                                "-Xmethod-trace-file:");
885             parseRuntimeOption("dalvik.vm.method-trace-file-siz",
886                                methodTraceFileSizeBuf,
887                                "-Xmethod-trace-file-size:");
888             property_get("dalvik.vm.method-trace-stream", propBuf, "false");
889             if (strcmp(propBuf, "true") == 0) {
890                 addOption("-Xmethod-trace-stream");
891             }
892         }
893     }
894 
895     // Native bridge library. "0" means that native bridge is disabled.
896     property_get("ro.dalvik.vm.native.bridge", propBuf, "");
897     if (propBuf[0] == '\0') {
898         ALOGW("ro.dalvik.vm.native.bridge is not expected to be empty");
899     } else if (strcmp(propBuf, "0") != 0) {
900         snprintf(nativeBridgeLibrary, sizeof("-XX:NativeBridge=") + PROPERTY_VALUE_MAX,
901                  "-XX:NativeBridge=%s", propBuf);
902         addOption(nativeBridgeLibrary);
903     }
904 
905 #if defined(__LP64__)
906     const char* cpu_abilist_property_name = "ro.product.cpu.abilist64";
907 #else
908     const char* cpu_abilist_property_name = "ro.product.cpu.abilist32";
909 #endif  // defined(__LP64__)
910     property_get(cpu_abilist_property_name, propBuf, "");
911     if (propBuf[0] == '\0') {
912         ALOGE("%s is not expected to be empty", cpu_abilist_property_name);
913         return -1;
914     }
915     snprintf(cpuAbiListBuf, sizeof(cpuAbiListBuf), "--cpu-abilist=%s", propBuf);
916     addOption(cpuAbiListBuf);
917 
918     // Dalvik-cache pruning counter.
919     parseRuntimeOption("dalvik.vm.zygote.max-boot-retry", cachePruneBuf,
920                        "-Xzygote-max-boot-retry=");
921 
922     /*
923      * When running with debug.generate-debug-info, add --generate-debug-info to
924      * the compiler options so that the boot image, if it is compiled on device,
925      * will include native debugging information.
926      */
927     property_get("debug.generate-debug-info", propBuf, "");
928     if (strcmp(propBuf, "true") == 0) {
929         addOption("-Xcompiler-option");
930         addOption("--generate-debug-info");
931         addOption("-Ximage-compiler-option");
932         addOption("--generate-debug-info");
933     }
934 
935     /*
936      * Retrieve the build fingerprint and provide it to the runtime. That way, ANR dumps will
937      * contain the fingerprint and can be parsed.
938      */
939     parseRuntimeOption("ro.build.fingerprint", fingerprintBuf, "-Xfingerprint:");
940 
941     initArgs.version = JNI_VERSION_1_4;
942     initArgs.options = mOptions.editArray();
943     initArgs.nOptions = mOptions.size();
944     initArgs.ignoreUnrecognized = JNI_FALSE;
945 
946     /*
947      * Initialize the VM.
948      *
949      * The JavaVM* is essentially per-process, and the JNIEnv* is per-thread.
950      * If this call succeeds, the VM is ready, and we can start issuing
951      * JNI calls.
952      */
953     if (JNI_CreateJavaVM(pJavaVM, pEnv, &initArgs) < 0) {
954         ALOGE("JNI_CreateJavaVM failed\n");
955         return -1;
956     }
957 
958     return 0;
959 }
960 
toSlashClassName(const char * className)961 char* AndroidRuntime::toSlashClassName(const char* className)
962 {
963     char* result = strdup(className);
964     for (char* cp = result; *cp != '\0'; cp++) {
965         if (*cp == '.') {
966             *cp = '/';
967         }
968     }
969     return result;
970 }
971 
972 /** Create a Java string from an ASCII or Latin-1 string */
NewStringLatin1(JNIEnv * env,const char * bytes)973 jstring AndroidRuntime::NewStringLatin1(JNIEnv* env, const char* bytes) {
974     if (!bytes) return NULL;
975     int length = strlen(bytes);
976     jchar* buffer = (jchar *)alloca(length * sizeof(jchar));
977     if (!buffer) return NULL;
978     jchar* chp = buffer;
979     for (int i = 0; i < length; i++) {
980         *chp++ = *bytes++;
981     }
982     return env->NewString(buffer, length);
983 }
984 
985 
986 /*
987  * Start the Android runtime.  This involves starting the virtual machine
988  * and calling the "static void main(String[] args)" method in the class
989  * named by "className".
990  *
991  * Passes the main function two arguments, the class name and the specified
992  * options string.
993  */
start(const char * className,const Vector<String8> & options,bool zygote)994 void AndroidRuntime::start(const char* className, const Vector<String8>& options, bool zygote)
995 {
996     ALOGD(">>>>>> START %s uid %d <<<<<<\n",
997             className != NULL ? className : "(unknown)", getuid());
998 
999     static const String8 startSystemServer("start-system-server");
1000 
1001     /*
1002      * 'startSystemServer == true' means runtime is obsolete and not run from
1003      * init.rc anymore, so we print out the boot start event here.
1004      */
1005     for (size_t i = 0; i < options.size(); ++i) {
1006         if (options[i] == startSystemServer) {
1007            /* track our progress through the boot sequence */
1008            const int LOG_BOOT_PROGRESS_START = 3000;
1009            LOG_EVENT_LONG(LOG_BOOT_PROGRESS_START,  ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
1010         }
1011     }
1012 
1013     const char* rootDir = getenv("ANDROID_ROOT");
1014     if (rootDir == NULL) {
1015         rootDir = "/system";
1016         if (!hasDir("/system")) {
1017             LOG_FATAL("No root directory specified, and /android does not exist.");
1018             return;
1019         }
1020         setenv("ANDROID_ROOT", rootDir, 1);
1021     }
1022 
1023     //const char* kernelHack = getenv("LD_ASSUME_KERNEL");
1024     //ALOGD("Found LD_ASSUME_KERNEL='%s'\n", kernelHack);
1025 
1026     /* start the virtual machine */
1027     JniInvocation jni_invocation;
1028     jni_invocation.Init(NULL);
1029     JNIEnv* env;
1030     if (startVm(&mJavaVM, &env, zygote) != 0) {
1031         return;
1032     }
1033     onVmCreated(env);
1034 
1035     /*
1036      * Register android functions.
1037      */
1038     if (startReg(env) < 0) {
1039         ALOGE("Unable to register all android natives\n");
1040         return;
1041     }
1042 
1043     /*
1044      * We want to call main() with a String array with arguments in it.
1045      * At present we have two arguments, the class name and an option string.
1046      * Create an array to hold them.
1047      */
1048     jclass stringClass;
1049     jobjectArray strArray;
1050     jstring classNameStr;
1051 
1052     stringClass = env->FindClass("java/lang/String");
1053     assert(stringClass != NULL);
1054     strArray = env->NewObjectArray(options.size() + 1, stringClass, NULL);
1055     assert(strArray != NULL);
1056     classNameStr = env->NewStringUTF(className);
1057     assert(classNameStr != NULL);
1058     env->SetObjectArrayElement(strArray, 0, classNameStr);
1059 
1060     for (size_t i = 0; i < options.size(); ++i) {
1061         jstring optionsStr = env->NewStringUTF(options.itemAt(i).string());
1062         assert(optionsStr != NULL);
1063         env->SetObjectArrayElement(strArray, i + 1, optionsStr);
1064     }
1065 
1066     /*
1067      * Start VM.  This thread becomes the main thread of the VM, and will
1068      * not return until the VM exits.
1069      */
1070     char* slashClassName = toSlashClassName(className);
1071     jclass startClass = env->FindClass(slashClassName);
1072     if (startClass == NULL) {
1073         ALOGE("JavaVM unable to locate class '%s'\n", slashClassName);
1074         /* keep going */
1075     } else {
1076         jmethodID startMeth = env->GetStaticMethodID(startClass, "main",
1077             "([Ljava/lang/String;)V");
1078         if (startMeth == NULL) {
1079             ALOGE("JavaVM unable to find main() in '%s'\n", className);
1080             /* keep going */
1081         } else {
1082             env->CallStaticVoidMethod(startClass, startMeth, strArray);
1083 
1084 #if 0
1085             if (env->ExceptionCheck())
1086                 threadExitUncaughtException(env);
1087 #endif
1088         }
1089     }
1090     free(slashClassName);
1091 
1092     ALOGD("Shutting down VM\n");
1093     if (mJavaVM->DetachCurrentThread() != JNI_OK)
1094         ALOGW("Warning: unable to detach main thread\n");
1095     if (mJavaVM->DestroyJavaVM() != 0)
1096         ALOGW("Warning: VM did not shut down cleanly\n");
1097 }
1098 
exit(int code)1099 void AndroidRuntime::exit(int code)
1100 {
1101     if (mExitWithoutCleanup) {
1102         ALOGI("VM exiting with result code %d, cleanup skipped.", code);
1103         ::_exit(code);
1104     } else {
1105         ALOGI("VM exiting with result code %d.", code);
1106         onExit(code);
1107         ::exit(code);
1108     }
1109 }
1110 
onVmCreated(JNIEnv * env)1111 void AndroidRuntime::onVmCreated(JNIEnv* env)
1112 {
1113     // If AndroidRuntime had anything to do here, we'd have done it in 'start'.
1114 }
1115 
1116 /*
1117  * Get the JNIEnv pointer for this thread.
1118  *
1119  * Returns NULL if the slot wasn't allocated or populated.
1120  */
getJNIEnv()1121 /*static*/ JNIEnv* AndroidRuntime::getJNIEnv()
1122 {
1123     JNIEnv* env;
1124     JavaVM* vm = AndroidRuntime::getJavaVM();
1125     assert(vm != NULL);
1126 
1127     if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK)
1128         return NULL;
1129     return env;
1130 }
1131 
1132 /*
1133  * Makes the current thread visible to the VM.
1134  *
1135  * The JNIEnv pointer returned is only valid for the current thread, and
1136  * thus must be tucked into thread-local storage.
1137  */
javaAttachThread(const char * threadName,JNIEnv ** pEnv)1138 static int javaAttachThread(const char* threadName, JNIEnv** pEnv)
1139 {
1140     JavaVMAttachArgs args;
1141     JavaVM* vm;
1142     jint result;
1143 
1144     vm = AndroidRuntime::getJavaVM();
1145     assert(vm != NULL);
1146 
1147     args.version = JNI_VERSION_1_4;
1148     args.name = (char*) threadName;
1149     args.group = NULL;
1150 
1151     result = vm->AttachCurrentThread(pEnv, (void*) &args);
1152     if (result != JNI_OK)
1153         ALOGI("NOTE: attach of thread '%s' failed\n", threadName);
1154 
1155     return result;
1156 }
1157 
1158 /*
1159  * Detach the current thread from the set visible to the VM.
1160  */
javaDetachThread(void)1161 static int javaDetachThread(void)
1162 {
1163     JavaVM* vm;
1164     jint result;
1165 
1166     vm = AndroidRuntime::getJavaVM();
1167     assert(vm != NULL);
1168 
1169     result = vm->DetachCurrentThread();
1170     if (result != JNI_OK)
1171         ALOGE("ERROR: thread detach failed\n");
1172     return result;
1173 }
1174 
1175 /*
1176  * When starting a native thread that will be visible from the VM, we
1177  * bounce through this to get the right attach/detach action.
1178  * Note that this function calls free(args)
1179  */
javaThreadShell(void * args)1180 /*static*/ int AndroidRuntime::javaThreadShell(void* args) {
1181     void* start = ((void**)args)[0];
1182     void* userData = ((void **)args)[1];
1183     char* name = (char*) ((void **)args)[2];        // we own this storage
1184     free(args);
1185     JNIEnv* env;
1186     int result;
1187 
1188     /* hook us into the VM */
1189     if (javaAttachThread(name, &env) != JNI_OK)
1190         return -1;
1191 
1192     /* start the thread running */
1193     result = (*(android_thread_func_t)start)(userData);
1194 
1195     /* unhook us */
1196     javaDetachThread();
1197     free(name);
1198 
1199     return result;
1200 }
1201 
1202 /*
1203  * This is invoked from androidCreateThreadEtc() via the callback
1204  * set with androidSetCreateThreadFunc().
1205  *
1206  * We need to create the new thread in such a way that it gets hooked
1207  * into the VM before it really starts executing.
1208  */
javaCreateThreadEtc(android_thread_func_t entryFunction,void * userData,const char * threadName,int32_t threadPriority,size_t threadStackSize,android_thread_id_t * threadId)1209 /*static*/ int AndroidRuntime::javaCreateThreadEtc(
1210                                 android_thread_func_t entryFunction,
1211                                 void* userData,
1212                                 const char* threadName,
1213                                 int32_t threadPriority,
1214                                 size_t threadStackSize,
1215                                 android_thread_id_t* threadId)
1216 {
1217     void** args = (void**) malloc(3 * sizeof(void*));   // javaThreadShell must free
1218     int result;
1219 
1220     LOG_ALWAYS_FATAL_IF(threadName == nullptr, "threadName not provided to javaCreateThreadEtc");
1221 
1222     args[0] = (void*) entryFunction;
1223     args[1] = userData;
1224     args[2] = (void*) strdup(threadName);   // javaThreadShell must free
1225 
1226     result = androidCreateRawThreadEtc(AndroidRuntime::javaThreadShell, args,
1227         threadName, threadPriority, threadStackSize, threadId);
1228     return result;
1229 }
1230 
1231 /*
1232  * Create a thread that is visible from the VM.
1233  *
1234  * This is called from elsewhere in the library.
1235  */
createJavaThread(const char * name,void (* start)(void *),void * arg)1236 /*static*/ android_thread_id_t AndroidRuntime::createJavaThread(const char* name,
1237     void (*start)(void *), void* arg)
1238 {
1239     android_thread_id_t threadId = 0;
1240     javaCreateThreadEtc((android_thread_func_t) start, arg, name,
1241         ANDROID_PRIORITY_DEFAULT, 0, &threadId);
1242     return threadId;
1243 }
1244 
1245 #if 0
1246 static void quickTest(void* arg)
1247 {
1248     const char* str = (const char*) arg;
1249 
1250     printf("In quickTest: %s\n", str);
1251 }
1252 #endif
1253 
1254 #ifdef NDEBUG
1255     #define REG_JNI(name)      { name }
1256     struct RegJNIRec {
1257         int (*mProc)(JNIEnv*);
1258     };
1259 #else
1260     #define REG_JNI(name)      { name, #name }
1261     struct RegJNIRec {
1262         int (*mProc)(JNIEnv*);
1263         const char* mName;
1264     };
1265 #endif
1266 
1267 typedef void (*RegJAMProc)();
1268 
register_jni_procs(const RegJNIRec array[],size_t count,JNIEnv * env)1269 static int register_jni_procs(const RegJNIRec array[], size_t count, JNIEnv* env)
1270 {
1271     for (size_t i = 0; i < count; i++) {
1272         if (array[i].mProc(env) < 0) {
1273 #ifndef NDEBUG
1274             ALOGD("----------!!! %s failed to load\n", array[i].mName);
1275 #endif
1276             return -1;
1277         }
1278     }
1279     return 0;
1280 }
1281 
1282 static const RegJNIRec gRegJNI[] = {
1283     REG_JNI(register_com_android_internal_os_RuntimeInit),
1284     REG_JNI(register_com_android_internal_os_ZygoteInit),
1285     REG_JNI(register_android_os_SystemClock),
1286     REG_JNI(register_android_util_EventLog),
1287     REG_JNI(register_android_util_Log),
1288     REG_JNI(register_android_util_MemoryIntArray),
1289     REG_JNI(register_android_util_PathParser),
1290     REG_JNI(register_android_app_admin_SecurityLog),
1291     REG_JNI(register_android_content_AssetManager),
1292     REG_JNI(register_android_content_StringBlock),
1293     REG_JNI(register_android_content_XmlBlock),
1294     REG_JNI(register_android_text_AndroidCharacter),
1295     REG_JNI(register_android_text_StaticLayout),
1296     REG_JNI(register_android_text_AndroidBidi),
1297     REG_JNI(register_android_view_InputDevice),
1298     REG_JNI(register_android_view_KeyCharacterMap),
1299     REG_JNI(register_android_os_Process),
1300     REG_JNI(register_android_os_SystemProperties),
1301     REG_JNI(register_android_os_Binder),
1302     REG_JNI(register_android_os_Parcel),
1303     REG_JNI(register_android_os_HwBinder),
1304     REG_JNI(register_android_os_HwBlob),
1305     REG_JNI(register_android_os_HwParcel),
1306     REG_JNI(register_android_os_HwRemoteBinder),
1307     REG_JNI(register_android_os_VintfObject),
1308     REG_JNI(register_android_os_VintfRuntimeInfo),
1309     REG_JNI(register_android_nio_utils),
1310     REG_JNI(register_android_graphics_Canvas),
1311     REG_JNI(register_android_graphics_Graphics),
1312     REG_JNI(register_android_view_DisplayEventReceiver),
1313     REG_JNI(register_android_view_RenderNode),
1314     REG_JNI(register_android_view_RenderNodeAnimator),
1315     REG_JNI(register_android_view_DisplayListCanvas),
1316     REG_JNI(register_android_view_HardwareLayer),
1317     REG_JNI(register_android_view_ThreadedRenderer),
1318     REG_JNI(register_android_view_Surface),
1319     REG_JNI(register_android_view_SurfaceControl),
1320     REG_JNI(register_android_view_SurfaceSession),
1321     REG_JNI(register_android_view_TextureView),
1322     REG_JNI(register_com_android_internal_view_animation_NativeInterpolatorFactoryHelper),
1323     REG_JNI(register_com_google_android_gles_jni_EGLImpl),
1324     REG_JNI(register_com_google_android_gles_jni_GLImpl),
1325     REG_JNI(register_android_opengl_jni_EGL14),
1326     REG_JNI(register_android_opengl_jni_EGLExt),
1327     REG_JNI(register_android_opengl_jni_GLES10),
1328     REG_JNI(register_android_opengl_jni_GLES10Ext),
1329     REG_JNI(register_android_opengl_jni_GLES11),
1330     REG_JNI(register_android_opengl_jni_GLES11Ext),
1331     REG_JNI(register_android_opengl_jni_GLES20),
1332     REG_JNI(register_android_opengl_jni_GLES30),
1333     REG_JNI(register_android_opengl_jni_GLES31),
1334     REG_JNI(register_android_opengl_jni_GLES31Ext),
1335     REG_JNI(register_android_opengl_jni_GLES32),
1336 
1337     REG_JNI(register_android_graphics_Bitmap),
1338     REG_JNI(register_android_graphics_BitmapFactory),
1339     REG_JNI(register_android_graphics_BitmapRegionDecoder),
1340     REG_JNI(register_android_graphics_Camera),
1341     REG_JNI(register_android_graphics_CreateJavaOutputStreamAdaptor),
1342     REG_JNI(register_android_graphics_CanvasProperty),
1343     REG_JNI(register_android_graphics_ColorFilter),
1344     REG_JNI(register_android_graphics_DrawFilter),
1345     REG_JNI(register_android_graphics_FontFamily),
1346     REG_JNI(register_android_graphics_GraphicBuffer),
1347     REG_JNI(register_android_graphics_Interpolator),
1348     REG_JNI(register_android_graphics_MaskFilter),
1349     REG_JNI(register_android_graphics_Matrix),
1350     REG_JNI(register_android_graphics_Movie),
1351     REG_JNI(register_android_graphics_NinePatch),
1352     REG_JNI(register_android_graphics_Paint),
1353     REG_JNI(register_android_graphics_Path),
1354     REG_JNI(register_android_graphics_PathMeasure),
1355     REG_JNI(register_android_graphics_PathEffect),
1356     REG_JNI(register_android_graphics_Picture),
1357     REG_JNI(register_android_graphics_Region),
1358     REG_JNI(register_android_graphics_Shader),
1359     REG_JNI(register_android_graphics_SurfaceTexture),
1360     REG_JNI(register_android_graphics_Typeface),
1361     REG_JNI(register_android_graphics_YuvImage),
1362     REG_JNI(register_android_graphics_drawable_AnimatedVectorDrawable),
1363     REG_JNI(register_android_graphics_drawable_VectorDrawable),
1364     REG_JNI(register_android_graphics_pdf_PdfDocument),
1365     REG_JNI(register_android_graphics_pdf_PdfEditor),
1366     REG_JNI(register_android_graphics_pdf_PdfRenderer),
1367 
1368     REG_JNI(register_android_database_CursorWindow),
1369     REG_JNI(register_android_database_SQLiteConnection),
1370     REG_JNI(register_android_database_SQLiteGlobal),
1371     REG_JNI(register_android_database_SQLiteDebug),
1372     REG_JNI(register_android_os_Debug),
1373     REG_JNI(register_android_os_FileObserver),
1374     REG_JNI(register_android_os_GraphicsEnvironment),
1375     REG_JNI(register_android_os_MessageQueue),
1376     REG_JNI(register_android_os_SELinux),
1377     REG_JNI(register_android_os_seccomp),
1378     REG_JNI(register_android_os_Trace),
1379     REG_JNI(register_android_os_UEventObserver),
1380     REG_JNI(register_android_net_LocalSocketImpl),
1381     REG_JNI(register_android_net_NetworkUtils),
1382     REG_JNI(register_android_net_TrafficStats),
1383     REG_JNI(register_android_os_MemoryFile),
1384     REG_JNI(register_com_android_internal_os_PathClassLoaderFactory),
1385     REG_JNI(register_com_android_internal_os_Zygote),
1386     REG_JNI(register_com_android_internal_util_VirtualRefBasePtr),
1387     REG_JNI(register_android_hardware_Camera),
1388     REG_JNI(register_android_hardware_camera2_CameraMetadata),
1389     REG_JNI(register_android_hardware_camera2_legacy_LegacyCameraDevice),
1390     REG_JNI(register_android_hardware_camera2_legacy_PerfMeasurement),
1391     REG_JNI(register_android_hardware_camera2_DngCreator),
1392     REG_JNI(register_android_hardware_HardwareBuffer),
1393     REG_JNI(register_android_hardware_Radio),
1394     REG_JNI(register_android_hardware_SensorManager),
1395     REG_JNI(register_android_hardware_SerialPort),
1396     REG_JNI(register_android_hardware_SoundTrigger),
1397     REG_JNI(register_android_hardware_UsbDevice),
1398     REG_JNI(register_android_hardware_UsbDeviceConnection),
1399     REG_JNI(register_android_hardware_UsbRequest),
1400     REG_JNI(register_android_hardware_location_ActivityRecognitionHardware),
1401     REG_JNI(register_android_media_AudioRecord),
1402     REG_JNI(register_android_media_AudioSystem),
1403     REG_JNI(register_android_media_AudioTrack),
1404     REG_JNI(register_android_media_JetPlayer),
1405     REG_JNI(register_android_media_RemoteDisplay),
1406     REG_JNI(register_android_media_ToneGenerator),
1407 
1408     REG_JNI(register_android_opengl_classes),
1409     REG_JNI(register_android_server_NetworkManagementSocketTagger),
1410     REG_JNI(register_android_ddm_DdmHandleNativeHeap),
1411     REG_JNI(register_android_backup_BackupDataInput),
1412     REG_JNI(register_android_backup_BackupDataOutput),
1413     REG_JNI(register_android_backup_FileBackupHelperBase),
1414     REG_JNI(register_android_backup_BackupHelperDispatcher),
1415     REG_JNI(register_android_app_backup_FullBackup),
1416     REG_JNI(register_android_app_Activity),
1417     REG_JNI(register_android_app_ActivityThread),
1418     REG_JNI(register_android_app_ApplicationLoaders),
1419     REG_JNI(register_android_app_NativeActivity),
1420     REG_JNI(register_android_util_jar_StrictJarFile),
1421     REG_JNI(register_android_view_InputChannel),
1422     REG_JNI(register_android_view_InputEventReceiver),
1423     REG_JNI(register_android_view_InputEventSender),
1424     REG_JNI(register_android_view_InputQueue),
1425     REG_JNI(register_android_view_KeyEvent),
1426     REG_JNI(register_android_view_MotionEvent),
1427     REG_JNI(register_android_view_PointerIcon),
1428     REG_JNI(register_android_view_VelocityTracker),
1429 
1430     REG_JNI(register_android_content_res_ObbScanner),
1431     REG_JNI(register_android_content_res_Configuration),
1432 
1433     REG_JNI(register_android_animation_PropertyValuesHolder),
1434     REG_JNI(register_com_android_internal_content_NativeLibraryHelper),
1435     REG_JNI(register_com_android_internal_net_NetworkStatsFactory),
1436     REG_JNI(register_com_android_internal_os_FuseAppLoop),
1437 };
1438 
1439 /*
1440  * Register android native functions with the VM.
1441  */
startReg(JNIEnv * env)1442 /*static*/ int AndroidRuntime::startReg(JNIEnv* env)
1443 {
1444     ATRACE_NAME("RegisterAndroidNatives");
1445     /*
1446      * This hook causes all future threads created in this process to be
1447      * attached to the JavaVM.  (This needs to go away in favor of JNI
1448      * Attach calls.)
1449      */
1450     androidSetCreateThreadFunc((android_create_thread_fn) javaCreateThreadEtc);
1451 
1452     ALOGV("--- registering native functions ---\n");
1453 
1454     /*
1455      * Every "register" function calls one or more things that return
1456      * a local reference (e.g. FindClass).  Because we haven't really
1457      * started the VM yet, they're all getting stored in the base frame
1458      * and never released.  Use Push/Pop to manage the storage.
1459      */
1460     env->PushLocalFrame(200);
1461 
1462     if (register_jni_procs(gRegJNI, NELEM(gRegJNI), env) < 0) {
1463         env->PopLocalFrame(NULL);
1464         return -1;
1465     }
1466     env->PopLocalFrame(NULL);
1467 
1468     //createJavaThread("fubar", quickTest, (void*) "hello");
1469 
1470     return 0;
1471 }
1472 
getRuntime()1473 AndroidRuntime* AndroidRuntime::getRuntime()
1474 {
1475     return gCurRuntime;
1476 }
1477 
1478 /**
1479  * Used by surface flinger's DdmConnection to register native methods from
1480  * the framework.
1481  */
registerFrameworkNatives(JNIEnv * env)1482 extern "C" jint registerFrameworkNatives(JNIEnv* env) {
1483     return register_jni_procs(gRegJNI, NELEM(gRegJNI), env);
1484 }
1485 }   // namespace android
1486