OSDN Git Service

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