blob: e4eb6925a0d878261dd2788bee167abf2ae48cc6 [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>
Brad Fitzpatrick0bd52432010-12-13 16:52:35 -080023#include <binder/IPCThreadState.h>
Mathias Agopian07952722009-05-19 19:08:10 -070024#include <binder/IServiceManager.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025#include <utils/Log.h>
26#include <utils/misc.h>
Mathias Agopian07952722009-05-19 19:08:10 -070027#include <binder/Parcel.h>
Mathias Agopian8ed6beb2009-06-05 01:26:23 -070028#include <utils/StringArray.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029#include <utils/threads.h>
30#include <cutils/properties.h>
31
32#include <SkGraphics.h>
33#include <SkImageDecoder.h>
Mike Reedfc8db532009-04-27 11:43:30 -040034#include <SkImageRef_GlobalPool.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035
36#include "jni.h"
37#include "JNIHelp.h"
38#include "android_util_Binder.h"
39
40#include <stdio.h>
41#include <signal.h>
42#include <sys/stat.h>
43#include <sys/types.h>
44#include <signal.h>
45#include <dirent.h>
46#include <assert.h>
47
48
49using namespace android;
50
51extern void register_BindTest();
52
53extern int register_android_os_Binder(JNIEnv* env);
54extern int register_android_os_Process(JNIEnv* env);
55extern int register_android_graphics_Bitmap(JNIEnv*);
56extern int register_android_graphics_BitmapFactory(JNIEnv*);
Wei-Ta Chen6b849e22010-09-07 17:32:18 +080057extern int register_android_graphics_BitmapRegionDecoder(JNIEnv*);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058extern int register_android_graphics_Camera(JNIEnv* env);
59extern int register_android_graphics_Graphics(JNIEnv* env);
60extern int register_android_graphics_Interpolator(JNIEnv* env);
61extern int register_android_graphics_LayerRasterizer(JNIEnv*);
62extern int register_android_graphics_MaskFilter(JNIEnv* env);
63extern int register_android_graphics_Movie(JNIEnv* env);
64extern int register_android_graphics_NinePatch(JNIEnv*);
65extern int register_android_graphics_PathEffect(JNIEnv* env);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066extern 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);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079extern int register_android_hardware_SensorManager(JNIEnv *env);
Mike Lockwoode7d511e2010-12-30 13:39:37 -050080extern int register_android_hardware_UsbDevice(JNIEnv *env);
Mike Lockwoodacc29cc2011-03-11 08:18:08 -050081extern int register_android_hardware_UsbDeviceConnection(JNIEnv *env);
Mike Lockwoode7d511e2010-12-30 13:39:37 -050082extern int register_android_hardware_UsbRequest(JNIEnv *env);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083
84extern int register_android_media_AudioRecord(JNIEnv *env);
85extern int register_android_media_AudioSystem(JNIEnv *env);
86extern int register_android_media_AudioTrack(JNIEnv *env);
87extern int register_android_media_JetPlayer(JNIEnv *env);
88extern int register_android_media_ToneGenerator(JNIEnv *env);
89
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090extern 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);
Jeff Brownfbf09772011-01-16 14:06:57 -0800114extern int register_android_graphics_Region(JNIEnv* env);
Jamie Gennisaa0ce332011-01-06 17:04:26 -0800115extern int register_android_graphics_SurfaceTexture(JNIEnv* env);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116extern int register_android_graphics_Xfermode(JNIEnv* env);
117extern int register_android_graphics_PixelFormat(JNIEnv* env);
118extern int register_com_android_internal_graphics_NativeUtils(JNIEnv *env);
119extern int register_android_view_Display(JNIEnv* env);
Romain Guye4d01122010-06-16 18:44:05 -0700120extern int register_android_view_GLES20Canvas(JNIEnv* env);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121extern int register_android_view_Surface(JNIEnv* env);
122extern int register_android_view_ViewRoot(JNIEnv* env);
123extern int register_android_database_CursorWindow(JNIEnv* env);
Vasu Nori5a03f362009-10-20 15:16:35 -0700124extern int register_android_database_SQLiteCompiledSql(JNIEnv* env);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125extern int register_android_database_SQLiteDatabase(JNIEnv* env);
126extern int register_android_database_SQLiteDebug(JNIEnv* env);
127extern int register_android_database_SQLiteProgram(JNIEnv* env);
128extern int register_android_database_SQLiteQuery(JNIEnv* env);
129extern int register_android_database_SQLiteStatement(JNIEnv* env);
130extern int register_android_debug_JNITest(JNIEnv* env);
131extern int register_android_nio_utils(JNIEnv* env);
Nick Pellycd0e8392010-10-13 17:25:24 -0700132extern int register_android_nfc_NdefMessage(JNIEnv *env);
133extern int register_android_nfc_NdefRecord(JNIEnv *env);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134extern int register_android_pim_EventRecurrence(JNIEnv* env);
135extern int register_android_text_format_Time(JNIEnv* env);
136extern int register_android_os_Debug(JNIEnv* env);
Christopher Tatefa9e7c02010-05-06 12:07:10 -0700137extern int register_android_os_MessageQueue(JNIEnv* env);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138extern int register_android_os_ParcelFileDescriptor(JNIEnv *env);
139extern int register_android_os_Power(JNIEnv *env);
140extern int register_android_os_StatFs(JNIEnv *env);
141extern int register_android_os_SystemProperties(JNIEnv *env);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142extern int register_android_os_SystemClock(JNIEnv* env);
143extern int register_android_os_FileObserver(JNIEnv *env);
144extern int register_android_os_FileUtils(JNIEnv *env);
145extern int register_android_os_UEventObserver(JNIEnv* env);
146extern int register_android_os_MemoryFile(JNIEnv* env);
147extern int register_android_net_LocalSocketImpl(JNIEnv* env);
148extern int register_android_net_NetworkUtils(JNIEnv* env);
Dan Egnor2b4abcd2010-04-07 17:30:50 -0700149extern int register_android_net_TrafficStats(JNIEnv* env);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150extern int register_android_net_wifi_WifiManager(JNIEnv* env);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151extern int register_android_text_AndroidCharacter(JNIEnv *env);
Doug Feltdae8e942010-02-24 14:33:15 -0800152extern int register_android_text_AndroidBidi(JNIEnv *env);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153extern int register_android_text_KeyCharacterMap(JNIEnv *env);
154extern int register_android_opengl_classes(JNIEnv *env);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155extern int register_android_bluetooth_HeadsetBase(JNIEnv* env);
156extern int register_android_bluetooth_BluetoothAudioGateway(JNIEnv* env);
Nick Pelly0b6955a2009-05-26 19:13:43 -0700157extern int register_android_bluetooth_BluetoothSocket(JNIEnv *env);
Nick Pellybd022f42009-08-14 18:33:38 -0700158extern int register_android_server_BluetoothService(JNIEnv* env);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159extern int register_android_server_BluetoothEventLoop(JNIEnv *env);
160extern int register_android_server_BluetoothA2dpService(JNIEnv* env);
Christopher Tateecaa7b42010-06-04 14:55:02 -0700161extern int register_android_server_Watchdog(JNIEnv* env);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162extern int register_android_ddm_DdmHandleNativeHeap(JNIEnv *env);
163extern int register_com_android_internal_os_ZygoteInit(JNIEnv* env);
Joe Onorato1cf58742009-06-12 11:06:24 -0700164extern int register_android_backup_BackupDataInput(JNIEnv *env);
Joe Onoratod2110db2009-05-19 13:41:21 -0700165extern int register_android_backup_BackupDataOutput(JNIEnv *env);
Joe Onorato06290a42009-06-18 20:10:37 -0700166extern int register_android_backup_FileBackupHelperBase(JNIEnv *env);
Joe Onorato4ababd92009-06-25 18:29:18 -0400167extern int register_android_backup_BackupHelperDispatcher(JNIEnv *env);
Dianne Hackborn69969e42010-05-04 11:40:40 -0700168extern int register_android_app_NativeActivity(JNIEnv *env);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700169extern int register_android_view_InputChannel(JNIEnv* env);
170extern int register_android_view_InputQueue(JNIEnv* env);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700171extern int register_android_view_KeyEvent(JNIEnv* env);
172extern int register_android_view_MotionEvent(JNIEnv* env);
Jeff Brown5b2b4d92011-03-14 19:39:54 -0700173extern int register_android_view_VelocityTracker(JNIEnv* env);
Kenny Root02c87302010-07-01 08:10:18 -0700174extern int register_android_content_res_ObbScanner(JNIEnv* env);
Dianne Hackborn08d5b8f2010-08-04 11:12:40 -0700175extern int register_android_content_res_Configuration(JNIEnv* env);
Chet Haase6e0ecb42010-11-03 19:41:18 -0700176extern int register_android_animation_PropertyValuesHolder(JNIEnv *env);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177
178static AndroidRuntime* gCurRuntime = NULL;
179
180static void doThrow(JNIEnv* env, const char* exc, const char* msg = NULL)
181{
182 if (jniThrowException(env, exc, msg) != 0)
183 assert(false);
184}
185
186/*
187 * Code written in the Java Programming Language calls here from main().
188 */
189static void com_android_internal_os_RuntimeInit_finishInit(JNIEnv* env, jobject clazz)
190{
191 gCurRuntime->onStarted();
192}
193
194static void com_android_internal_os_RuntimeInit_zygoteInit(JNIEnv* env, jobject clazz)
195{
196 gCurRuntime->onZygoteInit();
197}
198
199static jint com_android_internal_os_RuntimeInit_isComputerOn(JNIEnv* env, jobject clazz)
200{
201 return 1;
202}
203
204static void com_android_internal_os_RuntimeInit_turnComputerOn(JNIEnv* env, jobject clazz)
205{
206}
207
208static jint com_android_internal_os_RuntimeInit_getQwertyKeyboard(JNIEnv* env, jobject clazz)
209{
210 char* value = getenv("qwerty");
211 if (value != NULL && strcmp(value, "true") == 0) {
212 return 1;
213 }
214
215 return 0;
216}
217
218/*
219 * JNI registration.
220 */
221static JNINativeMethod gMethods[] = {
222 { "finishInit", "()V",
223 (void*) com_android_internal_os_RuntimeInit_finishInit },
224 { "zygoteInitNative", "()V",
225 (void*) com_android_internal_os_RuntimeInit_zygoteInit },
226 { "isComputerOn", "()I",
227 (void*) com_android_internal_os_RuntimeInit_isComputerOn },
228 { "turnComputerOn", "()V",
229 (void*) com_android_internal_os_RuntimeInit_turnComputerOn },
230 { "getQwertyKeyboard", "()I",
231 (void*) com_android_internal_os_RuntimeInit_getQwertyKeyboard },
232};
233
234int register_com_android_internal_os_RuntimeInit(JNIEnv* env)
235{
236 return jniRegisterNativeMethods(env, "com/android/internal/os/RuntimeInit",
237 gMethods, NELEM(gMethods));
238}
239
240// ----------------------------------------------------------------------
241
242/*static*/ JavaVM* AndroidRuntime::mJavaVM = NULL;
243
244
245AndroidRuntime::AndroidRuntime()
246{
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700247 SkGraphics::Init();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 // this sets our preference for 16bit images during decode
249 // in case the src is opaque and 24bit
250 SkImageDecoder::SetDeviceConfig(SkBitmap::kRGB_565_Config);
Mike Reedfc8db532009-04-27 11:43:30 -0400251 // This cache is shared between browser native images, and java "purgeable"
252 // bitmaps. This globalpool is for images that do not either use the java
253 // heap, or are not backed by ashmem. See BitmapFactory.cpp for the key
254 // java call site.
255 SkImageRef_GlobalPool::SetRAMBudget(512 * 1024);
256 // There is also a global font cache, but its budget is specified in code
257 // see SkFontHost_android.cpp
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800258
259 // Pre-allocate enough space to hold a fair number of options.
260 mOptions.setCapacity(20);
261
262 assert(gCurRuntime == NULL); // one per process
263 gCurRuntime = this;
264}
265
266AndroidRuntime::~AndroidRuntime()
267{
268 SkGraphics::Term();
269}
270
271/*
272 * Register native methods using JNI.
273 */
274/*static*/ int AndroidRuntime::registerNativeMethods(JNIEnv* env,
275 const char* className, const JNINativeMethod* gMethods, int numMethods)
276{
277 return jniRegisterNativeMethods(env, className, gMethods, numMethods);
278}
279
280/*
281 * Call a static Java Programming Language function that takes no arguments and returns void.
282 */
283status_t AndroidRuntime::callStatic(const char* className, const char* methodName)
284{
285 JNIEnv* env;
286 jclass clazz;
287 jmethodID methodId;
288
289 env = getJNIEnv();
290 if (env == NULL)
291 return UNKNOWN_ERROR;
292
293 clazz = findClass(env, className);
294 if (clazz == NULL) {
295 LOGE("ERROR: could not find class '%s'\n", className);
296 return UNKNOWN_ERROR;
297 }
298 methodId = env->GetStaticMethodID(clazz, methodName, "()V");
299 if (methodId == NULL) {
300 LOGE("ERROR: could not find method %s.%s\n", className, methodName);
301 return UNKNOWN_ERROR;
302 }
303
304 env->CallStaticVoidMethod(clazz, methodId);
305
306 return NO_ERROR;
307}
308
309status_t AndroidRuntime::callMain(
310 const char* className, int argc, const char* const argv[])
311{
312 JNIEnv* env;
313 jclass clazz;
314 jmethodID methodId;
315
Dianne Hackborn08e60f22010-09-01 18:17:17 -0700316 LOGD("Calling main entry %s", className);
317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318 env = getJNIEnv();
319 if (env == NULL)
320 return UNKNOWN_ERROR;
321
322 clazz = findClass(env, className);
323 if (clazz == NULL) {
324 LOGE("ERROR: could not find class '%s'\n", className);
325 return UNKNOWN_ERROR;
326 }
327
328 methodId = env->GetStaticMethodID(clazz, "main", "([Ljava/lang/String;)V");
329 if (methodId == NULL) {
330 LOGE("ERROR: could not find method %s.main(String[])\n", className);
331 return UNKNOWN_ERROR;
332 }
333
334 /*
335 * We want to call main() with a String array with our arguments in it.
336 * Create an array and populate it.
337 */
338 jclass stringClass;
339 jobjectArray strArray;
340
341 stringClass = env->FindClass("java/lang/String");
342 strArray = env->NewObjectArray(argc, stringClass, NULL);
343
344 for (int i = 0; i < argc; i++) {
345 jstring argStr = env->NewStringUTF(argv[i]);
346 env->SetObjectArrayElement(strArray, i, argStr);
347 }
348
349 env->CallStaticVoidMethod(clazz, methodId, strArray);
350 return NO_ERROR;
351}
352
353/*
354 * Find the named class.
355 */
356jclass AndroidRuntime::findClass(JNIEnv* env, const char* className)
357{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800358 if (env->ExceptionCheck()) {
Carl Shapiroca7e1ed2010-12-07 16:39:05 -0800359 LOGE("ERROR: exception pending on entry to findClass()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800360 return NULL;
361 }
362
363 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800364 * This is a little awkward because the JNI FindClass call uses the
365 * class loader associated with the native method we're executing in.
366 * Because this native method is part of a "boot" class, JNI doesn't
367 * look for the class in CLASSPATH, which unfortunately is a likely
368 * location for it. (Had we issued the FindClass call before calling
369 * into the VM -- at which point there isn't a native method frame on
370 * the stack -- the VM would have checked CLASSPATH. We have to do
371 * this because we call into Java Programming Language code and
372 * bounce back out.)
373 *
374 * JNI lacks a "find class in a specific class loader" operation, so we
375 * have to do things the hard way.
376 */
377 jclass cls = NULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800378
379 jclass javaLangClassLoader;
380 jmethodID getSystemClassLoader, loadClass;
381 jobject systemClassLoader;
382 jstring strClassName;
383
384 /* find the "system" class loader; none of this is expected to fail */
385 javaLangClassLoader = env->FindClass("java/lang/ClassLoader");
386 assert(javaLangClassLoader != NULL);
387 getSystemClassLoader = env->GetStaticMethodID(javaLangClassLoader,
388 "getSystemClassLoader", "()Ljava/lang/ClassLoader;");
389 loadClass = env->GetMethodID(javaLangClassLoader,
390 "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
391 assert(getSystemClassLoader != NULL && loadClass != NULL);
392 systemClassLoader = env->CallStaticObjectMethod(javaLangClassLoader,
393 getSystemClassLoader);
394 assert(systemClassLoader != NULL);
395
396 /* create an object for the class name string; alloc could fail */
397 strClassName = env->NewStringUTF(className);
398 if (env->ExceptionCheck()) {
Carl Shapiroca7e1ed2010-12-07 16:39:05 -0800399 LOGE("ERROR: unable to convert '%s' to string", className);
400 return NULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800401 }
Carl Shapiroca7e1ed2010-12-07 16:39:05 -0800402 LOGV("system class loader is %p, loading %p (%s)",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800403 systemClassLoader, strClassName, className);
404
405 /* try to find the named class */
406 cls = (jclass) env->CallObjectMethod(systemClassLoader, loadClass,
407 strClassName);
408 if (env->ExceptionCheck()) {
Carl Shapiroca7e1ed2010-12-07 16:39:05 -0800409 LOGE("ERROR: unable to load class '%s' from %p",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800410 className, systemClassLoader);
Carl Shapiroca7e1ed2010-12-07 16:39:05 -0800411 return NULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800412 }
413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800414 return cls;
415}
416
417/*
418 * The VM calls this through the "exit" hook.
419 */
420static void runtime_exit(int code)
421{
422 gCurRuntime->onExit(code);
423 exit(code);
424}
425
426/*
427 * The VM calls this through the "vfprintf" hook.
428 *
429 * We ignore "fp" and just write the results to the log file.
430 */
431static void runtime_vfprintf(FILE* fp, const char* format, va_list ap)
432{
433 LOG_PRI_VA(ANDROID_LOG_INFO, "vm-printf", format, ap);
434}
435
Brad Fitzpatrick0bd52432010-12-13 16:52:35 -0800436/**
437 * The VM calls this when mutex contention debugging is enabled to
438 * determine whether or not the blocked thread was a "sensitive thread"
439 * for user responsiveness/smoothess.
440 *
441 * Our policy for this is whether or not we're tracing any StrictMode
442 * events on this thread (which we might've inherited via Binder calls
443 * into us)
444 */
445static bool runtime_isSensitiveThread() {
446 IPCThreadState* state = IPCThreadState::selfOrNull();
447 return state && state->getStrictModePolicy() != 0;
448}
449
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800450
451/**
452 * Add VM arguments to the to-be-executed VM
453 * Stops at first non '-' argument (also stops at an argument of '--')
454 * Returns the number of args consumed
455 */
456int AndroidRuntime::addVmArguments(int argc, const char* const argv[])
457{
458 int i;
459
460 for (i = 0; i<argc; i++) {
461 if (argv[i][0] != '-') {
462 return i;
463 }
464 if (argv[i][1] == '-' && argv[i][2] == 0) {
465 return i+1;
466 }
467
468 JavaVMOption opt;
469 memset(&opt, 0, sizeof(opt));
470 opt.optionString = (char*)argv[i];
471 mOptions.add(opt);
472 }
473 return i;
474}
475
476static int hasDir(const char* dir)
477{
478 struct stat s;
479 int res = stat(dir, &s);
480 if (res == 0) {
481 return S_ISDIR(s.st_mode);
482 }
483 return 0;
484}
485
486/*
487 * We just want failed write() calls to just return with an error.
488 */
489static void blockSigpipe()
490{
491 sigset_t mask;
492
493 sigemptyset(&mask);
494 sigaddset(&mask, SIGPIPE);
495 if (sigprocmask(SIG_BLOCK, &mask, NULL) != 0)
496 LOGW("WARNING: SIGPIPE not blocked\n");
497}
498
499/*
500 * Read the persistent locale.
501 */
502static void readLocale(char* language, char* region)
503{
504 char propLang[PROPERTY_VALUE_MAX], propRegn[PROPERTY_VALUE_MAX];
Brian Carlstrom171ea892010-08-24 21:27:52 -0700505
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800506 property_get("persist.sys.language", propLang, "");
507 property_get("persist.sys.country", propRegn, "");
508 if (*propLang == 0 && *propRegn == 0) {
509 /* Set to ro properties, default is en_US */
510 property_get("ro.product.locale.language", propLang, "en");
511 property_get("ro.product.locale.region", propRegn, "US");
512 }
513 strncat(language, propLang, 2);
514 strncat(region, propRegn, 2);
515 //LOGD("language=%s region=%s\n", language, region);
516}
517
Andy McFaddenf70188a2009-03-31 15:52:13 -0700518/*
Andy McFaddene4d81f22010-07-14 16:02:20 -0700519 * Parse a property containing space-separated options that should be
520 * passed directly to the VM, e.g. "-Xmx32m -verbose:gc -Xregenmap".
521 *
522 * This will cut up "extraOptsBuf" as we chop it into individual options.
523 *
524 * Adds the strings, if any, to mOptions.
525 */
526void AndroidRuntime::parseExtraOpts(char* extraOptsBuf)
527{
528 JavaVMOption opt;
529 char* start;
530 char* end;
531
532 memset(&opt, 0, sizeof(opt));
533 start = extraOptsBuf;
534 while (*start != '\0') {
535 while (*start == ' ') /* skip leading whitespace */
536 start++;
537 if (*start == '\0') /* was trailing ws, bail */
538 break;
539
540 end = start+1;
541 while (*end != ' ' && *end != '\0') /* find end of token */
542 end++;
543 if (*end == ' ')
544 *end++ = '\0'; /* mark end, advance to indicate more */
545
546 opt.optionString = start;
547 mOptions.add(opt);
548 start = end;
549 }
550}
551
552/*
Andy McFaddenf70188a2009-03-31 15:52:13 -0700553 * Start the Dalvik Virtual Machine.
554 *
555 * Various arguments, most determined by system properties, are passed in.
556 * The "mOptions" vector is updated.
557 *
558 * Returns 0 on success.
559 */
560int AndroidRuntime::startVm(JavaVM** pJavaVM, JNIEnv** pEnv)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800561{
Andy McFaddenf70188a2009-03-31 15:52:13 -0700562 int result = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800563 JavaVMInitArgs initArgs;
564 JavaVMOption opt;
565 char propBuf[PROPERTY_VALUE_MAX];
566 char stackTraceFileBuf[PROPERTY_VALUE_MAX];
567 char dexoptFlagsBuf[PROPERTY_VALUE_MAX];
568 char enableAssertBuf[sizeof("-ea:")-1 + PROPERTY_VALUE_MAX];
569 char jniOptsBuf[sizeof("-Xjniopts:")-1 + PROPERTY_VALUE_MAX];
Carl Shapiro38cfa8c2010-12-07 16:48:29 -0800570 char heapstartsizeOptsBuf[sizeof("-Xms")-1 + PROPERTY_VALUE_MAX];
Dianne Hackbornbdcef702009-08-18 19:15:36 -0700571 char heapsizeOptsBuf[sizeof("-Xmx")-1 + PROPERTY_VALUE_MAX];
Carl Shapiro8cdf27c32011-01-19 12:33:12 -0800572 char heapgrowthlimitOptsBuf[sizeof("-XX:HeapGrowthLimit=")-1 + PROPERTY_VALUE_MAX];
Andy McFaddene4d81f22010-07-14 16:02:20 -0700573 char extraOptsBuf[PROPERTY_VALUE_MAX];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800574 char* stackTraceFile = NULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 bool checkJni = false;
Andy McFaddene2b23e12009-04-03 11:09:46 -0700576 bool checkDexSum = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800577 bool logStdio = false;
Ben Cheng52b0e732009-06-19 13:31:12 -0700578 enum {
579 kEMDefault,
580 kEMIntPortable,
581 kEMIntFast,
582#if defined(WITH_JIT)
583 kEMJitCompiler,
584#endif
585 } executionMode = kEMDefault;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800586
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800587
588 property_get("dalvik.vm.checkjni", propBuf, "");
589 if (strcmp(propBuf, "true") == 0) {
590 checkJni = true;
591 } else if (strcmp(propBuf, "false") != 0) {
592 /* property is neither true nor false; fall back on kernel parameter */
593 property_get("ro.kernel.android.checkjni", propBuf, "");
594 if (propBuf[0] == '1') {
595 checkJni = true;
596 }
597 }
598
599 property_get("dalvik.vm.execution-mode", propBuf, "");
600 if (strcmp(propBuf, "int:portable") == 0) {
601 executionMode = kEMIntPortable;
602 } else if (strcmp(propBuf, "int:fast") == 0) {
603 executionMode = kEMIntFast;
Ben Cheng52b0e732009-06-19 13:31:12 -0700604#if defined(WITH_JIT)
605 } else if (strcmp(propBuf, "int:jit") == 0) {
606 executionMode = kEMJitCompiler;
607#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608 }
609
610 property_get("dalvik.vm.stack-trace-file", stackTraceFileBuf, "");
611
Andy McFaddene2b23e12009-04-03 11:09:46 -0700612 property_get("dalvik.vm.check-dex-sum", propBuf, "");
613 if (strcmp(propBuf, "true") == 0) {
614 checkDexSum = true;
615 }
616
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800617 property_get("log.redirect-stdio", propBuf, "");
618 if (strcmp(propBuf, "true") == 0) {
619 logStdio = true;
620 }
621
622 strcpy(enableAssertBuf, "-ea:");
623 property_get("dalvik.vm.enableassertions", enableAssertBuf+4, "");
624
625 strcpy(jniOptsBuf, "-Xjniopts:");
626 property_get("dalvik.vm.jniopts", jniOptsBuf+10, "");
627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800628 /* route exit() to our handler */
629 opt.extraInfo = (void*) runtime_exit;
630 opt.optionString = "exit";
631 mOptions.add(opt);
632
633 /* route fprintf() to our handler */
634 opt.extraInfo = (void*) runtime_vfprintf;
635 opt.optionString = "vfprintf";
636 mOptions.add(opt);
637
Brad Fitzpatrick0bd52432010-12-13 16:52:35 -0800638 /* register the framework-specific "is sensitive thread" hook */
639 opt.extraInfo = (void*) runtime_isSensitiveThread;
640 opt.optionString = "sensitiveThread";
641 mOptions.add(opt);
642
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800643 opt.extraInfo = NULL;
644
645 /* enable verbose; standard options are { jni, gc, class } */
646 //options[curOpt++].optionString = "-verbose:jni";
647 opt.optionString = "-verbose:gc";
648 mOptions.add(opt);
649 //options[curOpt++].optionString = "-verbose:class";
650
Carl Shapiro9e4c8842010-12-08 12:14:46 -0800651 /*
652 * The default starting and maximum size of the heap. Larger
653 * values should be specified in a product property override.
654 */
Carl Shapiro38cfa8c2010-12-07 16:48:29 -0800655 strcpy(heapstartsizeOptsBuf, "-Xms");
Carl Shapiro9e4c8842010-12-08 12:14:46 -0800656 property_get("dalvik.vm.heapstartsize", heapstartsizeOptsBuf+4, "4m");
Carl Shapiro38cfa8c2010-12-07 16:48:29 -0800657 opt.optionString = heapstartsizeOptsBuf;
658 mOptions.add(opt);
Dianne Hackbornbdcef702009-08-18 19:15:36 -0700659 strcpy(heapsizeOptsBuf, "-Xmx");
660 property_get("dalvik.vm.heapsize", heapsizeOptsBuf+4, "16m");
Dianne Hackbornbdcef702009-08-18 19:15:36 -0700661 opt.optionString = heapsizeOptsBuf;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800662 mOptions.add(opt);
663
Carl Shapiro8cdf27c32011-01-19 12:33:12 -0800664 strcpy(heapgrowthlimitOptsBuf, "-XX:HeapGrowthLimit=");
665 property_get("dalvik.vm.heapgrowthlimit", heapgrowthlimitOptsBuf+20, "");
666 if (heapgrowthlimitOptsBuf[20] != '\0') {
667 opt.optionString = heapgrowthlimitOptsBuf;
668 mOptions.add(opt);
669 }
670
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671 /*
672 * Enable or disable dexopt features, such as bytecode verification and
673 * calculation of register maps for precise GC.
674 */
675 property_get("dalvik.vm.dexopt-flags", dexoptFlagsBuf, "");
676 if (dexoptFlagsBuf[0] != '\0') {
677 const char* opc;
678 const char* val;
679
680 opc = strstr(dexoptFlagsBuf, "v="); /* verification */
681 if (opc != NULL) {
682 switch (*(opc+2)) {
683 case 'n': val = "-Xverify:none"; break;
684 case 'r': val = "-Xverify:remote"; break;
685 case 'a': val = "-Xverify:all"; break;
686 default: val = NULL; break;
687 }
688
689 if (val != NULL) {
690 opt.optionString = val;
691 mOptions.add(opt);
692 }
693 }
694
695 opc = strstr(dexoptFlagsBuf, "o="); /* optimization */
696 if (opc != NULL) {
697 switch (*(opc+2)) {
698 case 'n': val = "-Xdexopt:none"; break;
699 case 'v': val = "-Xdexopt:verified"; break;
700 case 'a': val = "-Xdexopt:all"; break;
701 default: val = NULL; break;
702 }
703
704 if (val != NULL) {
705 opt.optionString = val;
706 mOptions.add(opt);
707 }
708 }
709
710 opc = strstr(dexoptFlagsBuf, "m=y"); /* register map */
711 if (opc != NULL) {
712 opt.optionString = "-Xgenregmap";
713 mOptions.add(opt);
The Android Open Source Project7b0b1ed2009-03-18 22:20:26 -0700714
715 /* turn on precise GC while we're at it */
716 opt.optionString = "-Xgc:precise";
717 mOptions.add(opt);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 }
719 }
720
721 /* enable debugging; set suspend=y to pause during VM init */
722#ifdef HAVE_ANDROID_OS
723 /* use android ADB transport */
724 opt.optionString =
725 "-agentlib:jdwp=transport=dt_android_adb,suspend=n,server=y";
726#else
727 /* use TCP socket; address=0 means start at port 8000 and probe up */
728 LOGI("Using TCP socket for JDWP\n");
729 opt.optionString =
730 "-agentlib:jdwp=transport=dt_socket,suspend=n,server=y,address=0";
731#endif
732 mOptions.add(opt);
733
734 char enableDPBuf[sizeof("-Xdeadlockpredict:") + PROPERTY_VALUE_MAX];
735 property_get("dalvik.vm.deadlock-predict", propBuf, "");
736 if (strlen(propBuf) > 0) {
737 strcpy(enableDPBuf, "-Xdeadlockpredict:");
738 strcat(enableDPBuf, propBuf);
739 opt.optionString = enableDPBuf;
740 mOptions.add(opt);
741 }
742
743 LOGD("CheckJNI is %s\n", checkJni ? "ON" : "OFF");
744 if (checkJni) {
745 /* extended JNI checking */
746 opt.optionString = "-Xcheck:jni";
747 mOptions.add(opt);
748
749 /* set a cap on JNI global references */
750 opt.optionString = "-Xjnigreflimit:2000";
751 mOptions.add(opt);
752
753 /* with -Xcheck:jni, this provides a JNI function call trace */
754 //opt.optionString = "-verbose:jni";
755 //mOptions.add(opt);
756 }
Ben Cheng52b0e732009-06-19 13:31:12 -0700757
Carl Shapirod8f3ec62010-04-12 16:31:59 -0700758 char lockProfThresholdBuf[sizeof("-Xlockprofthreshold:") + sizeof(propBuf)];
759 property_get("dalvik.vm.lockprof.threshold", propBuf, "");
760 if (strlen(propBuf) > 0) {
761 strcpy(lockProfThresholdBuf, "-Xlockprofthreshold:");
762 strcat(lockProfThresholdBuf, propBuf);
763 opt.optionString = lockProfThresholdBuf;
764 mOptions.add(opt);
765 }
766
Ben Cheng52b0e732009-06-19 13:31:12 -0700767#if defined(WITH_JIT)
Ben Cheng52b0e732009-06-19 13:31:12 -0700768 /* Force interpreter-only mode for selected opcodes. Eg "1-0a,3c,f1-ff" */
769 char jitOpBuf[sizeof("-Xjitop:") + PROPERTY_VALUE_MAX];
770 property_get("dalvik.vm.jit.op", propBuf, "");
771 if (strlen(propBuf) > 0) {
772 strcpy(jitOpBuf, "-Xjitop:");
773 strcat(jitOpBuf, propBuf);
774 opt.optionString = jitOpBuf;
775 mOptions.add(opt);
776 }
777
Ben Cheng52b0e732009-06-19 13:31:12 -0700778 /* Force interpreter-only mode for selected methods */
779 char jitMethodBuf[sizeof("-Xjitmethod:") + PROPERTY_VALUE_MAX];
780 property_get("dalvik.vm.jit.method", propBuf, "");
781 if (strlen(propBuf) > 0) {
782 strcpy(jitMethodBuf, "-Xjitmethod:");
783 strcat(jitMethodBuf, propBuf);
784 opt.optionString = jitMethodBuf;
785 mOptions.add(opt);
786 }
Ben Cheng52b0e732009-06-19 13:31:12 -0700787#endif
788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789 if (executionMode == kEMIntPortable) {
790 opt.optionString = "-Xint:portable";
791 mOptions.add(opt);
792 } else if (executionMode == kEMIntFast) {
793 opt.optionString = "-Xint:fast";
794 mOptions.add(opt);
Ben Cheng52b0e732009-06-19 13:31:12 -0700795#if defined(WITH_JIT)
796 } else if (executionMode == kEMJitCompiler) {
797 opt.optionString = "-Xint:jit";
798 mOptions.add(opt);
799#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800800 }
Andy McFaddene2b23e12009-04-03 11:09:46 -0700801
802 if (checkDexSum) {
803 /* perform additional DEX checksum tests */
804 opt.optionString = "-Xcheckdexsum";
805 mOptions.add(opt);
806 }
807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808 if (logStdio) {
809 /* convert stdout/stderr to log messages */
810 opt.optionString = "-Xlog-stdio";
811 mOptions.add(opt);
812 }
813
814 if (enableAssertBuf[4] != '\0') {
815 /* accept "all" to mean "all classes and packages" */
816 if (strcmp(enableAssertBuf+4, "all") == 0)
817 enableAssertBuf[3] = '\0';
818 LOGI("Assertions enabled: '%s'\n", enableAssertBuf);
819 opt.optionString = enableAssertBuf;
820 mOptions.add(opt);
821 } else {
822 LOGV("Assertions disabled\n");
823 }
824
825 if (jniOptsBuf[10] != '\0') {
826 LOGI("JNI options: '%s'\n", jniOptsBuf);
827 opt.optionString = jniOptsBuf;
828 mOptions.add(opt);
829 }
830
831 if (stackTraceFileBuf[0] != '\0') {
832 static const char* stfOptName = "-Xstacktracefile:";
833
834 stackTraceFile = (char*) malloc(strlen(stfOptName) +
835 strlen(stackTraceFileBuf) +1);
836 strcpy(stackTraceFile, stfOptName);
837 strcat(stackTraceFile, stackTraceFileBuf);
838 opt.optionString = stackTraceFile;
839 mOptions.add(opt);
840 }
Andy McFaddene4d81f22010-07-14 16:02:20 -0700841
842 /* extra options; parse this late so it overrides others */
843 property_get("dalvik.vm.extra-opts", extraOptsBuf, "");
844 parseExtraOpts(extraOptsBuf);
845
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846 /* Set the properties for locale */
847 {
848 char langOption[sizeof("-Duser.language=") + 3];
849 char regionOption[sizeof("-Duser.region=") + 3];
850 strcpy(langOption, "-Duser.language=");
851 strcpy(regionOption, "-Duser.region=");
852 readLocale(langOption, regionOption);
853 opt.extraInfo = NULL;
854 opt.optionString = langOption;
855 mOptions.add(opt);
856 opt.optionString = regionOption;
857 mOptions.add(opt);
858 }
859
860 /*
861 * We don't have /tmp on the device, but we often have an SD card. Apps
862 * shouldn't use this, but some test suites might want to exercise it.
863 */
864 opt.optionString = "-Djava.io.tmpdir=/sdcard";
865 mOptions.add(opt);
866
867 initArgs.version = JNI_VERSION_1_4;
868 initArgs.options = mOptions.editArray();
869 initArgs.nOptions = mOptions.size();
870 initArgs.ignoreUnrecognized = JNI_FALSE;
871
872 /*
873 * Initialize the VM.
874 *
875 * The JavaVM* is essentially per-process, and the JNIEnv* is per-thread.
876 * If this call succeeds, the VM is ready, and we can start issuing
877 * JNI calls.
878 */
Andy McFaddenf70188a2009-03-31 15:52:13 -0700879 if (JNI_CreateJavaVM(pJavaVM, pEnv, &initArgs) < 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880 LOGE("JNI_CreateJavaVM failed\n");
881 goto bail;
882 }
883
Andy McFaddenf70188a2009-03-31 15:52:13 -0700884 result = 0;
885
886bail:
887 free(stackTraceFile);
888 return result;
889}
890
891/*
892 * Start the Android runtime. This involves starting the virtual machine
893 * and calling the "static void main(String[] args)" method in the class
894 * named by "className".
895 */
896void AndroidRuntime::start(const char* className, const bool startSystemServer)
897{
Dianne Hackborn08e60f22010-09-01 18:17:17 -0700898 LOGD("\n>>>>>> AndroidRuntime START %s <<<<<<\n",
899 className != NULL ? className : "(unknown)");
Andy McFaddenf70188a2009-03-31 15:52:13 -0700900
901 char* slashClassName = NULL;
902 char* cp;
903 JNIEnv* env;
904
905 blockSigpipe();
906
907 /*
908 * 'startSystemServer == true' means runtime is obslete and not run from
909 * init.rc anymore, so we print out the boot start event here.
910 */
911 if (startSystemServer) {
912 /* track our progress through the boot sequence */
913 const int LOG_BOOT_PROGRESS_START = 3000;
914 LOG_EVENT_LONG(LOG_BOOT_PROGRESS_START,
915 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
916 }
917
918 const char* rootDir = getenv("ANDROID_ROOT");
919 if (rootDir == NULL) {
920 rootDir = "/system";
921 if (!hasDir("/system")) {
922 LOG_FATAL("No root directory specified, and /android does not exist.");
923 goto bail;
924 }
925 setenv("ANDROID_ROOT", rootDir, 1);
926 }
927
928 //const char* kernelHack = getenv("LD_ASSUME_KERNEL");
929 //LOGD("Found LD_ASSUME_KERNEL='%s'\n", kernelHack);
930
931 /* start the virtual machine */
932 if (startVm(&mJavaVM, &env) != 0)
933 goto bail;
934
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 /*
936 * Register android functions.
937 */
938 if (startReg(env) < 0) {
939 LOGE("Unable to register all android natives\n");
940 goto bail;
941 }
942
943 /*
944 * We want to call main() with a String array with arguments in it.
945 * At present we only have one argument, the class name. Create an
946 * array to hold it.
947 */
948 jclass stringClass;
949 jobjectArray strArray;
950 jstring classNameStr;
951 jstring startSystemServerStr;
952
953 stringClass = env->FindClass("java/lang/String");
954 assert(stringClass != NULL);
955 strArray = env->NewObjectArray(2, stringClass, NULL);
956 assert(strArray != NULL);
957 classNameStr = env->NewStringUTF(className);
958 assert(classNameStr != NULL);
959 env->SetObjectArrayElement(strArray, 0, classNameStr);
960 startSystemServerStr = env->NewStringUTF(startSystemServer ?
961 "true" : "false");
962 env->SetObjectArrayElement(strArray, 1, startSystemServerStr);
963
964 /*
965 * Start VM. This thread becomes the main thread of the VM, and will
966 * not return until the VM exits.
967 */
968 jclass startClass;
969 jmethodID startMeth;
970
971 slashClassName = strdup(className);
972 for (cp = slashClassName; *cp != '\0'; cp++)
973 if (*cp == '.')
974 *cp = '/';
975
976 startClass = env->FindClass(slashClassName);
977 if (startClass == NULL) {
978 LOGE("JavaVM unable to locate class '%s'\n", slashClassName);
979 /* keep going */
980 } else {
981 startMeth = env->GetStaticMethodID(startClass, "main",
982 "([Ljava/lang/String;)V");
983 if (startMeth == NULL) {
984 LOGE("JavaVM unable to find main() in '%s'\n", className);
985 /* keep going */
986 } else {
987 env->CallStaticVoidMethod(startClass, startMeth, strArray);
988
989#if 0
990 if (env->ExceptionCheck())
991 threadExitUncaughtException(env);
992#endif
993 }
994 }
995
996 LOGD("Shutting down VM\n");
997 if (mJavaVM->DetachCurrentThread() != JNI_OK)
998 LOGW("Warning: unable to detach main thread\n");
999 if (mJavaVM->DestroyJavaVM() != 0)
1000 LOGW("Warning: VM did not shut down cleanly\n");
1001
1002bail:
1003 free(slashClassName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001004}
1005
1006void AndroidRuntime::start()
1007{
1008 start("com.android.internal.os.RuntimeInit",
1009 false /* Don't start the system server */);
1010}
1011
1012void AndroidRuntime::onExit(int code)
1013{
Dianne Hackborn08e60f22010-09-01 18:17:17 -07001014 LOGV("AndroidRuntime onExit calling exit(%d)", code);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015 exit(code);
1016}
1017
1018/*
1019 * Get the JNIEnv pointer for this thread.
1020 *
1021 * Returns NULL if the slot wasn't allocated or populated.
1022 */
1023/*static*/ JNIEnv* AndroidRuntime::getJNIEnv()
1024{
1025 JNIEnv* env;
1026 JavaVM* vm = AndroidRuntime::getJavaVM();
1027 assert(vm != NULL);
1028
1029 if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK)
1030 return NULL;
1031 return env;
1032}
1033
1034/*
1035 * Makes the current thread visible to the VM.
1036 *
1037 * The JNIEnv pointer returned is only valid for the current thread, and
1038 * thus must be tucked into thread-local storage.
1039 */
1040static int javaAttachThread(const char* threadName, JNIEnv** pEnv)
1041{
1042 JavaVMAttachArgs args;
1043 JavaVM* vm;
1044 jint result;
1045
1046 vm = AndroidRuntime::getJavaVM();
1047 assert(vm != NULL);
1048
1049 args.version = JNI_VERSION_1_4;
1050 args.name = (char*) threadName;
1051 args.group = NULL;
1052
1053 result = vm->AttachCurrentThread(pEnv, (void*) &args);
1054 if (result != JNI_OK)
Andy McFadden701d9162010-03-01 14:03:13 -08001055 LOGI("NOTE: attach of thread '%s' failed\n", threadName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056
1057 return result;
1058}
1059
1060/*
1061 * Detach the current thread from the set visible to the VM.
1062 */
1063static int javaDetachThread(void)
1064{
1065 JavaVM* vm;
1066 jint result;
1067
1068 vm = AndroidRuntime::getJavaVM();
1069 assert(vm != NULL);
1070
1071 result = vm->DetachCurrentThread();
1072 if (result != JNI_OK)
1073 LOGE("ERROR: thread detach failed\n");
1074 return result;
1075}
1076
1077/*
1078 * When starting a native thread that will be visible from the VM, we
1079 * bounce through this to get the right attach/detach action.
1080 * Note that this function calls free(args)
1081 */
1082/*static*/ int AndroidRuntime::javaThreadShell(void* args) {
1083 void* start = ((void**)args)[0];
1084 void* userData = ((void **)args)[1];
1085 char* name = (char*) ((void **)args)[2]; // we own this storage
1086 free(args);
1087 JNIEnv* env;
1088 int result;
1089
1090 /* hook us into the VM */
1091 if (javaAttachThread(name, &env) != JNI_OK)
1092 return -1;
1093
1094 /* start the thread running */
1095 result = (*(android_thread_func_t)start)(userData);
1096
1097 /* unhook us */
1098 javaDetachThread();
1099 free(name);
1100
1101 return result;
1102}
1103
1104/*
1105 * This is invoked from androidCreateThreadEtc() via the callback
1106 * set with androidSetCreateThreadFunc().
1107 *
1108 * We need to create the new thread in such a way that it gets hooked
1109 * into the VM before it really starts executing.
1110 */
1111/*static*/ int AndroidRuntime::javaCreateThreadEtc(
1112 android_thread_func_t entryFunction,
1113 void* userData,
1114 const char* threadName,
1115 int32_t threadPriority,
1116 size_t threadStackSize,
1117 android_thread_id_t* threadId)
1118{
1119 void** args = (void**) malloc(3 * sizeof(void*)); // javaThreadShell must free
1120 int result;
1121
1122 assert(threadName != NULL);
1123
1124 args[0] = (void*) entryFunction;
1125 args[1] = userData;
1126 args[2] = (void*) strdup(threadName); // javaThreadShell must free
1127
1128 result = androidCreateRawThreadEtc(AndroidRuntime::javaThreadShell, args,
1129 threadName, threadPriority, threadStackSize, threadId);
1130 return result;
1131}
1132
1133/*
1134 * Create a thread that is visible from the VM.
1135 *
1136 * This is called from elsewhere in the library.
1137 */
Mike Lockwoodf602d362010-06-20 14:28:16 -07001138/*static*/ android_thread_id_t AndroidRuntime::createJavaThread(const char* name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001139 void (*start)(void *), void* arg)
1140{
Mike Lockwoodf602d362010-06-20 14:28:16 -07001141 android_thread_id_t threadId = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142 javaCreateThreadEtc((android_thread_func_t) start, arg, name,
Mike Lockwoodf602d362010-06-20 14:28:16 -07001143 ANDROID_PRIORITY_DEFAULT, 0, &threadId);
1144 return threadId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001145}
1146
1147#if 0
1148static void quickTest(void* arg)
1149{
1150 const char* str = (const char*) arg;
1151
1152 printf("In quickTest: %s\n", str);
1153}
1154#endif
1155
1156#ifdef NDEBUG
1157 #define REG_JNI(name) { name }
1158 struct RegJNIRec {
1159 int (*mProc)(JNIEnv*);
1160 };
1161#else
1162 #define REG_JNI(name) { name, #name }
1163 struct RegJNIRec {
1164 int (*mProc)(JNIEnv*);
1165 const char* mName;
1166 };
1167#endif
1168
1169typedef void (*RegJAMProc)();
1170
1171static int register_jni_procs(const RegJNIRec array[], size_t count, JNIEnv* env)
1172{
1173 for (size_t i = 0; i < count; i++) {
1174 if (array[i].mProc(env) < 0) {
1175#ifndef NDEBUG
1176 LOGD("----------!!! %s failed to load\n", array[i].mName);
1177#endif
1178 return -1;
1179 }
1180 }
1181 return 0;
1182}
1183
1184static void register_jam_procs(const RegJAMProc array[], size_t count)
1185{
1186 for (size_t i = 0; i < count; i++) {
1187 array[i]();
1188 }
1189}
1190
1191static const RegJNIRec gRegJNI[] = {
1192 REG_JNI(register_android_debug_JNITest),
1193 REG_JNI(register_com_android_internal_os_RuntimeInit),
1194 REG_JNI(register_android_os_SystemClock),
1195 REG_JNI(register_android_util_EventLog),
1196 REG_JNI(register_android_util_Log),
1197 REG_JNI(register_android_util_FloatMath),
1198 REG_JNI(register_android_text_format_Time),
1199 REG_JNI(register_android_pim_EventRecurrence),
1200 REG_JNI(register_android_content_AssetManager),
1201 REG_JNI(register_android_content_StringBlock),
1202 REG_JNI(register_android_content_XmlBlock),
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001203 REG_JNI(register_android_emoji_EmojiFactory),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001204 REG_JNI(register_android_text_AndroidCharacter),
Doug Feltdae8e942010-02-24 14:33:15 -08001205 REG_JNI(register_android_text_AndroidBidi),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001206 REG_JNI(register_android_text_KeyCharacterMap),
1207 REG_JNI(register_android_os_Process),
Andreas Hubera8079bf2010-11-16 14:40:31 -08001208 REG_JNI(register_android_os_SystemProperties),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209 REG_JNI(register_android_os_Binder),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001210 REG_JNI(register_android_view_Display),
1211 REG_JNI(register_android_nio_utils),
1212 REG_JNI(register_android_graphics_PixelFormat),
1213 REG_JNI(register_android_graphics_Graphics),
Romain Guye4d01122010-06-16 18:44:05 -07001214 REG_JNI(register_android_view_GLES20Canvas),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001215 REG_JNI(register_android_view_Surface),
1216 REG_JNI(register_android_view_ViewRoot),
1217 REG_JNI(register_com_google_android_gles_jni_EGLImpl),
1218 REG_JNI(register_com_google_android_gles_jni_GLImpl),
Jack Palevich1c4907e2009-04-13 16:22:25 -07001219 REG_JNI(register_android_opengl_jni_GLES10),
1220 REG_JNI(register_android_opengl_jni_GLES10Ext),
1221 REG_JNI(register_android_opengl_jni_GLES11),
1222 REG_JNI(register_android_opengl_jni_GLES11Ext),
Jack Palevich560814f2009-11-19 16:34:55 +08001223 REG_JNI(register_android_opengl_jni_GLES20),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001224
1225 REG_JNI(register_android_graphics_Bitmap),
1226 REG_JNI(register_android_graphics_BitmapFactory),
Wei-Ta Chen6b849e22010-09-07 17:32:18 +08001227 REG_JNI(register_android_graphics_BitmapRegionDecoder),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001228 REG_JNI(register_android_graphics_Camera),
1229 REG_JNI(register_android_graphics_Canvas),
1230 REG_JNI(register_android_graphics_ColorFilter),
1231 REG_JNI(register_android_graphics_DrawFilter),
1232 REG_JNI(register_android_graphics_Interpolator),
1233 REG_JNI(register_android_graphics_LayerRasterizer),
1234 REG_JNI(register_android_graphics_MaskFilter),
1235 REG_JNI(register_android_graphics_Matrix),
1236 REG_JNI(register_android_graphics_Movie),
1237 REG_JNI(register_android_graphics_NinePatch),
1238 REG_JNI(register_android_graphics_Paint),
1239 REG_JNI(register_android_graphics_Path),
1240 REG_JNI(register_android_graphics_PathMeasure),
1241 REG_JNI(register_android_graphics_PathEffect),
1242 REG_JNI(register_android_graphics_Picture),
1243 REG_JNI(register_android_graphics_PorterDuff),
1244 REG_JNI(register_android_graphics_Rasterizer),
1245 REG_JNI(register_android_graphics_Region),
1246 REG_JNI(register_android_graphics_Shader),
Jamie Gennisaa0ce332011-01-06 17:04:26 -08001247 REG_JNI(register_android_graphics_SurfaceTexture),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001248 REG_JNI(register_android_graphics_Typeface),
1249 REG_JNI(register_android_graphics_Xfermode),
Wei-Ta Chenbca2d612009-11-30 17:52:05 +08001250 REG_JNI(register_android_graphics_YuvImage),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001251 REG_JNI(register_com_android_internal_graphics_NativeUtils),
1252
1253 REG_JNI(register_android_database_CursorWindow),
Vasu Nori5a03f362009-10-20 15:16:35 -07001254 REG_JNI(register_android_database_SQLiteCompiledSql),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 REG_JNI(register_android_database_SQLiteDatabase),
1256 REG_JNI(register_android_database_SQLiteDebug),
1257 REG_JNI(register_android_database_SQLiteProgram),
1258 REG_JNI(register_android_database_SQLiteQuery),
1259 REG_JNI(register_android_database_SQLiteStatement),
1260 REG_JNI(register_android_os_Debug),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001261 REG_JNI(register_android_os_FileObserver),
1262 REG_JNI(register_android_os_FileUtils),
Christopher Tatefa9e7c02010-05-06 12:07:10 -07001263 REG_JNI(register_android_os_MessageQueue),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264 REG_JNI(register_android_os_ParcelFileDescriptor),
1265 REG_JNI(register_android_os_Power),
1266 REG_JNI(register_android_os_StatFs),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001267 REG_JNI(register_android_os_UEventObserver),
1268 REG_JNI(register_android_net_LocalSocketImpl),
1269 REG_JNI(register_android_net_NetworkUtils),
Dan Egnor2b4abcd2010-04-07 17:30:50 -07001270 REG_JNI(register_android_net_TrafficStats),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001271 REG_JNI(register_android_net_wifi_WifiManager),
Nick Pellycd0e8392010-10-13 17:25:24 -07001272 REG_JNI(register_android_nfc_NdefMessage),
1273 REG_JNI(register_android_nfc_NdefRecord),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274 REG_JNI(register_android_os_MemoryFile),
1275 REG_JNI(register_com_android_internal_os_ZygoteInit),
1276 REG_JNI(register_android_hardware_Camera),
1277 REG_JNI(register_android_hardware_SensorManager),
Mike Lockwoode7d511e2010-12-30 13:39:37 -05001278 REG_JNI(register_android_hardware_UsbDevice),
Mike Lockwoodacc29cc2011-03-11 08:18:08 -05001279 REG_JNI(register_android_hardware_UsbDeviceConnection),
Mike Lockwoode7d511e2010-12-30 13:39:37 -05001280 REG_JNI(register_android_hardware_UsbRequest),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001281 REG_JNI(register_android_media_AudioRecord),
1282 REG_JNI(register_android_media_AudioSystem),
1283 REG_JNI(register_android_media_AudioTrack),
1284 REG_JNI(register_android_media_JetPlayer),
1285 REG_JNI(register_android_media_ToneGenerator),
1286
1287 REG_JNI(register_android_opengl_classes),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288 REG_JNI(register_android_bluetooth_HeadsetBase),
1289 REG_JNI(register_android_bluetooth_BluetoothAudioGateway),
Nick Pelly0b6955a2009-05-26 19:13:43 -07001290 REG_JNI(register_android_bluetooth_BluetoothSocket),
Nick Pellybd022f42009-08-14 18:33:38 -07001291 REG_JNI(register_android_server_BluetoothService),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001292 REG_JNI(register_android_server_BluetoothEventLoop),
1293 REG_JNI(register_android_server_BluetoothA2dpService),
Christopher Tateecaa7b42010-06-04 14:55:02 -07001294 REG_JNI(register_android_server_Watchdog),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001295 REG_JNI(register_android_ddm_DdmHandleNativeHeap),
Joe Onorato1cf58742009-06-12 11:06:24 -07001296 REG_JNI(register_android_backup_BackupDataInput),
Joe Onoratod2110db2009-05-19 13:41:21 -07001297 REG_JNI(register_android_backup_BackupDataOutput),
Joe Onorato06290a42009-06-18 20:10:37 -07001298 REG_JNI(register_android_backup_FileBackupHelperBase),
Joe Onorato4ababd92009-06-25 18:29:18 -04001299 REG_JNI(register_android_backup_BackupHelperDispatcher),
Dianne Hackborn69969e42010-05-04 11:40:40 -07001300
1301 REG_JNI(register_android_app_NativeActivity),
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001302 REG_JNI(register_android_view_InputChannel),
1303 REG_JNI(register_android_view_InputQueue),
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001304 REG_JNI(register_android_view_KeyEvent),
1305 REG_JNI(register_android_view_MotionEvent),
Jeff Brown5b2b4d92011-03-14 19:39:54 -07001306 REG_JNI(register_android_view_VelocityTracker),
Kenny Root02c87302010-07-01 08:10:18 -07001307
1308 REG_JNI(register_android_content_res_ObbScanner),
Dianne Hackborn08d5b8f2010-08-04 11:12:40 -07001309 REG_JNI(register_android_content_res_Configuration),
Chet Haase6e0ecb42010-11-03 19:41:18 -07001310
1311 REG_JNI(register_android_animation_PropertyValuesHolder),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001312};
1313
1314/*
1315 * Register android native functions with the VM.
1316 */
1317/*static*/ int AndroidRuntime::startReg(JNIEnv* env)
1318{
1319 /*
1320 * This hook causes all future threads created in this process to be
1321 * attached to the JavaVM. (This needs to go away in favor of JNI
1322 * Attach calls.)
1323 */
1324 androidSetCreateThreadFunc((android_create_thread_fn) javaCreateThreadEtc);
1325
Dianne Hackborn08e60f22010-09-01 18:17:17 -07001326 LOGV("--- registering native functions ---\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327
1328 /*
1329 * Every "register" function calls one or more things that return
1330 * a local reference (e.g. FindClass). Because we haven't really
1331 * started the VM yet, they're all getting stored in the base frame
1332 * and never released. Use Push/Pop to manage the storage.
1333 */
1334 env->PushLocalFrame(200);
1335
1336 if (register_jni_procs(gRegJNI, NELEM(gRegJNI), env) < 0) {
1337 env->PopLocalFrame(NULL);
1338 return -1;
1339 }
1340 env->PopLocalFrame(NULL);
1341
1342 //createJavaThread("fubar", quickTest, (void*) "hello");
1343
1344 return 0;
1345}
1346
1347AndroidRuntime* AndroidRuntime::getRuntime()
1348{
1349 return gCurRuntime;
1350}
1351
1352/**
1353 * Used by WithFramework to register native functions.
1354 */
1355extern "C"
1356jint Java_com_android_internal_util_WithFramework_registerNatives(
1357 JNIEnv* env, jclass clazz) {
1358 return register_jni_procs(gRegJNI, NELEM(gRegJNI), env);
1359}
1360
1361/**
1362 * Used by LoadClass to register native functions.
1363 */
1364extern "C"
1365jint Java_LoadClass_registerNatives(JNIEnv* env, jclass clazz) {
1366 return register_jni_procs(gRegJNI, NELEM(gRegJNI), env);
1367}
1368
1369} // namespace android