OSDN Git Service

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