OSDN Git Service

Clean entire arg block when setting process name.
[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)
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     /* enable debugging; set suspend=y to pause during VM init */
728     /* use android ADB transport */
729     addOption("-agentlib:jdwp=transport=dt_android_adb,suspend=n,server=y");
730
731     parseRuntimeOption("dalvik.vm.lockprof.threshold",
732                        lockProfThresholdBuf,
733                        "-Xlockprofthreshold:");
734
735     /* Force interpreter-only mode for selected opcodes. Eg "1-0a,3c,f1-ff" */
736     parseRuntimeOption("dalvik.vm.jit.op", jitOpBuf, "-Xjitop:");
737
738     /* Force interpreter-only mode for selected methods */
739     parseRuntimeOption("dalvik.vm.jit.method", jitMethodBuf, "-Xjitmethod:");
740
741     if (executionMode == kEMIntPortable) {
742         addOption("-Xint:portable");
743     } else if (executionMode == kEMIntFast) {
744         addOption("-Xint:fast");
745     } else if (executionMode == kEMJitCompiler) {
746         addOption("-Xint:jit");
747     }
748
749     // libart tolerates libdvm flags, but not vice versa, so only pass some options if libart.
750     property_get("persist.sys.dalvik.vm.lib.2", dalvikVmLibBuf, "libart.so");
751     bool libart = (strncmp(dalvikVmLibBuf, "libart", 6) == 0);
752
753     if (libart) {
754         // If we booting without the real /data, don't spend time compiling.
755         property_get("vold.decrypt", voldDecryptBuf, "");
756         bool skip_compilation = ((strcmp(voldDecryptBuf, "trigger_restart_min_framework") == 0) ||
757                                  (strcmp(voldDecryptBuf, "1") == 0));
758
759         // Extra options for boot.art/boot.oat image generation.
760         parseCompilerRuntimeOption("dalvik.vm.image-dex2oat-Xms", dex2oatXmsImageFlagsBuf,
761                                    "-Xms", "-Ximage-compiler-option");
762         parseCompilerRuntimeOption("dalvik.vm.image-dex2oat-Xmx", dex2oatXmxImageFlagsBuf,
763                                    "-Xmx", "-Ximage-compiler-option");
764         if (skip_compilation) {
765             addOption("-Ximage-compiler-option");
766             addOption("--compiler-filter=verify-none");
767         } else {
768             parseCompilerOption("dalvik.vm.image-dex2oat-filter", dex2oatImageCompilerFilterBuf,
769                                 "--compiler-filter=", "-Ximage-compiler-option");
770         }
771         addOption("-Ximage-compiler-option");
772         addOption("--image-classes-zip=/system/framework/framework.jar");
773         addOption("-Ximage-compiler-option");
774         addOption("--image-classes=preloaded-classes");
775         property_get("dalvik.vm.image-dex2oat-flags", dex2oatImageFlagsBuf, "");
776         parseExtraOpts(dex2oatImageFlagsBuf, "-Ximage-compiler-option");
777
778         // Extra options for DexClassLoader.
779         parseCompilerRuntimeOption("dalvik.vm.dex2oat-Xms", dex2oatXmsFlagsBuf,
780                                    "-Xms", "-Xcompiler-option");
781         parseCompilerRuntimeOption("dalvik.vm.dex2oat-Xmx", dex2oatXmxFlagsBuf,
782                                    "-Xmx", "-Xcompiler-option");
783         if (skip_compilation) {
784             addOption("-Xcompiler-option");
785             addOption("--compiler-filter=verify-none");
786         } else {
787             parseCompilerOption("dalvik.vm.dex2oat-filter", dex2oatCompilerFilterBuf,
788                                 "--compiler-filter=", "-Xcompiler-option");
789         }
790         property_get("dalvik.vm.dex2oat-flags", dex2oatFlagsBuf, "");
791         parseExtraOpts(dex2oatFlagsBuf, "-Xcompiler-option");
792
793     }
794
795     /* extra options; parse this late so it overrides others */
796     property_get("dalvik.vm.extra-opts", extraOptsBuf, "");
797     parseExtraOpts(extraOptsBuf, NULL);
798
799     /* Set the properties for locale */
800     {
801         strcpy(langOption, "-Duser.language=");
802         strcpy(regionOption, "-Duser.region=");
803         readLocale(langOption, regionOption);
804         addOption(langOption);
805         addOption(regionOption);
806     }
807
808     /*
809      * Set profiler options
810      */
811     if (libart) {
812         // Whether or not the profiler should be enabled.
813         property_get("dalvik.vm.profiler", propBuf, "0");
814         if (propBuf[0] == '1') {
815             addOption("-Xenable-profiler");
816         }
817
818         // Whether the profile should start upon app startup or be delayed by some random offset
819         // (in seconds) that is bound between 0 and a fixed value.
820         property_get("dalvik.vm.profile.start-immed", propBuf, "0");
821         if (propBuf[0] == '1') {
822             addOption("-Xprofile-start-immediately");
823         }
824
825         // Number of seconds during profile runs.
826         parseRuntimeOption("dalvik.vm.profile.period-secs", profilePeriod, "-Xprofile-period:");
827
828         // Length of each profile run (seconds).
829         parseRuntimeOption("dalvik.vm.profile.duration-secs",
830                            profileDuration,
831                            "-Xprofile-duration:");
832
833         // Polling interval during profile run (microseconds).
834         parseRuntimeOption("dalvik.vm.profile.interval-us", profileInterval, "-Xprofile-interval:");
835
836         // Coefficient for period backoff.  The the period is multiplied
837         // by this value after each profile run.
838         parseRuntimeOption("dalvik.vm.profile.backoff-coeff", profileBackoff, "-Xprofile-backoff:");
839
840         // Top K% of samples that are considered relevant when
841         // deciding if the app should be recompiled.
842         parseRuntimeOption("dalvik.vm.profile.top-k-thr",
843                            profileTopKThreshold,
844                            "-Xprofile-top-k-threshold:");
845
846         // The threshold after which a change in the structure of the
847         // top K% profiled samples becomes significant and triggers
848         // recompilation. A change in profile is considered
849         // significant if X% (top-k-change-threshold) of the top K%
850         // (top-k-threshold property) samples has changed.
851         parseRuntimeOption("dalvik.vm.profile.top-k-ch-thr",
852                            profileTopKChangeThreshold,
853                            "-Xprofile-top-k-change-threshold:");
854
855         // Type of profile data.
856         parseRuntimeOption("dalvik.vm.profiler.type", profileType, "-Xprofile-type:");
857
858         // Depth of bounded stack data
859         parseRuntimeOption("dalvik.vm.profile.max-stack-depth",
860                            profileMaxStackDepth,
861                            "-Xprofile-max-stack-depth:");
862
863         // Native bridge library. "0" means that native bridge is disabled.
864         property_get("ro.dalvik.vm.native.bridge", propBuf, "");
865         if (propBuf[0] == '\0') {
866             ALOGW("ro.dalvik.vm.native.bridge is not expected to be empty");
867         } else if (strcmp(propBuf, "0") != 0) {
868             snprintf(nativeBridgeLibrary, sizeof("-XX:NativeBridge=") + PROPERTY_VALUE_MAX,
869                      "-XX:NativeBridge=%s", propBuf);
870             addOption(nativeBridgeLibrary);
871         }
872     }
873
874     initArgs.version = JNI_VERSION_1_4;
875     initArgs.options = mOptions.editArray();
876     initArgs.nOptions = mOptions.size();
877     initArgs.ignoreUnrecognized = JNI_FALSE;
878
879     /*
880      * Initialize the VM.
881      *
882      * The JavaVM* is essentially per-process, and the JNIEnv* is per-thread.
883      * If this call succeeds, the VM is ready, and we can start issuing
884      * JNI calls.
885      */
886     if (JNI_CreateJavaVM(pJavaVM, pEnv, &initArgs) < 0) {
887         ALOGE("JNI_CreateJavaVM failed\n");
888         goto bail;
889     }
890
891     result = 0;
892
893 bail:
894     return result;
895 }
896
897 char* AndroidRuntime::toSlashClassName(const char* className)
898 {
899     char* result = strdup(className);
900     for (char* cp = result; *cp != '\0'; cp++) {
901         if (*cp == '.') {
902             *cp = '/';
903         }
904     }
905     return result;
906 }
907
908 /*
909  * Start the Android runtime.  This involves starting the virtual machine
910  * and calling the "static void main(String[] args)" method in the class
911  * named by "className".
912  *
913  * Passes the main function two arguments, the class name and the specified
914  * options string.
915  */
916 void AndroidRuntime::start(const char* className, const Vector<String8>& options)
917 {
918     ALOGD("\n>>>>>> AndroidRuntime START %s <<<<<<\n",
919             className != NULL ? className : "(unknown)");
920
921     static const String8 startSystemServer("start-system-server");
922
923     /*
924      * 'startSystemServer == true' means runtime is obsolete and not run from
925      * init.rc anymore, so we print out the boot start event here.
926      */
927     for (size_t i = 0; i < options.size(); ++i) {
928         if (options[i] == startSystemServer) {
929            /* track our progress through the boot sequence */
930            const int LOG_BOOT_PROGRESS_START = 3000;
931            LOG_EVENT_LONG(LOG_BOOT_PROGRESS_START,  ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
932         }
933     }
934
935     const char* rootDir = getenv("ANDROID_ROOT");
936     if (rootDir == NULL) {
937         rootDir = "/system";
938         if (!hasDir("/system")) {
939             LOG_FATAL("No root directory specified, and /android does not exist.");
940             return;
941         }
942         setenv("ANDROID_ROOT", rootDir, 1);
943     }
944
945     //const char* kernelHack = getenv("LD_ASSUME_KERNEL");
946     //ALOGD("Found LD_ASSUME_KERNEL='%s'\n", kernelHack);
947
948     /* start the virtual machine */
949     JniInvocation jni_invocation;
950     jni_invocation.Init(NULL);
951     JNIEnv* env;
952     if (startVm(&mJavaVM, &env) != 0) {
953         return;
954     }
955     onVmCreated(env);
956
957     /*
958      * Register android functions.
959      */
960     if (startReg(env) < 0) {
961         ALOGE("Unable to register all android natives\n");
962         return;
963     }
964
965     /*
966      * We want to call main() with a String array with arguments in it.
967      * At present we have two arguments, the class name and an option string.
968      * Create an array to hold them.
969      */
970     jclass stringClass;
971     jobjectArray strArray;
972     jstring classNameStr;
973
974     stringClass = env->FindClass("java/lang/String");
975     assert(stringClass != NULL);
976     strArray = env->NewObjectArray(options.size() + 1, stringClass, NULL);
977     assert(strArray != NULL);
978     classNameStr = env->NewStringUTF(className);
979     assert(classNameStr != NULL);
980     env->SetObjectArrayElement(strArray, 0, classNameStr);
981
982     for (size_t i = 0; i < options.size(); ++i) {
983         jstring optionsStr = env->NewStringUTF(options.itemAt(i).string());
984         assert(optionsStr != NULL);
985         env->SetObjectArrayElement(strArray, i + 1, optionsStr);
986     }
987
988     /*
989      * Start VM.  This thread becomes the main thread of the VM, and will
990      * not return until the VM exits.
991      */
992     char* slashClassName = toSlashClassName(className);
993     jclass startClass = env->FindClass(slashClassName);
994     if (startClass == NULL) {
995         ALOGE("JavaVM unable to locate class '%s'\n", slashClassName);
996         /* keep going */
997     } else {
998         jmethodID startMeth = env->GetStaticMethodID(startClass, "main",
999             "([Ljava/lang/String;)V");
1000         if (startMeth == NULL) {
1001             ALOGE("JavaVM unable to find main() in '%s'\n", className);
1002             /* keep going */
1003         } else {
1004             env->CallStaticVoidMethod(startClass, startMeth, strArray);
1005
1006 #if 0
1007             if (env->ExceptionCheck())
1008                 threadExitUncaughtException(env);
1009 #endif
1010         }
1011     }
1012     free(slashClassName);
1013
1014     ALOGD("Shutting down VM\n");
1015     if (mJavaVM->DetachCurrentThread() != JNI_OK)
1016         ALOGW("Warning: unable to detach main thread\n");
1017     if (mJavaVM->DestroyJavaVM() != 0)
1018         ALOGW("Warning: VM did not shut down cleanly\n");
1019 }
1020
1021 void AndroidRuntime::exit(int code)
1022 {
1023     if (mExitWithoutCleanup) {
1024         ALOGI("VM exiting with result code %d, cleanup skipped.", code);
1025         ::_exit(code);
1026     } else {
1027         ALOGI("VM exiting with result code %d.", code);
1028         onExit(code);
1029         ::exit(code);
1030     }
1031 }
1032
1033 void AndroidRuntime::onVmCreated(JNIEnv* env)
1034 {
1035     // If AndroidRuntime had anything to do here, we'd have done it in 'start'.
1036 }
1037
1038 /*
1039  * Get the JNIEnv pointer for this thread.
1040  *
1041  * Returns NULL if the slot wasn't allocated or populated.
1042  */
1043 /*static*/ JNIEnv* AndroidRuntime::getJNIEnv()
1044 {
1045     JNIEnv* env;
1046     JavaVM* vm = AndroidRuntime::getJavaVM();
1047     assert(vm != NULL);
1048
1049     if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK)
1050         return NULL;
1051     return env;
1052 }
1053
1054 /*
1055  * Makes the current thread visible to the VM.
1056  *
1057  * The JNIEnv pointer returned is only valid for the current thread, and
1058  * thus must be tucked into thread-local storage.
1059  */
1060 static int javaAttachThread(const char* threadName, JNIEnv** pEnv)
1061 {
1062     JavaVMAttachArgs args;
1063     JavaVM* vm;
1064     jint result;
1065
1066     vm = AndroidRuntime::getJavaVM();
1067     assert(vm != NULL);
1068
1069     args.version = JNI_VERSION_1_4;
1070     args.name = (char*) threadName;
1071     args.group = NULL;
1072
1073     result = vm->AttachCurrentThread(pEnv, (void*) &args);
1074     if (result != JNI_OK)
1075         ALOGI("NOTE: attach of thread '%s' failed\n", threadName);
1076
1077     return result;
1078 }
1079
1080 /*
1081  * Detach the current thread from the set visible to the VM.
1082  */
1083 static int javaDetachThread(void)
1084 {
1085     JavaVM* vm;
1086     jint result;
1087
1088     vm = AndroidRuntime::getJavaVM();
1089     assert(vm != NULL);
1090
1091     result = vm->DetachCurrentThread();
1092     if (result != JNI_OK)
1093         ALOGE("ERROR: thread detach failed\n");
1094     return result;
1095 }
1096
1097 /*
1098  * When starting a native thread that will be visible from the VM, we
1099  * bounce through this to get the right attach/detach action.
1100  * Note that this function calls free(args)
1101  */
1102 /*static*/ int AndroidRuntime::javaThreadShell(void* args) {
1103     void* start = ((void**)args)[0];
1104     void* userData = ((void **)args)[1];
1105     char* name = (char*) ((void **)args)[2];        // we own this storage
1106     free(args);
1107     JNIEnv* env;
1108     int result;
1109
1110     /* hook us into the VM */
1111     if (javaAttachThread(name, &env) != JNI_OK)
1112         return -1;
1113
1114     /* start the thread running */
1115     result = (*(android_thread_func_t)start)(userData);
1116
1117     /* unhook us */
1118     javaDetachThread();
1119     free(name);
1120
1121     return result;
1122 }
1123
1124 /*
1125  * This is invoked from androidCreateThreadEtc() via the callback
1126  * set with androidSetCreateThreadFunc().
1127  *
1128  * We need to create the new thread in such a way that it gets hooked
1129  * into the VM before it really starts executing.
1130  */
1131 /*static*/ int AndroidRuntime::javaCreateThreadEtc(
1132                                 android_thread_func_t entryFunction,
1133                                 void* userData,
1134                                 const char* threadName,
1135                                 int32_t threadPriority,
1136                                 size_t threadStackSize,
1137                                 android_thread_id_t* threadId)
1138 {
1139     void** args = (void**) malloc(3 * sizeof(void*));   // javaThreadShell must free
1140     int result;
1141
1142     if (!threadName)
1143         threadName = "unnamed thread";
1144
1145     args[0] = (void*) entryFunction;
1146     args[1] = userData;
1147     args[2] = (void*) strdup(threadName);   // javaThreadShell must free
1148
1149     result = androidCreateRawThreadEtc(AndroidRuntime::javaThreadShell, args,
1150         threadName, threadPriority, threadStackSize, threadId);
1151     return result;
1152 }
1153
1154 /*
1155  * Create a thread that is visible from the VM.
1156  *
1157  * This is called from elsewhere in the library.
1158  */
1159 /*static*/ android_thread_id_t AndroidRuntime::createJavaThread(const char* name,
1160     void (*start)(void *), void* arg)
1161 {
1162     android_thread_id_t threadId = 0;
1163     javaCreateThreadEtc((android_thread_func_t) start, arg, name,
1164         ANDROID_PRIORITY_DEFAULT, 0, &threadId);
1165     return threadId;
1166 }
1167
1168 #if 0
1169 static void quickTest(void* arg)
1170 {
1171     const char* str = (const char*) arg;
1172
1173     printf("In quickTest: %s\n", str);
1174 }
1175 #endif
1176
1177 #ifdef NDEBUG
1178     #define REG_JNI(name)      { name }
1179     struct RegJNIRec {
1180         int (*mProc)(JNIEnv*);
1181     };
1182 #else
1183     #define REG_JNI(name)      { name, #name }
1184     struct RegJNIRec {
1185         int (*mProc)(JNIEnv*);
1186         const char* mName;
1187     };
1188 #endif
1189
1190 typedef void (*RegJAMProc)();
1191
1192 static int register_jni_procs(const RegJNIRec array[], size_t count, JNIEnv* env)
1193 {
1194     for (size_t i = 0; i < count; i++) {
1195         if (array[i].mProc(env) < 0) {
1196 #ifndef NDEBUG
1197             ALOGD("----------!!! %s failed to load\n", array[i].mName);
1198 #endif
1199             return -1;
1200         }
1201     }
1202     return 0;
1203 }
1204
1205 static void register_jam_procs(const RegJAMProc array[], size_t count)
1206 {
1207     for (size_t i = 0; i < count; i++) {
1208         array[i]();
1209     }
1210 }
1211
1212 static const RegJNIRec gRegJNI[] = {
1213     REG_JNI(register_com_android_internal_os_RuntimeInit),
1214     REG_JNI(register_android_os_SystemClock),
1215     REG_JNI(register_android_util_EventLog),
1216     REG_JNI(register_android_util_Log),
1217     REG_JNI(register_android_util_FloatMath),
1218     REG_JNI(register_android_content_AssetManager),
1219     REG_JNI(register_android_content_StringBlock),
1220     REG_JNI(register_android_content_XmlBlock),
1221     REG_JNI(register_android_emoji_EmojiFactory),
1222     REG_JNI(register_android_text_AndroidCharacter),
1223     REG_JNI(register_android_text_StaticLayout),
1224     REG_JNI(register_android_text_AndroidBidi),
1225     REG_JNI(register_android_view_InputDevice),
1226     REG_JNI(register_android_view_KeyCharacterMap),
1227     REG_JNI(register_android_os_Process),
1228     REG_JNI(register_android_os_SystemProperties),
1229     REG_JNI(register_android_os_Binder),
1230     REG_JNI(register_android_os_Parcel),
1231     REG_JNI(register_android_nio_utils),
1232     REG_JNI(register_android_graphics_Graphics),
1233     REG_JNI(register_android_view_DisplayEventReceiver),
1234     REG_JNI(register_android_view_RenderNode),
1235     REG_JNI(register_android_view_RenderNodeAnimator),
1236     REG_JNI(register_android_view_GraphicBuffer),
1237     REG_JNI(register_android_view_GLES20Canvas),
1238     REG_JNI(register_android_view_HardwareLayer),
1239     REG_JNI(register_android_view_ThreadedRenderer),
1240     REG_JNI(register_android_view_Surface),
1241     REG_JNI(register_android_view_SurfaceControl),
1242     REG_JNI(register_android_view_SurfaceSession),
1243     REG_JNI(register_android_view_TextureView),
1244     REG_JNI(register_com_android_internal_view_animation_NativeInterpolatorFactoryHelper),
1245     REG_JNI(register_com_google_android_gles_jni_EGLImpl),
1246     REG_JNI(register_com_google_android_gles_jni_GLImpl),
1247     REG_JNI(register_android_opengl_jni_EGL14),
1248     REG_JNI(register_android_opengl_jni_EGLExt),
1249     REG_JNI(register_android_opengl_jni_GLES10),
1250     REG_JNI(register_android_opengl_jni_GLES10Ext),
1251     REG_JNI(register_android_opengl_jni_GLES11),
1252     REG_JNI(register_android_opengl_jni_GLES11Ext),
1253     REG_JNI(register_android_opengl_jni_GLES20),
1254     REG_JNI(register_android_opengl_jni_GLES30),
1255     REG_JNI(register_android_opengl_jni_GLES31),
1256     REG_JNI(register_android_opengl_jni_GLES31Ext),
1257
1258     REG_JNI(register_android_graphics_Bitmap),
1259     REG_JNI(register_android_graphics_BitmapFactory),
1260     REG_JNI(register_android_graphics_BitmapRegionDecoder),
1261     REG_JNI(register_android_graphics_Camera),
1262     REG_JNI(register_android_graphics_CreateJavaOutputStreamAdaptor),
1263     REG_JNI(register_android_graphics_Canvas),
1264     REG_JNI(register_android_graphics_CanvasProperty),
1265     REG_JNI(register_android_graphics_ColorFilter),
1266     REG_JNI(register_android_graphics_DrawFilter),
1267     REG_JNI(register_android_graphics_FontFamily),
1268     REG_JNI(register_android_graphics_Interpolator),
1269     REG_JNI(register_android_graphics_LayerRasterizer),
1270     REG_JNI(register_android_graphics_MaskFilter),
1271     REG_JNI(register_android_graphics_Matrix),
1272     REG_JNI(register_android_graphics_Movie),
1273     REG_JNI(register_android_graphics_NinePatch),
1274     REG_JNI(register_android_graphics_Paint),
1275     REG_JNI(register_android_graphics_Path),
1276     REG_JNI(register_android_graphics_PathMeasure),
1277     REG_JNI(register_android_graphics_PathEffect),
1278     REG_JNI(register_android_graphics_Picture),
1279     REG_JNI(register_android_graphics_PorterDuff),
1280     REG_JNI(register_android_graphics_Rasterizer),
1281     REG_JNI(register_android_graphics_Region),
1282     REG_JNI(register_android_graphics_Shader),
1283     REG_JNI(register_android_graphics_SurfaceTexture),
1284     REG_JNI(register_android_graphics_Typeface),
1285     REG_JNI(register_android_graphics_Xfermode),
1286     REG_JNI(register_android_graphics_YuvImage),
1287     REG_JNI(register_android_graphics_pdf_PdfDocument),
1288     REG_JNI(register_android_graphics_pdf_PdfEditor),
1289     REG_JNI(register_android_graphics_pdf_PdfRenderer),
1290
1291     REG_JNI(register_android_database_CursorWindow),
1292     REG_JNI(register_android_database_SQLiteConnection),
1293     REG_JNI(register_android_database_SQLiteGlobal),
1294     REG_JNI(register_android_database_SQLiteDebug),
1295     REG_JNI(register_android_os_Debug),
1296     REG_JNI(register_android_os_FileObserver),
1297     REG_JNI(register_android_os_MessageQueue),
1298     REG_JNI(register_android_os_SELinux),
1299     REG_JNI(register_android_os_Trace),
1300     REG_JNI(register_android_os_UEventObserver),
1301     REG_JNI(register_android_net_LocalSocketImpl),
1302     REG_JNI(register_android_net_NetworkUtils),
1303     REG_JNI(register_android_net_TrafficStats),
1304     REG_JNI(register_android_os_MemoryFile),
1305     REG_JNI(register_com_android_internal_os_ZygoteInit),
1306     REG_JNI(register_com_android_internal_os_Zygote),
1307     REG_JNI(register_com_android_internal_util_VirtualRefBasePtr),
1308     REG_JNI(register_android_hardware_Camera),
1309     REG_JNI(register_android_hardware_camera2_CameraMetadata),
1310     REG_JNI(register_android_hardware_camera2_legacy_LegacyCameraDevice),
1311     REG_JNI(register_android_hardware_camera2_legacy_PerfMeasurement),
1312     REG_JNI(register_android_hardware_camera2_DngCreator),
1313     REG_JNI(register_android_hardware_SensorManager),
1314     REG_JNI(register_android_hardware_SerialPort),
1315     REG_JNI(register_android_hardware_SoundTrigger),
1316     REG_JNI(register_android_hardware_UsbDevice),
1317     REG_JNI(register_android_hardware_UsbDeviceConnection),
1318     REG_JNI(register_android_hardware_UsbRequest),
1319     REG_JNI(register_android_hardware_location_ActivityRecognitionHardware),
1320     REG_JNI(register_android_media_AudioRecord),
1321     REG_JNI(register_android_media_AudioSystem),
1322     REG_JNI(register_android_media_AudioTrack),
1323     REG_JNI(register_android_media_JetPlayer),
1324     REG_JNI(register_android_media_RemoteDisplay),
1325     REG_JNI(register_android_media_ToneGenerator),
1326
1327     REG_JNI(register_android_opengl_classes),
1328     REG_JNI(register_android_server_NetworkManagementSocketTagger),
1329     REG_JNI(register_android_ddm_DdmHandleNativeHeap),
1330     REG_JNI(register_android_backup_BackupDataInput),
1331     REG_JNI(register_android_backup_BackupDataOutput),
1332     REG_JNI(register_android_backup_FileBackupHelperBase),
1333     REG_JNI(register_android_backup_BackupHelperDispatcher),
1334     REG_JNI(register_android_app_backup_FullBackup),
1335     REG_JNI(register_android_app_ActivityThread),
1336     REG_JNI(register_android_app_NativeActivity),
1337     REG_JNI(register_android_view_InputChannel),
1338     REG_JNI(register_android_view_InputEventReceiver),
1339     REG_JNI(register_android_view_InputEventSender),
1340     REG_JNI(register_android_view_InputQueue),
1341     REG_JNI(register_android_view_KeyEvent),
1342     REG_JNI(register_android_view_MotionEvent),
1343     REG_JNI(register_android_view_PointerIcon),
1344     REG_JNI(register_android_view_VelocityTracker),
1345
1346     REG_JNI(register_android_content_res_ObbScanner),
1347     REG_JNI(register_android_content_res_Configuration),
1348
1349     REG_JNI(register_android_animation_PropertyValuesHolder),
1350     REG_JNI(register_com_android_internal_content_NativeLibraryHelper),
1351     REG_JNI(register_com_android_internal_net_NetworkStatsFactory),
1352 };
1353
1354 /*
1355  * Register android native functions with the VM.
1356  */
1357 /*static*/ int AndroidRuntime::startReg(JNIEnv* env)
1358 {
1359     /*
1360      * This hook causes all future threads created in this process to be
1361      * attached to the JavaVM.  (This needs to go away in favor of JNI
1362      * Attach calls.)
1363      */
1364     androidSetCreateThreadFunc((android_create_thread_fn) javaCreateThreadEtc);
1365
1366     ALOGV("--- registering native functions ---\n");
1367
1368     /*
1369      * Every "register" function calls one or more things that return
1370      * a local reference (e.g. FindClass).  Because we haven't really
1371      * started the VM yet, they're all getting stored in the base frame
1372      * and never released.  Use Push/Pop to manage the storage.
1373      */
1374     env->PushLocalFrame(200);
1375
1376     if (register_jni_procs(gRegJNI, NELEM(gRegJNI), env) < 0) {
1377         env->PopLocalFrame(NULL);
1378         return -1;
1379     }
1380     env->PopLocalFrame(NULL);
1381
1382     //createJavaThread("fubar", quickTest, (void*) "hello");
1383
1384     return 0;
1385 }
1386
1387 AndroidRuntime* AndroidRuntime::getRuntime()
1388 {
1389     return gCurRuntime;
1390 }
1391
1392 /**
1393  * Used by WithFramework to register native functions.
1394  */
1395 extern "C"
1396 jint Java_com_android_internal_util_WithFramework_registerNatives(
1397         JNIEnv* env, jclass clazz) {
1398     return register_jni_procs(gRegJNI, NELEM(gRegJNI), env);
1399 }
1400
1401 /**
1402  * Used by LoadClass to register native functions.
1403  */
1404 extern "C"
1405 jint Java_LoadClass_registerNatives(JNIEnv* env, jclass clazz) {
1406     return register_jni_procs(gRegJNI, NELEM(gRegJNI), env);
1407 }
1408
1409 }   // namespace android