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