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