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