blob: 62ca2efe3b8b235112cadf5a26b8c28168da318f [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/* //device/libs/android_runtime/AndroidRuntime.cpp
2**
3** Copyright 2006, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18#define LOG_TAG "AndroidRuntime"
19//#define LOG_NDEBUG 0
20
21#include <android_runtime/AndroidRuntime.h>
Mathias Agopian07952722009-05-19 19:08:10 -070022#include <binder/IBinder.h>
23#include <binder/IServiceManager.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024#include <utils/Log.h>
25#include <utils/misc.h>
Mathias Agopian07952722009-05-19 19:08:10 -070026#include <binder/Parcel.h>
Mathias Agopian8ed6beb2009-06-05 01:26:23 -070027#include <utils/StringArray.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028#include <utils/threads.h>
29#include <cutils/properties.h>
30
31#include <SkGraphics.h>
32#include <SkImageDecoder.h>
Mike Reedfc8db532009-04-27 11:43:30 -040033#include <SkImageRef_GlobalPool.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034
35#include "jni.h"
36#include "JNIHelp.h"
37#include "android_util_Binder.h"
38
39#include <stdio.h>
40#include <signal.h>
41#include <sys/stat.h>
42#include <sys/types.h>
43#include <signal.h>
44#include <dirent.h>
45#include <assert.h>
46
47
48using namespace android;
49
50extern void register_BindTest();
51
52extern int register_android_os_Binder(JNIEnv* env);
53extern int register_android_os_Process(JNIEnv* env);
54extern int register_android_graphics_Bitmap(JNIEnv*);
55extern int register_android_graphics_BitmapFactory(JNIEnv*);
56extern int register_android_graphics_Camera(JNIEnv* env);
57extern int register_android_graphics_Graphics(JNIEnv* env);
58extern int register_android_graphics_Interpolator(JNIEnv* env);
59extern int register_android_graphics_LayerRasterizer(JNIEnv*);
60extern int register_android_graphics_MaskFilter(JNIEnv* env);
61extern int register_android_graphics_Movie(JNIEnv* env);
62extern int register_android_graphics_NinePatch(JNIEnv*);
63extern int register_android_graphics_PathEffect(JNIEnv* env);
64extern int register_android_graphics_Region(JNIEnv* env);
65extern int register_android_graphics_Shader(JNIEnv* env);
66extern int register_android_graphics_Typeface(JNIEnv* env);
Wei-Ta Chenbca2d612009-11-30 17:52:05 +080067extern int register_android_graphics_YuvImage(JNIEnv* env);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068
69extern int register_com_google_android_gles_jni_EGLImpl(JNIEnv* env);
70extern int register_com_google_android_gles_jni_GLImpl(JNIEnv* env);
Jack Palevich1c4907e2009-04-13 16:22:25 -070071extern int register_android_opengl_jni_GLES10(JNIEnv* env);
72extern int register_android_opengl_jni_GLES10Ext(JNIEnv* env);
73extern int register_android_opengl_jni_GLES11(JNIEnv* env);
74extern int register_android_opengl_jni_GLES11Ext(JNIEnv* env);
Jack Palevich560814f2009-11-19 16:34:55 +080075extern int register_android_opengl_jni_GLES20(JNIEnv* env);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076
77extern int register_android_hardware_Camera(JNIEnv *env);
78
79extern int register_android_hardware_SensorManager(JNIEnv *env);
80
81extern int register_android_media_AudioRecord(JNIEnv *env);
82extern int register_android_media_AudioSystem(JNIEnv *env);
83extern int register_android_media_AudioTrack(JNIEnv *env);
84extern int register_android_media_JetPlayer(JNIEnv *env);
85extern int register_android_media_ToneGenerator(JNIEnv *env);
86
87extern int register_android_message_digest_sha1(JNIEnv *env);
88
89extern int register_android_util_FloatMath(JNIEnv* env);
90
91namespace android {
92
93/*
94 * JNI-based registration functions. Note these are properly contained in
95 * namespace android.
96 */
97extern int register_android_content_AssetManager(JNIEnv* env);
98extern int register_android_util_EventLog(JNIEnv* env);
99extern int register_android_util_Log(JNIEnv* env);
100extern int register_android_content_StringBlock(JNIEnv* env);
101extern int register_android_content_XmlBlock(JNIEnv* env);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700102extern int register_android_emoji_EmojiFactory(JNIEnv* env);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103extern int register_android_graphics_Canvas(JNIEnv* env);
104extern int register_android_graphics_ColorFilter(JNIEnv* env);
105extern int register_android_graphics_DrawFilter(JNIEnv* env);
106extern int register_android_graphics_Matrix(JNIEnv* env);
107extern int register_android_graphics_Paint(JNIEnv* env);
108extern int register_android_graphics_Path(JNIEnv* env);
109extern int register_android_graphics_PathMeasure(JNIEnv* env);
110extern int register_android_graphics_Picture(JNIEnv*);
111extern int register_android_graphics_PorterDuff(JNIEnv* env);
112extern int register_android_graphics_Rasterizer(JNIEnv* env);
113extern int register_android_graphics_Xfermode(JNIEnv* env);
114extern int register_android_graphics_PixelFormat(JNIEnv* env);
115extern int register_com_android_internal_graphics_NativeUtils(JNIEnv *env);
116extern int register_android_view_Display(JNIEnv* env);
117extern int register_android_view_Surface(JNIEnv* env);
118extern int register_android_view_ViewRoot(JNIEnv* env);
119extern int register_android_database_CursorWindow(JNIEnv* env);
Vasu Nori5a03f362009-10-20 15:16:35 -0700120extern int register_android_database_SQLiteCompiledSql(JNIEnv* env);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121extern int register_android_database_SQLiteDatabase(JNIEnv* env);
122extern int register_android_database_SQLiteDebug(JNIEnv* env);
123extern int register_android_database_SQLiteProgram(JNIEnv* env);
124extern int register_android_database_SQLiteQuery(JNIEnv* env);
125extern int register_android_database_SQLiteStatement(JNIEnv* env);
126extern int register_android_debug_JNITest(JNIEnv* env);
127extern int register_android_nio_utils(JNIEnv* env);
128extern int register_android_pim_EventRecurrence(JNIEnv* env);
129extern int register_android_text_format_Time(JNIEnv* env);
130extern int register_android_os_Debug(JNIEnv* env);
Christopher Tatefa9e7c02010-05-06 12:07:10 -0700131extern int register_android_os_MessageQueue(JNIEnv* env);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132extern int register_android_os_ParcelFileDescriptor(JNIEnv *env);
133extern int register_android_os_Power(JNIEnv *env);
134extern int register_android_os_StatFs(JNIEnv *env);
135extern int register_android_os_SystemProperties(JNIEnv *env);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136extern int register_android_os_SystemClock(JNIEnv* env);
137extern int register_android_os_FileObserver(JNIEnv *env);
138extern int register_android_os_FileUtils(JNIEnv *env);
139extern int register_android_os_UEventObserver(JNIEnv* env);
140extern int register_android_os_MemoryFile(JNIEnv* env);
141extern int register_android_net_LocalSocketImpl(JNIEnv* env);
142extern int register_android_net_NetworkUtils(JNIEnv* env);
Dan Egnor2b4abcd2010-04-07 17:30:50 -0700143extern int register_android_net_TrafficStats(JNIEnv* env);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144extern int register_android_net_wifi_WifiManager(JNIEnv* env);
145extern int register_android_security_Md5MessageDigest(JNIEnv *env);
146extern int register_android_text_AndroidCharacter(JNIEnv *env);
Doug Feltdae8e942010-02-24 14:33:15 -0800147extern int register_android_text_AndroidBidi(JNIEnv *env);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148extern int register_android_text_KeyCharacterMap(JNIEnv *env);
149extern int register_android_opengl_classes(JNIEnv *env);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150extern int register_android_bluetooth_HeadsetBase(JNIEnv* env);
151extern int register_android_bluetooth_BluetoothAudioGateway(JNIEnv* env);
Nick Pelly0b6955a2009-05-26 19:13:43 -0700152extern int register_android_bluetooth_BluetoothSocket(JNIEnv *env);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153extern int register_android_bluetooth_ScoSocket(JNIEnv *env);
Nick Pellybd022f42009-08-14 18:33:38 -0700154extern int register_android_server_BluetoothService(JNIEnv* env);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155extern int register_android_server_BluetoothEventLoop(JNIEnv *env);
156extern int register_android_server_BluetoothA2dpService(JNIEnv* env);
Christopher Tateecaa7b42010-06-04 14:55:02 -0700157extern int register_android_server_Watchdog(JNIEnv* env);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158extern int register_android_ddm_DdmHandleNativeHeap(JNIEnv *env);
159extern int register_com_android_internal_os_ZygoteInit(JNIEnv* env);
Joe Onorato1cf58742009-06-12 11:06:24 -0700160extern int register_android_backup_BackupDataInput(JNIEnv *env);
Joe Onoratod2110db2009-05-19 13:41:21 -0700161extern int register_android_backup_BackupDataOutput(JNIEnv *env);
Joe Onorato06290a42009-06-18 20:10:37 -0700162extern int register_android_backup_FileBackupHelperBase(JNIEnv *env);
Joe Onorato4ababd92009-06-25 18:29:18 -0400163extern int register_android_backup_BackupHelperDispatcher(JNIEnv *env);
Dianne Hackborn69969e42010-05-04 11:40:40 -0700164extern int register_android_app_NativeActivity(JNIEnv *env);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700165extern int register_android_view_InputChannel(JNIEnv* env);
166extern int register_android_view_InputQueue(JNIEnv* env);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700167extern int register_android_view_KeyEvent(JNIEnv* env);
168extern int register_android_view_MotionEvent(JNIEnv* env);
Kenny Root02c87302010-07-01 08:10:18 -0700169extern int register_android_content_res_ObbScanner(JNIEnv* env);
Dianne Hackborn08d5b8f2010-08-04 11:12:40 -0700170extern int register_android_content_res_Configuration(JNIEnv* env);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171
172static AndroidRuntime* gCurRuntime = NULL;
173
174static void doThrow(JNIEnv* env, const char* exc, const char* msg = NULL)
175{
176 if (jniThrowException(env, exc, msg) != 0)
177 assert(false);
178}
179
180/*
181 * Code written in the Java Programming Language calls here from main().
182 */
183static void com_android_internal_os_RuntimeInit_finishInit(JNIEnv* env, jobject clazz)
184{
185 gCurRuntime->onStarted();
186}
187
188static void com_android_internal_os_RuntimeInit_zygoteInit(JNIEnv* env, jobject clazz)
189{
190 gCurRuntime->onZygoteInit();
191}
192
193static jint com_android_internal_os_RuntimeInit_isComputerOn(JNIEnv* env, jobject clazz)
194{
195 return 1;
196}
197
198static void com_android_internal_os_RuntimeInit_turnComputerOn(JNIEnv* env, jobject clazz)
199{
200}
201
202static jint com_android_internal_os_RuntimeInit_getQwertyKeyboard(JNIEnv* env, jobject clazz)
203{
204 char* value = getenv("qwerty");
205 if (value != NULL && strcmp(value, "true") == 0) {
206 return 1;
207 }
208
209 return 0;
210}
211
212/*
213 * JNI registration.
214 */
215static JNINativeMethod gMethods[] = {
216 { "finishInit", "()V",
217 (void*) com_android_internal_os_RuntimeInit_finishInit },
218 { "zygoteInitNative", "()V",
219 (void*) com_android_internal_os_RuntimeInit_zygoteInit },
220 { "isComputerOn", "()I",
221 (void*) com_android_internal_os_RuntimeInit_isComputerOn },
222 { "turnComputerOn", "()V",
223 (void*) com_android_internal_os_RuntimeInit_turnComputerOn },
224 { "getQwertyKeyboard", "()I",
225 (void*) com_android_internal_os_RuntimeInit_getQwertyKeyboard },
226};
227
228int register_com_android_internal_os_RuntimeInit(JNIEnv* env)
229{
230 return jniRegisterNativeMethods(env, "com/android/internal/os/RuntimeInit",
231 gMethods, NELEM(gMethods));
232}
233
234// ----------------------------------------------------------------------
235
236/*static*/ JavaVM* AndroidRuntime::mJavaVM = NULL;
237
238
239AndroidRuntime::AndroidRuntime()
240{
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700241 SkGraphics::Init();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242 // this sets our preference for 16bit images during decode
243 // in case the src is opaque and 24bit
244 SkImageDecoder::SetDeviceConfig(SkBitmap::kRGB_565_Config);
Mike Reedfc8db532009-04-27 11:43:30 -0400245 // This cache is shared between browser native images, and java "purgeable"
246 // bitmaps. This globalpool is for images that do not either use the java
247 // heap, or are not backed by ashmem. See BitmapFactory.cpp for the key
248 // java call site.
249 SkImageRef_GlobalPool::SetRAMBudget(512 * 1024);
250 // There is also a global font cache, but its budget is specified in code
251 // see SkFontHost_android.cpp
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252
253 // Pre-allocate enough space to hold a fair number of options.
254 mOptions.setCapacity(20);
255
256 assert(gCurRuntime == NULL); // one per process
257 gCurRuntime = this;
258}
259
260AndroidRuntime::~AndroidRuntime()
261{
262 SkGraphics::Term();
263}
264
265/*
266 * Register native methods using JNI.
267 */
268/*static*/ int AndroidRuntime::registerNativeMethods(JNIEnv* env,
269 const char* className, const JNINativeMethod* gMethods, int numMethods)
270{
271 return jniRegisterNativeMethods(env, className, gMethods, numMethods);
272}
273
274/*
275 * Call a static Java Programming Language function that takes no arguments and returns void.
276 */
277status_t AndroidRuntime::callStatic(const char* className, const char* methodName)
278{
279 JNIEnv* env;
280 jclass clazz;
281 jmethodID methodId;
282
283 env = getJNIEnv();
284 if (env == NULL)
285 return UNKNOWN_ERROR;
286
287 clazz = findClass(env, className);
288 if (clazz == NULL) {
289 LOGE("ERROR: could not find class '%s'\n", className);
290 return UNKNOWN_ERROR;
291 }
292 methodId = env->GetStaticMethodID(clazz, methodName, "()V");
293 if (methodId == NULL) {
294 LOGE("ERROR: could not find method %s.%s\n", className, methodName);
295 return UNKNOWN_ERROR;
296 }
297
298 env->CallStaticVoidMethod(clazz, methodId);
299
300 return NO_ERROR;
301}
302
303status_t AndroidRuntime::callMain(
304 const char* className, int argc, const char* const argv[])
305{
306 JNIEnv* env;
307 jclass clazz;
308 jmethodID methodId;
309
310 env = getJNIEnv();
311 if (env == NULL)
312 return UNKNOWN_ERROR;
313
314 clazz = findClass(env, className);
315 if (clazz == NULL) {
316 LOGE("ERROR: could not find class '%s'\n", className);
317 return UNKNOWN_ERROR;
318 }
319
320 methodId = env->GetStaticMethodID(clazz, "main", "([Ljava/lang/String;)V");
321 if (methodId == NULL) {
322 LOGE("ERROR: could not find method %s.main(String[])\n", className);
323 return UNKNOWN_ERROR;
324 }
325
326 /*
327 * We want to call main() with a String array with our arguments in it.
328 * Create an array and populate it.
329 */
330 jclass stringClass;
331 jobjectArray strArray;
332
333 stringClass = env->FindClass("java/lang/String");
334 strArray = env->NewObjectArray(argc, stringClass, NULL);
335
336 for (int i = 0; i < argc; i++) {
337 jstring argStr = env->NewStringUTF(argv[i]);
338 env->SetObjectArrayElement(strArray, i, argStr);
339 }
340
341 env->CallStaticVoidMethod(clazz, methodId, strArray);
342 return NO_ERROR;
343}
344
345/*
346 * Find the named class.
347 */
348jclass AndroidRuntime::findClass(JNIEnv* env, const char* className)
349{
350 char* convName = NULL;
351
352 if (env->ExceptionCheck()) {
353 LOGE("ERROR: exception pending on entry to findClass()\n");
354 return NULL;
355 }
356
357 /*
358 * JNI FindClass uses class names with slashes, but ClassLoader.loadClass
359 * uses the dotted "binary name" format. We don't need to convert the
360 * name with the new approach.
361 */
362#if 0
363 /* (convName only created if necessary -- use className) */
364 for (char* cp = const_cast<char*>(className); *cp != '\0'; cp++) {
365 if (*cp == '.') {
366 if (convName == NULL) {
367 convName = strdup(className);
368 cp = convName + (cp-className);
369 className = convName;
370 }
371 *cp = '/';
372 }
373 }
374#endif
375
376 /*
377 * This is a little awkward because the JNI FindClass call uses the
378 * class loader associated with the native method we're executing in.
379 * Because this native method is part of a "boot" class, JNI doesn't
380 * look for the class in CLASSPATH, which unfortunately is a likely
381 * location for it. (Had we issued the FindClass call before calling
382 * into the VM -- at which point there isn't a native method frame on
383 * the stack -- the VM would have checked CLASSPATH. We have to do
384 * this because we call into Java Programming Language code and
385 * bounce back out.)
386 *
387 * JNI lacks a "find class in a specific class loader" operation, so we
388 * have to do things the hard way.
389 */
390 jclass cls = NULL;
391 //cls = env->FindClass(className);
392
393 jclass javaLangClassLoader;
394 jmethodID getSystemClassLoader, loadClass;
395 jobject systemClassLoader;
396 jstring strClassName;
397
398 /* find the "system" class loader; none of this is expected to fail */
399 javaLangClassLoader = env->FindClass("java/lang/ClassLoader");
400 assert(javaLangClassLoader != NULL);
401 getSystemClassLoader = env->GetStaticMethodID(javaLangClassLoader,
402 "getSystemClassLoader", "()Ljava/lang/ClassLoader;");
403 loadClass = env->GetMethodID(javaLangClassLoader,
404 "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
405 assert(getSystemClassLoader != NULL && loadClass != NULL);
406 systemClassLoader = env->CallStaticObjectMethod(javaLangClassLoader,
407 getSystemClassLoader);
408 assert(systemClassLoader != NULL);
409
410 /* create an object for the class name string; alloc could fail */
411 strClassName = env->NewStringUTF(className);
412 if (env->ExceptionCheck()) {
413 LOGE("ERROR: unable to convert '%s' to string\n", className);
414 goto bail;
415 }
416 LOGV("system class loader is %p, loading %p (%s)\n",
417 systemClassLoader, strClassName, className);
418
419 /* try to find the named class */
420 cls = (jclass) env->CallObjectMethod(systemClassLoader, loadClass,
421 strClassName);
422 if (env->ExceptionCheck()) {
423 LOGE("ERROR: unable to load class '%s' from %p\n",
424 className, systemClassLoader);
425 cls = NULL;
426 goto bail;
427 }
428
429bail:
430 free(convName);
431 return cls;
432}
433
434/*
435 * The VM calls this through the "exit" hook.
436 */
437static void runtime_exit(int code)
438{
439 gCurRuntime->onExit(code);
440 exit(code);
441}
442
443/*
444 * The VM calls this through the "vfprintf" hook.
445 *
446 * We ignore "fp" and just write the results to the log file.
447 */
448static void runtime_vfprintf(FILE* fp, const char* format, va_list ap)
449{
450 LOG_PRI_VA(ANDROID_LOG_INFO, "vm-printf", format, ap);
451}
452
453
454/**
455 * Add VM arguments to the to-be-executed VM
456 * Stops at first non '-' argument (also stops at an argument of '--')
457 * Returns the number of args consumed
458 */
459int AndroidRuntime::addVmArguments(int argc, const char* const argv[])
460{
461 int i;
462
463 for (i = 0; i<argc; i++) {
464 if (argv[i][0] != '-') {
465 return i;
466 }
467 if (argv[i][1] == '-' && argv[i][2] == 0) {
468 return i+1;
469 }
470
471 JavaVMOption opt;
472 memset(&opt, 0, sizeof(opt));
473 opt.optionString = (char*)argv[i];
474 mOptions.add(opt);
475 }
476 return i;
477}
478
479static int hasDir(const char* dir)
480{
481 struct stat s;
482 int res = stat(dir, &s);
483 if (res == 0) {
484 return S_ISDIR(s.st_mode);
485 }
486 return 0;
487}
488
489/*
490 * We just want failed write() calls to just return with an error.
491 */
492static void blockSigpipe()
493{
494 sigset_t mask;
495
496 sigemptyset(&mask);
497 sigaddset(&mask, SIGPIPE);
498 if (sigprocmask(SIG_BLOCK, &mask, NULL) != 0)
499 LOGW("WARNING: SIGPIPE not blocked\n");
500}
501
502/*
503 * Read the persistent locale.
504 */
505static void readLocale(char* language, char* region)
506{
507 char propLang[PROPERTY_VALUE_MAX], propRegn[PROPERTY_VALUE_MAX];
508
509 property_get("persist.sys.language", propLang, "");
510 property_get("persist.sys.country", propRegn, "");
511 if (*propLang == 0 && *propRegn == 0) {
512 /* Set to ro properties, default is en_US */
513 property_get("ro.product.locale.language", propLang, "en");
514 property_get("ro.product.locale.region", propRegn, "US");
515 }
516 strncat(language, propLang, 2);
517 strncat(region, propRegn, 2);
518 //LOGD("language=%s region=%s\n", language, region);
519}
520
Andy McFaddenf70188a2009-03-31 15:52:13 -0700521/*
Brian Carlstrom3c7c3512010-08-04 15:44:39 -0700522 * Parse a property containing space-separated options that should be
523 * passed directly to the VM, e.g. "-Xmx32m -verbose:gc -Xregenmap".
524 *
525 * This will cut up "extraOptsBuf" as we chop it into individual options.
526 *
527 * Adds the strings, if any, to mOptions.
528 */
529void AndroidRuntime::parseExtraOpts(char* extraOptsBuf)
530{
531 JavaVMOption opt;
532 char* start;
533 char* end;
534
535 memset(&opt, 0, sizeof(opt));
536 start = extraOptsBuf;
537 while (*start != '\0') {
538 while (*start == ' ') /* skip leading whitespace */
539 start++;
540 if (*start == '\0') /* was trailing ws, bail */
541 break;
542
543 end = start+1;
544 while (*end != ' ' && *end != '\0') /* find end of token */
545 end++;
546 if (*end == ' ')
547 *end++ = '\0'; /* mark end, advance to indicate more */
548
549 opt.optionString = start;
550 mOptions.add(opt);
551 start = end;
552 }
553}
554
555/*
Andy McFaddenf70188a2009-03-31 15:52:13 -0700556 * Start the Dalvik Virtual Machine.
557 *
558 * Various arguments, most determined by system properties, are passed in.
559 * The "mOptions" vector is updated.
560 *
561 * Returns 0 on success.
562 */
563int AndroidRuntime::startVm(JavaVM** pJavaVM, JNIEnv** pEnv)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800564{
Andy McFaddenf70188a2009-03-31 15:52:13 -0700565 int result = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800566 JavaVMInitArgs initArgs;
567 JavaVMOption opt;
568 char propBuf[PROPERTY_VALUE_MAX];
569 char stackTraceFileBuf[PROPERTY_VALUE_MAX];
570 char dexoptFlagsBuf[PROPERTY_VALUE_MAX];
571 char enableAssertBuf[sizeof("-ea:")-1 + PROPERTY_VALUE_MAX];
572 char jniOptsBuf[sizeof("-Xjniopts:")-1 + PROPERTY_VALUE_MAX];
Dianne Hackbornbdcef702009-08-18 19:15:36 -0700573 char heapsizeOptsBuf[sizeof("-Xmx")-1 + PROPERTY_VALUE_MAX];
Brian Carlstrom3c7c3512010-08-04 15:44:39 -0700574 char extraOptsBuf[PROPERTY_VALUE_MAX];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 char* stackTraceFile = NULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576 bool checkJni = false;
Andy McFaddene2b23e12009-04-03 11:09:46 -0700577 bool checkDexSum = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800578 bool logStdio = false;
Ben Cheng52b0e732009-06-19 13:31:12 -0700579 enum {
580 kEMDefault,
581 kEMIntPortable,
582 kEMIntFast,
583#if defined(WITH_JIT)
584 kEMJitCompiler,
585#endif
586 } executionMode = kEMDefault;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800587
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800588
589 property_get("dalvik.vm.checkjni", propBuf, "");
590 if (strcmp(propBuf, "true") == 0) {
591 checkJni = true;
592 } else if (strcmp(propBuf, "false") != 0) {
593 /* property is neither true nor false; fall back on kernel parameter */
594 property_get("ro.kernel.android.checkjni", propBuf, "");
595 if (propBuf[0] == '1') {
596 checkJni = true;
597 }
598 }
599
600 property_get("dalvik.vm.execution-mode", propBuf, "");
601 if (strcmp(propBuf, "int:portable") == 0) {
602 executionMode = kEMIntPortable;
603 } else if (strcmp(propBuf, "int:fast") == 0) {
604 executionMode = kEMIntFast;
Ben Cheng52b0e732009-06-19 13:31:12 -0700605#if defined(WITH_JIT)
606 } else if (strcmp(propBuf, "int:jit") == 0) {
607 executionMode = kEMJitCompiler;
608#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800609 }
610
611 property_get("dalvik.vm.stack-trace-file", stackTraceFileBuf, "");
612
Andy McFaddene2b23e12009-04-03 11:09:46 -0700613 property_get("dalvik.vm.check-dex-sum", propBuf, "");
614 if (strcmp(propBuf, "true") == 0) {
615 checkDexSum = true;
616 }
617
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800618 property_get("log.redirect-stdio", propBuf, "");
619 if (strcmp(propBuf, "true") == 0) {
620 logStdio = true;
621 }
622
623 strcpy(enableAssertBuf, "-ea:");
624 property_get("dalvik.vm.enableassertions", enableAssertBuf+4, "");
625
626 strcpy(jniOptsBuf, "-Xjniopts:");
627 property_get("dalvik.vm.jniopts", jniOptsBuf+10, "");
628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800629 /* route exit() to our handler */
630 opt.extraInfo = (void*) runtime_exit;
631 opt.optionString = "exit";
632 mOptions.add(opt);
633
634 /* route fprintf() to our handler */
635 opt.extraInfo = (void*) runtime_vfprintf;
636 opt.optionString = "vfprintf";
637 mOptions.add(opt);
638
639 opt.extraInfo = NULL;
640
641 /* enable verbose; standard options are { jni, gc, class } */
642 //options[curOpt++].optionString = "-verbose:jni";
643 opt.optionString = "-verbose:gc";
644 mOptions.add(opt);
645 //options[curOpt++].optionString = "-verbose:class";
646
Dianne Hackbornbdcef702009-08-18 19:15:36 -0700647 strcpy(heapsizeOptsBuf, "-Xmx");
648 property_get("dalvik.vm.heapsize", heapsizeOptsBuf+4, "16m");
649 //LOGI("Heap size: %s", heapsizeOptsBuf);
650 opt.optionString = heapsizeOptsBuf;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800651 mOptions.add(opt);
652
653 /*
654 * Enable or disable dexopt features, such as bytecode verification and
655 * calculation of register maps for precise GC.
656 */
657 property_get("dalvik.vm.dexopt-flags", dexoptFlagsBuf, "");
658 if (dexoptFlagsBuf[0] != '\0') {
659 const char* opc;
660 const char* val;
661
662 opc = strstr(dexoptFlagsBuf, "v="); /* verification */
663 if (opc != NULL) {
664 switch (*(opc+2)) {
665 case 'n': val = "-Xverify:none"; break;
666 case 'r': val = "-Xverify:remote"; break;
667 case 'a': val = "-Xverify:all"; break;
668 default: val = NULL; break;
669 }
670
671 if (val != NULL) {
672 opt.optionString = val;
673 mOptions.add(opt);
674 }
675 }
676
677 opc = strstr(dexoptFlagsBuf, "o="); /* optimization */
678 if (opc != NULL) {
679 switch (*(opc+2)) {
680 case 'n': val = "-Xdexopt:none"; break;
681 case 'v': val = "-Xdexopt:verified"; break;
682 case 'a': val = "-Xdexopt:all"; break;
683 default: val = NULL; break;
684 }
685
686 if (val != NULL) {
687 opt.optionString = val;
688 mOptions.add(opt);
689 }
690 }
691
692 opc = strstr(dexoptFlagsBuf, "m=y"); /* register map */
693 if (opc != NULL) {
694 opt.optionString = "-Xgenregmap";
695 mOptions.add(opt);
The Android Open Source Project7b0b1ed2009-03-18 22:20:26 -0700696
697 /* turn on precise GC while we're at it */
698 opt.optionString = "-Xgc:precise";
699 mOptions.add(opt);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700 }
701 }
702
Barry Hayesc2b32172010-02-02 14:05:09 -0800703 /* enable poisoning of memory of freed objects */
704 property_get("dalvik.vm.gc.overwritefree", propBuf, "false");
705 if (strcmp(propBuf, "true") == 0) {
706 opt.optionString = "-Xgc:overwritefree";
707 mOptions.add(opt);
708 } else if (strcmp(propBuf, "false") != 0) {
709 LOGW("dalvik.vm.gc.overwritefree should be 'true' or 'false'");
710 }
711
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800712 /* enable debugging; set suspend=y to pause during VM init */
713#ifdef HAVE_ANDROID_OS
714 /* use android ADB transport */
715 opt.optionString =
716 "-agentlib:jdwp=transport=dt_android_adb,suspend=n,server=y";
717#else
718 /* use TCP socket; address=0 means start at port 8000 and probe up */
719 LOGI("Using TCP socket for JDWP\n");
720 opt.optionString =
721 "-agentlib:jdwp=transport=dt_socket,suspend=n,server=y,address=0";
722#endif
723 mOptions.add(opt);
724
725 char enableDPBuf[sizeof("-Xdeadlockpredict:") + PROPERTY_VALUE_MAX];
726 property_get("dalvik.vm.deadlock-predict", propBuf, "");
727 if (strlen(propBuf) > 0) {
728 strcpy(enableDPBuf, "-Xdeadlockpredict:");
729 strcat(enableDPBuf, propBuf);
730 opt.optionString = enableDPBuf;
731 mOptions.add(opt);
732 }
733
734 LOGD("CheckJNI is %s\n", checkJni ? "ON" : "OFF");
735 if (checkJni) {
736 /* extended JNI checking */
737 opt.optionString = "-Xcheck:jni";
738 mOptions.add(opt);
739
740 /* set a cap on JNI global references */
741 opt.optionString = "-Xjnigreflimit:2000";
742 mOptions.add(opt);
743
744 /* with -Xcheck:jni, this provides a JNI function call trace */
745 //opt.optionString = "-verbose:jni";
746 //mOptions.add(opt);
747 }
Ben Cheng52b0e732009-06-19 13:31:12 -0700748
Carl Shapirod8f3ec62010-04-12 16:31:59 -0700749 char lockProfThresholdBuf[sizeof("-Xlockprofthreshold:") + sizeof(propBuf)];
750 property_get("dalvik.vm.lockprof.threshold", propBuf, "");
751 if (strlen(propBuf) > 0) {
752 strcpy(lockProfThresholdBuf, "-Xlockprofthreshold:");
753 strcat(lockProfThresholdBuf, propBuf);
754 opt.optionString = lockProfThresholdBuf;
755 mOptions.add(opt);
756 }
757
Ben Cheng52b0e732009-06-19 13:31:12 -0700758#if defined(WITH_JIT)
759 /* Minimal profile threshold to trigger JIT compilation */
Ben Cheng69c997a2010-03-24 16:15:43 -0700760 char jitThresholdBuf[sizeof("-Xjitthreshold:") + PROPERTY_VALUE_MAX];
Ben Cheng52b0e732009-06-19 13:31:12 -0700761 property_get("dalvik.vm.jit.threshold", propBuf, "");
762 if (strlen(propBuf) > 0) {
Ben Cheng69c997a2010-03-24 16:15:43 -0700763 strcpy(jitThresholdBuf, "-Xjitthreshold:");
Ben Cheng52b0e732009-06-19 13:31:12 -0700764 strcat(jitThresholdBuf, propBuf);
765 opt.optionString = jitThresholdBuf;
766 mOptions.add(opt);
767 }
768
769 /* Force interpreter-only mode for selected opcodes. Eg "1-0a,3c,f1-ff" */
770 char jitOpBuf[sizeof("-Xjitop:") + PROPERTY_VALUE_MAX];
771 property_get("dalvik.vm.jit.op", propBuf, "");
772 if (strlen(propBuf) > 0) {
773 strcpy(jitOpBuf, "-Xjitop:");
774 strcat(jitOpBuf, propBuf);
775 opt.optionString = jitOpBuf;
776 mOptions.add(opt);
777 }
778
779 /*
780 * Reverse the polarity of dalvik.vm.jit.op and force interpreter-only
781 * for non-selected opcodes.
782 */
Ben Chenge090f3b2009-06-19 17:13:36 -0700783 property_get("dalvik.vm.jit.includeop", propBuf, "");
Ben Cheng52b0e732009-06-19 13:31:12 -0700784 if (strlen(propBuf) > 0) {
785 opt.optionString = "-Xincludeselectedop";
786 mOptions.add(opt);
787 }
788
789 /* Force interpreter-only mode for selected methods */
790 char jitMethodBuf[sizeof("-Xjitmethod:") + PROPERTY_VALUE_MAX];
791 property_get("dalvik.vm.jit.method", propBuf, "");
792 if (strlen(propBuf) > 0) {
793 strcpy(jitMethodBuf, "-Xjitmethod:");
794 strcat(jitMethodBuf, propBuf);
795 opt.optionString = jitMethodBuf;
796 mOptions.add(opt);
797 }
798
799 /*
800 * Reverse the polarity of dalvik.vm.jit.method and force interpreter-only
801 * for non-selected methods.
802 */
Ben Chenge090f3b2009-06-19 17:13:36 -0700803 property_get("dalvik.vm.jit.includemethod", propBuf, "");
Ben Cheng52b0e732009-06-19 13:31:12 -0700804 if (strlen(propBuf) > 0) {
805 opt.optionString = "-Xincludeselectedmethod";
806 mOptions.add(opt);
807 }
Ben Cheng0e01fbf2009-07-17 16:03:26 -0700808
809 /*
810 * Enable profile collection on JIT'ed code.
811 */
812 property_get("dalvik.vm.jit.profile", propBuf, "");
813 if (strlen(propBuf) > 0) {
814 opt.optionString = "-Xjitprofile";
815 mOptions.add(opt);
816 }
Ben Chengacc56ec2009-09-11 12:59:53 -0700817
818 /*
819 * Disable optimizations by setting the corresponding bit to 1.
820 */
821 char jitOptBuf[sizeof("-Xjitdisableopt:") + PROPERTY_VALUE_MAX];
822 property_get("dalvik.vm.jit.disableopt", propBuf, "");
823 if (strlen(propBuf) > 0) {
824 strcpy(jitOptBuf, "-Xjitdisableopt:");
825 strcat(jitOptBuf, propBuf);
826 opt.optionString = jitOptBuf;
827 mOptions.add(opt);
828 }
Ben Cheng52b0e732009-06-19 13:31:12 -0700829#endif
830
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800831 if (executionMode == kEMIntPortable) {
832 opt.optionString = "-Xint:portable";
833 mOptions.add(opt);
834 } else if (executionMode == kEMIntFast) {
835 opt.optionString = "-Xint:fast";
836 mOptions.add(opt);
Ben Cheng52b0e732009-06-19 13:31:12 -0700837#if defined(WITH_JIT)
838 } else if (executionMode == kEMJitCompiler) {
839 opt.optionString = "-Xint:jit";
840 mOptions.add(opt);
841#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 }
Andy McFaddene2b23e12009-04-03 11:09:46 -0700843
844 if (checkDexSum) {
845 /* perform additional DEX checksum tests */
846 opt.optionString = "-Xcheckdexsum";
847 mOptions.add(opt);
848 }
849
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 if (logStdio) {
851 /* convert stdout/stderr to log messages */
852 opt.optionString = "-Xlog-stdio";
853 mOptions.add(opt);
854 }
855
856 if (enableAssertBuf[4] != '\0') {
857 /* accept "all" to mean "all classes and packages" */
858 if (strcmp(enableAssertBuf+4, "all") == 0)
859 enableAssertBuf[3] = '\0';
860 LOGI("Assertions enabled: '%s'\n", enableAssertBuf);
861 opt.optionString = enableAssertBuf;
862 mOptions.add(opt);
863 } else {
864 LOGV("Assertions disabled\n");
865 }
866
867 if (jniOptsBuf[10] != '\0') {
868 LOGI("JNI options: '%s'\n", jniOptsBuf);
869 opt.optionString = jniOptsBuf;
870 mOptions.add(opt);
871 }
872
873 if (stackTraceFileBuf[0] != '\0') {
874 static const char* stfOptName = "-Xstacktracefile:";
875
876 stackTraceFile = (char*) malloc(strlen(stfOptName) +
877 strlen(stackTraceFileBuf) +1);
878 strcpy(stackTraceFile, stfOptName);
879 strcat(stackTraceFile, stackTraceFileBuf);
880 opt.optionString = stackTraceFile;
881 mOptions.add(opt);
882 }
Brian Carlstrom3c7c3512010-08-04 15:44:39 -0700883
884 /* extra options; parse this late so it overrides others */
885 property_get("dalvik.vm.extra-opts", extraOptsBuf, "");
886 parseExtraOpts(extraOptsBuf);
887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 /* Set the properties for locale */
889 {
890 char langOption[sizeof("-Duser.language=") + 3];
891 char regionOption[sizeof("-Duser.region=") + 3];
892 strcpy(langOption, "-Duser.language=");
893 strcpy(regionOption, "-Duser.region=");
894 readLocale(langOption, regionOption);
895 opt.extraInfo = NULL;
896 opt.optionString = langOption;
897 mOptions.add(opt);
898 opt.optionString = regionOption;
899 mOptions.add(opt);
900 }
901
902 /*
903 * We don't have /tmp on the device, but we often have an SD card. Apps
904 * shouldn't use this, but some test suites might want to exercise it.
905 */
906 opt.optionString = "-Djava.io.tmpdir=/sdcard";
907 mOptions.add(opt);
908
909 initArgs.version = JNI_VERSION_1_4;
910 initArgs.options = mOptions.editArray();
911 initArgs.nOptions = mOptions.size();
912 initArgs.ignoreUnrecognized = JNI_FALSE;
913
914 /*
915 * Initialize the VM.
916 *
917 * The JavaVM* is essentially per-process, and the JNIEnv* is per-thread.
918 * If this call succeeds, the VM is ready, and we can start issuing
919 * JNI calls.
920 */
Andy McFaddenf70188a2009-03-31 15:52:13 -0700921 if (JNI_CreateJavaVM(pJavaVM, pEnv, &initArgs) < 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800922 LOGE("JNI_CreateJavaVM failed\n");
923 goto bail;
924 }
925
Andy McFaddenf70188a2009-03-31 15:52:13 -0700926 result = 0;
927
928bail:
929 free(stackTraceFile);
930 return result;
931}
932
933/*
934 * Start the Android runtime. This involves starting the virtual machine
935 * and calling the "static void main(String[] args)" method in the class
936 * named by "className".
937 */
938void AndroidRuntime::start(const char* className, const bool startSystemServer)
939{
940 LOGD("\n>>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<<\n");
941
942 char* slashClassName = NULL;
943 char* cp;
944 JNIEnv* env;
945
946 blockSigpipe();
947
948 /*
949 * 'startSystemServer == true' means runtime is obslete and not run from
950 * init.rc anymore, so we print out the boot start event here.
951 */
952 if (startSystemServer) {
953 /* track our progress through the boot sequence */
954 const int LOG_BOOT_PROGRESS_START = 3000;
955 LOG_EVENT_LONG(LOG_BOOT_PROGRESS_START,
956 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
957 }
958
959 const char* rootDir = getenv("ANDROID_ROOT");
960 if (rootDir == NULL) {
961 rootDir = "/system";
962 if (!hasDir("/system")) {
963 LOG_FATAL("No root directory specified, and /android does not exist.");
964 goto bail;
965 }
966 setenv("ANDROID_ROOT", rootDir, 1);
967 }
968
969 //const char* kernelHack = getenv("LD_ASSUME_KERNEL");
970 //LOGD("Found LD_ASSUME_KERNEL='%s'\n", kernelHack);
971
972 /* start the virtual machine */
973 if (startVm(&mJavaVM, &env) != 0)
974 goto bail;
975
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 /*
977 * Register android functions.
978 */
979 if (startReg(env) < 0) {
980 LOGE("Unable to register all android natives\n");
981 goto bail;
982 }
983
984 /*
985 * We want to call main() with a String array with arguments in it.
986 * At present we only have one argument, the class name. Create an
987 * array to hold it.
988 */
989 jclass stringClass;
990 jobjectArray strArray;
991 jstring classNameStr;
992 jstring startSystemServerStr;
993
994 stringClass = env->FindClass("java/lang/String");
995 assert(stringClass != NULL);
996 strArray = env->NewObjectArray(2, stringClass, NULL);
997 assert(strArray != NULL);
998 classNameStr = env->NewStringUTF(className);
999 assert(classNameStr != NULL);
1000 env->SetObjectArrayElement(strArray, 0, classNameStr);
1001 startSystemServerStr = env->NewStringUTF(startSystemServer ?
1002 "true" : "false");
1003 env->SetObjectArrayElement(strArray, 1, startSystemServerStr);
1004
1005 /*
1006 * Start VM. This thread becomes the main thread of the VM, and will
1007 * not return until the VM exits.
1008 */
1009 jclass startClass;
1010 jmethodID startMeth;
1011
1012 slashClassName = strdup(className);
1013 for (cp = slashClassName; *cp != '\0'; cp++)
1014 if (*cp == '.')
1015 *cp = '/';
1016
1017 startClass = env->FindClass(slashClassName);
1018 if (startClass == NULL) {
1019 LOGE("JavaVM unable to locate class '%s'\n", slashClassName);
1020 /* keep going */
1021 } else {
1022 startMeth = env->GetStaticMethodID(startClass, "main",
1023 "([Ljava/lang/String;)V");
1024 if (startMeth == NULL) {
1025 LOGE("JavaVM unable to find main() in '%s'\n", className);
1026 /* keep going */
1027 } else {
1028 env->CallStaticVoidMethod(startClass, startMeth, strArray);
1029
1030#if 0
1031 if (env->ExceptionCheck())
1032 threadExitUncaughtException(env);
1033#endif
1034 }
1035 }
1036
1037 LOGD("Shutting down VM\n");
1038 if (mJavaVM->DetachCurrentThread() != JNI_OK)
1039 LOGW("Warning: unable to detach main thread\n");
1040 if (mJavaVM->DestroyJavaVM() != 0)
1041 LOGW("Warning: VM did not shut down cleanly\n");
1042
1043bail:
1044 free(slashClassName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045}
1046
1047void AndroidRuntime::start()
1048{
1049 start("com.android.internal.os.RuntimeInit",
1050 false /* Don't start the system server */);
1051}
1052
1053void AndroidRuntime::onExit(int code)
1054{
1055 LOGI("AndroidRuntime onExit calling exit(%d)", code);
1056 exit(code);
1057}
1058
1059/*
1060 * Get the JNIEnv pointer for this thread.
1061 *
1062 * Returns NULL if the slot wasn't allocated or populated.
1063 */
1064/*static*/ JNIEnv* AndroidRuntime::getJNIEnv()
1065{
1066 JNIEnv* env;
1067 JavaVM* vm = AndroidRuntime::getJavaVM();
1068 assert(vm != NULL);
1069
1070 if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK)
1071 return NULL;
1072 return env;
1073}
1074
1075/*
1076 * Makes the current thread visible to the VM.
1077 *
1078 * The JNIEnv pointer returned is only valid for the current thread, and
1079 * thus must be tucked into thread-local storage.
1080 */
1081static int javaAttachThread(const char* threadName, JNIEnv** pEnv)
1082{
1083 JavaVMAttachArgs args;
1084 JavaVM* vm;
1085 jint result;
1086
1087 vm = AndroidRuntime::getJavaVM();
1088 assert(vm != NULL);
1089
1090 args.version = JNI_VERSION_1_4;
1091 args.name = (char*) threadName;
1092 args.group = NULL;
1093
1094 result = vm->AttachCurrentThread(pEnv, (void*) &args);
1095 if (result != JNI_OK)
Andy McFadden701d9162010-03-01 14:03:13 -08001096 LOGI("NOTE: attach of thread '%s' failed\n", threadName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097
1098 return result;
1099}
1100
1101/*
1102 * Detach the current thread from the set visible to the VM.
1103 */
1104static int javaDetachThread(void)
1105{
1106 JavaVM* vm;
1107 jint result;
1108
1109 vm = AndroidRuntime::getJavaVM();
1110 assert(vm != NULL);
1111
1112 result = vm->DetachCurrentThread();
1113 if (result != JNI_OK)
1114 LOGE("ERROR: thread detach failed\n");
1115 return result;
1116}
1117
1118/*
1119 * When starting a native thread that will be visible from the VM, we
1120 * bounce through this to get the right attach/detach action.
1121 * Note that this function calls free(args)
1122 */
1123/*static*/ int AndroidRuntime::javaThreadShell(void* args) {
1124 void* start = ((void**)args)[0];
1125 void* userData = ((void **)args)[1];
1126 char* name = (char*) ((void **)args)[2]; // we own this storage
1127 free(args);
1128 JNIEnv* env;
1129 int result;
1130
1131 /* hook us into the VM */
1132 if (javaAttachThread(name, &env) != JNI_OK)
1133 return -1;
1134
1135 /* start the thread running */
1136 result = (*(android_thread_func_t)start)(userData);
1137
1138 /* unhook us */
1139 javaDetachThread();
1140 free(name);
1141
1142 return result;
1143}
1144
1145/*
1146 * This is invoked from androidCreateThreadEtc() via the callback
1147 * set with androidSetCreateThreadFunc().
1148 *
1149 * We need to create the new thread in such a way that it gets hooked
1150 * into the VM before it really starts executing.
1151 */
1152/*static*/ int AndroidRuntime::javaCreateThreadEtc(
1153 android_thread_func_t entryFunction,
1154 void* userData,
1155 const char* threadName,
1156 int32_t threadPriority,
1157 size_t threadStackSize,
1158 android_thread_id_t* threadId)
1159{
1160 void** args = (void**) malloc(3 * sizeof(void*)); // javaThreadShell must free
1161 int result;
1162
1163 assert(threadName != NULL);
1164
1165 args[0] = (void*) entryFunction;
1166 args[1] = userData;
1167 args[2] = (void*) strdup(threadName); // javaThreadShell must free
1168
1169 result = androidCreateRawThreadEtc(AndroidRuntime::javaThreadShell, args,
1170 threadName, threadPriority, threadStackSize, threadId);
1171 return result;
1172}
1173
1174/*
1175 * Create a thread that is visible from the VM.
1176 *
1177 * This is called from elsewhere in the library.
1178 */
Mike Lockwoodf602d362010-06-20 14:28:16 -07001179/*static*/ android_thread_id_t AndroidRuntime::createJavaThread(const char* name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001180 void (*start)(void *), void* arg)
1181{
Mike Lockwoodf602d362010-06-20 14:28:16 -07001182 android_thread_id_t threadId = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183 javaCreateThreadEtc((android_thread_func_t) start, arg, name,
Mike Lockwoodf602d362010-06-20 14:28:16 -07001184 ANDROID_PRIORITY_DEFAULT, 0, &threadId);
1185 return threadId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001186}
1187
1188#if 0
1189static void quickTest(void* arg)
1190{
1191 const char* str = (const char*) arg;
1192
1193 printf("In quickTest: %s\n", str);
1194}
1195#endif
1196
1197#ifdef NDEBUG
1198 #define REG_JNI(name) { name }
1199 struct RegJNIRec {
1200 int (*mProc)(JNIEnv*);
1201 };
1202#else
1203 #define REG_JNI(name) { name, #name }
1204 struct RegJNIRec {
1205 int (*mProc)(JNIEnv*);
1206 const char* mName;
1207 };
1208#endif
1209
1210typedef void (*RegJAMProc)();
1211
1212static int register_jni_procs(const RegJNIRec array[], size_t count, JNIEnv* env)
1213{
1214 for (size_t i = 0; i < count; i++) {
1215 if (array[i].mProc(env) < 0) {
1216#ifndef NDEBUG
1217 LOGD("----------!!! %s failed to load\n", array[i].mName);
1218#endif
1219 return -1;
1220 }
1221 }
1222 return 0;
1223}
1224
1225static void register_jam_procs(const RegJAMProc array[], size_t count)
1226{
1227 for (size_t i = 0; i < count; i++) {
1228 array[i]();
1229 }
1230}
1231
1232static const RegJNIRec gRegJNI[] = {
1233 REG_JNI(register_android_debug_JNITest),
1234 REG_JNI(register_com_android_internal_os_RuntimeInit),
1235 REG_JNI(register_android_os_SystemClock),
1236 REG_JNI(register_android_util_EventLog),
1237 REG_JNI(register_android_util_Log),
1238 REG_JNI(register_android_util_FloatMath),
1239 REG_JNI(register_android_text_format_Time),
1240 REG_JNI(register_android_pim_EventRecurrence),
1241 REG_JNI(register_android_content_AssetManager),
1242 REG_JNI(register_android_content_StringBlock),
1243 REG_JNI(register_android_content_XmlBlock),
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001244 REG_JNI(register_android_emoji_EmojiFactory),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245 REG_JNI(register_android_security_Md5MessageDigest),
1246 REG_JNI(register_android_text_AndroidCharacter),
Doug Feltdae8e942010-02-24 14:33:15 -08001247 REG_JNI(register_android_text_AndroidBidi),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001248 REG_JNI(register_android_text_KeyCharacterMap),
1249 REG_JNI(register_android_os_Process),
1250 REG_JNI(register_android_os_Binder),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001251 REG_JNI(register_android_view_Display),
1252 REG_JNI(register_android_nio_utils),
1253 REG_JNI(register_android_graphics_PixelFormat),
1254 REG_JNI(register_android_graphics_Graphics),
1255 REG_JNI(register_android_view_Surface),
1256 REG_JNI(register_android_view_ViewRoot),
1257 REG_JNI(register_com_google_android_gles_jni_EGLImpl),
1258 REG_JNI(register_com_google_android_gles_jni_GLImpl),
Jack Palevich1c4907e2009-04-13 16:22:25 -07001259 REG_JNI(register_android_opengl_jni_GLES10),
1260 REG_JNI(register_android_opengl_jni_GLES10Ext),
1261 REG_JNI(register_android_opengl_jni_GLES11),
1262 REG_JNI(register_android_opengl_jni_GLES11Ext),
Jack Palevich560814f2009-11-19 16:34:55 +08001263 REG_JNI(register_android_opengl_jni_GLES20),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264
1265 REG_JNI(register_android_graphics_Bitmap),
1266 REG_JNI(register_android_graphics_BitmapFactory),
1267 REG_JNI(register_android_graphics_Camera),
1268 REG_JNI(register_android_graphics_Canvas),
1269 REG_JNI(register_android_graphics_ColorFilter),
1270 REG_JNI(register_android_graphics_DrawFilter),
1271 REG_JNI(register_android_graphics_Interpolator),
1272 REG_JNI(register_android_graphics_LayerRasterizer),
1273 REG_JNI(register_android_graphics_MaskFilter),
1274 REG_JNI(register_android_graphics_Matrix),
1275 REG_JNI(register_android_graphics_Movie),
1276 REG_JNI(register_android_graphics_NinePatch),
1277 REG_JNI(register_android_graphics_Paint),
1278 REG_JNI(register_android_graphics_Path),
1279 REG_JNI(register_android_graphics_PathMeasure),
1280 REG_JNI(register_android_graphics_PathEffect),
1281 REG_JNI(register_android_graphics_Picture),
1282 REG_JNI(register_android_graphics_PorterDuff),
1283 REG_JNI(register_android_graphics_Rasterizer),
1284 REG_JNI(register_android_graphics_Region),
1285 REG_JNI(register_android_graphics_Shader),
1286 REG_JNI(register_android_graphics_Typeface),
1287 REG_JNI(register_android_graphics_Xfermode),
Wei-Ta Chenbca2d612009-11-30 17:52:05 +08001288 REG_JNI(register_android_graphics_YuvImage),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001289 REG_JNI(register_com_android_internal_graphics_NativeUtils),
1290
1291 REG_JNI(register_android_database_CursorWindow),
Vasu Nori5a03f362009-10-20 15:16:35 -07001292 REG_JNI(register_android_database_SQLiteCompiledSql),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001293 REG_JNI(register_android_database_SQLiteDatabase),
1294 REG_JNI(register_android_database_SQLiteDebug),
1295 REG_JNI(register_android_database_SQLiteProgram),
1296 REG_JNI(register_android_database_SQLiteQuery),
1297 REG_JNI(register_android_database_SQLiteStatement),
1298 REG_JNI(register_android_os_Debug),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 REG_JNI(register_android_os_FileObserver),
1300 REG_JNI(register_android_os_FileUtils),
Christopher Tatefa9e7c02010-05-06 12:07:10 -07001301 REG_JNI(register_android_os_MessageQueue),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302 REG_JNI(register_android_os_ParcelFileDescriptor),
1303 REG_JNI(register_android_os_Power),
1304 REG_JNI(register_android_os_StatFs),
1305 REG_JNI(register_android_os_SystemProperties),
1306 REG_JNI(register_android_os_UEventObserver),
1307 REG_JNI(register_android_net_LocalSocketImpl),
1308 REG_JNI(register_android_net_NetworkUtils),
Dan Egnor2b4abcd2010-04-07 17:30:50 -07001309 REG_JNI(register_android_net_TrafficStats),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001310 REG_JNI(register_android_net_wifi_WifiManager),
1311 REG_JNI(register_android_os_MemoryFile),
1312 REG_JNI(register_com_android_internal_os_ZygoteInit),
1313 REG_JNI(register_android_hardware_Camera),
1314 REG_JNI(register_android_hardware_SensorManager),
1315 REG_JNI(register_android_media_AudioRecord),
1316 REG_JNI(register_android_media_AudioSystem),
1317 REG_JNI(register_android_media_AudioTrack),
1318 REG_JNI(register_android_media_JetPlayer),
1319 REG_JNI(register_android_media_ToneGenerator),
1320
1321 REG_JNI(register_android_opengl_classes),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001322 REG_JNI(register_android_bluetooth_HeadsetBase),
1323 REG_JNI(register_android_bluetooth_BluetoothAudioGateway),
Nick Pelly0b6955a2009-05-26 19:13:43 -07001324 REG_JNI(register_android_bluetooth_BluetoothSocket),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 REG_JNI(register_android_bluetooth_ScoSocket),
Nick Pellybd022f42009-08-14 18:33:38 -07001326 REG_JNI(register_android_server_BluetoothService),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327 REG_JNI(register_android_server_BluetoothEventLoop),
1328 REG_JNI(register_android_server_BluetoothA2dpService),
Christopher Tateecaa7b42010-06-04 14:55:02 -07001329 REG_JNI(register_android_server_Watchdog),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001330 REG_JNI(register_android_message_digest_sha1),
1331 REG_JNI(register_android_ddm_DdmHandleNativeHeap),
Joe Onorato1cf58742009-06-12 11:06:24 -07001332 REG_JNI(register_android_backup_BackupDataInput),
Joe Onoratod2110db2009-05-19 13:41:21 -07001333 REG_JNI(register_android_backup_BackupDataOutput),
Joe Onorato06290a42009-06-18 20:10:37 -07001334 REG_JNI(register_android_backup_FileBackupHelperBase),
Joe Onorato4ababd92009-06-25 18:29:18 -04001335 REG_JNI(register_android_backup_BackupHelperDispatcher),
Dianne Hackborn69969e42010-05-04 11:40:40 -07001336
1337 REG_JNI(register_android_app_NativeActivity),
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001338 REG_JNI(register_android_view_InputChannel),
1339 REG_JNI(register_android_view_InputQueue),
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001340 REG_JNI(register_android_view_KeyEvent),
1341 REG_JNI(register_android_view_MotionEvent),
Kenny Root02c87302010-07-01 08:10:18 -07001342
1343 REG_JNI(register_android_content_res_ObbScanner),
Dianne Hackborn08d5b8f2010-08-04 11:12:40 -07001344 REG_JNI(register_android_content_res_Configuration),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001345};
1346
1347/*
1348 * Register android native functions with the VM.
1349 */
1350/*static*/ int AndroidRuntime::startReg(JNIEnv* env)
1351{
1352 /*
1353 * This hook causes all future threads created in this process to be
1354 * attached to the JavaVM. (This needs to go away in favor of JNI
1355 * Attach calls.)
1356 */
1357 androidSetCreateThreadFunc((android_create_thread_fn) javaCreateThreadEtc);
1358
1359 LOGD("--- registering native functions ---\n");
1360
1361 /*
1362 * Every "register" function calls one or more things that return
1363 * a local reference (e.g. FindClass). Because we haven't really
1364 * started the VM yet, they're all getting stored in the base frame
1365 * and never released. Use Push/Pop to manage the storage.
1366 */
1367 env->PushLocalFrame(200);
1368
1369 if (register_jni_procs(gRegJNI, NELEM(gRegJNI), env) < 0) {
1370 env->PopLocalFrame(NULL);
1371 return -1;
1372 }
1373 env->PopLocalFrame(NULL);
1374
1375 //createJavaThread("fubar", quickTest, (void*) "hello");
1376
1377 return 0;
1378}
1379
1380AndroidRuntime* AndroidRuntime::getRuntime()
1381{
1382 return gCurRuntime;
1383}
1384
1385/**
1386 * Used by WithFramework to register native functions.
1387 */
1388extern "C"
1389jint Java_com_android_internal_util_WithFramework_registerNatives(
1390 JNIEnv* env, jclass clazz) {
1391 return register_jni_procs(gRegJNI, NELEM(gRegJNI), env);
1392}
1393
1394/**
1395 * Used by LoadClass to register native functions.
1396 */
1397extern "C"
1398jint Java_LoadClass_registerNatives(JNIEnv* env, jclass clazz) {
1399 return register_jni_procs(gRegJNI, NELEM(gRegJNI), env);
1400}
1401
1402} // namespace android