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