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