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