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