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