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