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