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