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