OSDN Git Service

am fe4cbf2b: (-s ours) am cff4e09e: am bdf7f358: DO NOT MERGE - Backport of ag/748165...
[android-x86/frameworks-base.git] / core / jni / AndroidRuntime.cpp
1 /*
2  * Copyright (C) 2006 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #define LOG_TAG "AndroidRuntime"
18 //#define LOG_NDEBUG 0
19
20 #include <android_runtime/AndroidRuntime.h>
21 #include <binder/IBinder.h>
22 #include <binder/IPCThreadState.h>
23 #include <binder/IServiceManager.h>
24 #include <utils/Log.h>
25 #include <utils/misc.h>
26 #include <binder/Parcel.h>
27 #include <utils/threads.h>
28 #include <cutils/properties.h>
29
30 #include <SkGraphics.h>
31 #include <SkImageDecoder.h>
32
33 #include "jni.h"
34 #include "JNIHelp.h"
35 #include "JniInvocation.h"
36 #include "android_util_Binder.h"
37
38 #include <stdio.h>
39 #include <signal.h>
40 #include <sys/stat.h>
41 #include <sys/types.h>
42 #include <signal.h>
43 #include <dirent.h>
44 #include <assert.h>
45
46
47 using namespace android;
48
49 extern int register_android_os_Binder(JNIEnv* env);
50 extern int register_android_os_Process(JNIEnv* env);
51 extern int register_android_graphics_Bitmap(JNIEnv*);
52 extern int register_android_graphics_BitmapFactory(JNIEnv*);
53 extern int register_android_graphics_BitmapRegionDecoder(JNIEnv*);
54 extern int register_android_graphics_Camera(JNIEnv* env);
55 extern int register_android_graphics_CreateJavaOutputStreamAdaptor(JNIEnv* env);
56 extern int register_android_graphics_Graphics(JNIEnv* env);
57 extern int register_android_graphics_Interpolator(JNIEnv* env);
58 extern int register_android_graphics_MaskFilter(JNIEnv* env);
59 extern int register_android_graphics_Movie(JNIEnv* env);
60 extern int register_android_graphics_NinePatch(JNIEnv*);
61 extern int register_android_graphics_PathEffect(JNIEnv* env);
62 extern int register_android_graphics_Shader(JNIEnv* env);
63 extern int register_android_graphics_Typeface(JNIEnv* env);
64 extern int register_android_graphics_YuvImage(JNIEnv* env);
65
66 extern int register_com_google_android_gles_jni_EGLImpl(JNIEnv* env);
67 extern int register_com_google_android_gles_jni_GLImpl(JNIEnv* env);
68 extern int register_android_opengl_jni_EGL14(JNIEnv* env);
69 extern int register_android_opengl_jni_EGLExt(JNIEnv* env);
70 extern int register_android_opengl_jni_GLES10(JNIEnv* env);
71 extern int register_android_opengl_jni_GLES10Ext(JNIEnv* env);
72 extern int register_android_opengl_jni_GLES11(JNIEnv* env);
73 extern int register_android_opengl_jni_GLES11Ext(JNIEnv* env);
74 extern int register_android_opengl_jni_GLES20(JNIEnv* env);
75 extern int register_android_opengl_jni_GLES30(JNIEnv* env);
76 extern int register_android_opengl_jni_GLES31(JNIEnv* env);
77 extern int register_android_opengl_jni_GLES31Ext(JNIEnv* env);
78
79 extern int register_android_hardware_Camera(JNIEnv *env);
80 extern int register_android_hardware_camera2_CameraMetadata(JNIEnv *env);
81 extern int register_android_hardware_camera2_legacy_LegacyCameraDevice(JNIEnv *env);
82 extern int register_android_hardware_camera2_legacy_PerfMeasurement(JNIEnv *env);
83 extern int register_android_hardware_camera2_DngCreator(JNIEnv *env);
84 extern int register_android_hardware_SensorManager(JNIEnv *env);
85 extern int register_android_hardware_SerialPort(JNIEnv *env);
86 extern int register_android_hardware_SoundTrigger(JNIEnv *env);
87 extern int register_android_hardware_UsbDevice(JNIEnv *env);
88 extern int register_android_hardware_UsbDeviceConnection(JNIEnv *env);
89 extern int register_android_hardware_UsbRequest(JNIEnv *env);
90 extern int register_android_hardware_location_ActivityRecognitionHardware(JNIEnv* env);
91
92 extern int register_android_media_AudioRecord(JNIEnv *env);
93 extern int register_android_media_AudioSystem(JNIEnv *env);
94 extern int register_android_media_AudioTrack(JNIEnv *env);
95 extern int register_android_media_JetPlayer(JNIEnv *env);
96 extern int register_android_media_ToneGenerator(JNIEnv *env);
97
98 extern int register_android_util_FloatMath(JNIEnv* env);
99
100 namespace android {
101
102 /*
103  * JNI-based registration functions.  Note these are properly contained in
104  * namespace android.
105  */
106 extern int register_android_content_AssetManager(JNIEnv* env);
107 extern int register_android_util_EventLog(JNIEnv* env);
108 extern int register_android_util_Log(JNIEnv* env);
109 extern int register_android_content_StringBlock(JNIEnv* env);
110 extern int register_android_content_XmlBlock(JNIEnv* env);
111 extern int register_android_emoji_EmojiFactory(JNIEnv* env);
112 extern int register_android_graphics_Canvas(JNIEnv* env);
113 extern int register_android_graphics_CanvasProperty(JNIEnv* env);
114 extern int register_android_graphics_ColorFilter(JNIEnv* env);
115 extern int register_android_graphics_DrawFilter(JNIEnv* env);
116 extern int register_android_graphics_FontFamily(JNIEnv* env);
117 extern int register_android_graphics_LayerRasterizer(JNIEnv*);
118 extern int register_android_graphics_Matrix(JNIEnv* env);
119 extern int register_android_graphics_Paint(JNIEnv* env);
120 extern int register_android_graphics_Path(JNIEnv* env);
121 extern int register_android_graphics_PathMeasure(JNIEnv* env);
122 extern int register_android_graphics_Picture(JNIEnv*);
123 extern int register_android_graphics_PorterDuff(JNIEnv* env);
124 extern int register_android_graphics_Rasterizer(JNIEnv* env);
125 extern int register_android_graphics_Region(JNIEnv* env);
126 extern int register_android_graphics_SurfaceTexture(JNIEnv* env);
127 extern int register_android_graphics_Xfermode(JNIEnv* env);
128 extern int register_android_graphics_pdf_PdfDocument(JNIEnv* env);
129 extern int register_android_graphics_pdf_PdfEditor(JNIEnv* env);
130 extern int register_android_graphics_pdf_PdfRenderer(JNIEnv* env);
131 extern int register_android_view_DisplayEventReceiver(JNIEnv* env);
132 extern int register_android_view_RenderNode(JNIEnv* env);
133 extern int register_android_view_RenderNodeAnimator(JNIEnv* env);
134 extern int register_android_view_GraphicBuffer(JNIEnv* env);
135 extern int register_android_view_GLES20Canvas(JNIEnv* env);
136 extern int register_android_view_HardwareLayer(JNIEnv* env);
137 extern int register_android_view_ThreadedRenderer(JNIEnv* env);
138 extern int register_android_view_Surface(JNIEnv* env);
139 extern int register_android_view_SurfaceControl(JNIEnv* env);
140 extern int register_android_view_SurfaceSession(JNIEnv* env);
141 extern int register_android_view_TextureView(JNIEnv* env);
142 extern int register_com_android_internal_view_animation_NativeInterpolatorFactoryHelper(JNIEnv *env);
143 extern int register_android_database_CursorWindow(JNIEnv* env);
144 extern int register_android_database_SQLiteConnection(JNIEnv* env);
145 extern int register_android_database_SQLiteGlobal(JNIEnv* env);
146 extern int register_android_database_SQLiteDebug(JNIEnv* env);
147 extern int register_android_nio_utils(JNIEnv* env);
148 extern int register_android_os_Debug(JNIEnv* env);
149 extern int register_android_os_MessageQueue(JNIEnv* env);
150 extern int register_android_os_Parcel(JNIEnv* env);
151 extern int register_android_os_SELinux(JNIEnv* env);
152 extern int register_android_os_SystemProperties(JNIEnv *env);
153 extern int register_android_os_SystemClock(JNIEnv* env);
154 extern int register_android_os_Trace(JNIEnv* env);
155 extern int register_android_os_FileObserver(JNIEnv *env);
156 extern int register_android_os_UEventObserver(JNIEnv* env);
157 extern int register_android_os_MemoryFile(JNIEnv* env);
158 extern int register_android_net_LocalSocketImpl(JNIEnv* env);
159 extern int register_android_net_NetworkUtils(JNIEnv* env);
160 extern int register_android_net_TrafficStats(JNIEnv* env);
161 extern int register_android_text_AndroidCharacter(JNIEnv *env);
162 extern int register_android_text_StaticLayout(JNIEnv *env);
163 extern int register_android_text_AndroidBidi(JNIEnv *env);
164 extern int register_android_opengl_classes(JNIEnv *env);
165 extern int register_android_ddm_DdmHandleNativeHeap(JNIEnv *env);
166 extern int register_android_server_NetworkManagementSocketTagger(JNIEnv* env);
167 extern int register_com_android_internal_os_ZygoteInit(JNIEnv* env);
168 extern int register_android_backup_BackupDataInput(JNIEnv *env);
169 extern int register_android_backup_BackupDataOutput(JNIEnv *env);
170 extern int register_android_backup_FileBackupHelperBase(JNIEnv *env);
171 extern int register_android_backup_BackupHelperDispatcher(JNIEnv *env);
172 extern int register_android_app_backup_FullBackup(JNIEnv *env);
173 extern int register_android_app_ActivityThread(JNIEnv *env);
174 extern int register_android_app_NativeActivity(JNIEnv *env);
175 extern int register_android_media_RemoteDisplay(JNIEnv *env);
176 extern int register_android_view_InputChannel(JNIEnv* env);
177 extern int register_android_view_InputDevice(JNIEnv* env);
178 extern int register_android_view_InputEventReceiver(JNIEnv* env);
179 extern int register_android_view_InputEventSender(JNIEnv* env);
180 extern int register_android_view_InputQueue(JNIEnv* env);
181 extern int register_android_view_KeyCharacterMap(JNIEnv *env);
182 extern int register_android_view_KeyEvent(JNIEnv* env);
183 extern int register_android_view_MotionEvent(JNIEnv* env);
184 extern int register_android_view_PointerIcon(JNIEnv* env);
185 extern int register_android_view_VelocityTracker(JNIEnv* env);
186 extern int register_android_content_res_ObbScanner(JNIEnv* env);
187 extern int register_android_content_res_Configuration(JNIEnv* env);
188 extern int register_android_animation_PropertyValuesHolder(JNIEnv *env);
189 extern int register_com_android_internal_content_NativeLibraryHelper(JNIEnv *env);
190 extern int register_com_android_internal_net_NetworkStatsFactory(JNIEnv *env);
191 extern int register_com_android_internal_os_Zygote(JNIEnv *env);
192 extern int register_com_android_internal_util_VirtualRefBasePtr(JNIEnv *env);
193
194 static AndroidRuntime* gCurRuntime = NULL;
195
196 static void doThrow(JNIEnv* env, const char* exc, const char* msg = NULL)
197 {
198     if (jniThrowException(env, exc, msg) != 0)
199         assert(false);
200 }
201
202 /*
203  * Code written in the Java Programming Language calls here from main().
204  */
205 static void com_android_internal_os_RuntimeInit_nativeFinishInit(JNIEnv* env, jobject clazz)
206 {
207     gCurRuntime->onStarted();
208 }
209
210 static void com_android_internal_os_RuntimeInit_nativeZygoteInit(JNIEnv* env, jobject clazz)
211 {
212     gCurRuntime->onZygoteInit();
213 }
214
215 static void com_android_internal_os_RuntimeInit_nativeSetExitWithoutCleanup(JNIEnv* env,
216         jobject clazz, jboolean exitWithoutCleanup)
217 {
218     gCurRuntime->setExitWithoutCleanup(exitWithoutCleanup);
219 }
220
221 /*
222  * JNI registration.
223  */
224 static JNINativeMethod gMethods[] = {
225     { "nativeFinishInit", "()V",
226         (void*) com_android_internal_os_RuntimeInit_nativeFinishInit },
227     { "nativeZygoteInit", "()V",
228         (void*) com_android_internal_os_RuntimeInit_nativeZygoteInit },
229     { "nativeSetExitWithoutCleanup", "(Z)V",
230         (void*) com_android_internal_os_RuntimeInit_nativeSetExitWithoutCleanup },
231 };
232
233 int 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 AndroidRuntime::AndroidRuntime(char* argBlockStart, const size_t argBlockLength) :
244         mExitWithoutCleanup(false),
245         mArgBlockStart(argBlockStart),
246         mArgBlockLength(argBlockLength)
247 {
248     SkGraphics::Init();
249     // There is also a global font cache, but its budget is specified in code
250     // see SkFontHost_android.cpp
251
252     // Pre-allocate enough space to hold a fair number of options.
253     mOptions.setCapacity(20);
254
255     assert(gCurRuntime == NULL);        // one per process
256     gCurRuntime = this;
257 }
258
259 AndroidRuntime::~AndroidRuntime()
260 {
261     SkGraphics::Term();
262 }
263
264 /*
265  * Register native methods using JNI.
266  */
267 /*static*/ int AndroidRuntime::registerNativeMethods(JNIEnv* env,
268     const char* className, const JNINativeMethod* gMethods, int numMethods)
269 {
270     return jniRegisterNativeMethods(env, className, gMethods, numMethods);
271 }
272
273 void AndroidRuntime::setArgv0(const char* argv0) {
274     memset(mArgBlockStart, 0, mArgBlockLength);
275     strlcpy(mArgBlockStart, argv0, mArgBlockLength);
276 }
277
278 status_t AndroidRuntime::callMain(const String8& className, jclass clazz,
279     const Vector<String8>& args)
280 {
281     JNIEnv* env;
282     jmethodID methodId;
283
284     ALOGD("Calling main entry %s", className.string());
285
286     env = getJNIEnv();
287     if (clazz == NULL || env == NULL) {
288         return UNKNOWN_ERROR;
289     }
290
291     methodId = env->GetStaticMethodID(clazz, "main", "([Ljava/lang/String;)V");
292     if (methodId == NULL) {
293         ALOGE("ERROR: could not find method %s.main(String[])\n", className.string());
294         return UNKNOWN_ERROR;
295     }
296
297     /*
298      * We want to call main() with a String array with our arguments in it.
299      * Create an array and populate it.
300      */
301     jclass stringClass;
302     jobjectArray strArray;
303
304     const size_t numArgs = args.size();
305     stringClass = env->FindClass("java/lang/String");
306     strArray = env->NewObjectArray(numArgs, stringClass, NULL);
307
308     for (size_t i = 0; i < numArgs; i++) {
309         jstring argStr = env->NewStringUTF(args[i].string());
310         env->SetObjectArrayElement(strArray, i, argStr);
311     }
312
313     env->CallStaticVoidMethod(clazz, methodId, strArray);
314     return NO_ERROR;
315 }
316
317 /*
318  * The VM calls this through the "exit" hook.
319  */
320 static void runtime_exit(int code)
321 {
322     gCurRuntime->exit(code);
323 }
324
325 /*
326  * The VM calls this through the "vfprintf" hook.
327  *
328  * We ignore "fp" and just write the results to the log file.
329  */
330 static void runtime_vfprintf(FILE* fp, const char* format, va_list ap)
331 {
332     LOG_PRI_VA(ANDROID_LOG_INFO, "vm-printf", format, ap);
333 }
334
335 /**
336  * The VM calls this when mutex contention debugging is enabled to
337  * determine whether or not the blocked thread was a "sensitive thread"
338  * for user responsiveness/smoothess.
339  *
340  * Our policy for this is whether or not we're tracing any StrictMode
341  * events on this thread (which we might've inherited via Binder calls
342  * into us)
343  */
344 static bool runtime_isSensitiveThread() {
345     IPCThreadState* state = IPCThreadState::selfOrNull();
346     return state && state->getStrictModePolicy() != 0;
347 }
348
349 static int hasDir(const char* dir)
350 {
351     struct stat s;
352     int res = stat(dir, &s);
353     if (res == 0) {
354         return S_ISDIR(s.st_mode);
355     }
356     return 0;
357 }
358
359 /*
360  * Read the persistent locale.
361  */
362 static void readLocale(char* language, char* region)
363 {
364     char propLang[PROPERTY_VALUE_MAX], propRegn[PROPERTY_VALUE_MAX];
365
366     property_get("persist.sys.language", propLang, "");
367     property_get("persist.sys.country", propRegn, "");
368     if (*propLang == 0 && *propRegn == 0) {
369         /* Set to ro properties, default is en_US */
370         property_get("ro.product.locale.language", propLang, "en");
371         property_get("ro.product.locale.region", propRegn, "US");
372     }
373     strncat(language, propLang, 3);
374     strncat(region, propRegn, 3);
375     //ALOGD("language=%s region=%s\n", language, region);
376 }
377
378 void AndroidRuntime::addOption(const char* optionString, void* extraInfo)
379 {
380     JavaVMOption opt;
381     opt.optionString = optionString;
382     opt.extraInfo = extraInfo;
383     mOptions.add(opt);
384 }
385
386 /*
387  * Parse a property containing space-separated options that should be
388  * passed directly to the VM, e.g. "-Xmx32m -verbose:gc -Xregenmap".
389  *
390  * This will cut up "extraOptsBuf" as we chop it into individual options.
391  *
392  * If "quotingArg" is non-null, it is passed before each extra option in mOptions.
393  *
394  * Adds the strings, if any, to mOptions.
395  */
396 void AndroidRuntime::parseExtraOpts(char* extraOptsBuf, const char* quotingArg)
397 {
398     char* start = extraOptsBuf;
399     char* end = NULL;
400     while (*start != '\0') {
401         while (*start == ' ')                   /* skip leading whitespace */
402             start++;
403         if (*start == '\0')                     /* was trailing ws, bail */
404             break;
405
406         end = start+1;
407         while (*end != ' ' && *end != '\0')     /* find end of token */
408             end++;
409         if (*end == ' ')
410             *end++ = '\0';          /* mark end, advance to indicate more */
411
412         if (quotingArg != NULL) {
413             addOption(quotingArg);
414         }
415         addOption(start);
416         start = end;
417     }
418 }
419
420 /*
421  * Reads a "property" into "buffer" with a default of "defaultArg". If
422  * the property is non-empty, it is treated as a runtime option such
423  * as "-Xmx32m".
424  *
425  * The "runtimeArg" is a prefix for the option such as "-Xms" or "-Xmx".
426  *
427  * If an argument is found, it is added to mOptions.
428  *
429  * If an option is found, it is added to mOptions and true is
430  * returned. Otherwise false is returned.
431  */
432 bool AndroidRuntime::parseRuntimeOption(const char* property,
433                                         char* buffer,
434                                         const char* runtimeArg,
435                                         const char* defaultArg)
436 {
437     strcpy(buffer, runtimeArg);
438     size_t runtimeArgLen = strlen(runtimeArg);
439     property_get(property, buffer+runtimeArgLen, defaultArg);
440     if (buffer[runtimeArgLen] == '\0') {
441         return false;
442     }
443     addOption(buffer);
444     return true;
445 }
446
447 /*
448  * Reads a "property" into "buffer". If the property is non-empty, it
449  * is treated as a dex2oat compiler option that should be
450  * passed as a quoted option, e.g. "-Ximage-compiler-option --compiler-filter=verify-none".
451  *
452  * The "compilerArg" is a prefix for the option such as "--compiler-filter=".
453  *
454  * The "quotingArg" should be "-Ximage-compiler-option" or "-Xcompiler-option".
455  *
456  * If an option is found, it is added to mOptions and true is
457  * returned. Otherwise false is returned.
458  */
459 bool AndroidRuntime::parseCompilerOption(const char* property,
460                                          char* buffer,
461                                          const char* compilerArg,
462                                          const char* quotingArg)
463 {
464     strcpy(buffer, compilerArg);
465     size_t compilerArgLen = strlen(compilerArg);
466     property_get(property, buffer+compilerArgLen, "");
467     if (buffer[compilerArgLen] == '\0') {
468         return false;
469     }
470     addOption(quotingArg);
471     addOption(buffer);
472     return true;
473 }
474
475 /*
476  * Reads a "property" into "buffer". If the property is non-empty, it
477  * is treated as a dex2oat compiler runtime option that should be
478  * passed as a quoted option, e.g. "-Ximage-compiler-option
479  * --runtime-arg -Ximage-compiler-option -Xmx32m".
480  *
481  * The "runtimeArg" is a prefix for the option such as "-Xms" or "-Xmx".
482  *
483  * The "quotingArg" should be "-Ximage-compiler-option" or "-Xcompiler-option".
484  *
485  * If an option is found, it is added to mOptions and true is
486  * returned. Otherwise false is returned.
487  */
488 bool AndroidRuntime::parseCompilerRuntimeOption(const char* property,
489                                                 char* buffer,
490                                                 const char* runtimeArg,
491                                                 const char* quotingArg)
492 {
493     strcpy(buffer, runtimeArg);
494     size_t runtimeArgLen = strlen(runtimeArg);
495     property_get(property, buffer+runtimeArgLen, "");
496     if (buffer[runtimeArgLen] == '\0') {
497         return false;
498     }
499     addOption(quotingArg);
500     addOption("--runtime-arg");
501     addOption(quotingArg);
502     addOption(buffer);
503     return true;
504 }
505
506 /*
507  * Start the Dalvik Virtual Machine.
508  *
509  * Various arguments, most determined by system properties, are passed in.
510  * The "mOptions" vector is updated.
511  *
512  * CAUTION: when adding options in here, be careful not to put the
513  * char buffer inside a nested scope.  Adding the buffer to the
514  * options using mOptions.add() does not copy the buffer, so if the
515  * buffer goes out of scope the option may be overwritten.  It's best
516  * to put the buffer at the top of the function so that it is more
517  * unlikely that someone will surround it in a scope at a later time
518  * and thus introduce a bug.
519  *
520  * Returns 0 on success.
521  */
522 int AndroidRuntime::startVm(JavaVM** pJavaVM, JNIEnv** pEnv, bool zygote)
523 {
524     int result = -1;
525     JavaVMInitArgs initArgs;
526     char propBuf[PROPERTY_VALUE_MAX];
527     char stackTraceFileBuf[sizeof("-Xstacktracefile:")-1 + PROPERTY_VALUE_MAX];
528     char dexoptFlagsBuf[PROPERTY_VALUE_MAX];
529     char enableAssertBuf[sizeof("-ea:")-1 + PROPERTY_VALUE_MAX];
530     char jniOptsBuf[sizeof("-Xjniopts:")-1 + PROPERTY_VALUE_MAX];
531     char heapstartsizeOptsBuf[sizeof("-Xms")-1 + PROPERTY_VALUE_MAX];
532     char heapsizeOptsBuf[sizeof("-Xmx")-1 + PROPERTY_VALUE_MAX];
533     char heapgrowthlimitOptsBuf[sizeof("-XX:HeapGrowthLimit=")-1 + PROPERTY_VALUE_MAX];
534     char heapminfreeOptsBuf[sizeof("-XX:HeapMinFree=")-1 + PROPERTY_VALUE_MAX];
535     char heapmaxfreeOptsBuf[sizeof("-XX:HeapMaxFree=")-1 + PROPERTY_VALUE_MAX];
536     char gctypeOptsBuf[sizeof("-Xgc:")-1 + PROPERTY_VALUE_MAX];
537     char backgroundgcOptsBuf[sizeof("-XX:BackgroundGC=")-1 + PROPERTY_VALUE_MAX];
538     char heaptargetutilizationOptsBuf[sizeof("-XX:HeapTargetUtilization=")-1 + PROPERTY_VALUE_MAX];
539     char jitcodecachesizeOptsBuf[sizeof("-Xjitcodecachesize:")-1 + PROPERTY_VALUE_MAX];
540     char dalvikVmLibBuf[PROPERTY_VALUE_MAX];
541     char dex2oatXmsImageFlagsBuf[sizeof("-Xms")-1 + PROPERTY_VALUE_MAX];
542     char dex2oatXmxImageFlagsBuf[sizeof("-Xmx")-1 + PROPERTY_VALUE_MAX];
543     char dex2oatXmsFlagsBuf[sizeof("-Xms")-1 + PROPERTY_VALUE_MAX];
544     char dex2oatXmxFlagsBuf[sizeof("-Xmx")-1 + PROPERTY_VALUE_MAX];
545     char dex2oatCompilerFilterBuf[sizeof("--compiler-filter=")-1 + PROPERTY_VALUE_MAX];
546     char dex2oatImageCompilerFilterBuf[sizeof("--compiler-filter=")-1 + PROPERTY_VALUE_MAX];
547     char dex2oatFlagsBuf[PROPERTY_VALUE_MAX];
548     char dex2oatImageFlagsBuf[PROPERTY_VALUE_MAX];
549     char extraOptsBuf[PROPERTY_VALUE_MAX];
550     char voldDecryptBuf[PROPERTY_VALUE_MAX];
551     enum {
552       kEMDefault,
553       kEMIntPortable,
554       kEMIntFast,
555       kEMJitCompiler,
556     } executionMode = kEMDefault;
557     char profilePeriod[sizeof("-Xprofile-period:")-1 + PROPERTY_VALUE_MAX];
558     char profileDuration[sizeof("-Xprofile-duration:")-1 + PROPERTY_VALUE_MAX];
559     char profileInterval[sizeof("-Xprofile-interval:")-1 + PROPERTY_VALUE_MAX];
560     char profileBackoff[sizeof("-Xprofile-backoff:")-1 + PROPERTY_VALUE_MAX];
561     char profileTopKThreshold[sizeof("-Xprofile-top-k-threshold:")-1 + PROPERTY_VALUE_MAX];
562     char profileTopKChangeThreshold[sizeof("-Xprofile-top-k-change-threshold:")-1 +
563                                     PROPERTY_VALUE_MAX];
564     char profileType[sizeof("-Xprofile-type:")-1 + PROPERTY_VALUE_MAX];
565     char profileMaxStackDepth[sizeof("-Xprofile-max-stack-depth:")-1 + PROPERTY_VALUE_MAX];
566     char langOption[sizeof("-Duser.language=") + 3];
567     char regionOption[sizeof("-Duser.region=") + 3];
568     char lockProfThresholdBuf[sizeof("-Xlockprofthreshold:")-1 + PROPERTY_VALUE_MAX];
569     char jitOpBuf[sizeof("-Xjitop:")-1 + PROPERTY_VALUE_MAX];
570     char jitMethodBuf[sizeof("-Xjitmethod:")-1 + PROPERTY_VALUE_MAX];
571     char nativeBridgeLibrary[sizeof("-XX:NativeBridge=") + PROPERTY_VALUE_MAX];
572
573     bool checkJni = false;
574     property_get("dalvik.vm.checkjni", propBuf, "");
575     if (strcmp(propBuf, "true") == 0) {
576         checkJni = true;
577     } else if (strcmp(propBuf, "false") != 0) {
578         /* property is neither true nor false; fall back on kernel parameter */
579         property_get("ro.kernel.android.checkjni", propBuf, "");
580         if (propBuf[0] == '1') {
581             checkJni = true;
582         }
583     }
584     ALOGD("CheckJNI is %s\n", checkJni ? "ON" : "OFF");
585     if (checkJni) {
586         /* extended JNI checking */
587         addOption("-Xcheck:jni");
588
589         /* set a cap on JNI global references */
590         addOption("-Xjnigreflimit:2000");
591
592         /* with -Xcheck:jni, this provides a JNI function call trace */
593         //addOption("-verbose:jni");
594     }
595
596     property_get("dalvik.vm.execution-mode", propBuf, "");
597     if (strcmp(propBuf, "int:portable") == 0) {
598         executionMode = kEMIntPortable;
599     } else if (strcmp(propBuf, "int:fast") == 0) {
600         executionMode = kEMIntFast;
601     } else if (strcmp(propBuf, "int:jit") == 0) {
602         executionMode = kEMJitCompiler;
603     }
604
605     parseRuntimeOption("dalvik.vm.stack-trace-file", stackTraceFileBuf, "-Xstacktracefile:");
606
607     property_get("dalvik.vm.check-dex-sum", propBuf, "");
608     if (strcmp(propBuf, "true") == 0) {
609         /* perform additional DEX checksum tests */
610         addOption("-Xcheckdexsum");
611     }
612
613     property_get("log.redirect-stdio", propBuf, "");
614     if (strcmp(propBuf, "true") == 0) {
615         /* convert stdout/stderr to log messages */
616         addOption("-Xlog-stdio");
617     }
618
619     strcpy(enableAssertBuf, "-ea:");
620     property_get("dalvik.vm.enableassertions", enableAssertBuf+sizeof("-ea:")-1, "");
621     if (enableAssertBuf[sizeof("-ea:")-1] != '\0') {
622         /* accept "all" to mean "all classes and packages" */
623         if (strcmp(enableAssertBuf+sizeof("-ea:")-1, "all") == 0)
624             enableAssertBuf[3] = '\0'; // truncate to "-ea"
625         ALOGI("Assertions enabled: '%s'\n", enableAssertBuf);
626         addOption(enableAssertBuf);
627     } else {
628         ALOGV("Assertions disabled\n");
629     }
630
631     strcpy(jniOptsBuf, "-Xjniopts:");
632     if (parseRuntimeOption("dalvik.vm.jniopts", jniOptsBuf, "-Xjniopts:")) {
633         ALOGI("JNI options: '%s'\n", jniOptsBuf);
634     }
635
636     /* route exit() to our handler */
637     addOption("exit", (void*) runtime_exit);
638
639     /* route fprintf() to our handler */
640     addOption("vfprintf", (void*) runtime_vfprintf);
641
642     /* register the framework-specific "is sensitive thread" hook */
643     addOption("sensitiveThread", (void*) runtime_isSensitiveThread);
644
645     /* enable verbose; standard options are { jni, gc, class } */
646     //addOption("-verbose:jni");
647     addOption("-verbose:gc");
648     //addOption("-verbose:class");
649
650     /*
651      * The default starting and maximum size of the heap.  Larger
652      * values should be specified in a product property override.
653      */
654     parseRuntimeOption("dalvik.vm.heapstartsize", heapstartsizeOptsBuf, "-Xms", "4m");
655     parseRuntimeOption("dalvik.vm.heapsize", heapsizeOptsBuf, "-Xmx", "16m");
656
657     // Increase the main thread's interpreter stack size for bug 6315322.
658     addOption("-XX:mainThreadStackSize=24K");
659
660     // Set the max jit code cache size.  Note: size of 0 will disable the JIT.
661     parseRuntimeOption("dalvik.vm.jit.codecachesize",
662                        jitcodecachesizeOptsBuf,
663                        "-Xjitcodecachesize:");
664
665     parseRuntimeOption("dalvik.vm.heapgrowthlimit", heapgrowthlimitOptsBuf, "-XX:HeapGrowthLimit=");
666     parseRuntimeOption("dalvik.vm.heapminfree", heapminfreeOptsBuf, "-XX:HeapMinFree=");
667     parseRuntimeOption("dalvik.vm.heapmaxfree", heapmaxfreeOptsBuf, "-XX:HeapMaxFree=");
668     parseRuntimeOption("dalvik.vm.heaptargetutilization",
669                        heaptargetutilizationOptsBuf,
670                        "-XX:HeapTargetUtilization=");
671
672     property_get("ro.config.low_ram", propBuf, "");
673     if (strcmp(propBuf, "true") == 0) {
674       addOption("-XX:LowMemoryMode");
675     }
676
677     parseRuntimeOption("dalvik.vm.gctype", gctypeOptsBuf, "-Xgc:");
678     parseRuntimeOption("dalvik.vm.backgroundgctype", backgroundgcOptsBuf, "-XX:BackgroundGC=");
679
680     /*
681      * Enable or disable dexopt features, such as bytecode verification and
682      * calculation of register maps for precise GC.
683      */
684     property_get("dalvik.vm.dexopt-flags", dexoptFlagsBuf, "");
685     if (dexoptFlagsBuf[0] != '\0') {
686         const char* opc;
687         const char* val;
688
689         opc = strstr(dexoptFlagsBuf, "v=");     /* verification */
690         if (opc != NULL) {
691             switch (*(opc+2)) {
692             case 'n':   val = "-Xverify:none";      break;
693             case 'r':   val = "-Xverify:remote";    break;
694             case 'a':   val = "-Xverify:all";       break;
695             default:    val = NULL;                 break;
696             }
697
698             if (val != NULL) {
699                 addOption(val);
700             }
701         }
702
703         opc = strstr(dexoptFlagsBuf, "o=");     /* optimization */
704         if (opc != NULL) {
705             switch (*(opc+2)) {
706             case 'n':   val = "-Xdexopt:none";      break;
707             case 'v':   val = "-Xdexopt:verified";  break;
708             case 'a':   val = "-Xdexopt:all";       break;
709             case 'f':   val = "-Xdexopt:full";      break;
710             default:    val = NULL;                 break;
711             }
712
713             if (val != NULL) {
714                 addOption(val);
715             }
716         }
717
718         opc = strstr(dexoptFlagsBuf, "m=y");    /* register map */
719         if (opc != NULL) {
720             addOption("-Xgenregmap");
721
722             /* turn on precise GC while we're at it */
723             addOption("-Xgc:precise");
724         }
725     }
726
727     /*
728      * Enable debugging only for apps forked from zygote.
729      * Set suspend=y to pause during VM init and use android ADB transport.
730      */
731     if (zygote) {
732       addOption("-agentlib:jdwp=transport=dt_android_adb,suspend=n,server=y");
733     }
734
735     parseRuntimeOption("dalvik.vm.lockprof.threshold",
736                        lockProfThresholdBuf,
737                        "-Xlockprofthreshold:");
738
739     /* Force interpreter-only mode for selected opcodes. Eg "1-0a,3c,f1-ff" */
740     parseRuntimeOption("dalvik.vm.jit.op", jitOpBuf, "-Xjitop:");
741
742     /* Force interpreter-only mode for selected methods */
743     parseRuntimeOption("dalvik.vm.jit.method", jitMethodBuf, "-Xjitmethod:");
744
745     if (executionMode == kEMIntPortable) {
746         addOption("-Xint:portable");
747     } else if (executionMode == kEMIntFast) {
748         addOption("-Xint:fast");
749     } else if (executionMode == kEMJitCompiler) {
750         addOption("-Xint:jit");
751     }
752
753     // libart tolerates libdvm flags, but not vice versa, so only pass some options if libart.
754     property_get("persist.sys.dalvik.vm.lib.2", dalvikVmLibBuf, "libart.so");
755     bool libart = (strncmp(dalvikVmLibBuf, "libart", 6) == 0);
756
757     if (libart) {
758         // If we booting without the real /data, don't spend time compiling.
759         property_get("vold.decrypt", voldDecryptBuf, "");
760         bool skip_compilation = ((strcmp(voldDecryptBuf, "trigger_restart_min_framework") == 0) ||
761                                  (strcmp(voldDecryptBuf, "1") == 0));
762
763         // Extra options for boot.art/boot.oat image generation.
764         parseCompilerRuntimeOption("dalvik.vm.image-dex2oat-Xms", dex2oatXmsImageFlagsBuf,
765                                    "-Xms", "-Ximage-compiler-option");
766         parseCompilerRuntimeOption("dalvik.vm.image-dex2oat-Xmx", dex2oatXmxImageFlagsBuf,
767                                    "-Xmx", "-Ximage-compiler-option");
768         if (skip_compilation) {
769             addOption("-Ximage-compiler-option");
770             addOption("--compiler-filter=verify-none");
771         } else {
772             parseCompilerOption("dalvik.vm.image-dex2oat-filter", dex2oatImageCompilerFilterBuf,
773                                 "--compiler-filter=", "-Ximage-compiler-option");
774         }
775         addOption("-Ximage-compiler-option");
776         addOption("--image-classes-zip=/system/framework/framework.jar");
777         addOption("-Ximage-compiler-option");
778         addOption("--image-classes=preloaded-classes");
779         property_get("dalvik.vm.image-dex2oat-flags", dex2oatImageFlagsBuf, "");
780         parseExtraOpts(dex2oatImageFlagsBuf, "-Ximage-compiler-option");
781
782         // Extra options for DexClassLoader.
783         parseCompilerRuntimeOption("dalvik.vm.dex2oat-Xms", dex2oatXmsFlagsBuf,
784                                    "-Xms", "-Xcompiler-option");
785         parseCompilerRuntimeOption("dalvik.vm.dex2oat-Xmx", dex2oatXmxFlagsBuf,
786                                    "-Xmx", "-Xcompiler-option");
787         if (skip_compilation) {
788             addOption("-Xcompiler-option");
789             addOption("--compiler-filter=verify-none");
790         } else {
791             parseCompilerOption("dalvik.vm.dex2oat-filter", dex2oatCompilerFilterBuf,
792                                 "--compiler-filter=", "-Xcompiler-option");
793         }
794         property_get("dalvik.vm.dex2oat-flags", dex2oatFlagsBuf, "");
795         parseExtraOpts(dex2oatFlagsBuf, "-Xcompiler-option");
796
797     }
798
799     /* extra options; parse this late so it overrides others */
800     property_get("dalvik.vm.extra-opts", extraOptsBuf, "");
801     parseExtraOpts(extraOptsBuf, NULL);
802
803     /* Set the properties for locale */
804     {
805         strcpy(langOption, "-Duser.language=");
806         strcpy(regionOption, "-Duser.region=");
807         readLocale(langOption, regionOption);
808         addOption(langOption);
809         addOption(regionOption);
810     }
811
812     /*
813      * Set profiler options
814      */
815     if (libart) {
816         // Whether or not the profiler should be enabled.
817         property_get("dalvik.vm.profiler", propBuf, "0");
818         if (propBuf[0] == '1') {
819             addOption("-Xenable-profiler");
820         }
821
822         // Whether the profile should start upon app startup or be delayed by some random offset
823         // (in seconds) that is bound between 0 and a fixed value.
824         property_get("dalvik.vm.profile.start-immed", propBuf, "0");
825         if (propBuf[0] == '1') {
826             addOption("-Xprofile-start-immediately");
827         }
828
829         // Number of seconds during profile runs.
830         parseRuntimeOption("dalvik.vm.profile.period-secs", profilePeriod, "-Xprofile-period:");
831
832         // Length of each profile run (seconds).
833         parseRuntimeOption("dalvik.vm.profile.duration-secs",
834                            profileDuration,
835                            "-Xprofile-duration:");
836
837         // Polling interval during profile run (microseconds).
838         parseRuntimeOption("dalvik.vm.profile.interval-us", profileInterval, "-Xprofile-interval:");
839
840         // Coefficient for period backoff.  The the period is multiplied
841         // by this value after each profile run.
842         parseRuntimeOption("dalvik.vm.profile.backoff-coeff", profileBackoff, "-Xprofile-backoff:");
843
844         // Top K% of samples that are considered relevant when
845         // deciding if the app should be recompiled.
846         parseRuntimeOption("dalvik.vm.profile.top-k-thr",
847                            profileTopKThreshold,
848                            "-Xprofile-top-k-threshold:");
849
850         // The threshold after which a change in the structure of the
851         // top K% profiled samples becomes significant and triggers
852         // recompilation. A change in profile is considered
853         // significant if X% (top-k-change-threshold) of the top K%
854         // (top-k-threshold property) samples has changed.
855         parseRuntimeOption("dalvik.vm.profile.top-k-ch-thr",
856                            profileTopKChangeThreshold,
857                            "-Xprofile-top-k-change-threshold:");
858
859         // Type of profile data.
860         parseRuntimeOption("dalvik.vm.profiler.type", profileType, "-Xprofile-type:");
861
862         // Depth of bounded stack data
863         parseRuntimeOption("dalvik.vm.profile.max-stack-depth",
864                            profileMaxStackDepth,
865                            "-Xprofile-max-stack-depth:");
866
867         // Native bridge library. "0" means that native bridge is disabled.
868         property_get("ro.dalvik.vm.native.bridge", propBuf, "");
869         if (propBuf[0] == '\0') {
870             ALOGW("ro.dalvik.vm.native.bridge is not expected to be empty");
871         } else if (strcmp(propBuf, "0") != 0) {
872             snprintf(nativeBridgeLibrary, sizeof("-XX:NativeBridge=") + PROPERTY_VALUE_MAX,
873                      "-XX:NativeBridge=%s", propBuf);
874             addOption(nativeBridgeLibrary);
875         }
876     }
877
878     initArgs.version = JNI_VERSION_1_4;
879     initArgs.options = mOptions.editArray();
880     initArgs.nOptions = mOptions.size();
881     initArgs.ignoreUnrecognized = JNI_FALSE;
882
883     /*
884      * Initialize the VM.
885      *
886      * The JavaVM* is essentially per-process, and the JNIEnv* is per-thread.
887      * If this call succeeds, the VM is ready, and we can start issuing
888      * JNI calls.
889      */
890     if (JNI_CreateJavaVM(pJavaVM, pEnv, &initArgs) < 0) {
891         ALOGE("JNI_CreateJavaVM failed\n");
892         goto bail;
893     }
894
895     result = 0;
896
897 bail:
898     return result;
899 }
900
901 char* AndroidRuntime::toSlashClassName(const char* className)
902 {
903     char* result = strdup(className);
904     for (char* cp = result; *cp != '\0'; cp++) {
905         if (*cp == '.') {
906             *cp = '/';
907         }
908     }
909     return result;
910 }
911
912 /** Create a Java string from an ASCII or Latin-1 string */
913 jstring AndroidRuntime::NewStringLatin1(JNIEnv* env, const char* bytes) {
914     if (!bytes) return NULL;
915     int length = strlen(bytes);
916     jchar* buffer = (jchar *)alloca(length * sizeof(jchar));
917     if (!buffer) return NULL;
918     jchar* chp = buffer;
919     for (int i = 0; i < length; i++) {
920         *chp++ = *bytes++;
921     }
922     return env->NewString(buffer, length);
923 }
924
925
926 /*
927  * Start the Android runtime.  This involves starting the virtual machine
928  * and calling the "static void main(String[] args)" method in the class
929  * named by "className".
930  *
931  * Passes the main function two arguments, the class name and the specified
932  * options string.
933  */
934 void AndroidRuntime::start(const char* className, const Vector<String8>& options, bool zygote)
935 {
936     ALOGD("\n>>>>>> AndroidRuntime START %s <<<<<<\n",
937             className != NULL ? className : "(unknown)");
938
939     static const String8 startSystemServer("start-system-server");
940
941     /*
942      * 'startSystemServer == true' means runtime is obsolete and not run from
943      * init.rc anymore, so we print out the boot start event here.
944      */
945     for (size_t i = 0; i < options.size(); ++i) {
946         if (options[i] == startSystemServer) {
947            /* track our progress through the boot sequence */
948            const int LOG_BOOT_PROGRESS_START = 3000;
949            LOG_EVENT_LONG(LOG_BOOT_PROGRESS_START,  ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
950         }
951     }
952
953     const char* rootDir = getenv("ANDROID_ROOT");
954     if (rootDir == NULL) {
955         rootDir = "/system";
956         if (!hasDir("/system")) {
957             LOG_FATAL("No root directory specified, and /android does not exist.");
958             return;
959         }
960         setenv("ANDROID_ROOT", rootDir, 1);
961     }
962
963     //const char* kernelHack = getenv("LD_ASSUME_KERNEL");
964     //ALOGD("Found LD_ASSUME_KERNEL='%s'\n", kernelHack);
965
966     /* start the virtual machine */
967     JniInvocation jni_invocation;
968     jni_invocation.Init(NULL);
969     JNIEnv* env;
970     if (startVm(&mJavaVM, &env, zygote) != 0) {
971         return;
972     }
973     onVmCreated(env);
974
975     /*
976      * Register android functions.
977      */
978     if (startReg(env) < 0) {
979         ALOGE("Unable to register all android natives\n");
980         return;
981     }
982
983     /*
984      * We want to call main() with a String array with arguments in it.
985      * At present we have two arguments, the class name and an option string.
986      * Create an array to hold them.
987      */
988     jclass stringClass;
989     jobjectArray strArray;
990     jstring classNameStr;
991
992     stringClass = env->FindClass("java/lang/String");
993     assert(stringClass != NULL);
994     strArray = env->NewObjectArray(options.size() + 1, stringClass, NULL);
995     assert(strArray != NULL);
996     classNameStr = env->NewStringUTF(className);
997     assert(classNameStr != NULL);
998     env->SetObjectArrayElement(strArray, 0, classNameStr);
999
1000     for (size_t i = 0; i < options.size(); ++i) {
1001         jstring optionsStr = env->NewStringUTF(options.itemAt(i).string());
1002         assert(optionsStr != NULL);
1003         env->SetObjectArrayElement(strArray, i + 1, optionsStr);
1004     }
1005
1006     /*
1007      * Start VM.  This thread becomes the main thread of the VM, and will
1008      * not return until the VM exits.
1009      */
1010     char* slashClassName = toSlashClassName(className);
1011     jclass startClass = env->FindClass(slashClassName);
1012     if (startClass == NULL) {
1013         ALOGE("JavaVM unable to locate class '%s'\n", slashClassName);
1014         /* keep going */
1015     } else {
1016         jmethodID startMeth = env->GetStaticMethodID(startClass, "main",
1017             "([Ljava/lang/String;)V");
1018         if (startMeth == NULL) {
1019             ALOGE("JavaVM unable to find main() in '%s'\n", className);
1020             /* keep going */
1021         } else {
1022             env->CallStaticVoidMethod(startClass, startMeth, strArray);
1023
1024 #if 0
1025             if (env->ExceptionCheck())
1026                 threadExitUncaughtException(env);
1027 #endif
1028         }
1029     }
1030     free(slashClassName);
1031
1032     ALOGD("Shutting down VM\n");
1033     if (mJavaVM->DetachCurrentThread() != JNI_OK)
1034         ALOGW("Warning: unable to detach main thread\n");
1035     if (mJavaVM->DestroyJavaVM() != 0)
1036         ALOGW("Warning: VM did not shut down cleanly\n");
1037 }
1038
1039 void AndroidRuntime::exit(int code)
1040 {
1041     if (mExitWithoutCleanup) {
1042         ALOGI("VM exiting with result code %d, cleanup skipped.", code);
1043         ::_exit(code);
1044     } else {
1045         ALOGI("VM exiting with result code %d.", code);
1046         onExit(code);
1047         ::exit(code);
1048     }
1049 }
1050
1051 void AndroidRuntime::onVmCreated(JNIEnv* env)
1052 {
1053     // If AndroidRuntime had anything to do here, we'd have done it in 'start'.
1054 }
1055
1056 /*
1057  * Get the JNIEnv pointer for this thread.
1058  *
1059  * Returns NULL if the slot wasn't allocated or populated.
1060  */
1061 /*static*/ JNIEnv* AndroidRuntime::getJNIEnv()
1062 {
1063     JNIEnv* env;
1064     JavaVM* vm = AndroidRuntime::getJavaVM();
1065     assert(vm != NULL);
1066
1067     if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK)
1068         return NULL;
1069     return env;
1070 }
1071
1072 /*
1073  * Makes the current thread visible to the VM.
1074  *
1075  * The JNIEnv pointer returned is only valid for the current thread, and
1076  * thus must be tucked into thread-local storage.
1077  */
1078 static int javaAttachThread(const char* threadName, JNIEnv** pEnv)
1079 {
1080     JavaVMAttachArgs args;
1081     JavaVM* vm;
1082     jint result;
1083
1084     vm = AndroidRuntime::getJavaVM();
1085     assert(vm != NULL);
1086
1087     args.version = JNI_VERSION_1_4;
1088     args.name = (char*) threadName;
1089     args.group = NULL;
1090
1091     result = vm->AttachCurrentThread(pEnv, (void*) &args);
1092     if (result != JNI_OK)
1093         ALOGI("NOTE: attach of thread '%s' failed\n", threadName);
1094
1095     return result;
1096 }
1097
1098 /*
1099  * Detach the current thread from the set visible to the VM.
1100  */
1101 static int javaDetachThread(void)
1102 {
1103     JavaVM* vm;
1104     jint result;
1105
1106     vm = AndroidRuntime::getJavaVM();
1107     assert(vm != NULL);
1108
1109     result = vm->DetachCurrentThread();
1110     if (result != JNI_OK)
1111         ALOGE("ERROR: thread detach failed\n");
1112     return result;
1113 }
1114
1115 /*
1116  * When starting a native thread that will be visible from the VM, we
1117  * bounce through this to get the right attach/detach action.
1118  * Note that this function calls free(args)
1119  */
1120 /*static*/ int AndroidRuntime::javaThreadShell(void* args) {
1121     void* start = ((void**)args)[0];
1122     void* userData = ((void **)args)[1];
1123     char* name = (char*) ((void **)args)[2];        // we own this storage
1124     free(args);
1125     JNIEnv* env;
1126     int result;
1127
1128     /* hook us into the VM */
1129     if (javaAttachThread(name, &env) != JNI_OK)
1130         return -1;
1131
1132     /* start the thread running */
1133     result = (*(android_thread_func_t)start)(userData);
1134
1135     /* unhook us */
1136     javaDetachThread();
1137     free(name);
1138
1139     return result;
1140 }
1141
1142 /*
1143  * This is invoked from androidCreateThreadEtc() via the callback
1144  * set with androidSetCreateThreadFunc().
1145  *
1146  * We need to create the new thread in such a way that it gets hooked
1147  * into the VM before it really starts executing.
1148  */
1149 /*static*/ int AndroidRuntime::javaCreateThreadEtc(
1150                                 android_thread_func_t entryFunction,
1151                                 void* userData,
1152                                 const char* threadName,
1153                                 int32_t threadPriority,
1154                                 size_t threadStackSize,
1155                                 android_thread_id_t* threadId)
1156 {
1157     void** args = (void**) malloc(3 * sizeof(void*));   // javaThreadShell must free
1158     int result;
1159
1160     if (!threadName)
1161         threadName = "unnamed thread";
1162
1163     args[0] = (void*) entryFunction;
1164     args[1] = userData;
1165     args[2] = (void*) strdup(threadName);   // javaThreadShell must free
1166
1167     result = androidCreateRawThreadEtc(AndroidRuntime::javaThreadShell, args,
1168         threadName, threadPriority, threadStackSize, threadId);
1169     return result;
1170 }
1171
1172 /*
1173  * Create a thread that is visible from the VM.
1174  *
1175  * This is called from elsewhere in the library.
1176  */
1177 /*static*/ android_thread_id_t AndroidRuntime::createJavaThread(const char* name,
1178     void (*start)(void *), void* arg)
1179 {
1180     android_thread_id_t threadId = 0;
1181     javaCreateThreadEtc((android_thread_func_t) start, arg, name,
1182         ANDROID_PRIORITY_DEFAULT, 0, &threadId);
1183     return threadId;
1184 }
1185
1186 #if 0
1187 static void quickTest(void* arg)
1188 {
1189     const char* str = (const char*) arg;
1190
1191     printf("In quickTest: %s\n", str);
1192 }
1193 #endif
1194
1195 #ifdef NDEBUG
1196     #define REG_JNI(name)      { name }
1197     struct RegJNIRec {
1198         int (*mProc)(JNIEnv*);
1199     };
1200 #else
1201     #define REG_JNI(name)      { name, #name }
1202     struct RegJNIRec {
1203         int (*mProc)(JNIEnv*);
1204         const char* mName;
1205     };
1206 #endif
1207
1208 typedef void (*RegJAMProc)();
1209
1210 static int register_jni_procs(const RegJNIRec array[], size_t count, JNIEnv* env)
1211 {
1212     for (size_t i = 0; i < count; i++) {
1213         if (array[i].mProc(env) < 0) {
1214 #ifndef NDEBUG
1215             ALOGD("----------!!! %s failed to load\n", array[i].mName);
1216 #endif
1217             return -1;
1218         }
1219     }
1220     return 0;
1221 }
1222
1223 static void register_jam_procs(const RegJAMProc array[], size_t count)
1224 {
1225     for (size_t i = 0; i < count; i++) {
1226         array[i]();
1227     }
1228 }
1229
1230 static const RegJNIRec gRegJNI[] = {
1231     REG_JNI(register_com_android_internal_os_RuntimeInit),
1232     REG_JNI(register_android_os_SystemClock),
1233     REG_JNI(register_android_util_EventLog),
1234     REG_JNI(register_android_util_Log),
1235     REG_JNI(register_android_util_FloatMath),
1236     REG_JNI(register_android_content_AssetManager),
1237     REG_JNI(register_android_content_StringBlock),
1238     REG_JNI(register_android_content_XmlBlock),
1239     REG_JNI(register_android_emoji_EmojiFactory),
1240     REG_JNI(register_android_text_AndroidCharacter),
1241     REG_JNI(register_android_text_StaticLayout),
1242     REG_JNI(register_android_text_AndroidBidi),
1243     REG_JNI(register_android_view_InputDevice),
1244     REG_JNI(register_android_view_KeyCharacterMap),
1245     REG_JNI(register_android_os_Process),
1246     REG_JNI(register_android_os_SystemProperties),
1247     REG_JNI(register_android_os_Binder),
1248     REG_JNI(register_android_os_Parcel),
1249     REG_JNI(register_android_nio_utils),
1250     REG_JNI(register_android_graphics_Graphics),
1251     REG_JNI(register_android_view_DisplayEventReceiver),
1252     REG_JNI(register_android_view_RenderNode),
1253     REG_JNI(register_android_view_RenderNodeAnimator),
1254     REG_JNI(register_android_view_GraphicBuffer),
1255     REG_JNI(register_android_view_GLES20Canvas),
1256     REG_JNI(register_android_view_HardwareLayer),
1257     REG_JNI(register_android_view_ThreadedRenderer),
1258     REG_JNI(register_android_view_Surface),
1259     REG_JNI(register_android_view_SurfaceControl),
1260     REG_JNI(register_android_view_SurfaceSession),
1261     REG_JNI(register_android_view_TextureView),
1262     REG_JNI(register_com_android_internal_view_animation_NativeInterpolatorFactoryHelper),
1263     REG_JNI(register_com_google_android_gles_jni_EGLImpl),
1264     REG_JNI(register_com_google_android_gles_jni_GLImpl),
1265     REG_JNI(register_android_opengl_jni_EGL14),
1266     REG_JNI(register_android_opengl_jni_EGLExt),
1267     REG_JNI(register_android_opengl_jni_GLES10),
1268     REG_JNI(register_android_opengl_jni_GLES10Ext),
1269     REG_JNI(register_android_opengl_jni_GLES11),
1270     REG_JNI(register_android_opengl_jni_GLES11Ext),
1271     REG_JNI(register_android_opengl_jni_GLES20),
1272     REG_JNI(register_android_opengl_jni_GLES30),
1273     REG_JNI(register_android_opengl_jni_GLES31),
1274     REG_JNI(register_android_opengl_jni_GLES31Ext),
1275
1276     REG_JNI(register_android_graphics_Bitmap),
1277     REG_JNI(register_android_graphics_BitmapFactory),
1278     REG_JNI(register_android_graphics_BitmapRegionDecoder),
1279     REG_JNI(register_android_graphics_Camera),
1280     REG_JNI(register_android_graphics_CreateJavaOutputStreamAdaptor),
1281     REG_JNI(register_android_graphics_Canvas),
1282     REG_JNI(register_android_graphics_CanvasProperty),
1283     REG_JNI(register_android_graphics_ColorFilter),
1284     REG_JNI(register_android_graphics_DrawFilter),
1285     REG_JNI(register_android_graphics_FontFamily),
1286     REG_JNI(register_android_graphics_Interpolator),
1287     REG_JNI(register_android_graphics_LayerRasterizer),
1288     REG_JNI(register_android_graphics_MaskFilter),
1289     REG_JNI(register_android_graphics_Matrix),
1290     REG_JNI(register_android_graphics_Movie),
1291     REG_JNI(register_android_graphics_NinePatch),
1292     REG_JNI(register_android_graphics_Paint),
1293     REG_JNI(register_android_graphics_Path),
1294     REG_JNI(register_android_graphics_PathMeasure),
1295     REG_JNI(register_android_graphics_PathEffect),
1296     REG_JNI(register_android_graphics_Picture),
1297     REG_JNI(register_android_graphics_PorterDuff),
1298     REG_JNI(register_android_graphics_Rasterizer),
1299     REG_JNI(register_android_graphics_Region),
1300     REG_JNI(register_android_graphics_Shader),
1301     REG_JNI(register_android_graphics_SurfaceTexture),
1302     REG_JNI(register_android_graphics_Typeface),
1303     REG_JNI(register_android_graphics_Xfermode),
1304     REG_JNI(register_android_graphics_YuvImage),
1305     REG_JNI(register_android_graphics_pdf_PdfDocument),
1306     REG_JNI(register_android_graphics_pdf_PdfEditor),
1307     REG_JNI(register_android_graphics_pdf_PdfRenderer),
1308
1309     REG_JNI(register_android_database_CursorWindow),
1310     REG_JNI(register_android_database_SQLiteConnection),
1311     REG_JNI(register_android_database_SQLiteGlobal),
1312     REG_JNI(register_android_database_SQLiteDebug),
1313     REG_JNI(register_android_os_Debug),
1314     REG_JNI(register_android_os_FileObserver),
1315     REG_JNI(register_android_os_MessageQueue),
1316     REG_JNI(register_android_os_SELinux),
1317     REG_JNI(register_android_os_Trace),
1318     REG_JNI(register_android_os_UEventObserver),
1319     REG_JNI(register_android_net_LocalSocketImpl),
1320     REG_JNI(register_android_net_NetworkUtils),
1321     REG_JNI(register_android_net_TrafficStats),
1322     REG_JNI(register_android_os_MemoryFile),
1323     REG_JNI(register_com_android_internal_os_ZygoteInit),
1324     REG_JNI(register_com_android_internal_os_Zygote),
1325     REG_JNI(register_com_android_internal_util_VirtualRefBasePtr),
1326     REG_JNI(register_android_hardware_Camera),
1327     REG_JNI(register_android_hardware_camera2_CameraMetadata),
1328     REG_JNI(register_android_hardware_camera2_legacy_LegacyCameraDevice),
1329     REG_JNI(register_android_hardware_camera2_legacy_PerfMeasurement),
1330     REG_JNI(register_android_hardware_camera2_DngCreator),
1331     REG_JNI(register_android_hardware_SensorManager),
1332     REG_JNI(register_android_hardware_SerialPort),
1333     REG_JNI(register_android_hardware_SoundTrigger),
1334     REG_JNI(register_android_hardware_UsbDevice),
1335     REG_JNI(register_android_hardware_UsbDeviceConnection),
1336     REG_JNI(register_android_hardware_UsbRequest),
1337     REG_JNI(register_android_hardware_location_ActivityRecognitionHardware),
1338     REG_JNI(register_android_media_AudioRecord),
1339     REG_JNI(register_android_media_AudioSystem),
1340     REG_JNI(register_android_media_AudioTrack),
1341     REG_JNI(register_android_media_JetPlayer),
1342     REG_JNI(register_android_media_RemoteDisplay),
1343     REG_JNI(register_android_media_ToneGenerator),
1344
1345     REG_JNI(register_android_opengl_classes),
1346     REG_JNI(register_android_server_NetworkManagementSocketTagger),
1347     REG_JNI(register_android_ddm_DdmHandleNativeHeap),
1348     REG_JNI(register_android_backup_BackupDataInput),
1349     REG_JNI(register_android_backup_BackupDataOutput),
1350     REG_JNI(register_android_backup_FileBackupHelperBase),
1351     REG_JNI(register_android_backup_BackupHelperDispatcher),
1352     REG_JNI(register_android_app_backup_FullBackup),
1353     REG_JNI(register_android_app_ActivityThread),
1354     REG_JNI(register_android_app_NativeActivity),
1355     REG_JNI(register_android_view_InputChannel),
1356     REG_JNI(register_android_view_InputEventReceiver),
1357     REG_JNI(register_android_view_InputEventSender),
1358     REG_JNI(register_android_view_InputQueue),
1359     REG_JNI(register_android_view_KeyEvent),
1360     REG_JNI(register_android_view_MotionEvent),
1361     REG_JNI(register_android_view_PointerIcon),
1362     REG_JNI(register_android_view_VelocityTracker),
1363
1364     REG_JNI(register_android_content_res_ObbScanner),
1365     REG_JNI(register_android_content_res_Configuration),
1366
1367     REG_JNI(register_android_animation_PropertyValuesHolder),
1368     REG_JNI(register_com_android_internal_content_NativeLibraryHelper),
1369     REG_JNI(register_com_android_internal_net_NetworkStatsFactory),
1370 };
1371
1372 /*
1373  * Register android native functions with the VM.
1374  */
1375 /*static*/ int AndroidRuntime::startReg(JNIEnv* env)
1376 {
1377     /*
1378      * This hook causes all future threads created in this process to be
1379      * attached to the JavaVM.  (This needs to go away in favor of JNI
1380      * Attach calls.)
1381      */
1382     androidSetCreateThreadFunc((android_create_thread_fn) javaCreateThreadEtc);
1383
1384     ALOGV("--- registering native functions ---\n");
1385
1386     /*
1387      * Every "register" function calls one or more things that return
1388      * a local reference (e.g. FindClass).  Because we haven't really
1389      * started the VM yet, they're all getting stored in the base frame
1390      * and never released.  Use Push/Pop to manage the storage.
1391      */
1392     env->PushLocalFrame(200);
1393
1394     if (register_jni_procs(gRegJNI, NELEM(gRegJNI), env) < 0) {
1395         env->PopLocalFrame(NULL);
1396         return -1;
1397     }
1398     env->PopLocalFrame(NULL);
1399
1400     //createJavaThread("fubar", quickTest, (void*) "hello");
1401
1402     return 0;
1403 }
1404
1405 AndroidRuntime* AndroidRuntime::getRuntime()
1406 {
1407     return gCurRuntime;
1408 }
1409
1410 /**
1411  * Used by WithFramework to register native functions.
1412  */
1413 extern "C"
1414 jint Java_com_android_internal_util_WithFramework_registerNatives(
1415         JNIEnv* env, jclass clazz) {
1416     return register_jni_procs(gRegJNI, NELEM(gRegJNI), env);
1417 }
1418
1419 /**
1420  * Used by LoadClass to register native functions.
1421  */
1422 extern "C"
1423 jint Java_LoadClass_registerNatives(JNIEnv* env, jclass clazz) {
1424     return register_jni_procs(gRegJNI, NELEM(gRegJNI), env);
1425 }
1426
1427 }   // namespace android