diff options
Diffstat (limited to 'core/jni')
155 files changed, 2318 insertions, 3452 deletions
diff --git a/core/jni/Android.mk b/core/jni/Android.mk index dbaa4b8..d070c97 100644 --- a/core/jni/Android.mk +++ b/core/jni/Android.mk @@ -1,5 +1,6 @@ LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) +LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk LOCAL_CFLAGS += -DHAVE_CONFIG_H -DKHTML_NO_EXCEPTIONS -DGKWQ_NO_JAVA LOCAL_CFLAGS += -DNO_SUPPORT_JS_BINDING -DQT_NO_WHEELEVENT -DKHTML_NO_XBL @@ -10,262 +11,259 @@ LOCAL_CFLAGS += -Wno-maybe-uninitialized -Wno-parentheses LOCAL_CPPFLAGS += -Wno-conversion-null ifeq ($(TARGET_ARCH), arm) - LOCAL_CFLAGS += -DPACKED="__attribute__ ((packed))" + LOCAL_CFLAGS += -DPACKED="__attribute__ ((packed))" else - LOCAL_CFLAGS += -DPACKED="" + LOCAL_CFLAGS += -DPACKED="" endif ifeq ($(USE_OPENGL_RENDERER),true) - LOCAL_CFLAGS += -DUSE_OPENGL_RENDERER + LOCAL_CFLAGS += -DUSE_OPENGL_RENDERER endif LOCAL_CFLAGS += -DGL_GLEXT_PROTOTYPES -DEGL_EGLEXT_PROTOTYPES LOCAL_SRC_FILES:= \ - AndroidRuntime.cpp \ - com_android_internal_content_NativeLibraryHelper.cpp \ - com_google_android_gles_jni_EGLImpl.cpp \ - com_google_android_gles_jni_GLImpl.cpp.arm \ - android_app_NativeActivity.cpp \ - android_opengl_EGL14.cpp \ - android_opengl_EGLExt.cpp \ - android_opengl_GLES10.cpp \ - android_opengl_GLES10Ext.cpp \ - android_opengl_GLES11.cpp \ - android_opengl_GLES11Ext.cpp \ - android_opengl_GLES20.cpp \ - android_opengl_GLES30.cpp \ - android_opengl_GLES31.cpp \ - android_opengl_GLES31Ext.cpp \ - android_database_CursorWindow.cpp \ - android_database_SQLiteCommon.cpp \ - android_database_SQLiteConnection.cpp \ - android_database_SQLiteGlobal.cpp \ - android_database_SQLiteDebug.cpp \ - android_emoji_EmojiFactory.cpp \ - android_view_DisplayEventReceiver.cpp \ - android_view_Surface.cpp \ - android_view_SurfaceControl.cpp \ - android_view_SurfaceSession.cpp \ - android_view_TextureView.cpp \ - android_view_InputChannel.cpp \ - android_view_InputDevice.cpp \ - android_view_InputEventReceiver.cpp \ - android_view_InputEventSender.cpp \ - android_view_InputQueue.cpp \ - android_view_KeyEvent.cpp \ - android_view_KeyCharacterMap.cpp \ - android_view_GraphicBuffer.cpp \ - android_view_GLES20Canvas.cpp \ - android_view_HardwareLayer.cpp \ - android_view_ThreadedRenderer.cpp \ - android_view_MotionEvent.cpp \ - android_view_PointerIcon.cpp \ - android_view_RenderNode.cpp \ - android_view_RenderNodeAnimator.cpp \ - android_view_VelocityTracker.cpp \ - android_text_AndroidCharacter.cpp \ - android_text_AndroidBidi.cpp \ - android_text_StaticLayout.cpp \ - android_os_Debug.cpp \ - android_os_MemoryFile.cpp \ - android_os_MessageQueue.cpp \ - android_os_Parcel.cpp \ - android_os_SELinux.cpp \ - android_os_SystemClock.cpp \ - android_os_SystemProperties.cpp \ - android_os_Trace.cpp \ - android_os_UEventObserver.cpp \ - android_net_LocalSocketImpl.cpp \ - android_net_NetUtils.cpp \ - android_net_TrafficStats.cpp \ - android_nio_utils.cpp \ - android_util_AssetManager.cpp \ - android_util_Binder.cpp \ - android_util_EventLog.cpp \ - android_util_Log.cpp \ - android_util_FloatMath.cpp \ - android_util_Process.cpp \ - android_util_StringBlock.cpp \ - android_util_XmlBlock.cpp \ - android_graphics_Canvas.cpp \ - android_graphics_Picture.cpp \ - android/graphics/AutoDecodeCancel.cpp \ - android/graphics/Bitmap.cpp \ - android/graphics/BitmapFactory.cpp \ - android/graphics/Camera.cpp \ - android/graphics/CanvasProperty.cpp \ - android/graphics/ColorFilter.cpp \ - android/graphics/DrawFilter.cpp \ - android/graphics/FontFamily.cpp \ - android/graphics/CreateJavaOutputStreamAdaptor.cpp \ - android/graphics/Graphics.cpp \ - android/graphics/HarfBuzzNGFaceSkia.cpp \ - android/graphics/Interpolator.cpp \ - android/graphics/MaskFilter.cpp \ - android/graphics/Matrix.cpp \ - android/graphics/MinikinSkia.cpp \ - android/graphics/MinikinUtils.cpp \ - android/graphics/Movie.cpp \ - android/graphics/NinePatch.cpp \ - android/graphics/NinePatchImpl.cpp \ - android/graphics/NinePatchPeeker.cpp \ - android/graphics/Paint.cpp \ - android/graphics/PaintImpl.cpp \ - android/graphics/Path.cpp \ - android/graphics/PathMeasure.cpp \ - android/graphics/PathEffect.cpp \ - android/graphics/Picture.cpp \ - android/graphics/PorterDuff.cpp \ - android/graphics/BitmapRegionDecoder.cpp \ - android/graphics/Rasterizer.cpp \ - android/graphics/Region.cpp \ - android/graphics/Shader.cpp \ - android/graphics/SkiaCanvas.cpp \ - android/graphics/SurfaceTexture.cpp \ - android/graphics/Typeface.cpp \ - android/graphics/TypefaceImpl.cpp \ - android/graphics/Utils.cpp \ - android/graphics/Xfermode.cpp \ - android/graphics/YuvToJpegEncoder.cpp \ - android/graphics/pdf/PdfDocument.cpp \ - android/graphics/pdf/PdfEditor.cpp \ - android/graphics/pdf/PdfRenderer.cpp \ - android_media_AudioRecord.cpp \ - android_media_AudioSystem.cpp \ - android_media_AudioTrack.cpp \ - android_media_JetPlayer.cpp \ - android_media_RemoteDisplay.cpp \ - android_media_ToneGenerator.cpp \ - android_hardware_Camera.cpp \ - android_hardware_camera2_CameraMetadata.cpp \ - android_hardware_camera2_legacy_LegacyCameraDevice.cpp \ - android_hardware_camera2_legacy_PerfMeasurement.cpp \ - android_hardware_camera2_DngCreator.cpp \ - android_hardware_SensorManager.cpp \ - android_hardware_SerialPort.cpp \ - android_hardware_SoundTrigger.cpp \ - android_hardware_UsbDevice.cpp \ - android_hardware_UsbDeviceConnection.cpp \ - android_hardware_UsbRequest.cpp \ - android_hardware_location_ActivityRecognitionHardware.cpp \ - android_util_FileObserver.cpp \ - android/opengl/poly_clip.cpp.arm \ - android/opengl/util.cpp.arm \ - android_server_FingerprintManager.cpp \ - android_server_NetworkManagementSocketTagger.cpp \ - android_server_Watchdog.cpp \ - android_ddm_DdmHandleNativeHeap.cpp \ - com_android_internal_os_ZygoteInit.cpp \ - android_backup_BackupDataInput.cpp \ - android_backup_BackupDataOutput.cpp \ - android_backup_FileBackupHelperBase.cpp \ - android_backup_BackupHelperDispatcher.cpp \ - android_app_backup_FullBackup.cpp \ - android_content_res_ObbScanner.cpp \ - android_content_res_Configuration.cpp \ - android_animation_PropertyValuesHolder.cpp \ - com_android_internal_net_NetworkStatsFactory.cpp \ - com_android_internal_os_Zygote.cpp \ - com_android_internal_util_VirtualRefBasePtr.cpp \ - com_android_internal_view_animation_NativeInterpolatorFactoryHelper.cpp + AndroidRuntime.cpp \ + com_android_internal_content_NativeLibraryHelper.cpp \ + com_google_android_gles_jni_EGLImpl.cpp \ + com_google_android_gles_jni_GLImpl.cpp.arm \ + android_app_NativeActivity.cpp \ + android_opengl_EGL14.cpp \ + android_opengl_EGLExt.cpp \ + android_opengl_GLES10.cpp \ + android_opengl_GLES10Ext.cpp \ + android_opengl_GLES11.cpp \ + android_opengl_GLES11Ext.cpp \ + android_opengl_GLES20.cpp \ + android_opengl_GLES30.cpp \ + android_opengl_GLES31.cpp \ + android_opengl_GLES31Ext.cpp \ + android_database_CursorWindow.cpp \ + android_database_SQLiteCommon.cpp \ + android_database_SQLiteConnection.cpp \ + android_database_SQLiteGlobal.cpp \ + android_database_SQLiteDebug.cpp \ + android_emoji_EmojiFactory.cpp \ + android_view_DisplayEventReceiver.cpp \ + android_view_Surface.cpp \ + android_view_SurfaceControl.cpp \ + android_view_SurfaceSession.cpp \ + android_view_TextureView.cpp \ + android_view_InputChannel.cpp \ + android_view_InputDevice.cpp \ + android_view_InputEventReceiver.cpp \ + android_view_InputEventSender.cpp \ + android_view_InputQueue.cpp \ + android_view_KeyEvent.cpp \ + android_view_KeyCharacterMap.cpp \ + android_view_GraphicBuffer.cpp \ + android_view_GLES20Canvas.cpp \ + android_view_HardwareLayer.cpp \ + android_view_ThreadedRenderer.cpp \ + android_view_MotionEvent.cpp \ + android_view_PointerIcon.cpp \ + android_view_RenderNode.cpp \ + android_view_RenderNodeAnimator.cpp \ + android_view_VelocityTracker.cpp \ + android_text_AndroidCharacter.cpp \ + android_text_AndroidBidi.cpp \ + android_text_StaticLayout.cpp \ + android_os_Debug.cpp \ + android_os_MemoryFile.cpp \ + android_os_MessageQueue.cpp \ + android_os_Parcel.cpp \ + android_os_SELinux.cpp \ + android_os_SystemClock.cpp \ + android_os_SystemProperties.cpp \ + android_os_Trace.cpp \ + android_os_UEventObserver.cpp \ + android_net_LocalSocketImpl.cpp \ + android_net_NetUtils.cpp \ + android_net_TrafficStats.cpp \ + android_nio_utils.cpp \ + android_util_AssetManager.cpp \ + android_util_Binder.cpp \ + android_util_EventLog.cpp \ + android_util_Log.cpp \ + android_util_Process.cpp \ + android_util_StringBlock.cpp \ + android_util_XmlBlock.cpp \ + android_graphics_Canvas.cpp \ + android_graphics_Picture.cpp \ + android/graphics/AutoDecodeCancel.cpp \ + android/graphics/Bitmap.cpp \ + android/graphics/BitmapFactory.cpp \ + android/graphics/Camera.cpp \ + android/graphics/CanvasProperty.cpp \ + android/graphics/ColorFilter.cpp \ + android/graphics/DrawFilter.cpp \ + android/graphics/FontFamily.cpp \ + android/graphics/CreateJavaOutputStreamAdaptor.cpp \ + android/graphics/Graphics.cpp \ + android/graphics/HarfBuzzNGFaceSkia.cpp \ + android/graphics/Interpolator.cpp \ + android/graphics/MaskFilter.cpp \ + android/graphics/Matrix.cpp \ + android/graphics/MinikinSkia.cpp \ + android/graphics/MinikinUtils.cpp \ + android/graphics/Movie.cpp \ + android/graphics/NinePatch.cpp \ + android/graphics/NinePatchImpl.cpp \ + android/graphics/NinePatchPeeker.cpp \ + android/graphics/Paint.cpp \ + android/graphics/PaintImpl.cpp \ + android/graphics/Path.cpp \ + android/graphics/PathMeasure.cpp \ + android/graphics/PathEffect.cpp \ + android/graphics/Picture.cpp \ + android/graphics/PorterDuff.cpp \ + android/graphics/BitmapRegionDecoder.cpp \ + android/graphics/Rasterizer.cpp \ + android/graphics/Region.cpp \ + android/graphics/Shader.cpp \ + android/graphics/SkiaCanvas.cpp \ + android/graphics/SurfaceTexture.cpp \ + android/graphics/Typeface.cpp \ + android/graphics/TypefaceImpl.cpp \ + android/graphics/Utils.cpp \ + android/graphics/Xfermode.cpp \ + android/graphics/YuvToJpegEncoder.cpp \ + android/graphics/pdf/PdfDocument.cpp \ + android/graphics/pdf/PdfEditor.cpp \ + android/graphics/pdf/PdfRenderer.cpp \ + android_media_AudioRecord.cpp \ + android_media_AudioSystem.cpp \ + android_media_AudioTrack.cpp \ + android_media_JetPlayer.cpp \ + android_media_RemoteDisplay.cpp \ + android_media_ToneGenerator.cpp \ + android_hardware_Camera.cpp \ + android_hardware_camera2_CameraMetadata.cpp \ + android_hardware_camera2_legacy_LegacyCameraDevice.cpp \ + android_hardware_camera2_legacy_PerfMeasurement.cpp \ + android_hardware_camera2_DngCreator.cpp \ + android_hardware_SensorManager.cpp \ + android_hardware_SerialPort.cpp \ + android_hardware_SoundTrigger.cpp \ + android_hardware_UsbDevice.cpp \ + android_hardware_UsbDeviceConnection.cpp \ + android_hardware_UsbRequest.cpp \ + android_hardware_location_ActivityRecognitionHardware.cpp \ + android_util_FileObserver.cpp \ + android/opengl/poly_clip.cpp.arm \ + android/opengl/util.cpp.arm \ + android_server_FingerprintManager.cpp \ + android_server_NetworkManagementSocketTagger.cpp \ + android_server_Watchdog.cpp \ + android_ddm_DdmHandleNativeHeap.cpp \ + android_backup_BackupDataInput.cpp \ + android_backup_BackupDataOutput.cpp \ + android_backup_FileBackupHelperBase.cpp \ + android_backup_BackupHelperDispatcher.cpp \ + android_app_backup_FullBackup.cpp \ + android_content_res_ObbScanner.cpp \ + android_content_res_Configuration.cpp \ + android_animation_PropertyValuesHolder.cpp \ + com_android_internal_net_NetworkStatsFactory.cpp \ + com_android_internal_os_Zygote.cpp \ + com_android_internal_util_VirtualRefBasePtr.cpp \ + com_android_internal_view_animation_NativeInterpolatorFactoryHelper.cpp LOCAL_C_INCLUDES += \ - $(JNI_H_INCLUDE) \ - $(LOCAL_PATH)/android/graphics \ - $(LOCAL_PATH)/../../libs/hwui \ - $(LOCAL_PATH)/../../../native/opengl/libs \ - $(call include-path-for, bluedroid) \ - $(call include-path-for, libhardware)/hardware \ - $(call include-path-for, libhardware_legacy)/hardware_legacy \ - $(TOP)/bionic/libc/dns/include \ - $(TOP)/frameworks/av/include \ - $(TOP)/system/media/camera/include \ - $(TOP)/system/netd/include \ - external/icu/icu4c/source/common \ - external/pdfium/core/include/fpdfapi \ - external/pdfium/core/include/fpdfdoc \ - external/pdfium/fpdfsdk/include \ - external/skia/src/core \ - external/skia/src/effects \ - external/skia/src/images \ - external/sqlite/dist \ - external/sqlite/android \ - external/expat/lib \ - external/openssl/include \ - external/tremor/Tremor \ - external/jpeg \ - external/harfbuzz_ng/src \ - external/zlib \ - frameworks/opt/emoji \ - libcore/include \ - $(call include-path-for, audio-utils) \ - frameworks/minikin/include \ - external/freetype/include + $(JNI_H_INCLUDE) \ + $(LOCAL_PATH)/android/graphics \ + $(LOCAL_PATH)/../../libs/hwui \ + $(LOCAL_PATH)/../../../native/opengl/libs \ + $(call include-path-for, bluedroid) \ + $(call include-path-for, libhardware)/hardware \ + $(call include-path-for, libhardware_legacy)/hardware_legacy \ + $(TOP)/frameworks/av/include \ + $(TOP)/system/media/camera/include \ + $(TOP)/system/netd/include \ + external/pdfium/core/include/fpdfapi \ + external/pdfium/core/include/fpdfdoc \ + external/pdfium/fpdfsdk/include \ + external/skia/src/core \ + external/skia/src/effects \ + external/skia/src/images \ + external/sqlite/dist \ + external/sqlite/android \ + external/expat/lib \ + external/tremor/Tremor \ + external/jpeg \ + external/harfbuzz_ng/src \ + frameworks/opt/emoji \ + libcore/include \ + $(call include-path-for, audio-utils) \ + frameworks/minikin/include \ + external/freetype/include # TODO: clean up Minikin so it doesn't need the freetype include LOCAL_SHARED_LIBRARIES := \ - libmemtrack \ - libandroidfw \ - libexpat \ - libnativehelper \ - liblog \ - libcutils \ - libutils \ - libbinder \ - libnetutils \ - libui \ - libgui \ - libinput \ - libinputflinger \ - libcamera_client \ - libcamera_metadata \ - libskia \ - libsqlite \ - libEGL \ - libGLESv1_CM \ - libGLESv2 \ - libETC1 \ - libhardware \ - libhardware_legacy \ - libselinux \ - libsonivox \ - libcrypto \ - libssl \ - libicuuc \ - libicui18n \ - libmedia \ - libjpeg \ - libusbhost \ - libharfbuzz_ng \ - libz \ - libaudioutils \ - libpdfium \ - libimg_utils \ - libnetd_client \ - libsoundtrigger \ - libminikin \ - libstlport \ - libprocessgroup \ - libnativebridge \ + libmemtrack \ + libandroidfw \ + libexpat \ + libnativehelper \ + liblog \ + libcutils \ + libutils \ + libbinder \ + libnetutils \ + libui \ + libgui \ + libinput \ + libinputflinger \ + libcamera_client \ + libcamera_metadata \ + libskia \ + libsqlite \ + libEGL \ + libGLESv1_CM \ + libGLESv2 \ + libETC1 \ + libhardware \ + libhardware_legacy \ + libselinux \ + libsonivox \ + libcrypto \ + libssl \ + libicuuc \ + libicui18n \ + libmedia \ + libjpeg \ + libusbhost \ + libharfbuzz_ng \ + libz \ + libaudioutils \ + libpdfium \ + libimg_utils \ + libnetd_client \ + libsoundtrigger \ + libminikin \ + libprocessgroup \ + libnativebridge ifeq ($(USE_OPENGL_RENDERER),true) - LOCAL_SHARED_LIBRARIES += libhwui + LOCAL_SHARED_LIBRARIES += libhwui endif LOCAL_SHARED_LIBRARIES += \ - libdl + libdl + # we need to access the private Bionic header # <bionic_tls.h> in com_google_android_gles_jni_GLImpl.cpp -LOCAL_CFLAGS += -I$(LOCAL_PATH)/../../../../bionic/libc/private - -ifeq ($(WITH_MALLOC_LEAK_CHECK),true) - LOCAL_CFLAGS += -DMALLOC_LEAK_CHECK -endif +LOCAL_C_INCLUDES += bionic/libc/private LOCAL_MODULE:= libandroid_runtime -include external/stlport/libstlport.mk +# -Wno-unknown-pragmas: necessary for Clang as the GL bindings need to turn +# off a GCC warning that Clang doesn't know. +LOCAL_CFLAGS += -Wall -Werror -Wunused -Wunreachable-code -Wno-unknown-pragmas + +# -Wno-c++11-extensions: Clang warns about Skia using the C++11 override keyword, but this project +# is not being compiled with that level. Remove once this has changed. +LOCAL_CFLAGS += -Wno-c++11-extensions + include $(BUILD_SHARED_LIBRARY) include $(call all-makefiles-under,$(LOCAL_PATH)) diff --git a/core/jni/AndroidRuntime.cpp b/core/jni/AndroidRuntime.cpp index 1fbd4a1..f94341a 100644 --- a/core/jni/AndroidRuntime.cpp +++ b/core/jni/AndroidRuntime.cpp @@ -95,8 +95,6 @@ extern int register_android_media_AudioTrack(JNIEnv *env); extern int register_android_media_JetPlayer(JNIEnv *env); extern int register_android_media_ToneGenerator(JNIEnv *env); -extern int register_android_util_FloatMath(JNIEnv* env); - namespace android { /* @@ -164,7 +162,6 @@ extern int register_android_text_AndroidBidi(JNIEnv *env); extern int register_android_opengl_classes(JNIEnv *env); extern int register_android_ddm_DdmHandleNativeHeap(JNIEnv *env); extern int register_android_server_NetworkManagementSocketTagger(JNIEnv* env); -extern int register_com_android_internal_os_ZygoteInit(JNIEnv* env); extern int register_android_backup_BackupDataInput(JNIEnv *env); extern int register_android_backup_BackupDataOutput(JNIEnv *env); extern int register_android_backup_FileBackupHelperBase(JNIEnv *env); @@ -193,12 +190,6 @@ extern int register_com_android_internal_util_VirtualRefBasePtr(JNIEnv *env); static AndroidRuntime* gCurRuntime = NULL; -static void doThrow(JNIEnv* env, const char* exc, const char* msg = NULL) -{ - if (jniThrowException(env, exc, msg) != 0) - assert(false); -} - /* * Code written in the Java Programming Language calls here from main(). */ @@ -366,22 +357,37 @@ static bool hasFile(const char* file) { } /* - * Read the persistent locale. + * Read the persistent locale. Attempts to read to persist.sys.locale + * and falls back to the default locale (ro.product.locale) if + * persist.sys.locale is empty. */ -static void readLocale(char* language, char* region) +static void readLocale(char* locale) { - char propLang[PROPERTY_VALUE_MAX], propRegn[PROPERTY_VALUE_MAX]; - - property_get("persist.sys.language", propLang, ""); - property_get("persist.sys.country", propRegn, ""); - if (*propLang == 0 && *propRegn == 0) { - /* Set to ro properties, default is en_US */ - property_get("ro.product.locale.language", propLang, "en"); - property_get("ro.product.locale.region", propRegn, "US"); + // Allocate 4 extra bytes because we might read a property into + // this array at offset 4. + char propLocale[PROPERTY_VALUE_MAX + 4]; + + property_get("persist.sys.locale", propLocale, ""); + if (propLocale[0] == 0) { + property_get("ro.product.locale", propLocale, ""); + + if (propLocale[0] == 0) { + // If persist.sys.locale and ro.product.locale are missing, + // construct a locale value from the individual locale components. + property_get("ro.product.locale.language", propLocale, "en"); + + // The language code is either two or three chars in length. If it + // isn't 2 chars long, assume three. Anything else is an error + // anyway. + const int offset = (propLocale[2] == 0) ? 2 : 3; + propLocale[offset] = '-'; + + property_get("ro.product.locale.region", propLocale + offset + 1, "US"); + } } - strncat(language, propLang, 3); - strncat(region, propRegn, 3); - //ALOGD("language=%s region=%s\n", language, region); + + strncat(locale, propLocale, PROPERTY_VALUE_MAX); + // ALOGD("[DEBUG] locale=%s", locale); } void AndroidRuntime::addOption(const char* optionString, void* extraInfo) @@ -534,8 +540,6 @@ int AndroidRuntime::startVm(JavaVM** pJavaVM, JNIEnv** pEnv) JavaVMInitArgs initArgs; char propBuf[PROPERTY_VALUE_MAX]; char stackTraceFileBuf[sizeof("-Xstacktracefile:")-1 + PROPERTY_VALUE_MAX]; - char dexoptFlagsBuf[PROPERTY_VALUE_MAX]; - char enableAssertBuf[sizeof("-ea:")-1 + PROPERTY_VALUE_MAX]; char jniOptsBuf[sizeof("-Xjniopts:")-1 + PROPERTY_VALUE_MAX]; char heapstartsizeOptsBuf[sizeof("-Xms")-1 + PROPERTY_VALUE_MAX]; char heapsizeOptsBuf[sizeof("-Xmx")-1 + PROPERTY_VALUE_MAX]; @@ -545,8 +549,6 @@ int AndroidRuntime::startVm(JavaVM** pJavaVM, JNIEnv** pEnv) char gctypeOptsBuf[sizeof("-Xgc:")-1 + PROPERTY_VALUE_MAX]; char backgroundgcOptsBuf[sizeof("-XX:BackgroundGC=")-1 + PROPERTY_VALUE_MAX]; char heaptargetutilizationOptsBuf[sizeof("-XX:HeapTargetUtilization=")-1 + PROPERTY_VALUE_MAX]; - char jitcodecachesizeOptsBuf[sizeof("-Xjitcodecachesize:")-1 + PROPERTY_VALUE_MAX]; - char dalvikVmLibBuf[PROPERTY_VALUE_MAX]; char dex2oatXmsImageFlagsBuf[sizeof("-Xms")-1 + PROPERTY_VALUE_MAX]; char dex2oatXmxImageFlagsBuf[sizeof("-Xmx")-1 + PROPERTY_VALUE_MAX]; char dex2oatXmsFlagsBuf[sizeof("-Xms")-1 + PROPERTY_VALUE_MAX]; @@ -572,11 +574,8 @@ int AndroidRuntime::startVm(JavaVM** pJavaVM, JNIEnv** pEnv) PROPERTY_VALUE_MAX]; char profileType[sizeof("-Xprofile-type:")-1 + PROPERTY_VALUE_MAX]; char profileMaxStackDepth[sizeof("-Xprofile-max-stack-depth:")-1 + PROPERTY_VALUE_MAX]; - char langOption[sizeof("-Duser.language=") + 3]; - char regionOption[sizeof("-Duser.region=") + 3]; + char localeOption[sizeof("-Duser.locale=") + PROPERTY_VALUE_MAX]; char lockProfThresholdBuf[sizeof("-Xlockprofthreshold:")-1 + PROPERTY_VALUE_MAX]; - char jitOpBuf[sizeof("-Xjitop:")-1 + PROPERTY_VALUE_MAX]; - char jitMethodBuf[sizeof("-Xjitmethod:")-1 + PROPERTY_VALUE_MAX]; char nativeBridgeLibrary[sizeof("-XX:NativeBridge=") + PROPERTY_VALUE_MAX]; bool checkJni = false; @@ -595,9 +594,6 @@ int AndroidRuntime::startVm(JavaVM** pJavaVM, JNIEnv** pEnv) /* extended JNI checking */ addOption("-Xcheck:jni"); - /* set a cap on JNI global references */ - addOption("-Xjnigreflimit:2000"); - /* with -Xcheck:jni, this provides a JNI function call trace */ //addOption("-verbose:jni"); } @@ -613,30 +609,6 @@ int AndroidRuntime::startVm(JavaVM** pJavaVM, JNIEnv** pEnv) parseRuntimeOption("dalvik.vm.stack-trace-file", stackTraceFileBuf, "-Xstacktracefile:"); - property_get("dalvik.vm.check-dex-sum", propBuf, ""); - if (strcmp(propBuf, "true") == 0) { - /* perform additional DEX checksum tests */ - addOption("-Xcheckdexsum"); - } - - property_get("log.redirect-stdio", propBuf, ""); - if (strcmp(propBuf, "true") == 0) { - /* convert stdout/stderr to log messages */ - addOption("-Xlog-stdio"); - } - - strcpy(enableAssertBuf, "-ea:"); - property_get("dalvik.vm.enableassertions", enableAssertBuf+sizeof("-ea:")-1, ""); - if (enableAssertBuf[sizeof("-ea:")-1] != '\0') { - /* accept "all" to mean "all classes and packages" */ - if (strcmp(enableAssertBuf+sizeof("-ea:")-1, "all") == 0) - enableAssertBuf[3] = '\0'; // truncate to "-ea" - ALOGI("Assertions enabled: '%s'\n", enableAssertBuf); - addOption(enableAssertBuf); - } else { - ALOGV("Assertions disabled\n"); - } - strcpy(jniOptsBuf, "-Xjniopts:"); if (parseRuntimeOption("dalvik.vm.jniopts", jniOptsBuf, "-Xjniopts:")) { ALOGI("JNI options: '%s'\n", jniOptsBuf); @@ -663,14 +635,6 @@ int AndroidRuntime::startVm(JavaVM** pJavaVM, JNIEnv** pEnv) parseRuntimeOption("dalvik.vm.heapstartsize", heapstartsizeOptsBuf, "-Xms", "4m"); parseRuntimeOption("dalvik.vm.heapsize", heapsizeOptsBuf, "-Xmx", "16m"); - // Increase the main thread's interpreter stack size for bug 6315322. - addOption("-XX:mainThreadStackSize=24K"); - - // Set the max jit code cache size. Note: size of 0 will disable the JIT. - parseRuntimeOption("dalvik.vm.jit.codecachesize", - jitcodecachesizeOptsBuf, - "-Xjitcodecachesize:"); - parseRuntimeOption("dalvik.vm.heapgrowthlimit", heapgrowthlimitOptsBuf, "-XX:HeapGrowthLimit="); parseRuntimeOption("dalvik.vm.heapminfree", heapminfreeOptsBuf, "-XX:HeapMinFree="); parseRuntimeOption("dalvik.vm.heapmaxfree", heapmaxfreeOptsBuf, "-XX:HeapMaxFree="); @@ -686,53 +650,6 @@ int AndroidRuntime::startVm(JavaVM** pJavaVM, JNIEnv** pEnv) parseRuntimeOption("dalvik.vm.gctype", gctypeOptsBuf, "-Xgc:"); parseRuntimeOption("dalvik.vm.backgroundgctype", backgroundgcOptsBuf, "-XX:BackgroundGC="); - /* - * Enable or disable dexopt features, such as bytecode verification and - * calculation of register maps for precise GC. - */ - property_get("dalvik.vm.dexopt-flags", dexoptFlagsBuf, ""); - if (dexoptFlagsBuf[0] != '\0') { - const char* opc; - const char* val; - - opc = strstr(dexoptFlagsBuf, "v="); /* verification */ - if (opc != NULL) { - switch (*(opc+2)) { - case 'n': val = "-Xverify:none"; break; - case 'r': val = "-Xverify:remote"; break; - case 'a': val = "-Xverify:all"; break; - default: val = NULL; break; - } - - if (val != NULL) { - addOption(val); - } - } - - opc = strstr(dexoptFlagsBuf, "o="); /* optimization */ - if (opc != NULL) { - switch (*(opc+2)) { - case 'n': val = "-Xdexopt:none"; break; - case 'v': val = "-Xdexopt:verified"; break; - case 'a': val = "-Xdexopt:all"; break; - case 'f': val = "-Xdexopt:full"; break; - default: val = NULL; break; - } - - if (val != NULL) { - addOption(val); - } - } - - opc = strstr(dexoptFlagsBuf, "m=y"); /* register map */ - if (opc != NULL) { - addOption("-Xgenregmap"); - - /* turn on precise GC while we're at it */ - addOption("-Xgc:precise"); - } - } - /* enable debugging; set suspend=y to pause during VM init */ /* use android ADB transport */ addOption("-agentlib:jdwp=transport=dt_android_adb,suspend=n,server=y"); @@ -741,12 +658,6 @@ int AndroidRuntime::startVm(JavaVM** pJavaVM, JNIEnv** pEnv) lockProfThresholdBuf, "-Xlockprofthreshold:"); - /* Force interpreter-only mode for selected opcodes. Eg "1-0a,3c,f1-ff" */ - parseRuntimeOption("dalvik.vm.jit.op", jitOpBuf, "-Xjitop:"); - - /* Force interpreter-only mode for selected methods */ - parseRuntimeOption("dalvik.vm.jit.method", jitMethodBuf, "-Xjitmethod:"); - if (executionMode == kEMIntPortable) { addOption("-Xint:portable"); } else if (executionMode == kEMIntFast) { @@ -755,63 +666,64 @@ int AndroidRuntime::startVm(JavaVM** pJavaVM, JNIEnv** pEnv) addOption("-Xint:jit"); } - // libart tolerates libdvm flags, but not vice versa, so only pass some options if libart. - property_get("persist.sys.dalvik.vm.lib.2", dalvikVmLibBuf, "libart.so"); - bool libart = (strncmp(dalvikVmLibBuf, "libart", 6) == 0); - - if (libart) { - // If we booting without the real /data, don't spend time compiling. - property_get("vold.decrypt", voldDecryptBuf, ""); - bool skip_compilation = ((strcmp(voldDecryptBuf, "trigger_restart_min_framework") == 0) || - (strcmp(voldDecryptBuf, "1") == 0)); - - // Extra options for boot.art/boot.oat image generation. - parseCompilerRuntimeOption("dalvik.vm.image-dex2oat-Xms", dex2oatXmsImageFlagsBuf, - "-Xms", "-Ximage-compiler-option"); - parseCompilerRuntimeOption("dalvik.vm.image-dex2oat-Xmx", dex2oatXmxImageFlagsBuf, - "-Xmx", "-Ximage-compiler-option"); - if (skip_compilation) { - addOption("-Ximage-compiler-option"); - addOption("--compiler-filter=verify-none"); - } else { - parseCompilerOption("dalvik.vm.image-dex2oat-filter", dex2oatImageCompilerFilterBuf, - "--compiler-filter=", "-Ximage-compiler-option"); - } - - // Make sure there is a preloaded-classes file. - if (!hasFile("/system/etc/preloaded-classes")) { - ALOGE("Missing preloaded-classes file, /system/etc/preloaded-classes not found: %s\n", - strerror(errno)); - goto bail; - } + // If we are booting without the real /data, don't spend time compiling. + property_get("vold.decrypt", voldDecryptBuf, ""); + bool skip_compilation = ((strcmp(voldDecryptBuf, "trigger_restart_min_framework") == 0) || + (strcmp(voldDecryptBuf, "1") == 0)); + + // Extra options for boot.art/boot.oat image generation. + parseCompilerRuntimeOption("dalvik.vm.image-dex2oat-Xms", dex2oatXmsImageFlagsBuf, + "-Xms", "-Ximage-compiler-option"); + parseCompilerRuntimeOption("dalvik.vm.image-dex2oat-Xmx", dex2oatXmxImageFlagsBuf, + "-Xmx", "-Ximage-compiler-option"); + if (skip_compilation) { addOption("-Ximage-compiler-option"); - addOption("--image-classes=/system/etc/preloaded-classes"); + addOption("--compiler-filter=verify-none"); + } else { + parseCompilerOption("dalvik.vm.image-dex2oat-filter", dex2oatImageCompilerFilterBuf, + "--compiler-filter=", "-Ximage-compiler-option"); + } - // If there is a compiled-classes file, push it. - if (hasFile("/system/etc/compiled-classes")) { - addOption("-Ximage-compiler-option"); - addOption("--compiled-classes=/system/etc/compiled-classes"); - } + // Make sure there is a preloaded-classes file. + if (!hasFile("/system/etc/preloaded-classes")) { + ALOGE("Missing preloaded-classes file, /system/etc/preloaded-classes not found: %s\n", + strerror(errno)); + goto bail; + } + addOption("-Ximage-compiler-option"); + addOption("--image-classes=/system/etc/preloaded-classes"); - property_get("dalvik.vm.image-dex2oat-flags", dex2oatImageFlagsBuf, ""); - parseExtraOpts(dex2oatImageFlagsBuf, "-Ximage-compiler-option"); - - // Extra options for DexClassLoader. - parseCompilerRuntimeOption("dalvik.vm.dex2oat-Xms", dex2oatXmsFlagsBuf, - "-Xms", "-Xcompiler-option"); - parseCompilerRuntimeOption("dalvik.vm.dex2oat-Xmx", dex2oatXmxFlagsBuf, - "-Xmx", "-Xcompiler-option"); - if (skip_compilation) { - addOption("-Xcompiler-option"); - addOption("--compiler-filter=verify-none"); - } else { - parseCompilerOption("dalvik.vm.dex2oat-filter", dex2oatCompilerFilterBuf, - "--compiler-filter=", "-Xcompiler-option"); - } - property_get("dalvik.vm.dex2oat-flags", dex2oatFlagsBuf, ""); - parseExtraOpts(dex2oatFlagsBuf, "-Xcompiler-option"); + // If there is a compiled-classes file, push it. + if (hasFile("/system/etc/compiled-classes")) { + addOption("-Ximage-compiler-option"); + addOption("--compiled-classes=/system/etc/compiled-classes"); + } + property_get("dalvik.vm.image-dex2oat-flags", dex2oatImageFlagsBuf, ""); + parseExtraOpts(dex2oatImageFlagsBuf, "-Ximage-compiler-option"); + + // Extra options for DexClassLoader. + parseCompilerRuntimeOption("dalvik.vm.dex2oat-Xms", dex2oatXmsFlagsBuf, + "-Xms", "-Xcompiler-option"); + parseCompilerRuntimeOption("dalvik.vm.dex2oat-Xmx", dex2oatXmxFlagsBuf, + "-Xmx", "-Xcompiler-option"); + if (skip_compilation) { + addOption("-Xcompiler-option"); + addOption("--compiler-filter=verify-none"); + + // We skip compilation when a minimal runtime is brought up for decryption. In that case + // /data is temporarily backed by a tmpfs, which is usually small. + // If the system image contains prebuilts, they will be relocated into the tmpfs. In this + // specific situation it is acceptable to *not* relocate and run out of the prebuilts + // directly instead. + addOption("--runtime-arg"); + addOption("-Xnorelocate"); + } else { + parseCompilerOption("dalvik.vm.dex2oat-filter", dex2oatCompilerFilterBuf, + "--compiler-filter=", "-Xcompiler-option"); } + property_get("dalvik.vm.dex2oat-flags", dex2oatFlagsBuf, ""); + parseExtraOpts(dex2oatFlagsBuf, "-Xcompiler-option"); /* extra options; parse this late so it overrides others */ property_get("dalvik.vm.extra-opts", extraOptsBuf, ""); @@ -819,77 +731,73 @@ int AndroidRuntime::startVm(JavaVM** pJavaVM, JNIEnv** pEnv) /* Set the properties for locale */ { - strcpy(langOption, "-Duser.language="); - strcpy(regionOption, "-Duser.region="); - readLocale(langOption, regionOption); - addOption(langOption); - addOption(regionOption); + strcpy(localeOption, "-Duser.locale="); + readLocale(localeOption); + addOption(localeOption); } /* * Set profiler options */ - if (libart) { - // Whether or not the profiler should be enabled. - property_get("dalvik.vm.profiler", propBuf, "0"); - if (propBuf[0] == '1') { - addOption("-Xenable-profiler"); - } + // Whether or not the profiler should be enabled. + property_get("dalvik.vm.profiler", propBuf, "0"); + if (propBuf[0] == '1') { + addOption("-Xenable-profiler"); + } - // Whether the profile should start upon app startup or be delayed by some random offset - // (in seconds) that is bound between 0 and a fixed value. - property_get("dalvik.vm.profile.start-immed", propBuf, "0"); - if (propBuf[0] == '1') { - addOption("-Xprofile-start-immediately"); - } + // Whether the profile should start upon app startup or be delayed by some random offset + // (in seconds) that is bound between 0 and a fixed value. + property_get("dalvik.vm.profile.start-immed", propBuf, "0"); + if (propBuf[0] == '1') { + addOption("-Xprofile-start-immediately"); + } - // Number of seconds during profile runs. - parseRuntimeOption("dalvik.vm.profile.period-secs", profilePeriod, "-Xprofile-period:"); - - // Length of each profile run (seconds). - parseRuntimeOption("dalvik.vm.profile.duration-secs", - profileDuration, - "-Xprofile-duration:"); - - // Polling interval during profile run (microseconds). - parseRuntimeOption("dalvik.vm.profile.interval-us", profileInterval, "-Xprofile-interval:"); - - // Coefficient for period backoff. The the period is multiplied - // by this value after each profile run. - parseRuntimeOption("dalvik.vm.profile.backoff-coeff", profileBackoff, "-Xprofile-backoff:"); - - // Top K% of samples that are considered relevant when - // deciding if the app should be recompiled. - parseRuntimeOption("dalvik.vm.profile.top-k-thr", - profileTopKThreshold, - "-Xprofile-top-k-threshold:"); - - // The threshold after which a change in the structure of the - // top K% profiled samples becomes significant and triggers - // recompilation. A change in profile is considered - // significant if X% (top-k-change-threshold) of the top K% - // (top-k-threshold property) samples has changed. - parseRuntimeOption("dalvik.vm.profile.top-k-ch-thr", - profileTopKChangeThreshold, - "-Xprofile-top-k-change-threshold:"); - - // Type of profile data. - parseRuntimeOption("dalvik.vm.profiler.type", profileType, "-Xprofile-type:"); - - // Depth of bounded stack data - parseRuntimeOption("dalvik.vm.profile.stack-depth", - profileMaxStackDepth, - "-Xprofile-max-stack-depth:"); - - // Native bridge library. "0" means that native bridge is disabled. - property_get("ro.dalvik.vm.native.bridge", propBuf, ""); - if (propBuf[0] == '\0') { - ALOGW("ro.dalvik.vm.native.bridge is not expected to be empty"); - } else if (strcmp(propBuf, "0") != 0) { - snprintf(nativeBridgeLibrary, sizeof("-XX:NativeBridge=") + PROPERTY_VALUE_MAX, - "-XX:NativeBridge=%s", propBuf); - addOption(nativeBridgeLibrary); - } + // Number of seconds during profile runs. + parseRuntimeOption("dalvik.vm.profile.period-secs", profilePeriod, "-Xprofile-period:"); + + // Length of each profile run (seconds). + parseRuntimeOption("dalvik.vm.profile.duration-secs", + profileDuration, + "-Xprofile-duration:"); + + // Polling interval during profile run (microseconds). + parseRuntimeOption("dalvik.vm.profile.interval-us", profileInterval, "-Xprofile-interval:"); + + // Coefficient for period backoff. The the period is multiplied + // by this value after each profile run. + parseRuntimeOption("dalvik.vm.profile.backoff-coeff", profileBackoff, "-Xprofile-backoff:"); + + // Top K% of samples that are considered relevant when + // deciding if the app should be recompiled. + parseRuntimeOption("dalvik.vm.profile.top-k-thr", + profileTopKThreshold, + "-Xprofile-top-k-threshold:"); + + // The threshold after which a change in the structure of the + // top K% profiled samples becomes significant and triggers + // recompilation. A change in profile is considered + // significant if X% (top-k-change-threshold) of the top K% + // (top-k-threshold property) samples has changed. + parseRuntimeOption("dalvik.vm.profile.top-k-ch-thr", + profileTopKChangeThreshold, + "-Xprofile-top-k-change-threshold:"); + + // Type of profile data. + parseRuntimeOption("dalvik.vm.profiler.type", profileType, "-Xprofile-type:"); + + // Depth of bounded stack data + parseRuntimeOption("dalvik.vm.profile.stack-depth", + profileMaxStackDepth, + "-Xprofile-max-stack-depth:"); + + // Native bridge library. "0" means that native bridge is disabled. + property_get("ro.dalvik.vm.native.bridge", propBuf, ""); + if (propBuf[0] == '\0') { + ALOGW("ro.dalvik.vm.native.bridge is not expected to be empty"); + } else if (strcmp(propBuf, "0") != 0) { + snprintf(nativeBridgeLibrary, sizeof("-XX:NativeBridge=") + PROPERTY_VALUE_MAX, + "-XX:NativeBridge=%s", propBuf); + addOption(nativeBridgeLibrary); } initArgs.version = JNI_VERSION_1_4; @@ -1237,19 +1145,11 @@ static int register_jni_procs(const RegJNIRec array[], size_t count, JNIEnv* env return 0; } -static void register_jam_procs(const RegJAMProc array[], size_t count) -{ - for (size_t i = 0; i < count; i++) { - array[i](); - } -} - static const RegJNIRec gRegJNI[] = { REG_JNI(register_com_android_internal_os_RuntimeInit), REG_JNI(register_android_os_SystemClock), REG_JNI(register_android_util_EventLog), REG_JNI(register_android_util_Log), - REG_JNI(register_android_util_FloatMath), REG_JNI(register_android_content_AssetManager), REG_JNI(register_android_content_StringBlock), REG_JNI(register_android_content_XmlBlock), @@ -1337,7 +1237,6 @@ static const RegJNIRec gRegJNI[] = { REG_JNI(register_android_net_NetworkUtils), REG_JNI(register_android_net_TrafficStats), REG_JNI(register_android_os_MemoryFile), - REG_JNI(register_com_android_internal_os_ZygoteInit), REG_JNI(register_com_android_internal_os_Zygote), REG_JNI(register_com_android_internal_util_VirtualRefBasePtr), REG_JNI(register_android_hardware_Camera), diff --git a/core/jni/android/graphics/AutoDecodeCancel.h b/core/jni/android/graphics/AutoDecodeCancel.h index 37b86f9..dd6a0d4 100644 --- a/core/jni/android/graphics/AutoDecodeCancel.h +++ b/core/jni/android/graphics/AutoDecodeCancel.h @@ -1,5 +1,5 @@ -#ifndef AutoDecodeCancel_DEFINED -#define AutoDecodeCancel_DEFINED +#ifndef _ANDROID_GRAPHICS_AUTO_DECODE_CANCEL_H_ +#define _ANDROID_GRAPHICS_AUTO_DECODE_CANCEL_H_ #include <jni.h> #include "SkImageDecoder.h" @@ -24,4 +24,4 @@ private: #endif }; -#endif +#endif // _ANDROID_GRAPHICS_AUTO_DECODE_CANCEL_H_ diff --git a/core/jni/android/graphics/Bitmap.cpp b/core/jni/android/graphics/Bitmap.cpp index d7eef6e..ceec0e3 100755 --- a/core/jni/android/graphics/Bitmap.cpp +++ b/core/jni/android/graphics/Bitmap.cpp @@ -15,16 +15,12 @@ #include "android_nio_utils.h" #include "CreateJavaOutputStreamAdaptor.h" +#include "core_jni_helpers.h" + #include <jni.h> #include <ResourceCache.h> -#if 0 - #define TRACE_BITMAP(code) code -#else - #define TRACE_BITMAP(code) -#endif - /////////////////////////////////////////////////////////////////////////////// // Conversions to/from SkColor, for get/setPixels, and the create method, which // is basically like setPixels @@ -43,8 +39,11 @@ static void FromColor_D32(void* dst, const SkColor src[], int width, static void FromColor_D32_Raw(void* dst, const SkColor src[], int width, int, int) { + // Needed to thwart the unreachable code detection from clang. + static const bool sk_color_ne_zero = SK_COLOR_MATCHES_PMCOLOR_BYTE_ORDER; + // SkColor's ordering may be different from SkPMColor - if (SK_COLOR_MATCHES_PMCOLOR_BYTE_ORDER) { + if (sk_color_ne_zero) { memcpy(dst, src, width * sizeof(SkColor)); return; } @@ -873,8 +872,6 @@ static void Bitmap_prepareToDraw(JNIEnv* env, jobject, jlong bitmapHandle) { /////////////////////////////////////////////////////////////////////////////// -#include <android_runtime/AndroidRuntime.h> - static JNINativeMethod gBitmapMethods[] = { { "nativeCreate", "([IIIIIIZ)Landroid/graphics/Bitmap;", (void*)Bitmap_creator }, @@ -914,10 +911,8 @@ static JNINativeMethod gBitmapMethods[] = { { "nativePrepareToDraw", "(J)V", (void*)Bitmap_prepareToDraw }, }; -#define kClassPathName "android/graphics/Bitmap" - int register_android_graphics_Bitmap(JNIEnv* env) { - return android::AndroidRuntime::registerNativeMethods(env, kClassPathName, - gBitmapMethods, SK_ARRAY_COUNT(gBitmapMethods)); + return android::RegisterMethodsOrDie(env, "android/graphics/Bitmap", gBitmapMethods, + NELEM(gBitmapMethods)); } diff --git a/core/jni/android/graphics/BitmapFactory.cpp b/core/jni/android/graphics/BitmapFactory.cpp index 49577cf..e346fc3 100644 --- a/core/jni/android/graphics/BitmapFactory.cpp +++ b/core/jni/android/graphics/BitmapFactory.cpp @@ -15,7 +15,7 @@ #include "JNIHelp.h" #include "GraphicsJNI.h" -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" #include <androidfw/Asset.h> #include <androidfw/ResourceTypes.h> #include <cutils/compiler.h> @@ -49,12 +49,6 @@ jmethodID gInsetStruct_constructorMethodID; using namespace android; -static inline int32_t validOrNeg1(bool isValid, int32_t value) { -// return isValid ? value : -1; - SkASSERT((int)isValid == 0 || (int)isValid == 1); - return ((int32_t)isValid - 1) | value; -} - jstring getMimeTypeString(JNIEnv* env, SkImageDecoder::Format format) { static const struct { SkImageDecoder::Format fFormat; @@ -69,7 +63,7 @@ jstring getMimeTypeString(JNIEnv* env, SkImageDecoder::Format format) { { SkImageDecoder::kWBMP_Format, "image/vnd.wap.wbmp" } }; - const char* cstr = NULL; + const char* cstr = nullptr; for (size_t i = 0; i < SK_ARRAY_COUNT(gMimeTypes); i++) { if (gMimeTypes[i].fFormat == format) { cstr = gMimeTypes[i].fMimeType; @@ -77,10 +71,10 @@ jstring getMimeTypeString(JNIEnv* env, SkImageDecoder::Format format) { } } - jstring jstr = NULL; - if (cstr != NULL) { + jstring jstr = nullptr; + if (cstr != nullptr) { // NOTE: Caller should env->ExceptionCheck() for OOM - // (can't check for NULL as it's a valid return value) + // (can't check for nullptr as it's a valid return value) jstr = env->NewStringUTF(cstr); } return jstr; @@ -187,8 +181,8 @@ public: const size_t size = sk_64_asS32(size64); if (size > mSize) { - ALOGW("bitmap marked for reuse (%d bytes) can't fit new bitmap (%d bytes)", - mSize, size); + ALOGW("bitmap marked for reuse (%u bytes) can't fit new bitmap " + "(%zu bytes)", mSize, size); return false; } @@ -585,52 +579,40 @@ static JNINativeMethod gOptionsMethods[] = { { "requestCancel", "()V", (void*)nativeRequestCancel } }; -static jfieldID getFieldIDCheck(JNIEnv* env, jclass clazz, - const char fieldname[], const char type[]) { - jfieldID id = env->GetFieldID(clazz, fieldname, type); - SkASSERT(id); - return id; -} - int register_android_graphics_BitmapFactory(JNIEnv* env) { - jclass options_class = env->FindClass("android/graphics/BitmapFactory$Options"); - SkASSERT(options_class); - gOptions_bitmapFieldID = getFieldIDCheck(env, options_class, "inBitmap", + jclass options_class = FindClassOrDie(env, "android/graphics/BitmapFactory$Options"); + gOptions_bitmapFieldID = GetFieldIDOrDie(env, options_class, "inBitmap", "Landroid/graphics/Bitmap;"); - gOptions_justBoundsFieldID = getFieldIDCheck(env, options_class, "inJustDecodeBounds", "Z"); - gOptions_sampleSizeFieldID = getFieldIDCheck(env, options_class, "inSampleSize", "I"); - gOptions_configFieldID = getFieldIDCheck(env, options_class, "inPreferredConfig", + gOptions_justBoundsFieldID = GetFieldIDOrDie(env, options_class, "inJustDecodeBounds", "Z"); + gOptions_sampleSizeFieldID = GetFieldIDOrDie(env, options_class, "inSampleSize", "I"); + gOptions_configFieldID = GetFieldIDOrDie(env, options_class, "inPreferredConfig", "Landroid/graphics/Bitmap$Config;"); - gOptions_premultipliedFieldID = getFieldIDCheck(env, options_class, "inPremultiplied", "Z"); - gOptions_mutableFieldID = getFieldIDCheck(env, options_class, "inMutable", "Z"); - gOptions_ditherFieldID = getFieldIDCheck(env, options_class, "inDither", "Z"); - gOptions_preferQualityOverSpeedFieldID = getFieldIDCheck(env, options_class, + gOptions_premultipliedFieldID = GetFieldIDOrDie(env, options_class, "inPremultiplied", "Z"); + gOptions_mutableFieldID = GetFieldIDOrDie(env, options_class, "inMutable", "Z"); + gOptions_ditherFieldID = GetFieldIDOrDie(env, options_class, "inDither", "Z"); + gOptions_preferQualityOverSpeedFieldID = GetFieldIDOrDie(env, options_class, "inPreferQualityOverSpeed", "Z"); - gOptions_scaledFieldID = getFieldIDCheck(env, options_class, "inScaled", "Z"); - gOptions_densityFieldID = getFieldIDCheck(env, options_class, "inDensity", "I"); - gOptions_screenDensityFieldID = getFieldIDCheck(env, options_class, "inScreenDensity", "I"); - gOptions_targetDensityFieldID = getFieldIDCheck(env, options_class, "inTargetDensity", "I"); - gOptions_widthFieldID = getFieldIDCheck(env, options_class, "outWidth", "I"); - gOptions_heightFieldID = getFieldIDCheck(env, options_class, "outHeight", "I"); - gOptions_mimeFieldID = getFieldIDCheck(env, options_class, "outMimeType", "Ljava/lang/String;"); - gOptions_mCancelID = getFieldIDCheck(env, options_class, "mCancel", "Z"); - - jclass bitmap_class = env->FindClass("android/graphics/Bitmap"); - SkASSERT(bitmap_class); - gBitmap_nativeBitmapFieldID = getFieldIDCheck(env, bitmap_class, "mNativeBitmap", "J"); - gBitmap_ninePatchInsetsFieldID = getFieldIDCheck(env, bitmap_class, "mNinePatchInsets", + gOptions_scaledFieldID = GetFieldIDOrDie(env, options_class, "inScaled", "Z"); + gOptions_densityFieldID = GetFieldIDOrDie(env, options_class, "inDensity", "I"); + gOptions_screenDensityFieldID = GetFieldIDOrDie(env, options_class, "inScreenDensity", "I"); + gOptions_targetDensityFieldID = GetFieldIDOrDie(env, options_class, "inTargetDensity", "I"); + gOptions_widthFieldID = GetFieldIDOrDie(env, options_class, "outWidth", "I"); + gOptions_heightFieldID = GetFieldIDOrDie(env, options_class, "outHeight", "I"); + gOptions_mimeFieldID = GetFieldIDOrDie(env, options_class, "outMimeType", "Ljava/lang/String;"); + gOptions_mCancelID = GetFieldIDOrDie(env, options_class, "mCancel", "Z"); + + jclass bitmap_class = FindClassOrDie(env, "android/graphics/Bitmap"); + gBitmap_nativeBitmapFieldID = GetFieldIDOrDie(env, bitmap_class, "mNativeBitmap", "J"); + gBitmap_ninePatchInsetsFieldID = GetFieldIDOrDie(env, bitmap_class, "mNinePatchInsets", "Landroid/graphics/NinePatch$InsetStruct;"); - gInsetStruct_class = (jclass) env->NewGlobalRef(env->FindClass("android/graphics/NinePatch$InsetStruct")); - gInsetStruct_constructorMethodID = env->GetMethodID(gInsetStruct_class, "<init>", "(IIIIIIIIFIF)V"); + gInsetStruct_class = MakeGlobalRefOrDie(env, FindClassOrDie(env, + "android/graphics/NinePatch$InsetStruct")); + gInsetStruct_constructorMethodID = GetMethodIDOrDie(env, gInsetStruct_class, "<init>", + "(IIIIIIIIFIF)V"); - int ret = AndroidRuntime::registerNativeMethods(env, - "android/graphics/BitmapFactory$Options", - gOptionsMethods, - SK_ARRAY_COUNT(gOptionsMethods)); - if (ret) { - return ret; - } - return android::AndroidRuntime::registerNativeMethods(env, "android/graphics/BitmapFactory", - gMethods, SK_ARRAY_COUNT(gMethods)); + android::RegisterMethodsOrDie(env, "android/graphics/BitmapFactory$Options", + gOptionsMethods, NELEM(gOptionsMethods)); + return android::RegisterMethodsOrDie(env, "android/graphics/BitmapFactory", + gMethods, NELEM(gMethods)); } diff --git a/core/jni/android/graphics/BitmapFactory.h b/core/jni/android/graphics/BitmapFactory.h index 97dcc6d..a54da43 100644 --- a/core/jni/android/graphics/BitmapFactory.h +++ b/core/jni/android/graphics/BitmapFactory.h @@ -1,5 +1,5 @@ -#ifndef BitmapFactory_DEFINE -#define BitmapFactory_DEFINE +#ifndef _ANDROID_GRAPHICS_BITMAP_FACTORY_H_ +#define _ANDROID_GRAPHICS_BITMAP_FACTORY_H_ #include "GraphicsJNI.h" @@ -21,4 +21,4 @@ extern jfieldID gOptions_bitmapFieldID; jstring getMimeTypeString(JNIEnv* env, SkImageDecoder::Format format); -#endif +#endif // _ANDROID_GRAPHICS_BITMAP_FACTORY_H_ diff --git a/core/jni/android/graphics/BitmapRegionDecoder.cpp b/core/jni/android/graphics/BitmapRegionDecoder.cpp index 6633261..90a7f69 100644 --- a/core/jni/android/graphics/BitmapRegionDecoder.cpp +++ b/core/jni/android/graphics/BitmapRegionDecoder.cpp @@ -30,7 +30,7 @@ #include "Utils.h" #include "JNIHelp.h" -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" #include "android_util_Binder.h" #include "android_nio_utils.h" #include "CreateJavaOutputStreamAdaptor.h" @@ -40,12 +40,6 @@ #include <androidfw/Asset.h> #include <sys/stat.h> -#if 0 - #define TRACE_BITMAP(code) code -#else - #define TRACE_BITMAP(code) -#endif - using namespace android; class SkBitmapRegionDecoder { @@ -274,8 +268,6 @@ static void nativeClean(JNIEnv* env, jobject, jlong brdHandle) { /////////////////////////////////////////////////////////////////////////////// -#include <android_runtime/AndroidRuntime.h> - static JNINativeMethod gBitmapRegionDecoderMethods[] = { { "nativeDecodeRegion", "(JIIIILandroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;", @@ -308,10 +300,8 @@ static JNINativeMethod gBitmapRegionDecoderMethods[] = { }, }; -#define kClassPathName "android/graphics/BitmapRegionDecoder" - int register_android_graphics_BitmapRegionDecoder(JNIEnv* env) { - return android::AndroidRuntime::registerNativeMethods(env, kClassPathName, - gBitmapRegionDecoderMethods, SK_ARRAY_COUNT(gBitmapRegionDecoderMethods)); + return android::RegisterMethodsOrDie(env, "android/graphics/BitmapRegionDecoder", + gBitmapRegionDecoderMethods, NELEM(gBitmapRegionDecoderMethods)); } diff --git a/core/jni/android/graphics/Camera.cpp b/core/jni/android/graphics/Camera.cpp index 9f832b0..b572604 100644 --- a/core/jni/android/graphics/Camera.cpp +++ b/core/jni/android/graphics/Camera.cpp @@ -1,5 +1,5 @@ #include "jni.h" -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" #include "SkCamera.h" @@ -137,16 +137,8 @@ static JNINativeMethod gCameraMethods[] = { }; int register_android_graphics_Camera(JNIEnv* env) { - jclass clazz = env->FindClass("android/graphics/Camera"); - if (clazz == 0) { - return -1; - } - gNativeInstanceFieldID = env->GetFieldID(clazz, "native_instance", "J"); - if (gNativeInstanceFieldID == 0) { - return -1; - } - return android::AndroidRuntime::registerNativeMethods(env, - "android/graphics/Camera", - gCameraMethods, - SK_ARRAY_COUNT(gCameraMethods)); + jclass clazz = android::FindClassOrDie(env, "android/graphics/Camera"); + gNativeInstanceFieldID = android::GetFieldIDOrDie(env, clazz, "native_instance", "J"); + return android::RegisterMethodsOrDie(env, "android/graphics/Camera", gCameraMethods, + NELEM(gCameraMethods)); } diff --git a/core/jni/android/graphics/CanvasProperty.cpp b/core/jni/android/graphics/CanvasProperty.cpp index e63c5fa..a69a457 100644 --- a/core/jni/android/graphics/CanvasProperty.cpp +++ b/core/jni/android/graphics/CanvasProperty.cpp @@ -17,16 +17,20 @@ #include "jni.h" #include "GraphicsJNI.h" #include "Paint.h" -#include <android_runtime/AndroidRuntime.h> +#include <core_jni_helpers.h> #include <utils/RefBase.h> #include <CanvasProperty.h> namespace android { -using namespace uirenderer; - #ifdef USE_OPENGL_RENDERER +static const bool kUseOpenGLRenderer = true; +#else +static const bool kUseOpenGLRenderer = false; +#endif + +using namespace uirenderer; static jlong createFloat(JNIEnv* env, jobject clazz, jfloat initialValue) { return reinterpret_cast<jlong>(new CanvasPropertyPrimitive(initialValue)); @@ -37,23 +41,21 @@ static jlong createPaint(JNIEnv* env, jobject clazz, jlong paintPtr) { return reinterpret_cast<jlong>(new CanvasPropertyPaint(*paint)); } -#endif - // ---------------------------------------------------------------------------- // JNI Glue // ---------------------------------------------------------------------------- -const char* const kClassPathName = "android/graphics/CanvasProperty"; - static JNINativeMethod gMethods[] = { -#ifdef USE_OPENGL_RENDERER { "nCreateFloat", "(F)J", (void*) createFloat }, { "nCreatePaint", "(J)J", (void*) createPaint }, -#endif }; int register_android_graphics_CanvasProperty(JNIEnv* env) { - return AndroidRuntime::registerNativeMethods(env, kClassPathName, gMethods, NELEM(gMethods)); + if (kUseOpenGLRenderer) { + return RegisterMethodsOrDie(env, "android/graphics/CanvasProperty", gMethods, + NELEM(gMethods)); + } + return 0; } }; // namespace android diff --git a/core/jni/android/graphics/ColorFilter.cpp b/core/jni/android/graphics/ColorFilter.cpp index c66c844..026cbee 100644 --- a/core/jni/android/graphics/ColorFilter.cpp +++ b/core/jni/android/graphics/ColorFilter.cpp @@ -17,7 +17,7 @@ #include "jni.h" #include "GraphicsJNI.h" -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" #include "SkColorFilter.h" #include "SkColorMatrixFilter.h" @@ -74,18 +74,15 @@ static JNINativeMethod colormatrix_methods[] = { { "nativeColorMatrixFilter", "([F)J", (void*) SkColorFilterGlue::CreateColorMatrixFilter }, }; -#define REG(env, name, array) \ - result = android::AndroidRuntime::registerNativeMethods(env, name, array, \ - SK_ARRAY_COUNT(array)); \ - if (result < 0) return result - int register_android_graphics_ColorFilter(JNIEnv* env) { - int result; - - REG(env, "android/graphics/ColorFilter", colorfilter_methods); - REG(env, "android/graphics/PorterDuffColorFilter", porterduff_methods); - REG(env, "android/graphics/LightingColorFilter", lighting_methods); - REG(env, "android/graphics/ColorMatrixColorFilter", colormatrix_methods); + android::RegisterMethodsOrDie(env, "android/graphics/ColorFilter", colorfilter_methods, + NELEM(colorfilter_methods)); + android::RegisterMethodsOrDie(env, "android/graphics/PorterDuffColorFilter", porterduff_methods, + NELEM(porterduff_methods)); + android::RegisterMethodsOrDie(env, "android/graphics/LightingColorFilter", lighting_methods, + NELEM(lighting_methods)); + android::RegisterMethodsOrDie(env, "android/graphics/ColorMatrixColorFilter", + colormatrix_methods, NELEM(colormatrix_methods)); return 0; } diff --git a/core/jni/android/graphics/CreateJavaOutputStreamAdaptor.cpp b/core/jni/android/graphics/CreateJavaOutputStreamAdaptor.cpp index a67740c..7937941 100644 --- a/core/jni/android/graphics/CreateJavaOutputStreamAdaptor.cpp +++ b/core/jni/android/graphics/CreateJavaOutputStreamAdaptor.cpp @@ -24,7 +24,6 @@ public: } virtual size_t read(void* buffer, size_t size) { - JNIEnv* env = fEnv; if (NULL == buffer) { if (0 == size) { return 0; diff --git a/core/jni/android/graphics/CreateJavaOutputStreamAdaptor.h b/core/jni/android/graphics/CreateJavaOutputStreamAdaptor.h index ecd270f..56cba51 100644 --- a/core/jni/android/graphics/CreateJavaOutputStreamAdaptor.h +++ b/core/jni/android/graphics/CreateJavaOutputStreamAdaptor.h @@ -1,5 +1,5 @@ -#ifndef CreateJavaOutputStream_DEFINED -#define CreateJavaOutputStream_DEFINED +#ifndef _ANDROID_GRAPHICS_CREATE_JAVA_OUTPUT_STREAM_ADAPTOR_H_ +#define _ANDROID_GRAPHICS_CREATE_JAVA_OUTPUT_STREAM_ADAPTOR_H_ //#include <android_runtime/AndroidRuntime.h> #include "jni.h" @@ -38,4 +38,5 @@ SkStreamRewindable* CopyJavaInputStream(JNIEnv* env, jobject stream, SkWStream* CreateJavaOutputStreamAdaptor(JNIEnv* env, jobject stream, jbyteArray storage); -#endif + +#endif // _ANDROID_GRAPHICS_CREATE_JAVA_OUTPUT_STREAM_ADAPTOR_H_ diff --git a/core/jni/android/graphics/DrawFilter.cpp b/core/jni/android/graphics/DrawFilter.cpp index 3275875..bac124f 100644 --- a/core/jni/android/graphics/DrawFilter.cpp +++ b/core/jni/android/graphics/DrawFilter.cpp @@ -24,6 +24,8 @@ #include "GraphicsJNI.h" #include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" + #include "SkDrawFilter.h" #include "SkPaintFlagsDrawFilter.h" #include "SkPaint.h" @@ -103,16 +105,11 @@ static JNINativeMethod paintflags_methods[] = { {"nativeConstructor","(II)J", (void*) SkDrawFilterGlue::CreatePaintFlagsDF} }; -#define REG(env, name, array) \ - result = android::AndroidRuntime::registerNativeMethods(env, name, array, SK_ARRAY_COUNT(array)); \ - if (result < 0) return result - - int register_android_graphics_DrawFilter(JNIEnv* env) { - int result; - - REG(env, "android/graphics/DrawFilter", drawfilter_methods); - REG(env, "android/graphics/PaintFlagsDrawFilter", paintflags_methods); + int result = RegisterMethodsOrDie(env, "android/graphics/DrawFilter", drawfilter_methods, + NELEM(drawfilter_methods)); + result |= RegisterMethodsOrDie(env, "android/graphics/PaintFlagsDrawFilter", paintflags_methods, + NELEM(paintflags_methods)); return 0; } diff --git a/core/jni/android/graphics/FontFamily.cpp b/core/jni/android/graphics/FontFamily.cpp index bfb30b7..8a85d62 100644 --- a/core/jni/android/graphics/FontFamily.cpp +++ b/core/jni/android/graphics/FontFamily.cpp @@ -17,7 +17,7 @@ #define LOG_TAG "Minikin" #include "JNIHelp.h" -#include <android_runtime/AndroidRuntime.h> +#include <core_jni_helpers.h> #include "SkTypeface.h" #include "GraphicsJNI.h" @@ -125,9 +125,8 @@ static JNINativeMethod gFontFamilyMethods[] = { int register_android_graphics_FontFamily(JNIEnv* env) { - return android::AndroidRuntime::registerNativeMethods(env, - "android/graphics/FontFamily", - gFontFamilyMethods, NELEM(gFontFamilyMethods)); + return RegisterMethodsOrDie(env, "android/graphics/FontFamily", gFontFamilyMethods, + NELEM(gFontFamilyMethods)); } } diff --git a/core/jni/android/graphics/GraphicsJNI.h b/core/jni/android/graphics/GraphicsJNI.h index 42973ba..a48b764 100644 --- a/core/jni/android/graphics/GraphicsJNI.h +++ b/core/jni/android/graphics/GraphicsJNI.h @@ -1,5 +1,5 @@ -#ifndef GraphicsJNI_DEFINED -#define GraphicsJNI_DEFINED +#ifndef _ANDROID_GRAPHICS_GRAPHICS_JNI_H_ +#define _ANDROID_GRAPHICS_GRAPHICS_JNI_H_ #include "SkBitmap.h" #include "SkDevice.h" @@ -15,7 +15,7 @@ class SkCanvas; namespace android { class Paint; -class TypefaceImpl; +struct TypefaceImpl; } class GraphicsJNI { @@ -160,7 +160,6 @@ public: private: JavaVM* fVM; - bool fAllocateInJavaHeap; jbyteArray fStorageObj; int fAllocCount; }; @@ -248,4 +247,4 @@ void doThrowIOE(JNIEnv* env, const char* msg = NULL); // IO Exception #define NPE_CHECK_RETURN_VOID(env, object) \ do { if (NULL == (object)) { doThrowNPE(env); return; } } while (0) -#endif +#endif // _ANDROID_GRAPHICS_GRAPHICS_JNI_H_ diff --git a/core/jni/android/graphics/HarfBuzzNGFaceSkia.cpp b/core/jni/android/graphics/HarfBuzzNGFaceSkia.cpp index a75efcf..ca3a42f 100644 --- a/core/jni/android/graphics/HarfBuzzNGFaceSkia.cpp +++ b/core/jni/android/graphics/HarfBuzzNGFaceSkia.cpp @@ -44,6 +44,8 @@ namespace android { +static const bool kDebugGlyphs = false; + // Our implementation of the callbacks which Harfbuzz requires by using Skia // calls. See the Harfbuzz source for references about what these callbacks do. @@ -62,9 +64,9 @@ static void SkiaGetGlyphWidthAndExtents(SkPaint* paint, hb_codepoint_t codepoint uint16_t glyph = codepoint; paint->getTextWidths(&glyph, sizeof(glyph), &skWidth, &skBounds); -#if DEBUG_GLYPHS - ALOGD("returned glyph for %i: width = %f", codepoint, skWidth); -#endif + if (kDebugGlyphs) { + ALOGD("returned glyph for %i: width = %f", codepoint, skWidth); + } if (width) *width = SkScalarToHBFixed(skWidth); if (extents) { diff --git a/core/jni/android/graphics/HarfBuzzNGFaceSkia.h b/core/jni/android/graphics/HarfBuzzNGFaceSkia.h index 7b71ecc..3308d5d 100644 --- a/core/jni/android/graphics/HarfBuzzNGFaceSkia.h +++ b/core/jni/android/graphics/HarfBuzzNGFaceSkia.h @@ -24,8 +24,8 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef HarfBuzzNGFaceSkia_h -#define HarfBuzzNGFaceSkia_h +#ifndef _ANDROID_GRAPHICS_HARF_BUZZ_NG_FACE_SKIA_H_ +#define _ANDROID_GRAPHICS_HARF_BUZZ_NG_FACE_SKIA_H_ #include <SkScalar.h> #include <SkPaint.h> @@ -56,4 +56,4 @@ hb_font_t* createFont(hb_face_t* face, SkPaint* paint, float sizeX, float sizeY) } // namespace android -#endif +#endif // _ANDROID_GRAPHICS_HARF_BUZZ_NG_FACE_SKIA_H_ diff --git a/core/jni/android/graphics/Interpolator.cpp b/core/jni/android/graphics/Interpolator.cpp index 455f867..f7f3511 100644 --- a/core/jni/android/graphics/Interpolator.cpp +++ b/core/jni/android/graphics/Interpolator.cpp @@ -1,5 +1,5 @@ #include "jni.h" -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" #include "GraphicsJNI.h" #include "SkInterpolator.h" @@ -83,8 +83,6 @@ static JNINativeMethod gInterpolatorMethods[] = { int register_android_graphics_Interpolator(JNIEnv* env) { - return android::AndroidRuntime::registerNativeMethods(env, - "android/graphics/Interpolator", - gInterpolatorMethods, - SK_ARRAY_COUNT(gInterpolatorMethods)); + return android::RegisterMethodsOrDie(env, "android/graphics/Interpolator", + gInterpolatorMethods, NELEM(gInterpolatorMethods)); } diff --git a/core/jni/android/graphics/MaskFilter.cpp b/core/jni/android/graphics/MaskFilter.cpp index b394905..d658643 100644 --- a/core/jni/android/graphics/MaskFilter.cpp +++ b/core/jni/android/graphics/MaskFilter.cpp @@ -4,6 +4,8 @@ #include "SkBlurMaskFilter.h" #include "SkTableMaskFilter.h" +#include "core_jni_helpers.h" + #include <jni.h> static void ThrowIAE_IfNull(JNIEnv* env, void* ptr) { @@ -77,20 +79,16 @@ static JNINativeMethod gTableMaskFilterMethods[] = { { "nativeNewGamma", "(F)J", (void*)SkMaskFilterGlue::createGammaTable } }; -#include <android_runtime/AndroidRuntime.h> - -#define REG(env, name, array) \ - result = android::AndroidRuntime::registerNativeMethods(env, name, array, SK_ARRAY_COUNT(array)); \ - if (result < 0) return result - int register_android_graphics_MaskFilter(JNIEnv* env) { - int result; - - REG(env, "android/graphics/MaskFilter", gMaskFilterMethods); - REG(env, "android/graphics/BlurMaskFilter", gBlurMaskFilterMethods); - REG(env, "android/graphics/EmbossMaskFilter", gEmbossMaskFilterMethods); - REG(env, "android/graphics/TableMaskFilter", gTableMaskFilterMethods); + android::RegisterMethodsOrDie(env, "android/graphics/MaskFilter", gMaskFilterMethods, + NELEM(gMaskFilterMethods)); + android::RegisterMethodsOrDie(env, "android/graphics/BlurMaskFilter", gBlurMaskFilterMethods, + NELEM(gBlurMaskFilterMethods)); + android::RegisterMethodsOrDie(env, "android/graphics/EmbossMaskFilter", + gEmbossMaskFilterMethods, NELEM(gEmbossMaskFilterMethods)); + android::RegisterMethodsOrDie(env, "android/graphics/TableMaskFilter", gTableMaskFilterMethods, + NELEM(gTableMaskFilterMethods)); return 0; } diff --git a/core/jni/android/graphics/Matrix.cpp b/core/jni/android/graphics/Matrix.cpp index 01ab699..0ff7c78 100644 --- a/core/jni/android/graphics/Matrix.cpp +++ b/core/jni/android/graphics/Matrix.cpp @@ -17,7 +17,7 @@ #include "jni.h" #include "GraphicsJNI.h" -#include <android_runtime/AndroidRuntime.h> +#include <core_jni_helpers.h> #include "SkMatrix.h" #include "SkTemplates.h" @@ -354,11 +354,10 @@ static JNINativeMethod methods[] = { static jfieldID sNativeInstanceField; int register_android_graphics_Matrix(JNIEnv* env) { - int result = AndroidRuntime::registerNativeMethods(env, "android/graphics/Matrix", methods, - sizeof(methods) / sizeof(methods[0])); + int result = RegisterMethodsOrDie(env, "android/graphics/Matrix", methods, NELEM(methods)); - jclass clazz = env->FindClass("android/graphics/Matrix"); - sNativeInstanceField = env->GetFieldID(clazz, "native_instance", "J"); + jclass clazz = FindClassOrDie(env, "android/graphics/Matrix"); + sNativeInstanceField = GetFieldIDOrDie(env, clazz, "native_instance", "J"); return result; } diff --git a/core/jni/android/graphics/Matrix.h b/core/jni/android/graphics/Matrix.h index 31edf88..11c9e72 100644 --- a/core/jni/android/graphics/Matrix.h +++ b/core/jni/android/graphics/Matrix.h @@ -14,8 +14,8 @@ * limitations under the License. */ -#ifndef _ANDROID_GRAPHICS_MATRIX_H -#define _ANDROID_GRAPHICS_MATRIX_H +#ifndef _ANDROID_GRAPHICS_MATRIX_H_ +#define _ANDROID_GRAPHICS_MATRIX_H_ #include "jni.h" #include "SkMatrix.h" @@ -27,4 +27,4 @@ extern SkMatrix* android_graphics_Matrix_getSkMatrix(JNIEnv* env, jobject matrix } // namespace android -#endif // _ANDROID_GRAPHICS_MATRIX_H +#endif // _ANDROID_GRAPHICS_MATRIX_H_ diff --git a/core/jni/android/graphics/MinikinSkia.h b/core/jni/android/graphics/MinikinSkia.h index 255617e..a06428d 100644 --- a/core/jni/android/graphics/MinikinSkia.h +++ b/core/jni/android/graphics/MinikinSkia.h @@ -14,8 +14,8 @@ * limitations under the License. */ -#ifndef ANDROID_MINIKIN_SKIA_H -#define ANDROID_MINIKIN_SKIA_H +#ifndef _ANDROID_GRAPHICS_MINIKIN_SKIA_H_ +#define _ANDROID_GRAPHICS_MINIKIN_SKIA_H_ #include <minikin/MinikinFont.h> @@ -54,4 +54,4 @@ private: } // namespace android -#endif // ANDROID_MINIKIN_SKIA_H
\ No newline at end of file +#endif // _ANDROID_GRAPHICS_MINIKIN_SKIA_H_
\ No newline at end of file diff --git a/core/jni/android/graphics/MinikinUtils.cpp b/core/jni/android/graphics/MinikinUtils.cpp index f64ad7d..7dabf6b 100644 --- a/core/jni/android/graphics/MinikinUtils.cpp +++ b/core/jni/android/graphics/MinikinUtils.cpp @@ -26,18 +26,6 @@ namespace android { -// Do an sprintf starting at offset n, abort on overflow -static int snprintfcat(char* buf, int off, int size, const char* format, ...) - __attribute__((__format__(__printf__, 4, 5))); -static int snprintfcat(char* buf, int off, int size, const char* format, ...) { - va_list args; - va_start(args, format); - int n = vsnprintf(buf + off, size - off, format, args); - LOG_ALWAYS_FATAL_IF(n >= size - off, "String overflow in setting layout properties"); - va_end(args); - return off + n; -} - void MinikinUtils::doLayout(Layout* layout, const Paint* paint, int bidiFlags, TypefaceImpl* typeface, const uint16_t* buf, size_t start, size_t count, size_t bufSize) { TypefaceImpl* resolvedFace = TypefaceImpl_resolveDefault(typeface); diff --git a/core/jni/android/graphics/MinikinUtils.h b/core/jni/android/graphics/MinikinUtils.h index 3646c1a..236f1fd 100644 --- a/core/jni/android/graphics/MinikinUtils.h +++ b/core/jni/android/graphics/MinikinUtils.h @@ -21,8 +21,8 @@ // TODO: does this really need to be separate from MinikinSkia? -#ifndef ANDROID_MINIKIN_UTILS_H -#define ANDROID_MINIKIN_UTILS_H +#ifndef _ANDROID_GRAPHICS_MINIKIN_UTILS_H_ +#define _ANDROID_GRAPHICS_MINIKIN_UTILS_H_ #include <minikin/Layout.h> #include "Paint.h" @@ -81,4 +81,4 @@ public: } // namespace android -#endif // ANDROID_MINIKIN_UTILS_H +#endif // _ANDROID_GRAPHICS_MINIKIN_UTILS_H_ diff --git a/core/jni/android/graphics/Movie.cpp b/core/jni/android/graphics/Movie.cpp index 226f83e..b25fa84 100644 --- a/core/jni/android/graphics/Movie.cpp +++ b/core/jni/android/graphics/Movie.cpp @@ -13,11 +13,7 @@ #include <androidfw/ResourceTypes.h> #include <netinet/in.h> -#if 0 - #define TRACE_BITMAP(code) code -#else - #define TRACE_BITMAP(code) -#endif +#include "core_jni_helpers.h" static jclass gMovie_class; static jmethodID gMovie_constructorMethodID; @@ -138,8 +134,6 @@ static void movie_destructor(JNIEnv* env, jobject, jlong movieHandle) { ////////////////////////////////////////////////////////////////////////////////////////////// -#include <android_runtime/AndroidRuntime.h> - static JNINativeMethod gMethods[] = { { "width", "()I", (void*)movie_width }, { "height", "()I", (void*)movie_height }, @@ -157,22 +151,14 @@ static JNINativeMethod gMethods[] = { (void*)movie_decodeByteArray }, }; -#define kClassPathName "android/graphics/Movie" - -#define RETURN_ERR_IF_NULL(value) do { if (!(value)) { assert(0); return -1; } } while (false) - int register_android_graphics_Movie(JNIEnv* env) { - gMovie_class = env->FindClass(kClassPathName); - RETURN_ERR_IF_NULL(gMovie_class); - gMovie_class = (jclass)env->NewGlobalRef(gMovie_class); + gMovie_class = android::FindClassOrDie(env, "android/graphics/Movie"); + gMovie_class = android::MakeGlobalRefOrDie(env, gMovie_class); - gMovie_constructorMethodID = env->GetMethodID(gMovie_class, "<init>", "(J)V"); - RETURN_ERR_IF_NULL(gMovie_constructorMethodID); + gMovie_constructorMethodID = android::GetMethodIDOrDie(env, gMovie_class, "<init>", "(J)V"); - gMovie_nativeInstanceID = env->GetFieldID(gMovie_class, "mNativeMovie", "J"); - RETURN_ERR_IF_NULL(gMovie_nativeInstanceID); + gMovie_nativeInstanceID = android::GetFieldIDOrDie(env, gMovie_class, "mNativeMovie", "J"); - return android::AndroidRuntime::registerNativeMethods(env, kClassPathName, - gMethods, SK_ARRAY_COUNT(gMethods)); + return android::RegisterMethodsOrDie(env, "android/graphics/Movie", gMethods, NELEM(gMethods)); } diff --git a/core/jni/android/graphics/NinePatch.cpp b/core/jni/android/graphics/NinePatch.cpp index be62fdd..d868f28 100644 --- a/core/jni/android/graphics/NinePatch.cpp +++ b/core/jni/android/graphics/NinePatch.cpp @@ -30,6 +30,7 @@ #include "GraphicsJNI.h" #include "JNIHelp.h" +#include "core_jni_helpers.h" extern void NinePatch_Draw(SkCanvas* canvas, const SkRect& bounds, const SkBitmap& bitmap, const android::Res_png_9patch& chunk, const SkPaint* paint, SkRegion** outRegion); @@ -176,8 +177,6 @@ public: ///////////////////////////////////////////////////////////////////////////////////////// -#include <android_runtime/AndroidRuntime.h> - static JNINativeMethod gNinePatchMethods[] = { { "isNinePatchChunk", "([B)Z", (void*) SkNinePatchGlue::isNinePatchChunk }, { "validateNinePatchChunk", "(J[B)J", (void*) SkNinePatchGlue::validateNinePatchChunk }, @@ -189,6 +188,6 @@ static JNINativeMethod gNinePatchMethods[] = { }; int register_android_graphics_NinePatch(JNIEnv* env) { - return android::AndroidRuntime::registerNativeMethods(env, - "android/graphics/NinePatch", gNinePatchMethods, SK_ARRAY_COUNT(gNinePatchMethods)); + return android::RegisterMethodsOrDie(env, + "android/graphics/NinePatch", gNinePatchMethods, NELEM(gNinePatchMethods)); } diff --git a/core/jni/android/graphics/NinePatchImpl.cpp b/core/jni/android/graphics/NinePatchImpl.cpp index c162c48..26ce967 100644 --- a/core/jni/android/graphics/NinePatchImpl.cpp +++ b/core/jni/android/graphics/NinePatchImpl.cpp @@ -23,20 +23,16 @@ #include "SkBitmap.h" #include "SkCanvas.h" +#include "SkColorPriv.h" #include "SkNinePatch.h" #include "SkPaint.h" #include "SkUnPreMultiply.h" -#define USE_TRACE - -#ifdef USE_TRACE - static bool gTrace; -#endif - -#include "SkColorPriv.h" - #include <utils/Log.h> +static const bool kUseTrace = true; +static bool gTrace = false; + static bool getColor(const SkBitmap& bitmap, int x, int y, SkColor* c) { switch (bitmap.colorType()) { case kN32_SkColorType: @@ -120,7 +116,7 @@ void NinePatch_Draw(SkCanvas* canvas, const SkRect& bounds, const int32_t* yDivs = chunk.getYDivs(); // if our SkCanvas were back by GL we should enable this and draw this as // a mesh, which will be faster in most cases. - if (false) { + if ((false)) { SkNinePatch::DrawMesh(canvas, bounds, bitmap, xDivs, chunk.numXDivs, yDivs, chunk.numYDivs, @@ -128,37 +124,34 @@ void NinePatch_Draw(SkCanvas* canvas, const SkRect& bounds, return; } -#ifdef USE_TRACE - gTrace = true; -#endif + if (kUseTrace) { + gTrace = true; + } SkASSERT(canvas || outRegion); -#ifdef USE_TRACE - if (canvas) { - const SkMatrix& m = canvas->getTotalMatrix(); - ALOGV("ninepatch [%g %g %g] [%g %g %g]\n", - SkScalarToFloat(m[0]), SkScalarToFloat(m[1]), SkScalarToFloat(m[2]), - SkScalarToFloat(m[3]), SkScalarToFloat(m[4]), SkScalarToFloat(m[5])); - } -#endif + if (kUseTrace) { + if (canvas) { + const SkMatrix& m = canvas->getTotalMatrix(); + ALOGV("ninepatch [%g %g %g] [%g %g %g]\n", + SkScalarToFloat(m[0]), SkScalarToFloat(m[1]), SkScalarToFloat(m[2]), + SkScalarToFloat(m[3]), SkScalarToFloat(m[4]), SkScalarToFloat(m[5])); + } -#ifdef USE_TRACE - if (gTrace) { - ALOGV("======== ninepatch bounds [%g %g]\n", SkScalarToFloat(bounds.width()), SkScalarToFloat(bounds.height())); + ALOGV("======== ninepatch bounds [%g %g]\n", SkScalarToFloat(bounds.width()), + SkScalarToFloat(bounds.height())); ALOGV("======== ninepatch paint bm [%d,%d]\n", bitmap.width(), bitmap.height()); ALOGV("======== ninepatch xDivs [%d,%d]\n", xDivs[0], xDivs[1]); ALOGV("======== ninepatch yDivs [%d,%d]\n", yDivs[0], yDivs[1]); } -#endif if (bounds.isEmpty() || bitmap.width() == 0 || bitmap.height() == 0 || (paint && paint->getXfermode() == NULL && paint->getAlpha() == 0)) { -#ifdef USE_TRACE - if (gTrace) ALOGV("======== abort ninepatch draw\n"); -#endif + if (kUseTrace) { + ALOGV("======== abort ninepatch draw\n"); + } return; } @@ -202,18 +195,18 @@ void NinePatch_Draw(SkCanvas* canvas, const SkRect& bounds, } int numFixedYPixelsRemaining = bitmapHeight - numStretchyYPixelsRemaining; -#ifdef USE_TRACE - ALOGV("NinePatch [%d %d] bounds [%g %g %g %g] divs [%d %d]\n", - bitmap.width(), bitmap.height(), - SkScalarToFloat(bounds.fLeft), SkScalarToFloat(bounds.fTop), - SkScalarToFloat(bounds.width()), SkScalarToFloat(bounds.height()), - numXDivs, numYDivs); -#endif + if (kUseTrace) { + ALOGV("NinePatch [%d %d] bounds [%g %g %g %g] divs [%d %d]\n", + bitmap.width(), bitmap.height(), + SkScalarToFloat(bounds.fLeft), SkScalarToFloat(bounds.fTop), + SkScalarToFloat(bounds.width()), SkScalarToFloat(bounds.height()), + numXDivs, numYDivs); + } src.fTop = 0; dst.fTop = bounds.fTop; // The first row always starts with the top being at y=0 and the bottom - // being either yDivs[1] (if yDivs[0]=0) of yDivs[0]. In the former case + // being either yDivs[1] (if yDivs[0]=0) or yDivs[0]. In the former case // the first row is stretchable along the Y axis, otherwise it is fixed. // The last row always ends with the bottom being bitmap.height and the top // being either yDivs[numYDivs-2] (if yDivs[numYDivs-1]=bitmap.height) or @@ -307,15 +300,15 @@ void NinePatch_Draw(SkCanvas* canvas, const SkRect& bounds, goto nextDiv; } if (canvas) { -#ifdef USE_TRACE - ALOGV("-- src [%d %d %d %d] dst [%g %g %g %g]\n", - src.fLeft, src.fTop, src.width(), src.height(), - SkScalarToFloat(dst.fLeft), SkScalarToFloat(dst.fTop), - SkScalarToFloat(dst.width()), SkScalarToFloat(dst.height())); - if (2 == src.width() && SkIntToScalar(5) == dst.width()) { - ALOGV("--- skip patch\n"); + if (kUseTrace) { + ALOGV("-- src [%d %d %d %d] dst [%g %g %g %g]\n", + src.fLeft, src.fTop, src.width(), src.height(), + SkScalarToFloat(dst.fLeft), SkScalarToFloat(dst.fTop), + SkScalarToFloat(dst.width()), SkScalarToFloat(dst.height())); + if (2 == src.width() && SkIntToScalar(5) == dst.width()) { + ALOGV("--- skip patch\n"); + } } -#endif drawStretchyPatch(canvas, src, dst, bitmap, *paint, initColor, color, hasXfer); } diff --git a/core/jni/android/graphics/NinePatchPeeker.h b/core/jni/android/graphics/NinePatchPeeker.h index 7c18b2d..2d49b38 100644 --- a/core/jni/android/graphics/NinePatchPeeker.h +++ b/core/jni/android/graphics/NinePatchPeeker.h @@ -14,8 +14,8 @@ * limitations under the License. */ -#ifndef NinePatchPeeker_h -#define NinePatchPeeker_h +#ifndef _ANDROID_GRAPHICS_NINE_PATCH_PEEKER_H_ +#define _ANDROID_GRAPHICS_NINE_PATCH_PEEKER_H_ #include "SkImageDecoder.h" #include <androidfw/ResourceTypes.h> @@ -53,4 +53,4 @@ public: uint8_t mOutlineAlpha; }; -#endif // NinePatchPeeker_h +#endif // _ANDROID_GRAPHICS_NINE_PATCH_PEEKER_H_ diff --git a/core/jni/android/graphics/Paint.cpp b/core/jni/android/graphics/Paint.cpp index 6b02326..2cd2db7 100644 --- a/core/jni/android/graphics/Paint.cpp +++ b/core/jni/android/graphics/Paint.cpp @@ -21,7 +21,7 @@ #include "jni.h" #include "GraphicsJNI.h" -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" #include <ScopedUtfChars.h> #include "SkBlurDrawLooper.h" @@ -1021,35 +1021,26 @@ static JNINativeMethod methods[] = { {"native_hasShadowLayer", "!(J)Z", (void*)PaintGlue::hasShadowLayer} }; -static jfieldID req_fieldID(jfieldID id) { - SkASSERT(id); - return id; -} - int register_android_graphics_Paint(JNIEnv* env) { - gFontMetrics_class = env->FindClass("android/graphics/Paint$FontMetrics"); - SkASSERT(gFontMetrics_class); - gFontMetrics_class = (jclass)env->NewGlobalRef(gFontMetrics_class); - - gFontMetrics_fieldID.top = req_fieldID(env->GetFieldID(gFontMetrics_class, "top", "F")); - gFontMetrics_fieldID.ascent = req_fieldID(env->GetFieldID(gFontMetrics_class, "ascent", "F")); - gFontMetrics_fieldID.descent = req_fieldID(env->GetFieldID(gFontMetrics_class, "descent", "F")); - gFontMetrics_fieldID.bottom = req_fieldID(env->GetFieldID(gFontMetrics_class, "bottom", "F")); - gFontMetrics_fieldID.leading = req_fieldID(env->GetFieldID(gFontMetrics_class, "leading", "F")); - - gFontMetricsInt_class = env->FindClass("android/graphics/Paint$FontMetricsInt"); - SkASSERT(gFontMetricsInt_class); - gFontMetricsInt_class = (jclass)env->NewGlobalRef(gFontMetricsInt_class); - - gFontMetricsInt_fieldID.top = req_fieldID(env->GetFieldID(gFontMetricsInt_class, "top", "I")); - gFontMetricsInt_fieldID.ascent = req_fieldID(env->GetFieldID(gFontMetricsInt_class, "ascent", "I")); - gFontMetricsInt_fieldID.descent = req_fieldID(env->GetFieldID(gFontMetricsInt_class, "descent", "I")); - gFontMetricsInt_fieldID.bottom = req_fieldID(env->GetFieldID(gFontMetricsInt_class, "bottom", "I")); - gFontMetricsInt_fieldID.leading = req_fieldID(env->GetFieldID(gFontMetricsInt_class, "leading", "I")); - - int result = AndroidRuntime::registerNativeMethods(env, "android/graphics/Paint", methods, - sizeof(methods) / sizeof(methods[0])); - return result; + gFontMetrics_class = FindClassOrDie(env, "android/graphics/Paint$FontMetrics"); + gFontMetrics_class = MakeGlobalRefOrDie(env, gFontMetrics_class); + + gFontMetrics_fieldID.top = GetFieldIDOrDie(env, gFontMetrics_class, "top", "F"); + gFontMetrics_fieldID.ascent = GetFieldIDOrDie(env, gFontMetrics_class, "ascent", "F"); + gFontMetrics_fieldID.descent = GetFieldIDOrDie(env, gFontMetrics_class, "descent", "F"); + gFontMetrics_fieldID.bottom = GetFieldIDOrDie(env, gFontMetrics_class, "bottom", "F"); + gFontMetrics_fieldID.leading = GetFieldIDOrDie(env, gFontMetrics_class, "leading", "F"); + + gFontMetricsInt_class = FindClassOrDie(env, "android/graphics/Paint$FontMetricsInt"); + gFontMetricsInt_class = MakeGlobalRefOrDie(env, gFontMetricsInt_class); + + gFontMetricsInt_fieldID.top = GetFieldIDOrDie(env, gFontMetricsInt_class, "top", "I"); + gFontMetricsInt_fieldID.ascent = GetFieldIDOrDie(env, gFontMetricsInt_class, "ascent", "I"); + gFontMetricsInt_fieldID.descent = GetFieldIDOrDie(env, gFontMetricsInt_class, "descent", "I"); + gFontMetricsInt_fieldID.bottom = GetFieldIDOrDie(env, gFontMetricsInt_class, "bottom", "I"); + gFontMetricsInt_fieldID.leading = GetFieldIDOrDie(env, gFontMetricsInt_class, "leading", "I"); + + return RegisterMethodsOrDie(env, "android/graphics/Paint", methods, NELEM(methods)); } } diff --git a/core/jni/android/graphics/Paint.h b/core/jni/android/graphics/Paint.h index a20bb4b..fa539f5 100644 --- a/core/jni/android/graphics/Paint.h +++ b/core/jni/android/graphics/Paint.h @@ -14,8 +14,8 @@ * limitations under the License. */ -#ifndef ANDROID_GRAPHICS_PAINT_H -#define ANDROID_GRAPHICS_PAINT_H +#ifndef ANDROID_GRAPHICS_PAINT_H_ +#define ANDROID_GRAPHICS_PAINT_H_ #include <SkPaint.h> #include <string> @@ -78,4 +78,4 @@ private: } // namespace android -#endif // ANDROID_GRAPHICS_PAINT_H +#endif // ANDROID_GRAPHICS_PAINT_H_ diff --git a/core/jni/android/graphics/Path.cpp b/core/jni/android/graphics/Path.cpp index 30ce58d..1e4eb75 100644 --- a/core/jni/android/graphics/Path.cpp +++ b/core/jni/android/graphics/Path.cpp @@ -22,7 +22,7 @@ #include "jni.h" #include "GraphicsJNI.h" -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" #include "SkPath.h" #include "SkPathOps.h" @@ -520,9 +520,7 @@ static JNINativeMethod methods[] = { }; int register_android_graphics_Path(JNIEnv* env) { - int result = AndroidRuntime::registerNativeMethods(env, "android/graphics/Path", methods, - sizeof(methods) / sizeof(methods[0])); - return result; + return RegisterMethodsOrDie(env, "android/graphics/Path", methods, NELEM(methods)); } } diff --git a/core/jni/android/graphics/PathEffect.cpp b/core/jni/android/graphics/PathEffect.cpp index 28d881d..9d0f0ad 100644 --- a/core/jni/android/graphics/PathEffect.cpp +++ b/core/jni/android/graphics/PathEffect.cpp @@ -1,6 +1,8 @@ #include <jni.h> #include "GraphicsJNI.h" +#include "core_jni_helpers.h" + #include "SkPathEffect.h" #include "SkCornerPathEffect.h" #include "SkDashPathEffect.h" @@ -97,24 +99,22 @@ static JNINativeMethod gDiscretePathEffectMethods[] = { { "nativeCreate", "(FF)J", (void*)SkPathEffectGlue::Discrete_constructor } }; -#include <android_runtime/AndroidRuntime.h> - -#define REG(env, name, array) \ - result = android::AndroidRuntime::registerNativeMethods(env, name, array, \ - SK_ARRAY_COUNT(array)); \ - if (result < 0) return result - int register_android_graphics_PathEffect(JNIEnv* env) { - int result; - - REG(env, "android/graphics/PathEffect", gPathEffectMethods); - REG(env, "android/graphics/ComposePathEffect", gComposePathEffectMethods); - REG(env, "android/graphics/SumPathEffect", gSumPathEffectMethods); - REG(env, "android/graphics/DashPathEffect", gDashPathEffectMethods); - REG(env, "android/graphics/PathDashPathEffect", gPathDashPathEffectMethods); - REG(env, "android/graphics/CornerPathEffect", gCornerPathEffectMethods); - REG(env, "android/graphics/DiscretePathEffect", gDiscretePathEffectMethods); + android::RegisterMethodsOrDie(env, "android/graphics/PathEffect", gPathEffectMethods, + NELEM(gPathEffectMethods)); + android::RegisterMethodsOrDie(env, "android/graphics/ComposePathEffect", + gComposePathEffectMethods, NELEM(gComposePathEffectMethods)); + android::RegisterMethodsOrDie(env, "android/graphics/SumPathEffect", gSumPathEffectMethods, + NELEM(gSumPathEffectMethods)); + android::RegisterMethodsOrDie(env, "android/graphics/DashPathEffect", gDashPathEffectMethods, + NELEM(gDashPathEffectMethods)); + android::RegisterMethodsOrDie(env, "android/graphics/PathDashPathEffect", + gPathDashPathEffectMethods, NELEM(gPathDashPathEffectMethods)); + android::RegisterMethodsOrDie(env, "android/graphics/CornerPathEffect", + gCornerPathEffectMethods, NELEM(gCornerPathEffectMethods)); + android::RegisterMethodsOrDie(env, "android/graphics/DiscretePathEffect", + gDiscretePathEffectMethods, NELEM(gDiscretePathEffectMethods)); return 0; } diff --git a/core/jni/android/graphics/PathMeasure.cpp b/core/jni/android/graphics/PathMeasure.cpp index 13f68a9..fec5d9d 100644 --- a/core/jni/android/graphics/PathMeasure.cpp +++ b/core/jni/android/graphics/PathMeasure.cpp @@ -17,7 +17,7 @@ #include "jni.h" #include "GraphicsJNI.h" -#include <android_runtime/AndroidRuntime.h> +#include <core_jni_helpers.h> #include "SkPathMeasure.h" @@ -156,9 +156,7 @@ static JNINativeMethod methods[] = { }; int register_android_graphics_PathMeasure(JNIEnv* env) { - int result = AndroidRuntime::registerNativeMethods(env, "android/graphics/PathMeasure", methods, - sizeof(methods) / sizeof(methods[0])); - return result; + return RegisterMethodsOrDie(env, "android/graphics/PathMeasure", methods, NELEM(methods)); } } diff --git a/core/jni/android/graphics/Picture.h b/core/jni/android/graphics/Picture.h index a2e5d4a..4db923d 100644 --- a/core/jni/android/graphics/Picture.h +++ b/core/jni/android/graphics/Picture.h @@ -14,8 +14,8 @@ * limitations under the License. */ -#ifndef ANDROID_GRAPHICS_PICTURE_H -#define ANDROID_GRAPHICS_PICTURE_H +#ifndef ANDROID_GRAPHICS_PICTURE_H_ +#define ANDROID_GRAPHICS_PICTURE_H_ #include "SkPicture.h" #include "SkPictureRecorder.h" @@ -63,4 +63,4 @@ private: }; }; // namespace android -#endif // ANDROID_GRAPHICS_PICTURE_H +#endif // ANDROID_GRAPHICS_PICTURE_H_ diff --git a/core/jni/android/graphics/PorterDuff.cpp b/core/jni/android/graphics/PorterDuff.cpp index 8a49eb5..73b1691 100644 --- a/core/jni/android/graphics/PorterDuff.cpp +++ b/core/jni/android/graphics/PorterDuff.cpp @@ -22,7 +22,7 @@ #include "jni.h" #include "GraphicsJNI.h" -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" #include "SkPorterDuff.h" @@ -43,10 +43,7 @@ static JNINativeMethod methods[] = { }; int register_android_graphics_PorterDuff(JNIEnv* env) { - int result = AndroidRuntime::registerNativeMethods(env, - "android/graphics/PorterDuffXfermode", methods, - sizeof(methods) / sizeof(methods[0])); - return result; + return RegisterMethodsOrDie(env, "android/graphics/PorterDuffXfermode", methods, NELEM(methods)); } } diff --git a/core/jni/android/graphics/Rasterizer.cpp b/core/jni/android/graphics/Rasterizer.cpp index 2b1aca1..cfc23ac8 100644 --- a/core/jni/android/graphics/Rasterizer.cpp +++ b/core/jni/android/graphics/Rasterizer.cpp @@ -24,7 +24,7 @@ #include "GraphicsJNI.h" #include "Paint.h" #include "SkLayerRasterizer.h" -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" // Rasterizer.java holds a pointer (jlong) to this guy class NativeRasterizer { @@ -59,7 +59,6 @@ public: static void finalizer(JNIEnv* env, jobject clazz, jlong objHandle) { delete reinterpret_cast<NativeRasterizer *>(objHandle); } - }; static JNINativeMethod gRasterizerMethods[] = { @@ -67,9 +66,8 @@ static JNINativeMethod gRasterizerMethods[] = { }; int register_android_graphics_Rasterizer(JNIEnv* env) { - int result = AndroidRuntime::registerNativeMethods(env, "android/graphics/Rasterizer", gRasterizerMethods, - sizeof(gRasterizerMethods) / sizeof(gRasterizerMethods[0])); - return result; + return RegisterMethodsOrDie(env, "android/graphics/Rasterizer", gRasterizerMethods, + NELEM(gRasterizerMethods)); } class SkLayerRasterizerGlue { @@ -94,10 +92,8 @@ static JNINativeMethod gLayerRasterizerMethods[] = { int register_android_graphics_LayerRasterizer(JNIEnv* env) { - return android::AndroidRuntime::registerNativeMethods(env, - "android/graphics/LayerRasterizer", - gLayerRasterizerMethods, - SK_ARRAY_COUNT(gLayerRasterizerMethods)); + return RegisterMethodsOrDie(env, "android/graphics/LayerRasterizer", + gLayerRasterizerMethods, NELEM(gLayerRasterizerMethods)); } } diff --git a/core/jni/android/graphics/Region.cpp b/core/jni/android/graphics/Region.cpp index 912968a..90a020e 100644 --- a/core/jni/android/graphics/Region.cpp +++ b/core/jni/android/graphics/Region.cpp @@ -23,7 +23,7 @@ #include "android_util_Binder.h" #include <jni.h> -#include <android_runtime/AndroidRuntime.h> +#include <core_jni_helpers.h> namespace android { @@ -325,19 +325,13 @@ static JNINativeMethod gRegionMethods[] = { int register_android_graphics_Region(JNIEnv* env) { - jclass clazz = env->FindClass("android/graphics/Region"); - SkASSERT(clazz); + jclass clazz = FindClassOrDie(env, "android/graphics/Region"); - gRegion_nativeInstanceFieldID = env->GetFieldID(clazz, "mNativeRegion", "J"); - SkASSERT(gRegion_nativeInstanceFieldID); + gRegion_nativeInstanceFieldID = GetFieldIDOrDie(env, clazz, "mNativeRegion", "J"); - int result = android::AndroidRuntime::registerNativeMethods(env, "android/graphics/Region", - gRegionMethods, SK_ARRAY_COUNT(gRegionMethods)); - if (result < 0) - return result; - - return android::AndroidRuntime::registerNativeMethods(env, "android/graphics/RegionIterator", - gRegionIterMethods, SK_ARRAY_COUNT(gRegionIterMethods)); + RegisterMethodsOrDie(env, "android/graphics/Region", gRegionMethods, NELEM(gRegionMethods)); + return RegisterMethodsOrDie(env, "android/graphics/RegionIterator", gRegionIterMethods, + NELEM(gRegionIterMethods)); } SkRegion* android_graphics_Region_getSkRegion(JNIEnv* env, jobject regionObj) { diff --git a/core/jni/android/graphics/Region.h b/core/jni/android/graphics/Region.h index c15f06e..2e8e109 100644 --- a/core/jni/android/graphics/Region.h +++ b/core/jni/android/graphics/Region.h @@ -14,8 +14,8 @@ * limitations under the License. */ -#ifndef _ANDROID_GRAPHICS_REGION_H -#define _ANDROID_GRAPHICS_REGION_H +#ifndef _ANDROID_GRAPHICS_REGION_H_ +#define _ANDROID_GRAPHICS_REGION_H_ #include "jni.h" #include "SkRegion.h" @@ -27,4 +27,4 @@ extern SkRegion* android_graphics_Region_getSkRegion(JNIEnv* env, jobject region } // namespace android -#endif // _ANDROID_GRAPHICS_REGION_H +#endif // _ANDROID_GRAPHICS_REGION_H_ diff --git a/core/jni/android/graphics/RtlProperties.h b/core/jni/android/graphics/RtlProperties.h index d43745f..907dd59 100644 --- a/core/jni/android/graphics/RtlProperties.h +++ b/core/jni/android/graphics/RtlProperties.h @@ -14,8 +14,8 @@ * limitations under the License. */ -#ifndef ANDROID_RTL_PROPERTIES_H -#define ANDROID_RTL_PROPERTIES_H +#ifndef _ANDROID_GRAPHICS_RTL_PROPERTIES_H_ +#define _ANDROID_GRAPHICS_RTL_PROPERTIES_H_ #include <cutils/properties.h> #include <stdlib.h> @@ -45,11 +45,5 @@ static RtlDebugLevel readRtlDebugLevel() { return kRtlDebugDisabled; } -// Define if we want (1) to have Advances debug values or not (0) -#define DEBUG_ADVANCES 0 - -// Define if we want (1) to have Glyphs debug values or not (0) -#define DEBUG_GLYPHS 0 - } // namespace android -#endif // ANDROID_RTL_PROPERTIES_H +#endif // _ANDROID_GRAPHICS_RTL_PROPERTIES_H_ diff --git a/core/jni/android/graphics/Shader.cpp b/core/jni/android/graphics/Shader.cpp index 6146fff..9ec9c58 100644 --- a/core/jni/android/graphics/Shader.cpp +++ b/core/jni/android/graphics/Shader.cpp @@ -11,12 +11,9 @@ #include <SkiaShader.h> #include <Caches.h> -using namespace android::uirenderer; +#include "core_jni_helpers.h" -static struct { - jclass clazz; - jfieldID shader; -} gShaderClassInfo; +using namespace android::uirenderer; static void ThrowIAE_IfNull(JNIEnv* env, void* ptr) { if (NULL == ptr) { @@ -265,23 +262,22 @@ static JNINativeMethod gComposeShaderMethods[] = { { "nativeCreate2", "(JJI)J", (void*)ComposeShader_create2 }, }; -#include <android_runtime/AndroidRuntime.h> - -#define REG(env, name, array) \ - result = android::AndroidRuntime::registerNativeMethods(env, name, array, SK_ARRAY_COUNT(array)); \ - if (result < 0) return result - int register_android_graphics_Shader(JNIEnv* env) { - int result; - - REG(env, "android/graphics/Color", gColorMethods); - REG(env, "android/graphics/Shader", gShaderMethods); - REG(env, "android/graphics/BitmapShader", gBitmapShaderMethods); - REG(env, "android/graphics/LinearGradient", gLinearGradientMethods); - REG(env, "android/graphics/RadialGradient", gRadialGradientMethods); - REG(env, "android/graphics/SweepGradient", gSweepGradientMethods); - REG(env, "android/graphics/ComposeShader", gComposeShaderMethods); - - return result; + android::RegisterMethodsOrDie(env, "android/graphics/Color", gColorMethods, + NELEM(gColorMethods)); + android::RegisterMethodsOrDie(env, "android/graphics/Shader", gShaderMethods, + NELEM(gShaderMethods)); + android::RegisterMethodsOrDie(env, "android/graphics/BitmapShader", gBitmapShaderMethods, + NELEM(gBitmapShaderMethods)); + android::RegisterMethodsOrDie(env, "android/graphics/LinearGradient", gLinearGradientMethods, + NELEM(gLinearGradientMethods)); + android::RegisterMethodsOrDie(env, "android/graphics/RadialGradient", gRadialGradientMethods, + NELEM(gRadialGradientMethods)); + android::RegisterMethodsOrDie(env, "android/graphics/SweepGradient", gSweepGradientMethods, + NELEM(gSweepGradientMethods)); + android::RegisterMethodsOrDie(env, "android/graphics/ComposeShader", gComposeShaderMethods, + NELEM(gComposeShaderMethods)); + + return 0; } diff --git a/core/jni/android/graphics/SurfaceTexture.cpp b/core/jni/android/graphics/SurfaceTexture.cpp index eaca6d2..35d69fe 100644 --- a/core/jni/android/graphics/SurfaceTexture.cpp +++ b/core/jni/android/graphics/SurfaceTexture.cpp @@ -24,7 +24,7 @@ #include <gui/GLConsumer.h> #include <gui/Surface.h> -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" #include <utils/Log.h> #include <utils/misc.h> @@ -359,10 +359,8 @@ static JNINativeMethod gSurfaceTextureMethods[] = { int register_android_graphics_SurfaceTexture(JNIEnv* env) { - int err = 0; - err = AndroidRuntime::registerNativeMethods(env, kSurfaceTextureClassPathName, - gSurfaceTextureMethods, NELEM(gSurfaceTextureMethods)); - return err; + return RegisterMethodsOrDie(env, kSurfaceTextureClassPathName, gSurfaceTextureMethods, + NELEM(gSurfaceTextureMethods)); } } // namespace android diff --git a/core/jni/android/graphics/Typeface.cpp b/core/jni/android/graphics/Typeface.cpp index 2029658..808ae2c 100644 --- a/core/jni/android/graphics/Typeface.cpp +++ b/core/jni/android/graphics/Typeface.cpp @@ -15,7 +15,7 @@ */ #include "jni.h" -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" #include "GraphicsJNI.h" #include <ScopedPrimitiveArray.h> @@ -81,8 +81,6 @@ static JNINativeMethod gTypefaceMethods[] = { int register_android_graphics_Typeface(JNIEnv* env) { - return android::AndroidRuntime::registerNativeMethods(env, - "android/graphics/Typeface", - gTypefaceMethods, - SK_ARRAY_COUNT(gTypefaceMethods)); + return RegisterMethodsOrDie(env, "android/graphics/Typeface", gTypefaceMethods, + NELEM(gTypefaceMethods)); } diff --git a/core/jni/android/graphics/TypefaceImpl.h b/core/jni/android/graphics/TypefaceImpl.h index d129f62..d36f83a 100644 --- a/core/jni/android/graphics/TypefaceImpl.h +++ b/core/jni/android/graphics/TypefaceImpl.h @@ -15,8 +15,8 @@ */ -#ifndef ANDROID_TYPEFACE_IMPL_H -#define ANDROID_TYPEFACE_IMPL_H +#ifndef _ANDROID_GRAPHICS_TYPEFACE_IMPL_H_ +#define _ANDROID_GRAPHICS_TYPEFACE_IMPL_H_ #include "jni.h" // for jlong, eventually remove #include "SkTypeface.h" @@ -62,4 +62,4 @@ void TypefaceImpl_setDefault(TypefaceImpl* face); } -#endif // ANDROID_TYPEFACE_IMPL_H
\ No newline at end of file +#endif // _ANDROID_GRAPHICS_TYPEFACE_IMPL_H_
\ No newline at end of file diff --git a/core/jni/android/graphics/Utils.h b/core/jni/android/graphics/Utils.h index b90593c..bde87f0 100644 --- a/core/jni/android/graphics/Utils.h +++ b/core/jni/android/graphics/Utils.h @@ -14,8 +14,8 @@ * limitations under the License. */ -#ifndef UTILS_DEFINED -#define UTILS_DEFINED +#ifndef _ANDROID_GRAPHICS_UTILS_H_ +#define _ANDROID_GRAPHICS_UTILS_H_ #include "SkStream.h" @@ -89,4 +89,4 @@ jobject nullObjectReturn(const char msg[]); }; // namespace android -#endif +#endif // _ANDROID_GRAPHICS_UTILS_H_ diff --git a/core/jni/android/graphics/Xfermode.cpp b/core/jni/android/graphics/Xfermode.cpp index 6bf6f8a..5a3883a 100644 --- a/core/jni/android/graphics/Xfermode.cpp +++ b/core/jni/android/graphics/Xfermode.cpp @@ -16,7 +16,7 @@ #include "jni.h" #include "GraphicsJNI.h" -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" #include "SkAvoidXfermode.h" #include "SkPixelXorXfermode.h" @@ -59,19 +59,15 @@ static JNINativeMethod gPixelXorMethods[] = { {"nativeCreate", "(I)J", (void*) SkXfermodeGlue::pixelxor_create} }; -#include <android_runtime/AndroidRuntime.h> - -#define REG(env, name, array) \ - result = android::AndroidRuntime::registerNativeMethods(env, name, array, \ - SK_ARRAY_COUNT(array)); \ - if (result < 0) return result - int register_android_graphics_Xfermode(JNIEnv* env) { - int result; - - REG(env, "android/graphics/Xfermode", gXfermodeMethods); - REG(env, "android/graphics/AvoidXfermode", gAvoidMethods); - REG(env, "android/graphics/PixelXorXfermode", gPixelXorMethods); + android::RegisterMethodsOrDie(env, "android/graphics/Xfermode", gXfermodeMethods, + NELEM(gXfermodeMethods)); + android::RegisterMethodsOrDie(env, "android/graphics/Xfermode", gXfermodeMethods, + NELEM(gXfermodeMethods)); + android::RegisterMethodsOrDie(env, "android/graphics/AvoidXfermode", gAvoidMethods, + NELEM(gAvoidMethods)); + android::RegisterMethodsOrDie(env, "android/graphics/PixelXorXfermode", gPixelXorMethods, + NELEM(gPixelXorMethods)); return 0; } diff --git a/core/jni/android/graphics/YuvToJpegEncoder.cpp b/core/jni/android/graphics/YuvToJpegEncoder.cpp index 6591d60..5eede2a 100644 --- a/core/jni/android/graphics/YuvToJpegEncoder.cpp +++ b/core/jni/android/graphics/YuvToJpegEncoder.cpp @@ -4,6 +4,8 @@ #include <ui/PixelFormat.h> #include <hardware/hardware.h> +#include "core_jni_helpers.h" + #include <jni.h> YuvToJpegEncoder* YuvToJpegEncoder::create(int format, int* strides) { @@ -236,21 +238,18 @@ static jboolean YuvImage_compressToJpeg(JNIEnv* env, jobject, jbyteArray inYuv, env->ReleaseByteArrayElements(inYuv, yuv, 0); env->ReleaseIntArrayElements(offsets, imgOffsets, 0); env->ReleaseIntArrayElements(strides, imgStrides, 0); + delete strm; return result; } /////////////////////////////////////////////////////////////////////////////// -#include <android_runtime/AndroidRuntime.h> - static JNINativeMethod gYuvImageMethods[] = { { "nativeCompressToJpeg", "([BIII[I[IILjava/io/OutputStream;[B)Z", (void*)YuvImage_compressToJpeg } }; -#define kClassPathName "android/graphics/YuvImage" - int register_android_graphics_YuvImage(JNIEnv* env) { - return android::AndroidRuntime::registerNativeMethods(env, kClassPathName, - gYuvImageMethods, SK_ARRAY_COUNT(gYuvImageMethods)); + return android::RegisterMethodsOrDie(env, "android/graphics/YuvImage", gYuvImageMethods, + NELEM(gYuvImageMethods)); } diff --git a/core/jni/android/graphics/YuvToJpegEncoder.h b/core/jni/android/graphics/YuvToJpegEncoder.h index 0d418ed..1ea844a 100644 --- a/core/jni/android/graphics/YuvToJpegEncoder.h +++ b/core/jni/android/graphics/YuvToJpegEncoder.h @@ -1,5 +1,5 @@ -#ifndef YuvToJpegEncoder_DEFINED -#define YuvToJpegEncoder_DEFINED +#ifndef _ANDROID_GRAPHICS_YUV_TO_JPEG_ENCODER_H_ +#define _ANDROID_GRAPHICS_YUV_TO_JPEG_ENCODER_H_ #include "SkTypes.h" #include "SkStream.h" @@ -47,16 +47,16 @@ protected: class Yuv420SpToJpegEncoder : public YuvToJpegEncoder { public: - Yuv420SpToJpegEncoder(int* strides); - virtual ~Yuv420SpToJpegEncoder() {} + Yuv420SpToJpegEncoder(int* strides); + virtual ~Yuv420SpToJpegEncoder() {} private: - void configSamplingFactors(jpeg_compress_struct* cinfo); - void deinterleaveYuv(uint8_t* yuv, int width, int height, + void configSamplingFactors(jpeg_compress_struct* cinfo); + void deinterleaveYuv(uint8_t* yuv, int width, int height, uint8_t*& yPlanar, uint8_t*& uPlanar, uint8_t*& vPlanar); - void deinterleave(uint8_t* vuPlanar, uint8_t* uRows, uint8_t* vRows, - int rowIndex, int width, int height); - void compress(jpeg_compress_struct* cinfo, uint8_t* yuv, int* offsets); + void deinterleave(uint8_t* vuPlanar, uint8_t* uRows, uint8_t* vRows, + int rowIndex, int width, int height); + void compress(jpeg_compress_struct* cinfo, uint8_t* yuv, int* offsets); }; class Yuv422IToJpegEncoder : public YuvToJpegEncoder { @@ -71,4 +71,4 @@ private: uint8_t* vRows, int rowIndex, int width, int height); }; -#endif +#endif // _ANDROID_GRAPHICS_YUV_TO_JPEG_ENCODER_H_ diff --git a/core/jni/android/graphics/pdf/PdfDocument.cpp b/core/jni/android/graphics/pdf/PdfDocument.cpp index 9436a47..be90612 100644 --- a/core/jni/android/graphics/pdf/PdfDocument.cpp +++ b/core/jni/android/graphics/pdf/PdfDocument.cpp @@ -16,7 +16,7 @@ #include "jni.h" #include "GraphicsJNI.h" -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" #include <vector> #include "Canvas.h" @@ -164,10 +164,9 @@ static JNINativeMethod gPdfDocument_Methods[] = { }; int register_android_graphics_pdf_PdfDocument(JNIEnv* env) { - int result = android::AndroidRuntime::registerNativeMethods( + return RegisterMethodsOrDie( env, "android/graphics/pdf/PdfDocument", gPdfDocument_Methods, NELEM(gPdfDocument_Methods)); - return result; } }; diff --git a/core/jni/android/graphics/pdf/PdfEditor.cpp b/core/jni/android/graphics/pdf/PdfEditor.cpp index ed6f1d6..cb228f2 100644 --- a/core/jni/android/graphics/pdf/PdfEditor.cpp +++ b/core/jni/android/graphics/pdf/PdfEditor.cpp @@ -16,14 +16,19 @@ #include "jni.h" #include "JNIHelp.h" + +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdelete-non-virtual-dtor" #include "fpdfview.h" #include "fpdfedit.h" #include "fpdfsave.h" #include "fsdk_rendercontext.h" #include "fpdf_transformpage.h" +#pragma GCC diagnostic pop + #include "SkMatrix.h" -#include <android_runtime/AndroidRuntime.h> +#include <core_jni_helpers.h> #include <vector> #include <utils/Log.h> #include <unistd.h> @@ -92,12 +97,12 @@ static jlong nativeOpen(JNIEnv* env, jclass thiz, jint fd, jlong size) { switch (error) { case FPDF_ERR_PASSWORD: case FPDF_ERR_SECURITY: { - jniThrowException(env, "java/lang/SecurityException", - "cannot create document. Error:" + error); + jniThrowExceptionFmt(env, "java/lang/SecurityException", + "cannot create document. Error: %ld", error); } break; default: { - jniThrowException(env, "java/io/IOException", - "cannot create document. Error:" + error); + jniThrowExceptionFmt(env, "java/io/IOException", + "cannot create document. Error: %ld", error); } break; } destroyLibraryIfNeeded(); @@ -150,7 +155,7 @@ static bool writeAllBytes(const int fd, const void* buffer, const size_t byteCou static int writeBlock(FPDF_FILEWRITE* owner, const void* buffer, unsigned long size) { const PdfToFdWriter* writer = reinterpret_cast<PdfToFdWriter*>(owner); const bool success = writeAllBytes(writer->dstFd, buffer, size); - if (success < 0) { + if (!success) { ALOGE("Cannot write to file descriptor. Error:%d", errno); return 0; } @@ -164,8 +169,8 @@ static void nativeWrite(JNIEnv* env, jclass thiz, jlong documentPtr, jint fd) { writer.WriteBlock = &writeBlock; const bool success = FPDF_SaveAsCopy(document, &writer, FPDF_NO_INCREMENTAL); if (!success) { - jniThrowException(env, "java/io/IOException", - "cannot write to fd. Error:" + errno); + jniThrowExceptionFmt(env, "java/io/IOException", + "cannot write to fd. Error: %d", errno); destroyLibraryIfNeeded(); } } @@ -350,19 +355,19 @@ static JNINativeMethod gPdfEditor_Methods[] = { }; int register_android_graphics_pdf_PdfEditor(JNIEnv* env) { - const int result = android::AndroidRuntime::registerNativeMethods( + const int result = RegisterMethodsOrDie( env, "android/graphics/pdf/PdfEditor", gPdfEditor_Methods, NELEM(gPdfEditor_Methods)); - jclass pointClass = env->FindClass("android/graphics/Point"); - gPointClassInfo.x = env->GetFieldID(pointClass, "x", "I"); - gPointClassInfo.y = env->GetFieldID(pointClass, "y", "I"); + jclass pointClass = FindClassOrDie(env, "android/graphics/Point"); + gPointClassInfo.x = GetFieldIDOrDie(env, pointClass, "x", "I"); + gPointClassInfo.y = GetFieldIDOrDie(env, pointClass, "y", "I"); - jclass rectClass = env->FindClass("android/graphics/Rect"); - gRectClassInfo.left = env->GetFieldID(rectClass, "left", "I"); - gRectClassInfo.top = env->GetFieldID(rectClass, "top", "I"); - gRectClassInfo.right = env->GetFieldID(rectClass, "right", "I"); - gRectClassInfo.bottom = env->GetFieldID(rectClass, "bottom", "I"); + jclass rectClass = FindClassOrDie(env, "android/graphics/Rect"); + gRectClassInfo.left = GetFieldIDOrDie(env, rectClass, "left", "I"); + gRectClassInfo.top = GetFieldIDOrDie(env, rectClass, "top", "I"); + gRectClassInfo.right = GetFieldIDOrDie(env, rectClass, "right", "I"); + gRectClassInfo.bottom = GetFieldIDOrDie(env, rectClass, "bottom", "I"); return result; }; diff --git a/core/jni/android/graphics/pdf/PdfRenderer.cpp b/core/jni/android/graphics/pdf/PdfRenderer.cpp index 357d3c0..ae23cb4 100644 --- a/core/jni/android/graphics/pdf/PdfRenderer.cpp +++ b/core/jni/android/graphics/pdf/PdfRenderer.cpp @@ -20,9 +20,13 @@ #include "SkBitmap.h" #include "SkMatrix.h" #include "fpdfview.h" + +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdelete-non-virtual-dtor" #include "fsdk_rendercontext.h" +#pragma GCC diagnostic pop -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" #include <vector> #include <utils/Log.h> #include <unistd.h> @@ -85,12 +89,12 @@ static jlong nativeCreate(JNIEnv* env, jclass thiz, jint fd, jlong size) { switch (error) { case FPDF_ERR_PASSWORD: case FPDF_ERR_SECURITY: { - jniThrowException(env, "java/lang/SecurityException", - "cannot create document. Error:" + error); + jniThrowExceptionFmt(env, "java/lang/SecurityException", + "cannot create document. Error: %ld", error); } break; default: { - jniThrowException(env, "java/io/IOException", - "cannot create document. Error:" + error); + jniThrowExceptionFmt(env, "java/io/IOException", + "cannot create document. Error: %ld", error); } break; } destroyLibraryIfNeeded(); @@ -237,7 +241,6 @@ static void nativeRenderPage(JNIEnv* env, jclass thiz, jlong documentPtr, jlong jlong bitmapPtr, jint destLeft, jint destTop, jint destRight, jint destBottom, jlong matrixPtr, jint renderMode) { - FPDF_DOCUMENT document = reinterpret_cast<FPDF_DOCUMENT>(documentPtr); FPDF_PAGE page = reinterpret_cast<FPDF_PAGE>(pagePtr); SkBitmap* skBitmap = reinterpret_cast<SkBitmap*>(bitmapPtr); SkMatrix* skMatrix = reinterpret_cast<SkMatrix*>(matrixPtr); @@ -279,13 +282,13 @@ static JNINativeMethod gPdfRenderer_Methods[] = { }; int register_android_graphics_pdf_PdfRenderer(JNIEnv* env) { - int result = android::AndroidRuntime::registerNativeMethods( + int result = RegisterMethodsOrDie( env, "android/graphics/pdf/PdfRenderer", gPdfRenderer_Methods, NELEM(gPdfRenderer_Methods)); - jclass clazz = env->FindClass("android/graphics/Point"); - gPointClassInfo.x = env->GetFieldID(clazz, "x", "I"); - gPointClassInfo.y = env->GetFieldID(clazz, "y", "I"); + jclass clazz = FindClassOrDie(env, "android/graphics/Point"); + gPointClassInfo.x = GetFieldIDOrDie(env, clazz, "x", "I"); + gPointClassInfo.y = GetFieldIDOrDie(env, clazz, "y", "I"); return result; }; diff --git a/core/jni/android/opengl/poly_clip.cpp b/core/jni/android/opengl/poly_clip.cpp index 04e4b17..5c65220 100644 --- a/core/jni/android/opengl/poly_clip.cpp +++ b/core/jni/android/opengl/poly_clip.cpp @@ -58,7 +58,6 @@ namespace android { void poly_clip_to_halfspace(Poly* p, Poly* q, int index, float sign, float k) { - unsigned long m; float *up, *vp, *wp; Poly_vert *v; int i; diff --git a/core/jni/android/opengl/util.cpp b/core/jni/android/opengl/util.cpp index 89baef8..da30044 100644 --- a/core/jni/android/opengl/util.cpp +++ b/core/jni/android/opengl/util.cpp @@ -29,7 +29,7 @@ #include <SkBitmap.h> -#include "android_runtime/AndroidRuntime.h" +#include "core_jni_helpers.h" #undef LOG_TAG #define LOG_TAG "OpenGLUtil" @@ -471,13 +471,13 @@ static void multiplyMM(float* r, const float* lhs, const float* rhs) { for (int i=0 ; i<4 ; i++) { - register const float rhs_i0 = rhs[ I(i,0) ]; - register float ri0 = lhs[ I(0,0) ] * rhs_i0; - register float ri1 = lhs[ I(0,1) ] * rhs_i0; - register float ri2 = lhs[ I(0,2) ] * rhs_i0; - register float ri3 = lhs[ I(0,3) ] * rhs_i0; + const float rhs_i0 = rhs[ I(i,0) ]; + float ri0 = lhs[ I(0,0) ] * rhs_i0; + float ri1 = lhs[ I(0,1) ] * rhs_i0; + float ri2 = lhs[ I(0,2) ] * rhs_i0; + float ri3 = lhs[ I(0,3) ] * rhs_i0; for (int j=1 ; j<4 ; j++) { - register const float rhs_ij = rhs[ I(i,j) ]; + const float rhs_ij = rhs[ I(i,j) ]; ri0 += lhs[ I(j,0) ] * rhs_ij; ri1 += lhs[ I(j,1) ] * rhs_ij; ri2 += lhs[ I(j,2) ] * rhs_ij; @@ -732,24 +732,22 @@ static jfieldID elementSizeShiftID; /* Cache method IDs each time the class is loaded. */ static void -nativeClassInitBuffer(JNIEnv *_env) +nativeClassInitBuffer(JNIEnv *env) { - jclass nioAccessClassLocal = _env->FindClass("java/nio/NIOAccess"); - nioAccessClass = (jclass) _env->NewGlobalRef(nioAccessClassLocal); - - jclass bufferClassLocal = _env->FindClass("java/nio/Buffer"); - bufferClass = (jclass) _env->NewGlobalRef(bufferClassLocal); - - getBasePointerID = _env->GetStaticMethodID(nioAccessClass, + jclass nioAccessClassLocal = FindClassOrDie(env, "java/nio/NIOAccess"); + nioAccessClass = MakeGlobalRefOrDie(env, nioAccessClassLocal); + getBasePointerID = GetStaticMethodIDOrDie(env, nioAccessClass, "getBasePointer", "(Ljava/nio/Buffer;)J"); - getBaseArrayID = _env->GetStaticMethodID(nioAccessClass, + getBaseArrayID = GetStaticMethodIDOrDie(env, nioAccessClass, "getBaseArray", "(Ljava/nio/Buffer;)Ljava/lang/Object;"); - getBaseArrayOffsetID = _env->GetStaticMethodID(nioAccessClass, + getBaseArrayOffsetID = GetStaticMethodIDOrDie(env, nioAccessClass, "getBaseArrayOffset", "(Ljava/nio/Buffer;)I"); - positionID = _env->GetFieldID(bufferClass, "position", "I"); - limitID = _env->GetFieldID(bufferClass, "limit", "I"); - elementSizeShiftID = - _env->GetFieldID(bufferClass, "_elementSizeShift", "I"); + + jclass bufferClassLocal = FindClassOrDie(env, "java/nio/Buffer"); + bufferClass = MakeGlobalRefOrDie(env, bufferClassLocal); + positionID = GetFieldIDOrDie(env, bufferClass, "position", "I"); + limitID = GetFieldIDOrDie(env, bufferClass, "limit", "I"); + elementSizeShiftID = GetFieldIDOrDie(env, bufferClass, "_elementSizeShift", "I"); } static void * @@ -759,8 +757,6 @@ getPointer(JNIEnv *_env, jobject buffer, jint *remaining) jint limit; jint elementSizeShift; jlong pointer; - jint offset; - void *data; position = _env->GetIntField(buffer, positionID); limit = _env->GetIntField(buffer, limitID); @@ -900,10 +896,8 @@ static void etc1_encodeImage(JNIEnv *env, jclass clazz, } else if (outB.remaining() < encodedImageSize) { doThrowIAE(env, "out's remaining data < encoded image size"); } else { - int result = etc1_encode_image((etc1_byte*) inB.getData(), - width, height, pixelSize, - stride, - (etc1_byte*) outB.getData()); + etc1_encode_image((etc1_byte*) inB.getData(), width, height, pixelSize, stride, + (etc1_byte*) outB.getData()); } } } @@ -933,10 +927,8 @@ static void etc1_decodeImage(JNIEnv *env, jclass clazz, } else if (outB.remaining() < imageSize) { doThrowIAE(env, "out's remaining data < image size"); } else { - int result = etc1_decode_image((etc1_byte*) inB.getData(), - (etc1_byte*) outB.getData(), - width, height, pixelSize, - stride); + etc1_decode_image((etc1_byte*) inB.getData(), (etc1_byte*) outB.getData(), + width, height, pixelSize, stride); } } } @@ -1062,12 +1054,7 @@ int register_android_opengl_classes(JNIEnv* env) int result = 0; for (int i = 0; i < NELEM(gClasses); i++) { ClassRegistrationInfo* cri = &gClasses[i]; - result = AndroidRuntime::registerNativeMethods(env, - cri->classPath, cri->methods, cri->methodCount); - if (result < 0) { - ALOGE("Failed to register %s: %d", cri->classPath, result); - break; - } + result = RegisterMethodsOrDie(env, cri->classPath, cri->methods, cri->methodCount); } return result; } diff --git a/core/jni/android_animation_PropertyValuesHolder.cpp b/core/jni/android_animation_PropertyValuesHolder.cpp index ef1c4ed..d117741 100644 --- a/core/jni/android_animation_PropertyValuesHolder.cpp +++ b/core/jni/android_animation_PropertyValuesHolder.cpp @@ -18,7 +18,7 @@ #include <assert.h> #include "jni.h" -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" #include <utils/misc.h> // ---------------------------------------------------------------------------- @@ -168,8 +168,7 @@ static JNINativeMethod gMethods[] = { int register_android_animation_PropertyValuesHolder(JNIEnv* env) { - return AndroidRuntime::registerNativeMethods(env, - kClassPathName, gMethods, NELEM(gMethods)); + return RegisterMethodsOrDie(env, kClassPathName, gMethods, NELEM(gMethods)); } }; diff --git a/core/jni/android_app_NativeActivity.cpp b/core/jni/android_app_NativeActivity.cpp index 633a207..95be3f2 100644 --- a/core/jni/android_app_NativeActivity.cpp +++ b/core/jni/android_app_NativeActivity.cpp @@ -40,12 +40,17 @@ #include "nativebridge/native_bridge.h" +#include "core_jni_helpers.h" + + #define LOG_TRACE(...) //#define LOG_TRACE(...) ALOG(LOG_DEBUG, LOG_TAG, __VA_ARGS__) namespace android { +static const bool kLogTrace = false; + static struct { jmethodID finish; jmethodID setWindowFlags; @@ -75,8 +80,10 @@ static void write_work(int fd, int32_t cmd, int32_t arg1=0, int32_t arg2=0) { work.cmd = cmd; work.arg1 = arg1; work.arg2 = arg2; - - LOG_TRACE("write_work: cmd=%d", cmd); + + if (kLogTrace) { + ALOGD("write_work: cmd=%d", cmd); + } restart: int res = write(fd, &work, sizeof(work)); @@ -206,7 +213,9 @@ static int mainWorkCallback(int fd, int events, void* data) { return 1; } - LOG_TRACE("mainWorkCallback: cmd=%d", work.cmd); + if (kLogTrace) { + ALOGD("mainWorkCallback: cmd=%d", work.cmd); + } switch (work.cmd) { case CMD_FINISH: { @@ -249,7 +258,9 @@ loadNativeCode_native(JNIEnv* env, jobject clazz, jstring path, jstring funcName jstring externalDataDir, jint sdkVersion, jobject jAssetMgr, jbyteArray savedState) { - LOG_TRACE("loadNativeCode_native"); + if (kLogTrace) { + ALOGD("loadNativeCode_native"); + } const char* pathStr = env->GetStringUTFChars(path, NULL); NativeCode* code = NULL; @@ -358,7 +369,9 @@ loadNativeCode_native(JNIEnv* env, jobject clazz, jstring path, jstring funcName static void unloadNativeCode_native(JNIEnv* env, jobject clazz, jlong handle) { - LOG_TRACE("unloadNativeCode_native"); + if (kLogTrace) { + ALOGD("unloadNativeCode_native"); + } if (handle != 0) { NativeCode* code = (NativeCode*)handle; delete code; @@ -368,7 +381,9 @@ unloadNativeCode_native(JNIEnv* env, jobject clazz, jlong handle) static void onStart_native(JNIEnv* env, jobject clazz, jlong handle) { - LOG_TRACE("onStart_native"); + if (kLogTrace) { + ALOGD("onStart_native"); + } if (handle != 0) { NativeCode* code = (NativeCode*)handle; if (code->callbacks.onStart != NULL) { @@ -380,7 +395,9 @@ onStart_native(JNIEnv* env, jobject clazz, jlong handle) static void onResume_native(JNIEnv* env, jobject clazz, jlong handle) { - LOG_TRACE("onResume_native"); + if (kLogTrace) { + ALOGD("onResume_native"); + } if (handle != 0) { NativeCode* code = (NativeCode*)handle; if (code->callbacks.onResume != NULL) { @@ -392,7 +409,9 @@ onResume_native(JNIEnv* env, jobject clazz, jlong handle) static jbyteArray onSaveInstanceState_native(JNIEnv* env, jobject clazz, jlong handle) { - LOG_TRACE("onSaveInstanceState_native"); + if (kLogTrace) { + ALOGD("onSaveInstanceState_native"); + } jbyteArray array = NULL; @@ -419,7 +438,9 @@ onSaveInstanceState_native(JNIEnv* env, jobject clazz, jlong handle) static void onPause_native(JNIEnv* env, jobject clazz, jlong handle) { - LOG_TRACE("onPause_native"); + if (kLogTrace) { + ALOGD("onPause_native"); + } if (handle != 0) { NativeCode* code = (NativeCode*)handle; if (code->callbacks.onPause != NULL) { @@ -431,7 +452,9 @@ onPause_native(JNIEnv* env, jobject clazz, jlong handle) static void onStop_native(JNIEnv* env, jobject clazz, jlong handle) { - LOG_TRACE("onStop_native"); + if (kLogTrace) { + ALOGD("onStop_native"); + } if (handle != 0) { NativeCode* code = (NativeCode*)handle; if (code->callbacks.onStop != NULL) { @@ -443,7 +466,9 @@ onStop_native(JNIEnv* env, jobject clazz, jlong handle) static void onConfigurationChanged_native(JNIEnv* env, jobject clazz, jlong handle) { - LOG_TRACE("onConfigurationChanged_native"); + if (kLogTrace) { + ALOGD("onConfigurationChanged_native"); + } if (handle != 0) { NativeCode* code = (NativeCode*)handle; if (code->callbacks.onConfigurationChanged != NULL) { @@ -455,7 +480,9 @@ onConfigurationChanged_native(JNIEnv* env, jobject clazz, jlong handle) static void onLowMemory_native(JNIEnv* env, jobject clazz, jlong handle) { - LOG_TRACE("onLowMemory_native"); + if (kLogTrace) { + ALOGD("onLowMemory_native"); + } if (handle != 0) { NativeCode* code = (NativeCode*)handle; if (code->callbacks.onLowMemory != NULL) { @@ -467,7 +494,9 @@ onLowMemory_native(JNIEnv* env, jobject clazz, jlong handle) static void onWindowFocusChanged_native(JNIEnv* env, jobject clazz, jlong handle, jboolean focused) { - LOG_TRACE("onWindowFocusChanged_native"); + if (kLogTrace) { + ALOGD("onWindowFocusChanged_native"); + } if (handle != 0) { NativeCode* code = (NativeCode*)handle; if (code->callbacks.onWindowFocusChanged != NULL) { @@ -479,7 +508,9 @@ onWindowFocusChanged_native(JNIEnv* env, jobject clazz, jlong handle, jboolean f static void onSurfaceCreated_native(JNIEnv* env, jobject clazz, jlong handle, jobject surface) { - LOG_TRACE("onSurfaceCreated_native"); + if (kLogTrace) { + ALOGD("onSurfaceCreated_native"); + } if (handle != 0) { NativeCode* code = (NativeCode*)handle; code->setSurface(surface); @@ -500,7 +531,9 @@ static void onSurfaceChanged_native(JNIEnv* env, jobject clazz, jlong handle, jobject surface, jint format, jint width, jint height) { - LOG_TRACE("onSurfaceChanged_native"); + if (kLogTrace) { + ALOGD("onSurfaceChanged_native"); + } if (handle != 0) { NativeCode* code = (NativeCode*)handle; sp<ANativeWindow> oldNativeWindow = code->nativeWindow; @@ -540,7 +573,9 @@ onSurfaceChanged_native(JNIEnv* env, jobject clazz, jlong handle, jobject surfac static void onSurfaceRedrawNeeded_native(JNIEnv* env, jobject clazz, jlong handle) { - LOG_TRACE("onSurfaceRedrawNeeded_native"); + if (kLogTrace) { + ALOGD("onSurfaceRedrawNeeded_native"); + } if (handle != 0) { NativeCode* code = (NativeCode*)handle; if (code->nativeWindow != NULL && code->callbacks.onNativeWindowRedrawNeeded != NULL) { @@ -552,7 +587,9 @@ onSurfaceRedrawNeeded_native(JNIEnv* env, jobject clazz, jlong handle) static void onSurfaceDestroyed_native(JNIEnv* env, jobject clazz, jlong handle, jobject surface) { - LOG_TRACE("onSurfaceDestroyed_native"); + if (kLogTrace) { + ALOGD("onSurfaceDestroyed_native"); + } if (handle != 0) { NativeCode* code = (NativeCode*)handle; if (code->nativeWindow != NULL && code->callbacks.onNativeWindowDestroyed != NULL) { @@ -566,7 +603,9 @@ onSurfaceDestroyed_native(JNIEnv* env, jobject clazz, jlong handle, jobject surf static void onInputQueueCreated_native(JNIEnv* env, jobject clazz, jlong handle, jlong queuePtr) { - LOG_TRACE("onInputChannelCreated_native"); + if (kLogTrace) { + ALOGD("onInputChannelCreated_native"); + } if (handle != 0) { NativeCode* code = (NativeCode*)handle; if (code->callbacks.onInputQueueCreated != NULL) { @@ -579,7 +618,9 @@ onInputQueueCreated_native(JNIEnv* env, jobject clazz, jlong handle, jlong queue static void onInputQueueDestroyed_native(JNIEnv* env, jobject clazz, jlong handle, jlong queuePtr) { - LOG_TRACE("onInputChannelDestroyed_native"); + if (kLogTrace) { + ALOGD("onInputChannelDestroyed_native"); + } if (handle != 0) { NativeCode* code = (NativeCode*)handle; if (code->callbacks.onInputQueueDestroyed != NULL) { @@ -593,7 +634,9 @@ static void onContentRectChanged_native(JNIEnv* env, jobject clazz, jlong handle, jint x, jint y, jint w, jint h) { - LOG_TRACE("onContentRectChanged_native"); + if (kLogTrace) { + ALOGD("onContentRectChanged_native"); + } if (handle != 0) { NativeCode* code = (NativeCode*)handle; if (code->callbacks.onContentRectChanged != NULL) { @@ -632,39 +675,20 @@ static const JNINativeMethod g_methods[] = { static const char* const kNativeActivityPathName = "android/app/NativeActivity"; -#define FIND_CLASS(var, className) \ - var = env->FindClass(className); \ - LOG_FATAL_IF(! var, "Unable to find class %s", className); - -#define GET_METHOD_ID(var, clazz, methodName, fieldDescriptor) \ - var = env->GetMethodID(clazz, methodName, fieldDescriptor); \ - LOG_FATAL_IF(! var, "Unable to find method" methodName); - int register_android_app_NativeActivity(JNIEnv* env) { //ALOGD("register_android_app_NativeActivity"); - jclass clazz; - FIND_CLASS(clazz, kNativeActivityPathName); - - GET_METHOD_ID(gNativeActivityClassInfo.finish, - clazz, - "finish", "()V"); - GET_METHOD_ID(gNativeActivityClassInfo.setWindowFlags, - clazz, - "setWindowFlags", "(II)V"); - GET_METHOD_ID(gNativeActivityClassInfo.setWindowFormat, - clazz, - "setWindowFormat", "(I)V"); - GET_METHOD_ID(gNativeActivityClassInfo.showIme, - clazz, - "showIme", "(I)V"); - GET_METHOD_ID(gNativeActivityClassInfo.hideIme, - clazz, - "hideIme", "(I)V"); - - return AndroidRuntime::registerNativeMethods( - env, kNativeActivityPathName, - g_methods, NELEM(g_methods)); + jclass clazz = FindClassOrDie(env, kNativeActivityPathName); + + gNativeActivityClassInfo.finish = GetMethodIDOrDie(env, clazz, "finish", "()V"); + gNativeActivityClassInfo.setWindowFlags = GetMethodIDOrDie(env, clazz, "setWindowFlags", + "(II)V"); + gNativeActivityClassInfo.setWindowFormat = GetMethodIDOrDie(env, clazz, "setWindowFormat", + "(I)V"); + gNativeActivityClassInfo.showIme = GetMethodIDOrDie(env, clazz, "showIme", "(I)V"); + gNativeActivityClassInfo.hideIme = GetMethodIDOrDie(env, clazz, "hideIme", "(I)V"); + + return RegisterMethodsOrDie(env, kNativeActivityPathName, g_methods, NELEM(g_methods)); } } // namespace android diff --git a/core/jni/android_app_backup_FullBackup.cpp b/core/jni/android_app_backup_FullBackup.cpp index 3cfaa82..2c02b37 100644 --- a/core/jni/android_app_backup_FullBackup.cpp +++ b/core/jni/android_app_backup_FullBackup.cpp @@ -23,6 +23,8 @@ #include <androidfw/BackupHelpers.h> +#include "core_jni_helpers.h" + #include <string.h> namespace android @@ -73,8 +75,6 @@ static struct { static jint backupToTar(JNIEnv* env, jobject clazz, jstring packageNameObj, jstring domainObj, jstring linkdomain, jstring rootpathObj, jstring pathObj, jobject dataOutputObj) { - int ret; - // Extract the various strings, allowing for null object pointers const char* packagenamechars = (packageNameObj) ? env->GetStringUTFChars(packageNameObj, NULL) : NULL; const char* rootchars = (rootpathObj) ? env->GetStringUTFChars(rootpathObj, NULL) : NULL; @@ -118,15 +118,11 @@ static const JNINativeMethod g_methods[] = { int register_android_app_backup_FullBackup(JNIEnv* env) { - jclass clazz = env->FindClass("android/app/backup/BackupDataOutput"); - LOG_FATAL_IF(clazz == NULL, "Unable to find class android.app.backup.BackupDataOutput"); + jclass clazz = FindClassOrDie(env, "android/app/backup/BackupDataOutput"); - sBackupDataOutput.mBackupWriter = env->GetFieldID(clazz, "mBackupWriter", "J"); - LOG_FATAL_IF(sBackupDataOutput.mBackupwriter == NULL, - "Unable to find mBackupWriter field in android.app.backup.BackupDataOutput"); + sBackupDataOutput.mBackupWriter = GetFieldIDOrDie(env, clazz, "mBackupWriter", "J"); - return AndroidRuntime::registerNativeMethods(env, "android/app/backup/FullBackup", - g_methods, NELEM(g_methods)); + return RegisterMethodsOrDie(env, "android/app/backup/FullBackup", g_methods, NELEM(g_methods)); } } diff --git a/core/jni/android_backup_BackupDataInput.cpp b/core/jni/android_backup_BackupDataInput.cpp index 90763b0..096a784 100644 --- a/core/jni/android_backup_BackupDataInput.cpp +++ b/core/jni/android_backup_BackupDataInput.cpp @@ -22,6 +22,8 @@ #include <androidfw/BackupHelpers.h> +#include "core_jni_helpers.h" + namespace android { @@ -135,17 +137,12 @@ int register_android_backup_BackupDataInput(JNIEnv* env) { //ALOGD("register_android_backup_BackupDataInput"); - jclass clazz = env->FindClass("android/app/backup/BackupDataInput$EntityHeader"); - LOG_FATAL_IF(clazz == NULL, "Unable to find class android.app.backup.BackupDataInput.EntityHeader"); - s_keyField = env->GetFieldID(clazz, "key", "Ljava/lang/String;"); - LOG_FATAL_IF(s_keyField == NULL, - "Unable to find key field in android.app.backup.BackupDataInput.EntityHeader"); - s_dataSizeField = env->GetFieldID(clazz, "dataSize", "I"); - LOG_FATAL_IF(s_dataSizeField == NULL, - "Unable to find dataSize field in android.app.backup.BackupDataInput.EntityHeader"); - - return AndroidRuntime::registerNativeMethods(env, "android/app/backup/BackupDataInput", - g_methods, NELEM(g_methods)); + jclass clazz = FindClassOrDie(env, "android/app/backup/BackupDataInput$EntityHeader"); + s_keyField = GetFieldIDOrDie(env, clazz, "key", "Ljava/lang/String;"); + s_dataSizeField = GetFieldIDOrDie(env, clazz, "dataSize", "I"); + + return RegisterMethodsOrDie(env, "android/app/backup/BackupDataInput", g_methods, + NELEM(g_methods)); } } diff --git a/core/jni/android_backup_BackupDataOutput.cpp b/core/jni/android_backup_BackupDataOutput.cpp index 8244e1b..a7894f4 100644 --- a/core/jni/android_backup_BackupDataOutput.cpp +++ b/core/jni/android_backup_BackupDataOutput.cpp @@ -18,7 +18,7 @@ #include <utils/Log.h> #include "JNIHelp.h" -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" #include <androidfw/BackupHelpers.h> @@ -85,7 +85,6 @@ writeEntityData_native(JNIEnv* env, jobject clazz, jlong w, jbyteArray data, jin static void setKeyPrefix_native(JNIEnv* env, jobject clazz, jlong w, jstring keyPrefixObj) { - int err; BackupDataWriter* writer = (BackupDataWriter*)w; const char* keyPrefixUTF = env->GetStringUTFChars(keyPrefixObj, NULL); @@ -107,7 +106,7 @@ static const JNINativeMethod g_methods[] = { int register_android_backup_BackupDataOutput(JNIEnv* env) { //ALOGD("register_android_backup_BackupDataOutput"); - return AndroidRuntime::registerNativeMethods(env, "android/app/backup/BackupDataOutput", + return RegisterMethodsOrDie(env, "android/app/backup/BackupDataOutput", g_methods, NELEM(g_methods)); } diff --git a/core/jni/android_backup_BackupHelperDispatcher.cpp b/core/jni/android_backup_BackupHelperDispatcher.cpp index a8b7d44..80bdaf8 100644 --- a/core/jni/android_backup_BackupHelperDispatcher.cpp +++ b/core/jni/android_backup_BackupHelperDispatcher.cpp @@ -24,6 +24,7 @@ #include <sys/uio.h> #include <unistd.h> +#include "core_jni_helpers.h" #define VERSION_1_HEADER 0x01706c48 // 'Hlp'1 little endian @@ -227,18 +228,12 @@ static const JNINativeMethod g_methods[] = { int register_android_backup_BackupHelperDispatcher(JNIEnv* env) { - jclass clazz = env->FindClass("android/app/backup/BackupHelperDispatcher$Header"); - LOG_FATAL_IF(clazz == NULL, - "Unable to find class android.app.backup.BackupHelperDispatcher.Header"); - s_chunkSizeField = env->GetFieldID(clazz, "chunkSize", "I"); - LOG_FATAL_IF(s_chunkSizeField == NULL, - "Unable to find chunkSize field in android.app.backup.BackupHelperDispatcher.Header"); - s_keyPrefixField = env->GetFieldID(clazz, "keyPrefix", "Ljava/lang/String;"); - LOG_FATAL_IF(s_keyPrefixField == NULL, - "Unable to find keyPrefix field in android.app.backup.BackupHelperDispatcher.Header"); - - return AndroidRuntime::registerNativeMethods(env, "android/app/backup/BackupHelperDispatcher", - g_methods, NELEM(g_methods)); + jclass clazz = FindClassOrDie(env, "android/app/backup/BackupHelperDispatcher$Header"); + s_chunkSizeField = GetFieldIDOrDie(env, clazz, "chunkSize", "I"); + s_keyPrefixField = GetFieldIDOrDie(env, clazz, "keyPrefix", "Ljava/lang/String;"); + + return RegisterMethodsOrDie(env, "android/app/backup/BackupHelperDispatcher", g_methods, + NELEM(g_methods)); } } diff --git a/core/jni/android_backup_FileBackupHelperBase.cpp b/core/jni/android_backup_FileBackupHelperBase.cpp index 66e3e9d..6d6ac1b 100644 --- a/core/jni/android_backup_FileBackupHelperBase.cpp +++ b/core/jni/android_backup_FileBackupHelperBase.cpp @@ -18,7 +18,7 @@ #include <utils/Log.h> #include "JNIHelp.h" -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" #include <androidfw/BackupHelpers.h> @@ -118,7 +118,7 @@ static const JNINativeMethod g_methods[] = { int register_android_backup_FileBackupHelperBase(JNIEnv* env) { - return AndroidRuntime::registerNativeMethods(env, "android/app/backup/FileBackupHelperBase", + return RegisterMethodsOrDie(env, "android/app/backup/FileBackupHelperBase", g_methods, NELEM(g_methods)); } diff --git a/core/jni/android_content_res_Configuration.cpp b/core/jni/android_content_res_Configuration.cpp index 201ffe8..3b45e72 100644 --- a/core/jni/android_content_res_Configuration.cpp +++ b/core/jni/android_content_res_Configuration.cpp @@ -23,6 +23,8 @@ #include <android_runtime/android_content_res_Configuration.h> #include "android_runtime/AndroidRuntime.h" +#include "core_jni_helpers.h" + namespace android { static struct { @@ -70,49 +72,27 @@ void android_Configuration_getFromJava( gConfigurationClassInfo.smallestScreenWidthDp); } -#define FIND_CLASS(var, className) \ - var = env->FindClass(className); \ - LOG_FATAL_IF(! var, "Unable to find class " className); - -#define GET_FIELD_ID(var, clazz, fieldName, fieldDescriptor) \ - var = env->GetFieldID(clazz, fieldName, fieldDescriptor); \ - LOG_FATAL_IF(! var, "Unable to find field " fieldName); - int register_android_content_res_Configuration(JNIEnv* env) { - jclass clazz; - FIND_CLASS(clazz, "android/content/res/Configuration"); + jclass clazz = FindClassOrDie(env, "android/content/res/Configuration"); - GET_FIELD_ID(gConfigurationClassInfo.mcc, clazz, - "mcc", "I"); - GET_FIELD_ID(gConfigurationClassInfo.mnc, clazz, - "mnc", "I"); - GET_FIELD_ID(gConfigurationClassInfo.locale, clazz, - "locale", "Ljava/util/Locale;"); - GET_FIELD_ID(gConfigurationClassInfo.screenLayout, clazz, - "screenLayout", "I"); - GET_FIELD_ID(gConfigurationClassInfo.touchscreen, clazz, - "touchscreen", "I"); - GET_FIELD_ID(gConfigurationClassInfo.keyboard, clazz, - "keyboard", "I"); - GET_FIELD_ID(gConfigurationClassInfo.keyboardHidden, clazz, - "keyboardHidden", "I"); - GET_FIELD_ID(gConfigurationClassInfo.hardKeyboardHidden, clazz, - "hardKeyboardHidden", "I"); - GET_FIELD_ID(gConfigurationClassInfo.navigation, clazz, - "navigation", "I"); - GET_FIELD_ID(gConfigurationClassInfo.navigationHidden, clazz, - "navigationHidden", "I"); - GET_FIELD_ID(gConfigurationClassInfo.orientation, clazz, - "orientation", "I"); - GET_FIELD_ID(gConfigurationClassInfo.uiMode, clazz, - "uiMode", "I"); - GET_FIELD_ID(gConfigurationClassInfo.screenWidthDp, clazz, - "screenWidthDp", "I"); - GET_FIELD_ID(gConfigurationClassInfo.screenHeightDp, clazz, - "screenHeightDp", "I"); - GET_FIELD_ID(gConfigurationClassInfo.smallestScreenWidthDp, clazz, - "smallestScreenWidthDp", "I"); + gConfigurationClassInfo.mcc = GetFieldIDOrDie(env, clazz, "mcc", "I"); + gConfigurationClassInfo.mnc = GetFieldIDOrDie(env, clazz, "mnc", "I"); + gConfigurationClassInfo.locale = GetFieldIDOrDie(env, clazz, "locale", "Ljava/util/Locale;"); + gConfigurationClassInfo.screenLayout = GetFieldIDOrDie(env, clazz, "screenLayout", "I"); + gConfigurationClassInfo.touchscreen = GetFieldIDOrDie(env, clazz, "touchscreen", "I"); + gConfigurationClassInfo.keyboard = GetFieldIDOrDie(env, clazz, "keyboard", "I"); + gConfigurationClassInfo.keyboardHidden = GetFieldIDOrDie(env, clazz, "keyboardHidden", "I"); + gConfigurationClassInfo.hardKeyboardHidden = GetFieldIDOrDie(env, clazz, "hardKeyboardHidden", + "I"); + gConfigurationClassInfo.navigation = GetFieldIDOrDie(env, clazz, "navigation", "I"); + gConfigurationClassInfo.navigationHidden = GetFieldIDOrDie(env, clazz, "navigationHidden", "I"); + gConfigurationClassInfo.orientation = GetFieldIDOrDie(env, clazz, "orientation", "I"); + gConfigurationClassInfo.uiMode = GetFieldIDOrDie(env, clazz, "uiMode", "I"); + gConfigurationClassInfo.screenWidthDp = GetFieldIDOrDie(env, clazz, "screenWidthDp", "I"); + gConfigurationClassInfo.screenHeightDp = GetFieldIDOrDie(env, clazz, "screenHeightDp", "I"); + gConfigurationClassInfo.smallestScreenWidthDp = GetFieldIDOrDie(env, clazz, + "smallestScreenWidthDp", "I"); return 0; } diff --git a/core/jni/android_content_res_ObbScanner.cpp b/core/jni/android_content_res_ObbScanner.cpp index 5d51ee2..ef17db6 100644 --- a/core/jni/android_content_res_ObbScanner.cpp +++ b/core/jni/android_content_res_ObbScanner.cpp @@ -25,6 +25,8 @@ #include "utils/misc.h" #include "android_runtime/AndroidRuntime.h" +#include "core_jni_helpers.h" + namespace android { static struct { @@ -80,30 +82,17 @@ static JNINativeMethod gMethods[] = { (void*) android_content_res_ObbScanner_getObbInfo }, }; -#define FIND_CLASS(var, className) \ - var = env->FindClass(className); \ - LOG_FATAL_IF(! var, "Unable to find class " className); - -#define GET_FIELD_ID(var, clazz, fieldName, fieldDescriptor) \ - var = env->GetFieldID(clazz, fieldName, fieldDescriptor); \ - LOG_FATAL_IF(! var, "Unable to find field " fieldName); - int register_android_content_res_ObbScanner(JNIEnv* env) { - jclass clazz; - FIND_CLASS(clazz, "android/content/res/ObbInfo"); - - GET_FIELD_ID(gObbInfoClassInfo.packageName, clazz, - "packageName", "Ljava/lang/String;"); - GET_FIELD_ID(gObbInfoClassInfo.version, clazz, - "version", "I"); - GET_FIELD_ID(gObbInfoClassInfo.flags, clazz, - "flags", "I"); - GET_FIELD_ID(gObbInfoClassInfo.salt, clazz, - "salt", "[B"); - - return AndroidRuntime::registerNativeMethods(env, "android/content/res/ObbScanner", gMethods, - NELEM(gMethods)); + jclass clazz = FindClassOrDie(env, "android/content/res/ObbInfo"); + + gObbInfoClassInfo.packageName = GetFieldIDOrDie(env, clazz, "packageName", + "Ljava/lang/String;"); + gObbInfoClassInfo.version = GetFieldIDOrDie(env, clazz, "version", "I"); + gObbInfoClassInfo.flags = GetFieldIDOrDie(env, clazz, "flags", "I"); + gObbInfoClassInfo.salt = GetFieldIDOrDie(env, clazz, "salt", "[B"); + + return RegisterMethodsOrDie(env, "android/content/res/ObbScanner", gMethods, NELEM(gMethods)); } }; // namespace android diff --git a/core/jni/android_database_CursorWindow.cpp b/core/jni/android_database_CursorWindow.cpp index af6cc72..580ac02 100644 --- a/core/jni/android_database_CursorWindow.cpp +++ b/core/jni/android_database_CursorWindow.cpp @@ -36,6 +36,8 @@ #include "android_util_Binder.h" #include "android_database_SQLiteCommon.h" +#include "core_jni_helpers.h" + namespace android { static struct { @@ -522,29 +524,16 @@ static JNINativeMethod sMethods[] = (void*)nativePutNull }, }; -#define FIND_CLASS(var, className) \ - var = env->FindClass(className); \ - LOG_FATAL_IF(! var, "Unable to find class " className); - -#define GET_FIELD_ID(var, clazz, fieldName, fieldDescriptor) \ - var = env->GetFieldID(clazz, fieldName, fieldDescriptor); \ - LOG_FATAL_IF(! var, "Unable to find field " fieldName); - -int register_android_database_CursorWindow(JNIEnv * env) +int register_android_database_CursorWindow(JNIEnv* env) { - jclass clazz; - FIND_CLASS(clazz, "android/database/CharArrayBuffer"); + jclass clazz = FindClassOrDie(env, "android/database/CharArrayBuffer"); - GET_FIELD_ID(gCharArrayBufferClassInfo.data, clazz, - "data", "[C"); - GET_FIELD_ID(gCharArrayBufferClassInfo.sizeCopied, clazz, - "sizeCopied", "I"); + gCharArrayBufferClassInfo.data = GetFieldIDOrDie(env, clazz, "data", "[C"); + gCharArrayBufferClassInfo.sizeCopied = GetFieldIDOrDie(env, clazz, "sizeCopied", "I"); - gEmptyString = jstring(env->NewGlobalRef(env->NewStringUTF(""))); - LOG_FATAL_IF(!gEmptyString, "Unable to create empty string"); + gEmptyString = MakeGlobalRefOrDie(env, env->NewStringUTF("")); - return AndroidRuntime::registerNativeMethods(env, "android/database/CursorWindow", - sMethods, NELEM(sMethods)); + return RegisterMethodsOrDie(env, "android/database/CursorWindow", sMethods, NELEM(sMethods)); } } // namespace android diff --git a/core/jni/android_database_SQLiteConnection.cpp b/core/jni/android_database_SQLiteConnection.cpp index ae56432..7a3cdf6 100644 --- a/core/jni/android_database_SQLiteConnection.cpp +++ b/core/jni/android_database_SQLiteConnection.cpp @@ -37,6 +37,8 @@ #include "android_database_SQLiteCommon.h" +#include "core_jni_helpers.h" + // Set to 1 to use UTF16 storage for localized indexes. #define UTF16_STORAGE 0 @@ -325,7 +327,6 @@ static void nativeFinalizeStatement(JNIEnv* env, jclass clazz, jlong connectionP static jint nativeGetParameterCount(JNIEnv* env, jclass clazz, jlong connectionPtr, jlong statementPtr) { - SQLiteConnection* connection = reinterpret_cast<SQLiteConnection*>(connectionPtr); sqlite3_stmt* statement = reinterpret_cast<sqlite3_stmt*>(statementPtr); return sqlite3_bind_parameter_count(statement); @@ -333,7 +334,6 @@ static jint nativeGetParameterCount(JNIEnv* env, jclass clazz, jlong connectionP static jboolean nativeIsReadOnly(JNIEnv* env, jclass clazz, jlong connectionPtr, jlong statementPtr) { - SQLiteConnection* connection = reinterpret_cast<SQLiteConnection*>(connectionPtr); sqlite3_stmt* statement = reinterpret_cast<sqlite3_stmt*>(statementPtr); return sqlite3_stmt_readonly(statement) != 0; @@ -341,7 +341,6 @@ static jboolean nativeIsReadOnly(JNIEnv* env, jclass clazz, jlong connectionPtr, static jint nativeGetColumnCount(JNIEnv* env, jclass clazz, jlong connectionPtr, jlong statementPtr) { - SQLiteConnection* connection = reinterpret_cast<SQLiteConnection*>(connectionPtr); sqlite3_stmt* statement = reinterpret_cast<sqlite3_stmt*>(statementPtr); return sqlite3_column_count(statement); @@ -349,7 +348,6 @@ static jint nativeGetColumnCount(JNIEnv* env, jclass clazz, jlong connectionPtr, static jstring nativeGetColumnName(JNIEnv* env, jclass clazz, jlong connectionPtr, jlong statementPtr, jint index) { - SQLiteConnection* connection = reinterpret_cast<SQLiteConnection*>(connectionPtr); sqlite3_stmt* statement = reinterpret_cast<sqlite3_stmt*>(statementPtr); const jchar* name = static_cast<const jchar*>(sqlite3_column_name16(statement, index)); @@ -845,35 +843,20 @@ static JNINativeMethod sMethods[] = (void*)nativeResetCancel }, }; -#define FIND_CLASS(var, className) \ - var = env->FindClass(className); \ - LOG_FATAL_IF(! var, "Unable to find class " className); - -#define GET_METHOD_ID(var, clazz, methodName, fieldDescriptor) \ - var = env->GetMethodID(clazz, methodName, fieldDescriptor); \ - LOG_FATAL_IF(! var, "Unable to find method" methodName); - -#define GET_FIELD_ID(var, clazz, fieldName, fieldDescriptor) \ - var = env->GetFieldID(clazz, fieldName, fieldDescriptor); \ - LOG_FATAL_IF(! var, "Unable to find field " fieldName); - int register_android_database_SQLiteConnection(JNIEnv *env) { - jclass clazz; - FIND_CLASS(clazz, "android/database/sqlite/SQLiteCustomFunction"); + jclass clazz = FindClassOrDie(env, "android/database/sqlite/SQLiteCustomFunction"); - GET_FIELD_ID(gSQLiteCustomFunctionClassInfo.name, clazz, - "name", "Ljava/lang/String;"); - GET_FIELD_ID(gSQLiteCustomFunctionClassInfo.numArgs, clazz, - "numArgs", "I"); - GET_METHOD_ID(gSQLiteCustomFunctionClassInfo.dispatchCallback, - clazz, "dispatchCallback", "([Ljava/lang/String;)V"); + gSQLiteCustomFunctionClassInfo.name = GetFieldIDOrDie(env, clazz, "name", "Ljava/lang/String;"); + gSQLiteCustomFunctionClassInfo.numArgs = GetFieldIDOrDie(env, clazz, "numArgs", "I"); + gSQLiteCustomFunctionClassInfo.dispatchCallback = GetMethodIDOrDie(env, clazz, + "dispatchCallback", "([Ljava/lang/String;)V"); - FIND_CLASS(clazz, "java/lang/String"); - gStringClassInfo.clazz = jclass(env->NewGlobalRef(clazz)); + clazz = FindClassOrDie(env, "java/lang/String"); + gStringClassInfo.clazz = MakeGlobalRefOrDie(env, clazz); - return AndroidRuntime::registerNativeMethods(env, "android/database/sqlite/SQLiteConnection", - sMethods, NELEM(sMethods)); + return RegisterMethodsOrDie(env, "android/database/sqlite/SQLiteConnection", sMethods, + NELEM(sMethods)); } } // namespace android diff --git a/core/jni/android_database_SQLiteDebug.cpp b/core/jni/android_database_SQLiteDebug.cpp index c1e7305..26e13cf 100644 --- a/core/jni/android_database_SQLiteDebug.cpp +++ b/core/jni/android_database_SQLiteDebug.cpp @@ -28,6 +28,8 @@ #include <sqlite3.h> +#include "core_jni_helpers.h" + namespace android { static struct { @@ -62,27 +64,17 @@ static JNINativeMethod gMethods[] = (void*) nativeGetPagerStats }, }; -#define FIND_CLASS(var, className) \ - var = env->FindClass(className); \ - LOG_FATAL_IF(! var, "Unable to find class " className); - -#define GET_FIELD_ID(var, clazz, fieldName, fieldDescriptor) \ - var = env->GetFieldID(clazz, fieldName, fieldDescriptor); \ - LOG_FATAL_IF(! var, "Unable to find field " fieldName); - int register_android_database_SQLiteDebug(JNIEnv *env) { - jclass clazz; - FIND_CLASS(clazz, "android/database/sqlite/SQLiteDebug$PagerStats"); + jclass clazz = FindClassOrDie(env, "android/database/sqlite/SQLiteDebug$PagerStats"); - GET_FIELD_ID(gSQLiteDebugPagerStatsClassInfo.memoryUsed, clazz, - "memoryUsed", "I"); - GET_FIELD_ID(gSQLiteDebugPagerStatsClassInfo.largestMemAlloc, clazz, + gSQLiteDebugPagerStatsClassInfo.memoryUsed = GetFieldIDOrDie(env, clazz, "memoryUsed", "I"); + gSQLiteDebugPagerStatsClassInfo.largestMemAlloc = GetFieldIDOrDie(env, clazz, "largestMemAlloc", "I"); - GET_FIELD_ID(gSQLiteDebugPagerStatsClassInfo.pageCacheOverflow, clazz, + gSQLiteDebugPagerStatsClassInfo.pageCacheOverflow = GetFieldIDOrDie(env, clazz, "pageCacheOverflow", "I"); - return AndroidRuntime::registerNativeMethods(env, "android/database/sqlite/SQLiteDebug", + return RegisterMethodsOrDie(env, "android/database/sqlite/SQLiteDebug", gMethods, NELEM(gMethods)); } diff --git a/core/jni/android_database_SQLiteGlobal.cpp b/core/jni/android_database_SQLiteGlobal.cpp index 89d64fa..d0c592e 100644 --- a/core/jni/android_database_SQLiteGlobal.cpp +++ b/core/jni/android_database_SQLiteGlobal.cpp @@ -18,7 +18,7 @@ #include <jni.h> #include <JNIHelp.h> -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" #include <sqlite3.h> #include <sqlite3_android.h> @@ -74,15 +74,14 @@ static jint nativeReleaseMemory(JNIEnv* env, jclass clazz) { static JNINativeMethod sMethods[] = { /* name, signature, funcPtr */ - { "nativeReleaseMemory", "()I", - (void*)nativeReleaseMemory }, + { "nativeReleaseMemory", "()I", (void*)nativeReleaseMemory }, }; int register_android_database_SQLiteGlobal(JNIEnv *env) { sqliteInitialize(); - return AndroidRuntime::registerNativeMethods(env, "android/database/sqlite/SQLiteGlobal", + return RegisterMethodsOrDie(env, "android/database/sqlite/SQLiteGlobal", sMethods, NELEM(sMethods)); } diff --git a/core/jni/android_ddm_DdmHandleNativeHeap.cpp b/core/jni/android_ddm_DdmHandleNativeHeap.cpp index 9b96320..ae96936 100644 --- a/core/jni/android_ddm_DdmHandleNativeHeap.cpp +++ b/core/jni/android_ddm_DdmHandleNativeHeap.cpp @@ -20,7 +20,7 @@ #include <JNIHelp.h> #include <jni.h> -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" #include <utils/Log.h> #include <utils/String8.h> @@ -82,7 +82,7 @@ static jbyteArray DdmHandleNativeHeap_getLeakInfo(JNIEnv* env, jobject) { get_malloc_leak_info(&allocBytes, &header.allocSize, &header.allocInfoSize, &header.totalMemory, &header.backtraceSize); - ALOGD("*** mapSize: %d allocSize: %d allocInfoSize: %d totalMemory: %d", + ALOGD("*** mapSize: %zu allocSize: %zu allocInfoSize: %zu totalMemory: %zu", header.mapSize, header.allocSize, header.allocInfoSize, header.totalMemory); #if defined(__LP64__) @@ -110,7 +110,8 @@ static JNINativeMethod method_table[] = { }; int register_android_ddm_DdmHandleNativeHeap(JNIEnv* env) { - return AndroidRuntime::registerNativeMethods(env, "android/ddm/DdmHandleNativeHeap", method_table, NELEM(method_table)); + return RegisterMethodsOrDie(env, "android/ddm/DdmHandleNativeHeap", method_table, + NELEM(method_table)); } }; diff --git a/core/jni/android_emoji_EmojiFactory.cpp b/core/jni/android_emoji_EmojiFactory.cpp index f127d29..655b400 100644 --- a/core/jni/android_emoji_EmojiFactory.cpp +++ b/core/jni/android_emoji_EmojiFactory.cpp @@ -265,14 +265,6 @@ static jclass make_globalref(JNIEnv* env, const char classname[]) return (jclass)env->NewGlobalRef(c); } -static jfieldID getFieldIDCheck(JNIEnv* env, jclass clazz, - const char fieldname[], const char type[]) -{ - jfieldID id = env->GetFieldID(clazz, fieldname, type); - SkASSERT(id); - return id; -} - int register_android_emoji_EmojiFactory(JNIEnv* env) { gEmojiFactory_class = make_globalref(env, "android/emoji/EmojiFactory"); gEmojiFactory_constructorMethodID = env->GetMethodID( diff --git a/core/jni/android_graphics_Canvas.cpp b/core/jni/android_graphics_Canvas.cpp index 96607d2..19aad61 100644 --- a/core/jni/android_graphics_Canvas.cpp +++ b/core/jni/android_graphics_Canvas.cpp @@ -16,7 +16,7 @@ #include "jni.h" #include "GraphicsJNI.h" -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" #include "Canvas.h" #include "SkDrawFilter.h" @@ -556,42 +556,6 @@ static void drawTextRunString(JNIEnv* env, jobject obj, jlong canvasHandle, jstr env->ReleaseStringChars(text, jchars); } -static void drawPosTextChars(JNIEnv* env, jobject, jlong canvasHandle, jcharArray text, - jint index, jint count, jfloatArray pos, jlong paintHandle) { - Paint* paint = reinterpret_cast<Paint*>(paintHandle); - jchar* jchars = text ? env->GetCharArrayElements(text, NULL) : NULL; - float* posArray = pos ? env->GetFloatArrayElements(pos, NULL) : NULL; - int posCount = pos ? env->GetArrayLength(pos) >> 1: 0; - - get_canvas(canvasHandle)->drawPosText(jchars + index, posArray, count << 1, posCount, *paint); - - if (text) { - env->ReleaseCharArrayElements(text, jchars, 0); - } - if (pos) { - env->ReleaseFloatArrayElements(pos, posArray, 0); - } -} - - -static void drawPosTextString(JNIEnv* env, jobject, jlong canvasHandle, jstring text, - jfloatArray pos, jlong paintHandle) { - Paint* paint = reinterpret_cast<Paint*>(paintHandle); - const jchar* jchars = text ? env->GetStringChars(text, NULL) : NULL; - int byteLength = text ? env->GetStringLength(text) : 0; - float* posArray = pos ? env->GetFloatArrayElements(pos, NULL) : NULL; - int posCount = pos ? env->GetArrayLength(pos) >> 1: 0; - - get_canvas(canvasHandle)->drawPosText(jchars , posArray, byteLength << 1, posCount, *paint); - - if (text) { - env->ReleaseStringChars(text, jchars); - } - if (pos) { - env->ReleaseFloatArrayElements(pos, posArray, 0); - } -} - class DrawTextOnPathFunctor { public: DrawTextOnPathFunctor(const Layout& layout, Canvas* canvas, float hOffset, @@ -736,7 +700,7 @@ static JNINativeMethod gMethods[] = { }; int register_android_graphics_Canvas(JNIEnv* env) { - return AndroidRuntime::registerNativeMethods(env, "android/graphics/Canvas", gMethods, NELEM(gMethods)); + return RegisterMethodsOrDie(env, "android/graphics/Canvas", gMethods, NELEM(gMethods)); } }; // namespace android diff --git a/core/jni/android_graphics_Picture.cpp b/core/jni/android_graphics_Picture.cpp index eb8f6dd..308ee20 100644 --- a/core/jni/android_graphics_Picture.cpp +++ b/core/jni/android_graphics_Picture.cpp @@ -16,7 +16,7 @@ #include "jni.h" #include "GraphicsJNI.h" -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" #include "Picture.h" @@ -106,7 +106,7 @@ static JNINativeMethod gMethods[] = { }; int register_android_graphics_Picture(JNIEnv* env) { - return AndroidRuntime::registerNativeMethods(env, "android/graphics/Picture", gMethods, NELEM(gMethods)); + return RegisterMethodsOrDie(env, "android/graphics/Picture", gMethods, NELEM(gMethods)); } }; // namespace android diff --git a/core/jni/android_hardware_Camera.cpp b/core/jni/android_hardware_Camera.cpp index 69f46d3..169fb60 100644 --- a/core/jni/android_hardware_Camera.cpp +++ b/core/jni/android_hardware_Camera.cpp @@ -21,7 +21,7 @@ #include "jni.h" #include "JNIHelp.h" -#include "android_runtime/AndroidRuntime.h" +#include "core_jni_helpers.h" #include <android_runtime/android_graphics_SurfaceTexture.h> #include <android_runtime/android_view_Surface.h> @@ -222,7 +222,7 @@ jbyteArray JNICameraContext::getCallbackBuffer( // Vector access should be protected by lock in postData() if (!buffers->isEmpty()) { - ALOGV("Using callback buffer from queue of length %d", buffers->size()); + ALOGV("Using callback buffer from queue of length %zu", buffers->size()); jbyteArray globalBuffer = buffers->itemAt(0); buffers->removeAt(0); @@ -232,7 +232,7 @@ jbyteArray JNICameraContext::getCallbackBuffer( if (obj != NULL) { jsize bufferLength = env->GetArrayLength(obj); if ((int)bufferLength < (int)bufferSize) { - ALOGE("Callback buffer was too small! Expected %d bytes, but got %d bytes!", + ALOGE("Callback buffer was too small! Expected %zu bytes, but got %d bytes!", bufferSize, bufferLength); env->DeleteLocalRef(obj); return NULL; @@ -445,7 +445,7 @@ void JNICameraContext::addCallbackBuffer( jbyteArray callbackBuffer = (jbyteArray)env->NewGlobalRef(cbb); mCallbackBuffers.push(callbackBuffer); - ALOGV("Adding callback buffer to queue, %d total", + ALOGV("Adding callback buffer to queue, %zu total", mCallbackBuffers.size()); // We want to make sure the camera knows we're ready for the @@ -481,7 +481,7 @@ void JNICameraContext::clearCallbackBuffers_l(JNIEnv *env) } void JNICameraContext::clearCallbackBuffers_l(JNIEnv *env, Vector<jbyteArray> *buffers) { - ALOGV("Clearing callback buffers, %d remained", buffers->size()); + ALOGV("Clearing callback buffers, %zu remained", buffers->size()); while (!buffers->isEmpty()) { env->DeleteGlobalRef(buffers->top()); buffers->pop(); @@ -517,10 +517,12 @@ static jint android_hardware_Camera_native_setup(JNIEnv *env, jobject thiz, jobject weak_this, jint cameraId, jint halVersion, jstring clientPackageName) { // Convert jstring to String16 - const char16_t *rawClientName = env->GetStringChars(clientPackageName, NULL); + const char16_t *rawClientName = reinterpret_cast<const char16_t*>( + env->GetStringChars(clientPackageName, NULL)); jsize rawClientNameLen = env->GetStringLength(clientPackageName); String16 clientName(rawClientName, rawClientNameLen); - env->ReleaseStringChars(clientPackageName, rawClientName); + env->ReleaseStringChars(clientPackageName, + reinterpret_cast<const jchar*>(rawClientName)); sp<Camera> camera; if (halVersion == CAMERA_HAL_API_VERSION_NORMAL_CONNECT) { @@ -783,7 +785,8 @@ static void android_hardware_Camera_setParameters(JNIEnv *env, jobject thiz, jst const jchar* str = env->GetStringCritical(params, 0); String8 params8; if (params) { - params8 = String8(str, env->GetStringLength(params)); + params8 = String8(reinterpret_cast<const char16_t*>(str), + env->GetStringLength(params)); env->ReleaseStringCritical(params, str); } if (camera->setParameters(params8) != NO_ERROR) { @@ -1031,26 +1034,14 @@ struct field { jfieldID *jfield; }; -static int find_fields(JNIEnv *env, field *fields, int count) +static void find_fields(JNIEnv *env, field *fields, int count) { for (int i = 0; i < count; i++) { field *f = &fields[i]; - jclass clazz = env->FindClass(f->class_name); - if (clazz == NULL) { - ALOGE("Can't find %s", f->class_name); - return -1; - } - - jfieldID field = env->GetFieldID(clazz, f->field_name, f->field_type); - if (field == NULL) { - ALOGE("Can't find %s.%s", f->class_name, f->field_name); - return -1; - } - + jclass clazz = FindClassOrDie(env, f->class_name); + jfieldID field = GetFieldIDOrDie(env, clazz, f->field_name, f->field_type); *(f->jfield) = field; } - - return 0; } // Get all the required offsets in java class and register native functions @@ -1076,30 +1067,17 @@ int register_android_hardware_Camera(JNIEnv *env) { "android/graphics/Point", "y", "I", &fields.point_y}, }; - if (find_fields(env, fields_to_find, NELEM(fields_to_find)) < 0) - return -1; + find_fields(env, fields_to_find, NELEM(fields_to_find)); - jclass clazz = env->FindClass("android/hardware/Camera"); - fields.post_event = env->GetStaticMethodID(clazz, "postEventFromNative", + jclass clazz = FindClassOrDie(env, "android/hardware/Camera"); + fields.post_event = GetStaticMethodIDOrDie(env, clazz, "postEventFromNative", "(Ljava/lang/Object;IIILjava/lang/Object;)V"); - if (fields.post_event == NULL) { - ALOGE("Can't find android/hardware/Camera.postEventFromNative"); - return -1; - } - clazz = env->FindClass("android/graphics/Rect"); - fields.rect_constructor = env->GetMethodID(clazz, "<init>", "()V"); - if (fields.rect_constructor == NULL) { - ALOGE("Can't find android/graphics/Rect.Rect()"); - return -1; - } + clazz = FindClassOrDie(env, "android/graphics/Rect"); + fields.rect_constructor = GetMethodIDOrDie(env, clazz, "<init>", "()V"); - clazz = env->FindClass("android/hardware/Camera$Face"); - fields.face_constructor = env->GetMethodID(clazz, "<init>", "()V"); - if (fields.face_constructor == NULL) { - ALOGE("Can't find android/hardware/Camera$Face.Face()"); - return -1; - } + clazz = FindClassOrDie(env, "android/hardware/Camera$Face"); + fields.face_constructor = GetMethodIDOrDie(env, clazz, "<init>", "()V"); clazz = env->FindClass("android/graphics/Point"); fields.point_constructor = env->GetMethodID(clazz, "<init>", "()V"); @@ -1109,6 +1087,5 @@ int register_android_hardware_Camera(JNIEnv *env) } // Register native functions - return AndroidRuntime::registerNativeMethods(env, "android/hardware/Camera", - camMethods, NELEM(camMethods)); + return RegisterMethodsOrDie(env, "android/hardware/Camera", camMethods, NELEM(camMethods)); } diff --git a/core/jni/android_hardware_SensorManager.cpp b/core/jni/android_hardware_SensorManager.cpp index ec2bd84..d1b1a1a 100644 --- a/core/jni/android_hardware_SensorManager.cpp +++ b/core/jni/android_hardware_SensorManager.cpp @@ -28,6 +28,8 @@ #include "android_os_MessageQueue.h" #include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" + static struct { jclass clazz; jmethodID dispatchSensorEvent; @@ -294,32 +296,22 @@ static JNINativeMethod gBaseEventQueueMethods[] = { using namespace android; -#define FIND_CLASS(var, className) \ - var = env->FindClass(className); \ - LOG_FATAL_IF(! var, "Unable to find class " className); \ - var = jclass(env->NewGlobalRef(var)); - -#define GET_METHOD_ID(var, clazz, methodName, methodDescriptor) \ - var = env->GetMethodID(clazz, methodName, methodDescriptor); \ - LOG_FATAL_IF(! var, "Unable to find method " methodName); - int register_android_hardware_SensorManager(JNIEnv *env) { - jniRegisterNativeMethods(env, "android/hardware/SystemSensorManager", + RegisterMethodsOrDie(env, "android/hardware/SystemSensorManager", gSystemSensorManagerMethods, NELEM(gSystemSensorManagerMethods)); - jniRegisterNativeMethods(env, "android/hardware/SystemSensorManager$BaseEventQueue", + RegisterMethodsOrDie(env, "android/hardware/SystemSensorManager$BaseEventQueue", gBaseEventQueueMethods, NELEM(gBaseEventQueueMethods)); - FIND_CLASS(gBaseEventQueueClassInfo.clazz, "android/hardware/SystemSensorManager$BaseEventQueue"); + gBaseEventQueueClassInfo.clazz = FindClassOrDie(env, + "android/hardware/SystemSensorManager$BaseEventQueue"); - GET_METHOD_ID(gBaseEventQueueClassInfo.dispatchSensorEvent, - gBaseEventQueueClassInfo.clazz, - "dispatchSensorEvent", "(I[FIJ)V"); + gBaseEventQueueClassInfo.dispatchSensorEvent = GetMethodIDOrDie(env, + gBaseEventQueueClassInfo.clazz, "dispatchSensorEvent", "(I[FIJ)V"); - GET_METHOD_ID(gBaseEventQueueClassInfo.dispatchFlushCompleteEvent, - gBaseEventQueueClassInfo.clazz, - "dispatchFlushCompleteEvent", "(I)V"); + gBaseEventQueueClassInfo.dispatchFlushCompleteEvent = GetMethodIDOrDie(env, + gBaseEventQueueClassInfo.clazz, "dispatchFlushCompleteEvent", "(I)V"); return 0; } diff --git a/core/jni/android_hardware_SerialPort.cpp b/core/jni/android_hardware_SerialPort.cpp index 7f40a5c..2d2ff4d 100644 --- a/core/jni/android_hardware_SerialPort.cpp +++ b/core/jni/android_hardware_SerialPort.cpp @@ -20,7 +20,7 @@ #include "jni.h" #include "JNIHelp.h" -#include "android_runtime/AndroidRuntime.h" +#include "core_jni_helpers.h" #include <stdio.h> #include <sys/types.h> @@ -260,17 +260,9 @@ static JNINativeMethod method_table[] = { int register_android_hardware_SerialPort(JNIEnv *env) { - jclass clazz = env->FindClass("android/hardware/SerialPort"); - if (clazz == NULL) { - ALOGE("Can't find android/hardware/SerialPort"); - return -1; - } - field_context = env->GetFieldID(clazz, "mNativeContext", "I"); - if (field_context == NULL) { - ALOGE("Can't find SerialPort.mNativeContext"); - return -1; - } + jclass clazz = FindClassOrDie(env, "android/hardware/SerialPort"); + field_context = GetFieldIDOrDie(env, clazz, "mNativeContext", "I"); - return AndroidRuntime::registerNativeMethods(env, "android/hardware/SerialPort", + return RegisterMethodsOrDie(env, "android/hardware/SerialPort", method_table, NELEM(method_table)); } diff --git a/core/jni/android_hardware_SoundTrigger.cpp b/core/jni/android_hardware_SoundTrigger.cpp index 2a8e6d6..28e5030 100644 --- a/core/jni/android_hardware_SoundTrigger.cpp +++ b/core/jni/android_hardware_SoundTrigger.cpp @@ -21,7 +21,7 @@ #include "jni.h" #include "JNIHelp.h" -#include "android_runtime/AndroidRuntime.h" +#include "core_jni_helpers.h" #include <system/sound_trigger.h> #include <soundtrigger/SoundTriggerCallback.h> #include <soundtrigger/SoundTrigger.h> @@ -801,112 +801,102 @@ static JNINativeMethod gModuleMethods[] = { int register_android_hardware_SoundTrigger(JNIEnv *env) { - jclass arrayListClass = env->FindClass("java/util/ArrayList"); - gArrayListClass = (jclass) env->NewGlobalRef(arrayListClass); - gArrayListMethods.add = env->GetMethodID(arrayListClass, "add", "(Ljava/lang/Object;)Z"); - - jclass uuidClass = env->FindClass("java/util/UUID"); - gUUIDClass = (jclass) env->NewGlobalRef(uuidClass); - gUUIDMethods.toString = env->GetMethodID(uuidClass, "toString", "()Ljava/lang/String;"); - - jclass lClass = env->FindClass(kSoundTriggerClassPathName); - gSoundTriggerClass = (jclass) env->NewGlobalRef(lClass); - - jclass moduleClass = env->FindClass(kModuleClassPathName); - gModuleClass = (jclass) env->NewGlobalRef(moduleClass); - gPostEventFromNative = env->GetStaticMethodID(moduleClass, "postEventFromNative", - "(Ljava/lang/Object;IIILjava/lang/Object;)V"); - gModuleFields.mNativeContext = env->GetFieldID(moduleClass, "mNativeContext", "J"); - gModuleFields.mId = env->GetFieldID(moduleClass, "mId", "I"); - - - jclass modulePropertiesClass = env->FindClass(kModulePropertiesClassPathName); - gModulePropertiesClass = (jclass) env->NewGlobalRef(modulePropertiesClass); - gModulePropertiesCstor = env->GetMethodID(modulePropertiesClass, "<init>", - "(ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;IIIIIZIZIZ)V"); - - jclass soundModelClass = env->FindClass(kSoundModelClassPathName); - gSoundModelClass = (jclass) env->NewGlobalRef(soundModelClass); - gSoundModelFields.uuid = env->GetFieldID(soundModelClass, "uuid", "Ljava/util/UUID;"); - gSoundModelFields.vendorUuid = env->GetFieldID(soundModelClass, "vendorUuid", "Ljava/util/UUID;"); - gSoundModelFields.data = env->GetFieldID(soundModelClass, "data", "[B"); - - jclass keyphraseClass = env->FindClass(kKeyphraseClassPathName); - gKeyphraseClass = (jclass) env->NewGlobalRef(keyphraseClass); - gKeyphraseFields.id = env->GetFieldID(keyphraseClass, "id", "I"); - gKeyphraseFields.recognitionModes = env->GetFieldID(keyphraseClass, "recognitionModes", "I"); - gKeyphraseFields.locale = env->GetFieldID(keyphraseClass, "locale", "Ljava/lang/String;"); - gKeyphraseFields.text = env->GetFieldID(keyphraseClass, "text", "Ljava/lang/String;"); - gKeyphraseFields.users = env->GetFieldID(keyphraseClass, "users", "[I"); - - jclass keyphraseSoundModelClass = env->FindClass(kKeyphraseSoundModelClassPathName); - gKeyphraseSoundModelClass = (jclass) env->NewGlobalRef(keyphraseSoundModelClass); - gKeyphraseSoundModelFields.keyphrases = env->GetFieldID(keyphraseSoundModelClass, + jclass arrayListClass = FindClassOrDie(env, "java/util/ArrayList"); + gArrayListClass = MakeGlobalRefOrDie(env, arrayListClass); + gArrayListMethods.add = GetMethodIDOrDie(env, arrayListClass, "add", "(Ljava/lang/Object;)Z"); + + jclass uuidClass = FindClassOrDie(env, "java/util/UUID"); + gUUIDClass = MakeGlobalRefOrDie(env, uuidClass); + gUUIDMethods.toString = GetMethodIDOrDie(env, uuidClass, "toString", "()Ljava/lang/String;"); + + jclass lClass = FindClassOrDie(env, kSoundTriggerClassPathName); + gSoundTriggerClass = MakeGlobalRefOrDie(env, lClass); + + jclass moduleClass = FindClassOrDie(env, kModuleClassPathName); + gModuleClass = MakeGlobalRefOrDie(env, moduleClass); + gPostEventFromNative = GetStaticMethodIDOrDie(env, moduleClass, "postEventFromNative", + "(Ljava/lang/Object;IIILjava/lang/Object;)V"); + gModuleFields.mNativeContext = GetFieldIDOrDie(env, moduleClass, "mNativeContext", "J"); + gModuleFields.mId = GetFieldIDOrDie(env, moduleClass, "mId", "I"); + + jclass modulePropertiesClass = FindClassOrDie(env, kModulePropertiesClassPathName); + gModulePropertiesClass = MakeGlobalRefOrDie(env, modulePropertiesClass); + gModulePropertiesCstor = GetMethodIDOrDie(env, modulePropertiesClass, "<init>", + "(ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;IIIIIZIZIZ)V"); + + jclass soundModelClass = FindClassOrDie(env, kSoundModelClassPathName); + gSoundModelClass = MakeGlobalRefOrDie(env, soundModelClass); + gSoundModelFields.uuid = GetFieldIDOrDie(env, soundModelClass, "uuid", "Ljava/util/UUID;"); + gSoundModelFields.vendorUuid = GetFieldIDOrDie(env, soundModelClass, "vendorUuid", + "Ljava/util/UUID;"); + gSoundModelFields.data = GetFieldIDOrDie(env, soundModelClass, "data", "[B"); + + jclass keyphraseClass = FindClassOrDie(env, kKeyphraseClassPathName); + gKeyphraseClass = MakeGlobalRefOrDie(env, keyphraseClass); + gKeyphraseFields.id = GetFieldIDOrDie(env, keyphraseClass, "id", "I"); + gKeyphraseFields.recognitionModes = GetFieldIDOrDie(env, keyphraseClass, "recognitionModes", + "I"); + gKeyphraseFields.locale = GetFieldIDOrDie(env, keyphraseClass, "locale", "Ljava/lang/String;"); + gKeyphraseFields.text = GetFieldIDOrDie(env, keyphraseClass, "text", "Ljava/lang/String;"); + gKeyphraseFields.users = GetFieldIDOrDie(env, keyphraseClass, "users", "[I"); + + jclass keyphraseSoundModelClass = FindClassOrDie(env, kKeyphraseSoundModelClassPathName); + gKeyphraseSoundModelClass = MakeGlobalRefOrDie(env, keyphraseSoundModelClass); + gKeyphraseSoundModelFields.keyphrases = GetFieldIDOrDie(env, keyphraseSoundModelClass, "keyphrases", "[Landroid/hardware/soundtrigger/SoundTrigger$Keyphrase;"); - - jclass recognitionEventClass = env->FindClass(kRecognitionEventClassPathName); - gRecognitionEventClass = (jclass) env->NewGlobalRef(recognitionEventClass); - gRecognitionEventCstor = env->GetMethodID(recognitionEventClass, "<init>", + jclass recognitionEventClass = FindClassOrDie(env, kRecognitionEventClassPathName); + gRecognitionEventClass = MakeGlobalRefOrDie(env, recognitionEventClass); + gRecognitionEventCstor = GetMethodIDOrDie(env, recognitionEventClass, "<init>", "(IIZIIIZLandroid/media/AudioFormat;[B)V"); - jclass keyphraseRecognitionEventClass = env->FindClass(kKeyphraseRecognitionEventClassPathName); - gKeyphraseRecognitionEventClass = (jclass) env->NewGlobalRef(keyphraseRecognitionEventClass); - gKeyphraseRecognitionEventCstor = env->GetMethodID(keyphraseRecognitionEventClass, "<init>", + jclass keyphraseRecognitionEventClass = FindClassOrDie(env, + kKeyphraseRecognitionEventClassPathName); + gKeyphraseRecognitionEventClass = MakeGlobalRefOrDie(env, keyphraseRecognitionEventClass); + gKeyphraseRecognitionEventCstor = GetMethodIDOrDie(env, keyphraseRecognitionEventClass, "<init>", "(IIZIIIZLandroid/media/AudioFormat;[B[Landroid/hardware/soundtrigger/SoundTrigger$KeyphraseRecognitionExtra;)V"); - jclass keyRecognitionConfigClass = env->FindClass(kRecognitionConfigClassPathName); - gRecognitionConfigClass = (jclass) env->NewGlobalRef(keyRecognitionConfigClass); - gRecognitionConfigFields.captureRequested = env->GetFieldID(keyRecognitionConfigClass, - "captureRequested", - "Z"); - gRecognitionConfigFields.keyphrases = env->GetFieldID(keyRecognitionConfigClass, - "keyphrases", - "[Landroid/hardware/soundtrigger/SoundTrigger$KeyphraseRecognitionExtra;"); - gRecognitionConfigFields.data = env->GetFieldID(keyRecognitionConfigClass, - "data", - "[B"); - - jclass keyphraseRecognitionExtraClass = env->FindClass(kKeyphraseRecognitionExtraClassPathName); - gKeyphraseRecognitionExtraClass = (jclass) env->NewGlobalRef(keyphraseRecognitionExtraClass); - gKeyphraseRecognitionExtraCstor = env->GetMethodID(keyphraseRecognitionExtraClass, "<init>", - "(III[Landroid/hardware/soundtrigger/SoundTrigger$ConfidenceLevel;)V"); - gKeyphraseRecognitionExtraFields.id = env->GetFieldID(gKeyphraseRecognitionExtraClass, "id", "I"); - gKeyphraseRecognitionExtraFields.recognitionModes = env->GetFieldID(gKeyphraseRecognitionExtraClass, - "recognitionModes", "I"); - gKeyphraseRecognitionExtraFields.coarseConfidenceLevel = env->GetFieldID(gKeyphraseRecognitionExtraClass, - "coarseConfidenceLevel", "I"); - gKeyphraseRecognitionExtraFields.confidenceLevels = env->GetFieldID(gKeyphraseRecognitionExtraClass, - "confidenceLevels", - "[Landroid/hardware/soundtrigger/SoundTrigger$ConfidenceLevel;"); - - jclass confidenceLevelClass = env->FindClass(kConfidenceLevelClassPathName); - gConfidenceLevelClass = (jclass) env->NewGlobalRef(confidenceLevelClass); - gConfidenceLevelCstor = env->GetMethodID(confidenceLevelClass, "<init>", "(II)V"); - gConfidenceLevelFields.userId = env->GetFieldID(confidenceLevelClass, "userId", "I"); - gConfidenceLevelFields.confidenceLevel = env->GetFieldID(confidenceLevelClass, + jclass keyRecognitionConfigClass = FindClassOrDie(env, kRecognitionConfigClassPathName); + gRecognitionConfigClass = MakeGlobalRefOrDie(env, keyRecognitionConfigClass); + gRecognitionConfigFields.captureRequested = GetFieldIDOrDie(env, keyRecognitionConfigClass, + "captureRequested", "Z"); + gRecognitionConfigFields.keyphrases = GetFieldIDOrDie(env, keyRecognitionConfigClass, + "keyphrases", "[Landroid/hardware/soundtrigger/SoundTrigger$KeyphraseRecognitionExtra;"); + gRecognitionConfigFields.data = GetFieldIDOrDie(env, keyRecognitionConfigClass, "data", "[B"); + + jclass keyphraseRecognitionExtraClass = FindClassOrDie(env, + kKeyphraseRecognitionExtraClassPathName); + gKeyphraseRecognitionExtraClass = MakeGlobalRefOrDie(env, keyphraseRecognitionExtraClass); + gKeyphraseRecognitionExtraCstor = GetMethodIDOrDie(env, keyphraseRecognitionExtraClass, + "<init>", "(III[Landroid/hardware/soundtrigger/SoundTrigger$ConfidenceLevel;)V"); + gKeyphraseRecognitionExtraFields.id = GetFieldIDOrDie(env, gKeyphraseRecognitionExtraClass, + "id", "I"); + gKeyphraseRecognitionExtraFields.recognitionModes = GetFieldIDOrDie(env, + gKeyphraseRecognitionExtraClass, "recognitionModes", "I"); + gKeyphraseRecognitionExtraFields.coarseConfidenceLevel = GetFieldIDOrDie(env, + gKeyphraseRecognitionExtraClass, "coarseConfidenceLevel", "I"); + gKeyphraseRecognitionExtraFields.confidenceLevels = GetFieldIDOrDie(env, + gKeyphraseRecognitionExtraClass, "confidenceLevels", + "[Landroid/hardware/soundtrigger/SoundTrigger$ConfidenceLevel;"); + + jclass confidenceLevelClass = FindClassOrDie(env, kConfidenceLevelClassPathName); + gConfidenceLevelClass = MakeGlobalRefOrDie(env, confidenceLevelClass); + gConfidenceLevelCstor = GetMethodIDOrDie(env, confidenceLevelClass, "<init>", "(II)V"); + gConfidenceLevelFields.userId = GetFieldIDOrDie(env, confidenceLevelClass, "userId", "I"); + gConfidenceLevelFields.confidenceLevel = GetFieldIDOrDie(env, confidenceLevelClass, "confidenceLevel", "I"); - jclass audioFormatClass = env->FindClass(kAudioFormatClassPathName); - gAudioFormatClass = (jclass) env->NewGlobalRef(audioFormatClass); - gAudioFormatCstor = env->GetMethodID(audioFormatClass, "<init>", "(III)V"); - - jclass soundModelEventClass = env->FindClass(kSoundModelEventClassPathName); - gSoundModelEventClass = (jclass) env->NewGlobalRef(soundModelEventClass); - gSoundModelEventCstor = env->GetMethodID(soundModelEventClass, "<init>", - "(II[B)V"); - + jclass audioFormatClass = FindClassOrDie(env, kAudioFormatClassPathName); + gAudioFormatClass = MakeGlobalRefOrDie(env, audioFormatClass); + gAudioFormatCstor = GetMethodIDOrDie(env, audioFormatClass, "<init>", "(III)V"); - int status = AndroidRuntime::registerNativeMethods(env, - kSoundTriggerClassPathName, gMethods, NELEM(gMethods)); - - if (status == 0) { - status = AndroidRuntime::registerNativeMethods(env, - kModuleClassPathName, gModuleMethods, NELEM(gModuleMethods)); - } + jclass soundModelEventClass = FindClassOrDie(env, kSoundModelEventClassPathName); + gSoundModelEventClass = MakeGlobalRefOrDie(env, soundModelEventClass); + gSoundModelEventCstor = GetMethodIDOrDie(env, soundModelEventClass, "<init>", "(II[B)V"); - return status; + RegisterMethodsOrDie(env, kSoundTriggerClassPathName, gMethods, NELEM(gMethods)); + return RegisterMethodsOrDie(env, kModuleClassPathName, gModuleMethods, NELEM(gModuleMethods)); } diff --git a/core/jni/android_hardware_UsbDevice.cpp b/core/jni/android_hardware_UsbDevice.cpp index 25f901b..ef3b646 100644 --- a/core/jni/android_hardware_UsbDevice.cpp +++ b/core/jni/android_hardware_UsbDevice.cpp @@ -20,7 +20,7 @@ #include "jni.h" #include "JNIHelp.h" -#include "android_runtime/AndroidRuntime.h" +#include "core_jni_helpers.h" #include <usbhost/usbhost.h> @@ -54,6 +54,6 @@ static JNINativeMethod method_table[] = { int register_android_hardware_UsbDevice(JNIEnv *env) { - return AndroidRuntime::registerNativeMethods(env, "android/hardware/usb/UsbDevice", + return RegisterMethodsOrDie(env, "android/hardware/usb/UsbDevice", method_table, NELEM(method_table)); } diff --git a/core/jni/android_hardware_UsbDeviceConnection.cpp b/core/jni/android_hardware_UsbDeviceConnection.cpp index 467a9a1..e0cae6f 100644 --- a/core/jni/android_hardware_UsbDeviceConnection.cpp +++ b/core/jni/android_hardware_UsbDeviceConnection.cpp @@ -20,7 +20,7 @@ #include "jni.h" #include "JNIHelp.h" -#include "android_runtime/AndroidRuntime.h" +#include "core_jni_helpers.h" #include <usbhost/usbhost.h> @@ -268,17 +268,9 @@ static JNINativeMethod method_table[] = { int register_android_hardware_UsbDeviceConnection(JNIEnv *env) { - jclass clazz = env->FindClass("android/hardware/usb/UsbDeviceConnection"); - if (clazz == NULL) { - ALOGE("Can't find android/hardware/usb/UsbDeviceConnection"); - return -1; - } - field_context = env->GetFieldID(clazz, "mNativeContext", "J"); - if (field_context == NULL) { - ALOGE("Can't find UsbDeviceConnection.mNativeContext"); - return -1; - } + jclass clazz = FindClassOrDie(env, "android/hardware/usb/UsbDeviceConnection"); + field_context = GetFieldIDOrDie(env, clazz, "mNativeContext", "J"); - return AndroidRuntime::registerNativeMethods(env, "android/hardware/usb/UsbDeviceConnection", + return RegisterMethodsOrDie(env, "android/hardware/usb/UsbDeviceConnection", method_table, NELEM(method_table)); } diff --git a/core/jni/android_hardware_UsbRequest.cpp b/core/jni/android_hardware_UsbRequest.cpp index a3c7b0a..ce99e15 100644 --- a/core/jni/android_hardware_UsbRequest.cpp +++ b/core/jni/android_hardware_UsbRequest.cpp @@ -20,7 +20,7 @@ #include "jni.h" #include "JNIHelp.h" -#include "android_runtime/AndroidRuntime.h" +#include "core_jni_helpers.h" #include <usbhost/usbhost.h> @@ -215,7 +215,7 @@ int register_android_hardware_UsbRequest(JNIEnv *env) return -1; } - return AndroidRuntime::registerNativeMethods(env, "android/hardware/usb/UsbRequest", + return RegisterMethodsOrDie(env, "android/hardware/usb/UsbRequest", method_table, NELEM(method_table)); } diff --git a/core/jni/android_hardware_camera2_CameraMetadata.cpp b/core/jni/android_hardware_camera2_CameraMetadata.cpp index 7935329..7c8769d 100644 --- a/core/jni/android_hardware_camera2_CameraMetadata.cpp +++ b/core/jni/android_hardware_camera2_CameraMetadata.cpp @@ -16,7 +16,6 @@ */ // #define LOG_NDEBUG 0 -// #define LOG_NNDEBUG 0 #define LOG_TAG "CameraMetadata-JNI" #include <utils/Errors.h> #include <utils/Log.h> @@ -29,7 +28,7 @@ #include "jni.h" #include "JNIHelp.h" #include "android_os_Parcel.h" -#include "android_runtime/AndroidRuntime.h" +#include "core_jni_helpers.h" #include "android_runtime/android_hardware_camera2_CameraMetadata.h" #include <binder/IServiceManager.h> @@ -42,13 +41,7 @@ #include <sys/types.h> // for socketpair #include <sys/socket.h> // for socketpair -#if defined(LOG_NNDEBUG) -#if !LOG_NNDEBUG -#define ALOGVV ALOGV -#endif -#else -#define ALOGVV(...) -#endif +static const bool kIsDebug = false; // fully-qualified class name #define CAMERA_METADATA_CLASS_NAME "android/hardware/camera2/impl/CameraMetadataNative" @@ -111,8 +104,8 @@ struct Helpers { size_t typeSize = getTypeSize(type); if (dataBytes % typeSize != 0) { - ALOGE("%s: Expected dataBytes (%ud) to be divisible by typeSize " - "(%ud)", __FUNCTION__, dataBytes, typeSize); + ALOGE("%s: Expected dataBytes (%zu) to be divisible by typeSize " + "(%zu)", __FUNCTION__, dataBytes, typeSize); return BAD_VALUE; } @@ -219,7 +212,7 @@ static jboolean CameraMetadata_isEmpty(JNIEnv *env, jobject thiz) { jboolean empty = metadata->isEmpty(); - ALOGV("%s: Empty returned %d, entry count was %d", + ALOGV("%s: Empty returned %d, entry count was %zu", __FUNCTION__, empty, metadata->entryCount()); return empty; @@ -315,7 +308,6 @@ static void CameraMetadata_writeValues(JNIEnv *env, jobject thiz, jint tag, jbyt "Tag (%d) did not have a type", tag); return; } - size_t tagSize = Helpers::getTypeSize(tagType); status_t res; @@ -597,7 +589,7 @@ static int find_fields(JNIEnv *env, field *fields, int count) int register_android_hardware_camera2_CameraMetadata(JNIEnv *env) { // Register native functions - return AndroidRuntime::registerNativeMethods(env, + return RegisterMethodsOrDie(env, CAMERA_METADATA_CLASS_NAME, gCameraMetadataMethods, NELEM(gCameraMetadataMethods)); @@ -617,7 +609,7 @@ static void CameraMetadata_classInit(JNIEnv *env, jobject thiz) { if (find_fields(env, fields_to_find, NELEM(fields_to_find)) < 0) return; - jclass clazz = env->FindClass(CAMERA_METADATA_CLASS_NAME); + env->FindClass(CAMERA_METADATA_CLASS_NAME); } static jint CameraMetadata_getTagFromKey(JNIEnv *env, jobject thiz, jstring keyName) { @@ -651,12 +643,15 @@ static jint CameraMetadata_getTagFromKey(JNIEnv *env, jobject thiz, jstring keyN const char *str = (i < ANDROID_SECTION_COUNT) ? camera_metadata_section_names[i] : vendorSections[i - ANDROID_SECTION_COUNT].string(); - ALOGVV("%s: Trying to match against section '%s'", - __FUNCTION__, str); + if (kIsDebug) { + ALOGV("%s: Trying to match against section '%s'", __FUNCTION__, str); + } if (strstr(key, str) == key) { // key begins with the section name size_t strLength = strlen(str); - ALOGVV("%s: Key begins with section name", __FUNCTION__); + if (kIsDebug) { + ALOGV("%s: Key begins with section name", __FUNCTION__); + } // section name is the longest we've found so far if (section == NULL || sectionLength < strLength) { @@ -664,7 +659,9 @@ static jint CameraMetadata_getTagFromKey(JNIEnv *env, jobject thiz, jstring keyN sectionIndex = i; sectionLength = strLength; - ALOGVV("%s: Found new best section (%s)", __FUNCTION__, section); + if (kIsDebug) { + ALOGV("%s: Found new best section (%s)", __FUNCTION__, section); + } } } } @@ -676,7 +673,7 @@ static jint CameraMetadata_getTagFromKey(JNIEnv *env, jobject thiz, jstring keyN "Could not find section name for key '%s')", key); return 0; } else { - ALOGV("%s: Found matched section '%s' (%d)", + ALOGV("%s: Found matched section '%s' (%zu)", __FUNCTION__, section, sectionIndex); } diff --git a/core/jni/android_hardware_camera2_DngCreator.cpp b/core/jni/android_hardware_camera2_DngCreator.cpp index 7361858..5548476 100644 --- a/core/jni/android_hardware_camera2_DngCreator.cpp +++ b/core/jni/android_hardware_camera2_DngCreator.cpp @@ -16,6 +16,15 @@ //#define LOG_NDEBUG 0 #define LOG_TAG "DngCreator_JNI" +#include <inttypes.h> +#include <string.h> + +#include <utils/Log.h> +#include <utils/Errors.h> +#include <utils/StrongPointer.h> +#include <utils/RefBase.h> +#include <utils/Vector.h> +#include <cutils/properties.h> #include <system/camera_metadata.h> #include <camera/CameraMetadata.h> @@ -27,6 +36,7 @@ #include <img_utils/Input.h> #include <img_utils/StripSource.h> +#include "core_jni_helpers.h" #include <utils/Log.h> #include <utils/Errors.h> #include <utils/StrongPointer.h> @@ -431,7 +441,6 @@ InputStripSource::InputStripSource(JNIEnv* env, Input& input, uint32_t ifd, uint InputStripSource::~InputStripSource() {} status_t InputStripSource::writeToStream(Output& stream, uint32_t count) { - status_t err = OK; uint32_t fullSize = mWidth * mHeight * mBytesPerSample * mSamplesPerPixel; jlong offset = mOffset; @@ -765,7 +774,8 @@ static status_t generateNoiseProfile(const double* perChannelNoiseProfile, uint8 } } if (uninitialized) { - ALOGE("%s: No valid NoiseProfile coefficients for color plane %u", __FUNCTION__, p); + ALOGE("%s: No valid NoiseProfile coefficients for color plane %zu", + __FUNCTION__, p); return BAD_VALUE; } } @@ -809,29 +819,20 @@ static TiffWriter* DngCreator_getCreator(JNIEnv* env, jobject thiz) { static void DngCreator_nativeClassInit(JNIEnv* env, jclass clazz) { ALOGV("%s:", __FUNCTION__); - gDngCreatorClassInfo.mNativeContext = env->GetFieldID(clazz, - ANDROID_DNGCREATOR_CTX_JNI_ID, "J"); - LOG_ALWAYS_FATAL_IF(gDngCreatorClassInfo.mNativeContext == NULL, - "can't find android/hardware/camera2/DngCreator.%s", - ANDROID_DNGCREATOR_CTX_JNI_ID); - - jclass outputStreamClazz = env->FindClass("java/io/OutputStream"); - LOG_ALWAYS_FATAL_IF(outputStreamClazz == NULL, "Can't find java/io/OutputStream class"); - gOutputStreamClassInfo.mWriteMethod = env->GetMethodID(outputStreamClazz, "write", "([BII)V"); - LOG_ALWAYS_FATAL_IF(gOutputStreamClassInfo.mWriteMethod == NULL, "Can't find write method"); - - jclass inputStreamClazz = env->FindClass("java/io/InputStream"); - LOG_ALWAYS_FATAL_IF(inputStreamClazz == NULL, "Can't find java/io/InputStream class"); - gInputStreamClassInfo.mReadMethod = env->GetMethodID(inputStreamClazz, "read", "([BII)I"); - LOG_ALWAYS_FATAL_IF(gInputStreamClassInfo.mReadMethod == NULL, "Can't find read method"); - gInputStreamClassInfo.mSkipMethod = env->GetMethodID(inputStreamClazz, "skip", "(J)J"); - LOG_ALWAYS_FATAL_IF(gInputStreamClassInfo.mSkipMethod == NULL, "Can't find skip method"); - - jclass inputBufferClazz = env->FindClass("java/nio/ByteBuffer"); - LOG_ALWAYS_FATAL_IF(inputBufferClazz == NULL, "Can't find java/nio/ByteBuffer class"); - gInputByteBufferClassInfo.mGetMethod = env->GetMethodID(inputBufferClazz, "get", - "([BII)Ljava/nio/ByteBuffer;"); - LOG_ALWAYS_FATAL_IF(gInputByteBufferClassInfo.mGetMethod == NULL, "Can't find get method"); + gDngCreatorClassInfo.mNativeContext = GetFieldIDOrDie(env, + clazz, ANDROID_DNGCREATOR_CTX_JNI_ID, "J"); + + jclass outputStreamClazz = FindClassOrDie(env, "java/io/OutputStream"); + gOutputStreamClassInfo.mWriteMethod = GetMethodIDOrDie(env, + outputStreamClazz, "write", "([BII)V"); + + jclass inputStreamClazz = FindClassOrDie(env, "java/io/InputStream"); + gInputStreamClassInfo.mReadMethod = GetMethodIDOrDie(env, inputStreamClazz, "read", "([BII)I"); + gInputStreamClassInfo.mSkipMethod = GetMethodIDOrDie(env, inputStreamClazz, "skip", "(J)J"); + + jclass inputBufferClazz = FindClassOrDie(env, "java/nio/ByteBuffer"); + gInputByteBufferClassInfo.mGetMethod = GetMethodIDOrDie(env, + inputBufferClazz, "get", "([BII)Ljava/nio/ByteBuffer;"); } static void DngCreator_init(JNIEnv* env, jobject thiz, jobject characteristicsPtr, @@ -859,7 +860,6 @@ static void DngCreator_init(JNIEnv* env, jobject thiz, jobject characteristicsPt const uint32_t samplesPerPixel = 1; const uint32_t bitsPerSample = BITS_PER_SAMPLE; - const uint32_t bitsPerByte = BITS_PER_SAMPLE / BYTES_PER_SAMPLE; uint32_t imageWidth = 0; uint32_t imageHeight = 0; @@ -1407,8 +1407,9 @@ static void DngCreator_init(JNIEnv* env, jobject thiz, jobject characteristicsPt if (entry.count > 0) { if (entry.count != numCfaChannels * 2) { - ALOGW("%s: Invalid entry count %u for noise profile returned in characteristics," - " no noise profile tag written...", __FUNCTION__, entry.count); + ALOGW("%s: Invalid entry count %zu for noise profile returned " + "in characteristics, no noise profile tag written...", + __FUNCTION__, entry.count); } else { if ((err = generateNoiseProfile(entry.data.d, cfaOut, numCfaChannels, cfaPlaneColor, numPlaneColors, /*out*/ noiseProfile)) == OK) { @@ -1643,7 +1644,7 @@ static void DngCreator_nativeSetThumbnail(JNIEnv* env, jobject thiz, jobject buf size_t fullSize = width * height * BYTES_PER_RGB_PIXEL; jlong capacity = env->GetDirectBufferCapacity(buffer); - if (capacity != fullSize) { + if (static_cast<uint64_t>(capacity) != static_cast<uint64_t>(fullSize)) { jniThrowExceptionFmt(env, "java/lang/AssertionError", "Invalid size %d for thumbnail, expected size was %d", capacity, fullSize); @@ -1803,8 +1804,9 @@ static void DngCreator_nativeWriteImage(JNIEnv* env, jobject thiz, jobject outSt jint height, jobject inBuffer, jint rowStride, jint pixStride, jlong offset, jboolean isDirect) { ALOGV("%s:", __FUNCTION__); - ALOGV("%s: nativeWriteImage called with: width=%d, height=%d, rowStride=%d, pixStride=%d," - " offset=%lld", __FUNCTION__, width, height, rowStride, pixStride, offset); + ALOGV("%s: nativeWriteImage called with: width=%d, height=%d, " + "rowStride=%d, pixStride=%d, offset=%" PRId64, __FUNCTION__, width, + height, rowStride, pixStride, offset); uint32_t rStride = static_cast<uint32_t>(rowStride); uint32_t pStride = static_cast<uint32_t>(pixStride); uint32_t uWidth = static_cast<uint32_t>(width); @@ -1911,12 +1913,12 @@ static void DngCreator_nativeWriteInputStream(JNIEnv* env, jobject thiz, jobject uint32_t uHeight = static_cast<uint32_t>(height); uint64_t uOffset = static_cast<uint32_t>(offset); - ALOGV("%s: nativeWriteInputStream called with: width=%d, height=%d, rowStride=%u," - "pixStride=%u, offset=%lld", __FUNCTION__, width, height, rowStride, pixStride, - offset); + ALOGV("%s: nativeWriteInputStream called with: width=%d, height=%d, " + "rowStride=%d, pixStride=%d, offset=%" PRId64, __FUNCTION__, width, + height, rowStride, pixStride, offset); sp<JniOutputStream> out = new JniOutputStream(env, outStream); - if(env->ExceptionCheck()) { + if (env->ExceptionCheck()) { ALOGE("%s: Could not allocate buffers for output stream", __FUNCTION__); return; } @@ -1990,7 +1992,6 @@ static JNINativeMethod gDngCreatorMethods[] = { }; int register_android_hardware_camera2_DngCreator(JNIEnv *env) { - return AndroidRuntime::registerNativeMethods(env, - "android/hardware/camera2/DngCreator", gDngCreatorMethods, - NELEM(gDngCreatorMethods)); + return RegisterMethodsOrDie(env, + "android/hardware/camera2/DngCreator", gDngCreatorMethods, NELEM(gDngCreatorMethods)); } diff --git a/core/jni/android_hardware_camera2_legacy_LegacyCameraDevice.cpp b/core/jni/android_hardware_camera2_legacy_LegacyCameraDevice.cpp index b27add8..aabf320 100644 --- a/core/jni/android_hardware_camera2_legacy_LegacyCameraDevice.cpp +++ b/core/jni/android_hardware_camera2_legacy_LegacyCameraDevice.cpp @@ -23,7 +23,7 @@ #include "jni.h" #include "JNIHelp.h" -#include "android_runtime/AndroidRuntime.h" +#include "core_jni_helpers.h" #include "android_runtime/android_view_Surface.h" #include "android_runtime/android_graphics_SurfaceTexture.h" @@ -315,8 +315,8 @@ static status_t produceFrame(const sp<ANativeWindow>& anw, case HAL_PIXEL_FORMAT_BLOB: { int8_t* img = NULL; struct camera3_jpeg_blob footer = { - jpeg_blob_id: CAMERA3_JPEG_BLOB_ID, - jpeg_size: (uint32_t)bufferLength + .jpeg_blob_id = CAMERA3_JPEG_BLOB_ID, + .jpeg_size = (uint32_t)bufferLength }; size_t totalJpegSize = bufferLength + sizeof(footer); @@ -627,7 +627,7 @@ static jlong LegacyCameraDevice_nativeGetSurfaceId(JNIEnv* env, jobject thiz, jo ALOGE("%s: Could not retrieve IGraphicBufferProducer from surface.", __FUNCTION__); return 0; } - sp<IBinder> b = gbp->asBinder(); + sp<IBinder> b = IInterface::asBinder(gbp); if (b == NULL) { ALOGE("%s: Could not retrieve IBinder from surface.", __FUNCTION__); return 0; @@ -745,7 +745,7 @@ static JNINativeMethod gCameraDeviceMethods[] = { int register_android_hardware_camera2_legacy_LegacyCameraDevice(JNIEnv* env) { // Register native functions - return AndroidRuntime::registerNativeMethods(env, + return RegisterMethodsOrDie(env, CAMERA_DEVICE_CLASS_NAME, gCameraDeviceMethods, NELEM(gCameraDeviceMethods)); diff --git a/core/jni/android_hardware_camera2_legacy_PerfMeasurement.cpp b/core/jni/android_hardware_camera2_legacy_PerfMeasurement.cpp index 93473a5..7257597 100644 --- a/core/jni/android_hardware_camera2_legacy_PerfMeasurement.cpp +++ b/core/jni/android_hardware_camera2_legacy_PerfMeasurement.cpp @@ -22,7 +22,7 @@ #include "jni.h" #include "JNIHelp.h" -#include "android_runtime/AndroidRuntime.h" +#include "core_jni_helpers.h" #include <ui/GraphicBuffer.h> #include <system/window.h> @@ -328,7 +328,7 @@ static JNINativeMethod gPerfMeasurementMethods[] = { int register_android_hardware_camera2_legacy_PerfMeasurement(JNIEnv* env) { // Register native functions - return AndroidRuntime::registerNativeMethods(env, + return RegisterMethodsOrDie(env, PERF_MEASUREMENT_CLASS_NAME, gPerfMeasurementMethods, NELEM(gPerfMeasurementMethods)); diff --git a/core/jni/android_hardware_location_ActivityRecognitionHardware.cpp b/core/jni/android_hardware_location_ActivityRecognitionHardware.cpp index b8fa04c..470c5ba 100644 --- a/core/jni/android_hardware_location_ActivityRecognitionHardware.cpp +++ b/core/jni/android_hardware_location_ActivityRecognitionHardware.cpp @@ -123,7 +123,7 @@ static void activity_callback( detach_thread(); } -activity_recognition_callback_procs_t sCallbacks { +activity_recognition_callback_procs_t sCallbacks = { activity_callback, }; diff --git a/core/jni/android_media_AudioRecord.cpp b/core/jni/android_media_AudioRecord.cpp index 2b2bee9..df9f893 100644 --- a/core/jni/android_media_AudioRecord.cpp +++ b/core/jni/android_media_AudioRecord.cpp @@ -21,7 +21,7 @@ #include <inttypes.h> #include <jni.h> #include <JNIHelp.h> -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" #include <utils/Log.h> #include <media/AudioRecord.h> @@ -606,59 +606,28 @@ int register_android_media_AudioRecord(JNIEnv *env) // Get the AudioRecord class - jclass audioRecordClass = env->FindClass(kClassPathName); - if (audioRecordClass == NULL) { - ALOGE("Can't find %s", kClassPathName); - return -1; - } + jclass audioRecordClass = FindClassOrDie(env, kClassPathName); // Get the postEvent method - javaAudioRecordFields.postNativeEventInJava = env->GetStaticMethodID( - audioRecordClass, - JAVA_POSTEVENT_CALLBACK_NAME, "(Ljava/lang/Object;IIILjava/lang/Object;)V"); - if (javaAudioRecordFields.postNativeEventInJava == NULL) { - ALOGE("Can't find AudioRecord.%s", JAVA_POSTEVENT_CALLBACK_NAME); - return -1; - } + javaAudioRecordFields.postNativeEventInJava = GetStaticMethodIDOrDie(env, + audioRecordClass, JAVA_POSTEVENT_CALLBACK_NAME, + "(Ljava/lang/Object;IIILjava/lang/Object;)V"); // Get the variables // mNativeRecorderInJavaObj - javaAudioRecordFields.nativeRecorderInJavaObj = - env->GetFieldID(audioRecordClass, - JAVA_NATIVERECORDERINJAVAOBJ_FIELD_NAME, "J"); - if (javaAudioRecordFields.nativeRecorderInJavaObj == NULL) { - ALOGE("Can't find AudioRecord.%s", JAVA_NATIVERECORDERINJAVAOBJ_FIELD_NAME); - return -1; - } + javaAudioRecordFields.nativeRecorderInJavaObj = GetFieldIDOrDie(env, + audioRecordClass, JAVA_NATIVERECORDERINJAVAOBJ_FIELD_NAME, "J"); // mNativeCallbackCookie - javaAudioRecordFields.nativeCallbackCookie = env->GetFieldID( - audioRecordClass, - JAVA_NATIVECALLBACKINFO_FIELD_NAME, "J"); - if (javaAudioRecordFields.nativeCallbackCookie == NULL) { - ALOGE("Can't find AudioRecord.%s", JAVA_NATIVECALLBACKINFO_FIELD_NAME); - return -1; - } + javaAudioRecordFields.nativeCallbackCookie = GetFieldIDOrDie(env, + audioRecordClass, JAVA_NATIVECALLBACKINFO_FIELD_NAME, "J"); // Get the AudioAttributes class and fields - jclass audioAttrClass = env->FindClass(kAudioAttributesClassPathName); - if (audioAttrClass == NULL) { - ALOGE("Can't find %s", kAudioAttributesClassPathName); - return -1; - } - jclass audioAttributesClassRef = (jclass)env->NewGlobalRef(audioAttrClass); - javaAudioAttrFields.fieldRecSource = env->GetFieldID(audioAttributesClassRef, "mSource", "I"); - javaAudioAttrFields.fieldFlags = env->GetFieldID(audioAttributesClassRef, "mFlags", "I"); - javaAudioAttrFields.fieldFormattedTags = - env->GetFieldID(audioAttributesClassRef, "mFormattedTags", "Ljava/lang/String;"); - env->DeleteGlobalRef(audioAttributesClassRef); - if (javaAudioAttrFields.fieldRecSource == NULL - || javaAudioAttrFields.fieldFlags == NULL - || javaAudioAttrFields.fieldFormattedTags == NULL) { - ALOGE("Can't initialize AudioAttributes fields"); - return -1; - } + jclass audioAttrClass = FindClassOrDie(env, kAudioAttributesClassPathName); + javaAudioAttrFields.fieldRecSource = GetFieldIDOrDie(env, audioAttrClass, "mSource", "I"); + javaAudioAttrFields.fieldFlags = GetFieldIDOrDie(env, audioAttrClass, "mFlags", "I"); + javaAudioAttrFields.fieldFormattedTags = GetFieldIDOrDie(env, + audioAttrClass, "mFormattedTags", "Ljava/lang/String;"); - return AndroidRuntime::registerNativeMethods(env, - kClassPathName, gMethods, NELEM(gMethods)); + return RegisterMethodsOrDie(env, kClassPathName, gMethods, NELEM(gMethods)); } // ---------------------------------------------------------------------------- diff --git a/core/jni/android_media_AudioSystem.cpp b/core/jni/android_media_AudioSystem.cpp index fee1ead..0bf269f 100644 --- a/core/jni/android_media_AudioSystem.cpp +++ b/core/jni/android_media_AudioSystem.cpp @@ -22,7 +22,7 @@ #include <jni.h> #include <JNIHelp.h> -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" #include <media/AudioSystem.h> #include <media/AudioPolicy.h> @@ -298,7 +298,9 @@ android_media_AudioSystem_setParameters(JNIEnv *env, jobject thiz, jstring keyVa const jchar* c_keyValuePairs = env->GetStringCritical(keyValuePairs, 0); String8 c_keyValuePairs8; if (keyValuePairs) { - c_keyValuePairs8 = String8(c_keyValuePairs, env->GetStringLength(keyValuePairs)); + c_keyValuePairs8 = String8( + reinterpret_cast<const char16_t*>(c_keyValuePairs), + env->GetStringLength(keyValuePairs)); env->ReleaseStringCritical(keyValuePairs, c_keyValuePairs); } int status = check_AudioSystem_Command(AudioSystem::setParameters(c_keyValuePairs8)); @@ -311,7 +313,8 @@ android_media_AudioSystem_getParameters(JNIEnv *env, jobject thiz, jstring keys) const jchar* c_keys = env->GetStringCritical(keys, 0); String8 c_keys8; if (keys) { - c_keys8 = String8(c_keys, env->GetStringLength(keys)); + c_keys8 = String8(reinterpret_cast<const char16_t*>(c_keys), + env->GetStringLength(keys)); env->ReleaseStringCritical(keys, c_keys); } return env->NewStringUTF(AudioSystem::getParameters(c_keys8).string()); @@ -1120,7 +1123,7 @@ exit: return jStatus; } -static int +static jint android_media_AudioSystem_releaseAudioPatch(JNIEnv *env, jobject clazz, jobject jPatch) { @@ -1142,7 +1145,7 @@ android_media_AudioSystem_releaseAudioPatch(JNIEnv *env, jobject clazz, status_t status = AudioSystem::releaseAudioPatch(handle); ALOGV("AudioSystem::releaseAudioPatch() returned %d", status); jint jStatus = nativeToJavaStatus(status); - return status; + return jStatus; } static jint @@ -1222,7 +1225,7 @@ android_media_AudioSystem_listAudioPatches(JNIEnv *env, jobject clazz, jStatus = AUDIO_JAVA_ERROR; goto exit; } - ALOGV("listAudioPatches patch %d num_sources %d num_sinks %d", + ALOGV("listAudioPatches patch %zu num_sources %d num_sinks %d", i, nPatches[i].num_sources, nPatches[i].num_sinks); env->SetIntField(patchHandle, gAudioHandleFields.mId, nPatches[i].id); @@ -1246,7 +1249,7 @@ android_media_AudioSystem_listAudioPatches(JNIEnv *env, jobject clazz, env->SetObjectArrayElement(jSources, j, jSource); env->DeleteLocalRef(jSource); jSource = NULL; - ALOGV("listAudioPatches patch %d source %d is a %s handle %d", + ALOGV("listAudioPatches patch %zu source %zu is a %s handle %d", i, j, nPatches[i].sources[j].type == AUDIO_PORT_TYPE_DEVICE ? "device" : "mix", nPatches[i].sources[j].id); @@ -1271,7 +1274,7 @@ android_media_AudioSystem_listAudioPatches(JNIEnv *env, jobject clazz, env->SetObjectArrayElement(jSinks, j, jSink); env->DeleteLocalRef(jSink); jSink = NULL; - ALOGV("listAudioPatches patch %d sink %d is a %s handle %d", + ALOGV("listAudioPatches patch %zu sink %zu is a %s handle %d", i, j, nPatches[i].sinks[j].type == AUDIO_PORT_TYPE_DEVICE ? "device" : "mix", nPatches[i].sinks[j].id); @@ -1540,135 +1543,130 @@ static JNINativeMethod gEventHandlerMethods[] = { int register_android_media_AudioSystem(JNIEnv *env) { - - jclass arrayListClass = env->FindClass("java/util/ArrayList"); - gArrayListClass = (jclass) env->NewGlobalRef(arrayListClass); - gArrayListMethods.add = env->GetMethodID(arrayListClass, "add", "(Ljava/lang/Object;)Z"); - gArrayListMethods.toArray = env->GetMethodID(arrayListClass, "toArray", "()[Ljava/lang/Object;"); - - jclass audioHandleClass = env->FindClass("android/media/AudioHandle"); - gAudioHandleClass = (jclass) env->NewGlobalRef(audioHandleClass); - gAudioHandleCstor = env->GetMethodID(audioHandleClass, "<init>", "(I)V"); - gAudioHandleFields.mId = env->GetFieldID(audioHandleClass, "mId", "I"); - - jclass audioPortClass = env->FindClass("android/media/AudioPort"); - gAudioPortClass = (jclass) env->NewGlobalRef(audioPortClass); - gAudioPortCstor = env->GetMethodID(audioPortClass, "<init>", - "(Landroid/media/AudioHandle;I[I[I[I[Landroid/media/AudioGain;)V"); - gAudioPortFields.mHandle = env->GetFieldID(audioPortClass, "mHandle", + jclass arrayListClass = FindClassOrDie(env, "java/util/ArrayList"); + gArrayListClass = MakeGlobalRefOrDie(env, arrayListClass); + gArrayListMethods.add = GetMethodIDOrDie(env, arrayListClass, "add", "(Ljava/lang/Object;)Z"); + gArrayListMethods.toArray = GetMethodIDOrDie(env, arrayListClass, "toArray", "()[Ljava/lang/Object;"); + + jclass audioHandleClass = FindClassOrDie(env, "android/media/AudioHandle"); + gAudioHandleClass = MakeGlobalRefOrDie(env, audioHandleClass); + gAudioHandleCstor = GetMethodIDOrDie(env, audioHandleClass, "<init>", "(I)V"); + gAudioHandleFields.mId = GetFieldIDOrDie(env, audioHandleClass, "mId", "I"); + + jclass audioPortClass = FindClassOrDie(env, "android/media/AudioPort"); + gAudioPortClass = MakeGlobalRefOrDie(env, audioPortClass); + gAudioPortCstor = GetMethodIDOrDie(env, audioPortClass, "<init>", + "(Landroid/media/AudioHandle;I[I[I[I[Landroid/media/AudioGain;)V"); + gAudioPortFields.mHandle = GetFieldIDOrDie(env, audioPortClass, "mHandle", "Landroid/media/AudioHandle;"); - gAudioPortFields.mRole = env->GetFieldID(audioPortClass, "mRole", "I"); - gAudioPortFields.mGains = env->GetFieldID(audioPortClass, "mGains", + gAudioPortFields.mRole = GetFieldIDOrDie(env, audioPortClass, "mRole", "I"); + gAudioPortFields.mGains = GetFieldIDOrDie(env, audioPortClass, "mGains", "[Landroid/media/AudioGain;"); - gAudioPortFields.mActiveConfig = env->GetFieldID(audioPortClass, "mActiveConfig", - "Landroid/media/AudioPortConfig;"); - - jclass audioPortConfigClass = env->FindClass("android/media/AudioPortConfig"); - gAudioPortConfigClass = (jclass) env->NewGlobalRef(audioPortConfigClass); - gAudioPortConfigCstor = env->GetMethodID(audioPortConfigClass, "<init>", - "(Landroid/media/AudioPort;IIILandroid/media/AudioGainConfig;)V"); - gAudioPortConfigFields.mPort = env->GetFieldID(audioPortConfigClass, "mPort", + gAudioPortFields.mActiveConfig = GetFieldIDOrDie(env, audioPortClass, "mActiveConfig", + "Landroid/media/AudioPortConfig;"); + + jclass audioPortConfigClass = FindClassOrDie(env, "android/media/AudioPortConfig"); + gAudioPortConfigClass = MakeGlobalRefOrDie(env, audioPortConfigClass); + gAudioPortConfigCstor = GetMethodIDOrDie(env, audioPortConfigClass, "<init>", + "(Landroid/media/AudioPort;IIILandroid/media/AudioGainConfig;)V"); + gAudioPortConfigFields.mPort = GetFieldIDOrDie(env, audioPortConfigClass, "mPort", "Landroid/media/AudioPort;"); - gAudioPortConfigFields.mSamplingRate = env->GetFieldID(audioPortConfigClass, + gAudioPortConfigFields.mSamplingRate = GetFieldIDOrDie(env, audioPortConfigClass, "mSamplingRate", "I"); - gAudioPortConfigFields.mChannelMask = env->GetFieldID(audioPortConfigClass, + gAudioPortConfigFields.mChannelMask = GetFieldIDOrDie(env, audioPortConfigClass, "mChannelMask", "I"); - gAudioPortConfigFields.mFormat = env->GetFieldID(audioPortConfigClass, "mFormat", "I"); - gAudioPortConfigFields.mGain = env->GetFieldID(audioPortConfigClass, "mGain", + gAudioPortConfigFields.mFormat = GetFieldIDOrDie(env, audioPortConfigClass, "mFormat", "I"); + gAudioPortConfigFields.mGain = GetFieldIDOrDie(env, audioPortConfigClass, "mGain", "Landroid/media/AudioGainConfig;"); - gAudioPortConfigFields.mConfigMask = env->GetFieldID(audioPortConfigClass, "mConfigMask", "I"); - - jclass audioDevicePortConfigClass = env->FindClass("android/media/AudioDevicePortConfig"); - gAudioDevicePortConfigClass = (jclass) env->NewGlobalRef(audioDevicePortConfigClass); - gAudioDevicePortConfigCstor = env->GetMethodID(audioDevicePortConfigClass, "<init>", - "(Landroid/media/AudioDevicePort;IIILandroid/media/AudioGainConfig;)V"); - - jclass audioMixPortConfigClass = env->FindClass("android/media/AudioMixPortConfig"); - gAudioMixPortConfigClass = (jclass) env->NewGlobalRef(audioMixPortConfigClass); - gAudioMixPortConfigCstor = env->GetMethodID(audioMixPortConfigClass, "<init>", - "(Landroid/media/AudioMixPort;IIILandroid/media/AudioGainConfig;)V"); - - jclass audioDevicePortClass = env->FindClass("android/media/AudioDevicePort"); - gAudioDevicePortClass = (jclass) env->NewGlobalRef(audioDevicePortClass); - gAudioDevicePortCstor = env->GetMethodID(audioDevicePortClass, "<init>", - "(Landroid/media/AudioHandle;[I[I[I[Landroid/media/AudioGain;ILjava/lang/String;)V"); - - jclass audioMixPortClass = env->FindClass("android/media/AudioMixPort"); - gAudioMixPortClass = (jclass) env->NewGlobalRef(audioMixPortClass); - gAudioMixPortCstor = env->GetMethodID(audioMixPortClass, "<init>", - "(Landroid/media/AudioHandle;I[I[I[I[Landroid/media/AudioGain;)V"); - - jclass audioGainClass = env->FindClass("android/media/AudioGain"); - gAudioGainClass = (jclass) env->NewGlobalRef(audioGainClass); - gAudioGainCstor = env->GetMethodID(audioGainClass, "<init>", "(IIIIIIIII)V"); - - jclass audioGainConfigClass = env->FindClass("android/media/AudioGainConfig"); - gAudioGainConfigClass = (jclass) env->NewGlobalRef(audioGainConfigClass); - gAudioGainConfigCstor = env->GetMethodID(audioGainConfigClass, "<init>", + gAudioPortConfigFields.mConfigMask = GetFieldIDOrDie(env, audioPortConfigClass, "mConfigMask", + "I"); + + jclass audioDevicePortConfigClass = FindClassOrDie(env, "android/media/AudioDevicePortConfig"); + gAudioDevicePortConfigClass = MakeGlobalRefOrDie(env, audioDevicePortConfigClass); + gAudioDevicePortConfigCstor = GetMethodIDOrDie(env, audioDevicePortConfigClass, "<init>", + "(Landroid/media/AudioDevicePort;IIILandroid/media/AudioGainConfig;)V"); + + jclass audioMixPortConfigClass = FindClassOrDie(env, "android/media/AudioMixPortConfig"); + gAudioMixPortConfigClass = MakeGlobalRefOrDie(env, audioMixPortConfigClass); + gAudioMixPortConfigCstor = GetMethodIDOrDie(env, audioMixPortConfigClass, "<init>", + "(Landroid/media/AudioMixPort;IIILandroid/media/AudioGainConfig;)V"); + + jclass audioDevicePortClass = FindClassOrDie(env, "android/media/AudioDevicePort"); + gAudioDevicePortClass = MakeGlobalRefOrDie(env, audioDevicePortClass); + gAudioDevicePortCstor = GetMethodIDOrDie(env, audioDevicePortClass, "<init>", + "(Landroid/media/AudioHandle;[I[I[I[Landroid/media/AudioGain;ILjava/lang/String;)V"); + + jclass audioMixPortClass = FindClassOrDie(env, "android/media/AudioMixPort"); + gAudioMixPortClass = MakeGlobalRefOrDie(env, audioMixPortClass); + gAudioMixPortCstor = GetMethodIDOrDie(env, audioMixPortClass, "<init>", + "(Landroid/media/AudioHandle;I[I[I[I[Landroid/media/AudioGain;)V"); + + jclass audioGainClass = FindClassOrDie(env, "android/media/AudioGain"); + gAudioGainClass = MakeGlobalRefOrDie(env, audioGainClass); + gAudioGainCstor = GetMethodIDOrDie(env, audioGainClass, "<init>", "(IIIIIIIII)V"); + + jclass audioGainConfigClass = FindClassOrDie(env, "android/media/AudioGainConfig"); + gAudioGainConfigClass = MakeGlobalRefOrDie(env, audioGainConfigClass); + gAudioGainConfigCstor = GetMethodIDOrDie(env, audioGainConfigClass, "<init>", "(ILandroid/media/AudioGain;II[II)V"); - gAudioGainConfigFields.mIndex = env->GetFieldID(gAudioGainConfigClass, "mIndex", "I"); - gAudioGainConfigFields.mMode = env->GetFieldID(audioGainConfigClass, "mMode", "I"); - gAudioGainConfigFields.mChannelMask = env->GetFieldID(audioGainConfigClass, "mChannelMask", + gAudioGainConfigFields.mIndex = GetFieldIDOrDie(env, gAudioGainConfigClass, "mIndex", "I"); + gAudioGainConfigFields.mMode = GetFieldIDOrDie(env, audioGainConfigClass, "mMode", "I"); + gAudioGainConfigFields.mChannelMask = GetFieldIDOrDie(env, audioGainConfigClass, "mChannelMask", "I"); - gAudioGainConfigFields.mValues = env->GetFieldID(audioGainConfigClass, "mValues", "[I"); - gAudioGainConfigFields.mRampDurationMs = env->GetFieldID(audioGainConfigClass, + gAudioGainConfigFields.mValues = GetFieldIDOrDie(env, audioGainConfigClass, "mValues", "[I"); + gAudioGainConfigFields.mRampDurationMs = GetFieldIDOrDie(env, audioGainConfigClass, "mRampDurationMs", "I"); - jclass audioPatchClass = env->FindClass("android/media/AudioPatch"); - gAudioPatchClass = (jclass) env->NewGlobalRef(audioPatchClass); - gAudioPatchCstor = env->GetMethodID(audioPatchClass, "<init>", + jclass audioPatchClass = FindClassOrDie(env, "android/media/AudioPatch"); + gAudioPatchClass = MakeGlobalRefOrDie(env, audioPatchClass); + gAudioPatchCstor = GetMethodIDOrDie(env, audioPatchClass, "<init>", "(Landroid/media/AudioHandle;[Landroid/media/AudioPortConfig;[Landroid/media/AudioPortConfig;)V"); - gAudioPatchFields.mHandle = env->GetFieldID(audioPatchClass, "mHandle", + gAudioPatchFields.mHandle = GetFieldIDOrDie(env, audioPatchClass, "mHandle", "Landroid/media/AudioHandle;"); - jclass eventHandlerClass = env->FindClass(kEventHandlerClassPathName); - gPostEventFromNative = env->GetStaticMethodID(eventHandlerClass, "postEventFromNative", - "(Ljava/lang/Object;IIILjava/lang/Object;)V"); + jclass eventHandlerClass = FindClassOrDie(env, kEventHandlerClassPathName); + gPostEventFromNative = GetStaticMethodIDOrDie(env, eventHandlerClass, "postEventFromNative", + "(Ljava/lang/Object;IIILjava/lang/Object;)V"); - jclass audioMixClass = env->FindClass("android/media/audiopolicy/AudioMix"); - gAudioMixClass = (jclass) env->NewGlobalRef(audioMixClass); - gAudioMixFields.mRule = env->GetFieldID(audioMixClass, "mRule", + jclass audioMixClass = FindClassOrDie(env, "android/media/audiopolicy/AudioMix"); + gAudioMixClass = MakeGlobalRefOrDie(env, audioMixClass); + gAudioMixFields.mRule = GetFieldIDOrDie(env, audioMixClass, "mRule", "Landroid/media/audiopolicy/AudioMixingRule;"); - gAudioMixFields.mFormat = env->GetFieldID(audioMixClass, "mFormat", + gAudioMixFields.mFormat = GetFieldIDOrDie(env, audioMixClass, "mFormat", "Landroid/media/AudioFormat;"); - gAudioMixFields.mRouteFlags = env->GetFieldID(audioMixClass, "mRouteFlags", "I"); - gAudioMixFields.mRegistrationId = env->GetFieldID(audioMixClass, "mRegistrationId", + gAudioMixFields.mRouteFlags = GetFieldIDOrDie(env, audioMixClass, "mRouteFlags", "I"); + gAudioMixFields.mRegistrationId = GetFieldIDOrDie(env, audioMixClass, "mRegistrationId", "Ljava/lang/String;"); - gAudioMixFields.mMixType = env->GetFieldID(audioMixClass, "mMixType", "I"); + gAudioMixFields.mMixType = GetFieldIDOrDie(env, audioMixClass, "mMixType", "I"); - jclass audioFormatClass = env->FindClass("android/media/AudioFormat"); - gAudioFormatClass = (jclass) env->NewGlobalRef(audioFormatClass); - gAudioFormatFields.mEncoding = env->GetFieldID(audioFormatClass, "mEncoding", "I"); - gAudioFormatFields.mSampleRate = env->GetFieldID(audioFormatClass, "mSampleRate", "I"); - gAudioFormatFields.mChannelMask = env->GetFieldID(audioFormatClass, "mChannelMask", "I"); + jclass audioFormatClass = FindClassOrDie(env, "android/media/AudioFormat"); + gAudioFormatClass = MakeGlobalRefOrDie(env, audioFormatClass); + gAudioFormatFields.mEncoding = GetFieldIDOrDie(env, audioFormatClass, "mEncoding", "I"); + gAudioFormatFields.mSampleRate = GetFieldIDOrDie(env, audioFormatClass, "mSampleRate", "I"); + gAudioFormatFields.mChannelMask = GetFieldIDOrDie(env, audioFormatClass, "mChannelMask", "I"); - jclass audioMixingRuleClass = env->FindClass("android/media/audiopolicy/AudioMixingRule"); - gAudioMixingRuleClass = (jclass) env->NewGlobalRef(audioMixingRuleClass); - gAudioMixingRuleFields.mCriteria = env->GetFieldID(audioMixingRuleClass, "mCriteria", + jclass audioMixingRuleClass = FindClassOrDie(env, "android/media/audiopolicy/AudioMixingRule"); + gAudioMixingRuleClass = MakeGlobalRefOrDie(env, audioMixingRuleClass); + gAudioMixingRuleFields.mCriteria = GetFieldIDOrDie(env, audioMixingRuleClass, "mCriteria", "Ljava/util/ArrayList;"); jclass attributeMatchCriterionClass = - env->FindClass("android/media/audiopolicy/AudioMixingRule$AttributeMatchCriterion"); - gAttributeMatchCriterionClass = (jclass) env->NewGlobalRef(attributeMatchCriterionClass); - gAttributeMatchCriterionFields.mAttr = env->GetFieldID(attributeMatchCriterionClass, "mAttr", + FindClassOrDie(env, "android/media/audiopolicy/AudioMixingRule$AttributeMatchCriterion"); + gAttributeMatchCriterionClass = MakeGlobalRefOrDie(env, attributeMatchCriterionClass); + gAttributeMatchCriterionFields.mAttr = GetFieldIDOrDie(env, attributeMatchCriterionClass, "mAttr", "Landroid/media/AudioAttributes;"); - gAttributeMatchCriterionFields.mRule = env->GetFieldID(attributeMatchCriterionClass, "mRule", + gAttributeMatchCriterionFields.mRule = GetFieldIDOrDie(env, attributeMatchCriterionClass, "mRule", "I"); - jclass audioAttributesClass = env->FindClass("android/media/AudioAttributes"); - gAudioAttributesClass = (jclass) env->NewGlobalRef(audioAttributesClass); - gAudioAttributesFields.mUsage = env->GetFieldID(audioAttributesClass, "mUsage", "I"); - gAudioAttributesFields.mSource = env->GetFieldID(audioAttributesClass, "mSource", "I"); + jclass audioAttributesClass = FindClassOrDie(env, "android/media/AudioAttributes"); + gAudioAttributesClass = MakeGlobalRefOrDie(env, audioAttributesClass); + gAudioAttributesFields.mUsage = GetFieldIDOrDie(env, audioAttributesClass, "mUsage", "I"); + gAudioAttributesFields.mSource = GetFieldIDOrDie(env, audioAttributesClass, "mSource", "I"); AudioSystem::setErrorCallback(android_media_AudioSystem_error_callback); - int status = AndroidRuntime::registerNativeMethods(env, - kClassPathName, gMethods, NELEM(gMethods)); - - if (status == 0) { - status = AndroidRuntime::registerNativeMethods(env, - kEventHandlerClassPathName, gEventHandlerMethods, NELEM(gEventHandlerMethods)); - } - return status; + RegisterMethodsOrDie(env, kClassPathName, gMethods, NELEM(gMethods)); + return RegisterMethodsOrDie(env, kEventHandlerClassPathName, gEventHandlerMethods, + NELEM(gEventHandlerMethods)); } diff --git a/core/jni/android_media_AudioTrack.cpp b/core/jni/android_media_AudioTrack.cpp index ab38864..c6f4199 100644 --- a/core/jni/android_media_AudioTrack.cpp +++ b/core/jni/android_media_AudioTrack.cpp @@ -19,7 +19,7 @@ #include <JNIHelp.h> #include <JniConstants.h> -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" #include "ScopedBytes.h" @@ -1062,68 +1062,34 @@ int register_android_media_AudioTrack(JNIEnv *env) javaAudioTrackFields.postNativeEventInJava = NULL; // Get the AudioTrack class - jclass audioTrackClass = env->FindClass(kClassPathName); - if (audioTrackClass == NULL) { - ALOGE("Can't find %s", kClassPathName); - return -1; - } + jclass audioTrackClass = FindClassOrDie(env, kClassPathName); // Get the postEvent method - javaAudioTrackFields.postNativeEventInJava = env->GetStaticMethodID( - audioTrackClass, - JAVA_POSTEVENT_CALLBACK_NAME, "(Ljava/lang/Object;IIILjava/lang/Object;)V"); - if (javaAudioTrackFields.postNativeEventInJava == NULL) { - ALOGE("Can't find AudioTrack.%s", JAVA_POSTEVENT_CALLBACK_NAME); - return -1; - } + javaAudioTrackFields.postNativeEventInJava = GetStaticMethodIDOrDie(env, + audioTrackClass, JAVA_POSTEVENT_CALLBACK_NAME, + "(Ljava/lang/Object;IIILjava/lang/Object;)V"); // Get the variables fields // nativeTrackInJavaObj - javaAudioTrackFields.nativeTrackInJavaObj = env->GetFieldID( - audioTrackClass, - JAVA_NATIVETRACKINJAVAOBJ_FIELD_NAME, "J"); - if (javaAudioTrackFields.nativeTrackInJavaObj == NULL) { - ALOGE("Can't find AudioTrack.%s", JAVA_NATIVETRACKINJAVAOBJ_FIELD_NAME); - return -1; - } + javaAudioTrackFields.nativeTrackInJavaObj = GetFieldIDOrDie(env, + audioTrackClass, JAVA_NATIVETRACKINJAVAOBJ_FIELD_NAME, "J"); // jniData - javaAudioTrackFields.jniData = env->GetFieldID( - audioTrackClass, - JAVA_JNIDATA_FIELD_NAME, "J"); - if (javaAudioTrackFields.jniData == NULL) { - ALOGE("Can't find AudioTrack.%s", JAVA_JNIDATA_FIELD_NAME); - return -1; - } + javaAudioTrackFields.jniData = GetFieldIDOrDie(env, + audioTrackClass, JAVA_JNIDATA_FIELD_NAME, "J"); // fieldStreamType - javaAudioTrackFields.fieldStreamType = env->GetFieldID(audioTrackClass, - JAVA_STREAMTYPE_FIELD_NAME, "I"); - if (javaAudioTrackFields.fieldStreamType == NULL) { - ALOGE("Can't find AudioTrack.%s", JAVA_STREAMTYPE_FIELD_NAME); - return -1; - } + javaAudioTrackFields.fieldStreamType = GetFieldIDOrDie(env, + audioTrackClass, JAVA_STREAMTYPE_FIELD_NAME, "I"); // Get the AudioAttributes class and fields - jclass audioAttrClass = env->FindClass(kAudioAttributesClassPathName); - if (audioAttrClass == NULL) { - ALOGE("Can't find %s", kAudioAttributesClassPathName); - return -1; - } - jclass audioAttributesClassRef = (jclass)env->NewGlobalRef(audioAttrClass); - javaAudioAttrFields.fieldUsage = env->GetFieldID(audioAttributesClassRef, "mUsage", "I"); - javaAudioAttrFields.fieldContentType - = env->GetFieldID(audioAttributesClassRef, "mContentType", "I"); - javaAudioAttrFields.fieldFlags = env->GetFieldID(audioAttributesClassRef, "mFlags", "I"); - javaAudioAttrFields.fieldFormattedTags = - env->GetFieldID(audioAttributesClassRef, "mFormattedTags", "Ljava/lang/String;"); - env->DeleteGlobalRef(audioAttributesClassRef); - if (javaAudioAttrFields.fieldUsage == NULL || javaAudioAttrFields.fieldContentType == NULL - || javaAudioAttrFields.fieldFlags == NULL - || javaAudioAttrFields.fieldFormattedTags == NULL) { - ALOGE("Can't initialize AudioAttributes fields"); - return -1; - } - - return AndroidRuntime::registerNativeMethods(env, kClassPathName, gMethods, NELEM(gMethods)); + jclass audioAttrClass = FindClassOrDie(env, kAudioAttributesClassPathName); + javaAudioAttrFields.fieldUsage = GetFieldIDOrDie(env, audioAttrClass, "mUsage", "I"); + javaAudioAttrFields.fieldContentType = GetFieldIDOrDie(env, + audioAttrClass, "mContentType", "I"); + javaAudioAttrFields.fieldFlags = GetFieldIDOrDie(env, audioAttrClass, "mFlags", "I"); + javaAudioAttrFields.fieldFormattedTags = GetFieldIDOrDie(env, + audioAttrClass, "mFormattedTags", "Ljava/lang/String;"); + + return RegisterMethodsOrDie(env, kClassPathName, gMethods, NELEM(gMethods)); } diff --git a/core/jni/android_media_JetPlayer.cpp b/core/jni/android_media_JetPlayer.cpp index 69f5711..d441f10 100644 --- a/core/jni/android_media_JetPlayer.cpp +++ b/core/jni/android_media_JetPlayer.cpp @@ -24,7 +24,7 @@ #include <jni.h> #include <JNIHelp.h> -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" #include <utils/Log.h> #include <media/JetPlayer.h> @@ -517,36 +517,22 @@ static JNINativeMethod gMethods[] = { int register_android_media_JetPlayer(JNIEnv *env) { - jclass jetPlayerClass = NULL; javaJetPlayerFields.jetClass = NULL; javaJetPlayerFields.postNativeEventInJava = NULL; javaJetPlayerFields.nativePlayerInJavaObj = NULL; // Get the JetPlayer java class - jetPlayerClass = env->FindClass(kClassPathName); - if (jetPlayerClass == NULL) { - ALOGE("Can't find %s", kClassPathName); - return -1; - } - javaJetPlayerFields.jetClass = (jclass)env->NewGlobalRef(jetPlayerClass); + jclass jetPlayerClass = FindClassOrDie(env, kClassPathName); + javaJetPlayerFields.jetClass = MakeGlobalRefOrDie(env, jetPlayerClass); // Get the mNativePlayerInJavaObj variable field - javaJetPlayerFields.nativePlayerInJavaObj = env->GetFieldID( - jetPlayerClass, - JAVA_NATIVEJETPLAYERINJAVAOBJ_FIELD_NAME, "J"); - if (javaJetPlayerFields.nativePlayerInJavaObj == NULL) { - ALOGE("Can't find JetPlayer.%s", JAVA_NATIVEJETPLAYERINJAVAOBJ_FIELD_NAME); - return -1; - } + javaJetPlayerFields.nativePlayerInJavaObj = GetFieldIDOrDie(env, + jetPlayerClass, JAVA_NATIVEJETPLAYERINJAVAOBJ_FIELD_NAME, "J"); // Get the callback to post events from this native code to Java - javaJetPlayerFields.postNativeEventInJava = env->GetStaticMethodID(javaJetPlayerFields.jetClass, - JAVA_NATIVEJETPOSTEVENT_CALLBACK_NAME, "(Ljava/lang/Object;III)V"); - if (javaJetPlayerFields.postNativeEventInJava == NULL) { - ALOGE("Can't find Jet.%s", JAVA_NATIVEJETPOSTEVENT_CALLBACK_NAME); - return -1; - } + javaJetPlayerFields.postNativeEventInJava = GetStaticMethodIDOrDie(env, + javaJetPlayerFields.jetClass, JAVA_NATIVEJETPOSTEVENT_CALLBACK_NAME, + "(Ljava/lang/Object;III)V"); - return AndroidRuntime::registerNativeMethods(env, - kClassPathName, gMethods, NELEM(gMethods)); + return RegisterMethodsOrDie(env, kClassPathName, gMethods, NELEM(gMethods)); } diff --git a/core/jni/android_media_RemoteDisplay.cpp b/core/jni/android_media_RemoteDisplay.cpp index 1cd3fbb..e2bba30 100644 --- a/core/jni/android_media_RemoteDisplay.cpp +++ b/core/jni/android_media_RemoteDisplay.cpp @@ -22,7 +22,7 @@ #include "android_os_Parcel.h" #include "android_util_Binder.h" -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" #include <android_runtime/android_view_Surface.h> #include <android_runtime/Log.h> @@ -188,17 +188,15 @@ static JNINativeMethod gMethods[] = { int register_android_media_RemoteDisplay(JNIEnv* env) { - int err = AndroidRuntime::registerNativeMethods(env, "android/media/RemoteDisplay", - gMethods, NELEM(gMethods)); - - jclass clazz = env->FindClass("android/media/RemoteDisplay"); - gRemoteDisplayClassInfo.notifyDisplayConnected = - env->GetMethodID(clazz, "notifyDisplayConnected", - "(Landroid/view/Surface;IIII)V"); - gRemoteDisplayClassInfo.notifyDisplayDisconnected = - env->GetMethodID(clazz, "notifyDisplayDisconnected", "()V"); - gRemoteDisplayClassInfo.notifyDisplayError = - env->GetMethodID(clazz, "notifyDisplayError", "(I)V"); + int err = RegisterMethodsOrDie(env, "android/media/RemoteDisplay", gMethods, NELEM(gMethods)); + + jclass clazz = FindClassOrDie(env, "android/media/RemoteDisplay"); + gRemoteDisplayClassInfo.notifyDisplayConnected = GetMethodIDOrDie(env, + clazz, "notifyDisplayConnected", "(Landroid/view/Surface;IIII)V"); + gRemoteDisplayClassInfo.notifyDisplayDisconnected = GetMethodIDOrDie(env, + clazz, "notifyDisplayDisconnected", "()V"); + gRemoteDisplayClassInfo.notifyDisplayError = GetMethodIDOrDie(env, + clazz, "notifyDisplayError", "(I)V"); return err; } diff --git a/core/jni/android_media_ToneGenerator.cpp b/core/jni/android_media_ToneGenerator.cpp index ca00709..243f040 100644 --- a/core/jni/android_media_ToneGenerator.cpp +++ b/core/jni/android_media_ToneGenerator.cpp @@ -23,7 +23,7 @@ #include <jni.h> #include <JNIHelp.h> -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" #include <utils/Log.h> #include <media/AudioSystem.h> @@ -134,21 +134,10 @@ static JNINativeMethod gMethods[] = { int register_android_media_ToneGenerator(JNIEnv *env) { - jclass clazz; + jclass clazz = FindClassOrDie(env, "android/media/ToneGenerator"); - clazz = env->FindClass("android/media/ToneGenerator"); - if (clazz == NULL) { - ALOGE("Can't find %s", "android/media/ToneGenerator"); - return -1; - } - - fields.context = env->GetFieldID(clazz, "mNativeContext", "J"); - if (fields.context == NULL) { - ALOGE("Can't find ToneGenerator.mNativeContext"); - return -1; - } + fields.context = GetFieldIDOrDie(env, clazz, "mNativeContext", "J"); ALOGV("register_android_media_ToneGenerator ToneGenerator fields.context: %p", fields.context); - return AndroidRuntime::registerNativeMethods(env, - "android/media/ToneGenerator", gMethods, NELEM(gMethods)); + return RegisterMethodsOrDie(env, "android/media/ToneGenerator", gMethods, NELEM(gMethods)); } diff --git a/core/jni/android_net_LocalSocketImpl.cpp b/core/jni/android_net_LocalSocketImpl.cpp index 98f4bed..97abe6b 100644 --- a/core/jni/android_net_LocalSocketImpl.cpp +++ b/core/jni/android_net_LocalSocketImpl.cpp @@ -39,6 +39,9 @@ namespace android { +template <typename T> +void UNUSED(T t) {} + static jfieldID field_inboundFileDescriptors; static jfieldID field_outboundFileDescriptors; static jclass class_Credentials; @@ -57,7 +60,7 @@ socket_connect_local(JNIEnv *env, jobject object, fd = jniGetFDFromFileDescriptor(env, fileDescriptor); - if (env->ExceptionOccurred() != NULL) { + if (env->ExceptionCheck()) { return; } @@ -95,7 +98,7 @@ socket_bind_local (JNIEnv *env, jobject object, jobject fileDescriptor, fd = jniGetFDFromFileDescriptor(env, fileDescriptor); - if (env->ExceptionOccurred() != NULL) { + if (env->ExceptionCheck()) { return; } @@ -118,7 +121,7 @@ socket_listen (JNIEnv *env, jobject object, jobject fileDescriptor, jint backlog fd = jniGetFDFromFileDescriptor(env, fileDescriptor); - if (env->ExceptionOccurred() != NULL) { + if (env->ExceptionCheck()) { return; } @@ -154,7 +157,7 @@ socket_accept (JNIEnv *env, jobject object, jobject fileDescriptor, jobject s) fd = jniGetFDFromFileDescriptor(env, fileDescriptor); - if (env->ExceptionOccurred() != NULL) { + if (env->ExceptionCheck()) { return NULL; } @@ -184,7 +187,7 @@ socket_shutdown (JNIEnv *env, jobject object, jobject fileDescriptor, fd = jniGetFDFromFileDescriptor(env, fileDescriptor); - if (env->ExceptionOccurred() != NULL) { + if (env->ExceptionCheck()) { return; } @@ -246,7 +249,7 @@ socket_getOption(JNIEnv *env, jobject object, jobject fileDescriptor, jint optID fd = jniGetFDFromFileDescriptor(env, fileDescriptor); - if (env->ExceptionOccurred() != NULL) { + if (env->ExceptionCheck()) { return 0; } @@ -293,7 +296,7 @@ static void socket_setOption( fd = jniGetFDFromFileDescriptor(env, fileDescriptor); - if (env->ExceptionOccurred() != NULL) { + if (env->ExceptionCheck()) { return; } @@ -353,7 +356,7 @@ static jint socket_pending (JNIEnv *env, jobject object, fd = jniGetFDFromFileDescriptor(env, fileDescriptor); - if (env->ExceptionOccurred() != NULL) { + if (env->ExceptionCheck()) { return (jint)-1; } @@ -378,7 +381,7 @@ static jint socket_available (JNIEnv *env, jobject object, fd = jniGetFDFromFileDescriptor(env, fileDescriptor); - if (env->ExceptionOccurred() != NULL) { + if (env->ExceptionCheck()) { return (jint)-1; } @@ -459,20 +462,20 @@ static int socket_process_cmsg(JNIEnv *env, jobject thisJ, struct msghdr * pMsg) jobject fdObject = jniCreateFileDescriptor(env, pDescriptors[i]); - if (env->ExceptionOccurred() != NULL) { + if (env->ExceptionCheck()) { return -1; } env->SetObjectArrayElement(fdArray, i, fdObject); - if (env->ExceptionOccurred() != NULL) { + if (env->ExceptionCheck()) { return -1; } } env->SetObjectField(thisJ, field_inboundFileDescriptors, fdArray); - if (env->ExceptionOccurred() != NULL) { + if (env->ExceptionCheck()) { return -1; } } @@ -492,7 +495,6 @@ static ssize_t socket_read_all(JNIEnv *env, jobject thisJ, int fd, void *buffer, size_t len) { ssize_t ret; - ssize_t bytesread = 0; struct msghdr msg; struct iovec iv; unsigned char *buf = (unsigned char *)buffer; @@ -558,7 +560,7 @@ static int socket_write_all(JNIEnv *env, jobject object, int fd, = (jobjectArray)env->GetObjectField( object, field_outboundFileDescriptors); - if (env->ExceptionOccurred() != NULL) { + if (env->ExceptionCheck()) { return -1; } @@ -570,18 +572,18 @@ static int socket_write_all(JNIEnv *env, jobject object, int fd, // Add any pending outbound file descriptors to the message if (outboundFds != NULL) { - if (env->ExceptionOccurred() != NULL) { + if (env->ExceptionCheck()) { return -1; } for (int i = 0; i < countFds; i++) { jobject fdObject = env->GetObjectArrayElement(outboundFds, i); - if (env->ExceptionOccurred() != NULL) { + if (env->ExceptionCheck()) { return -1; } fds[i] = jniGetFDFromFileDescriptor(env, fdObject); - if (env->ExceptionOccurred() != NULL) { + if (env->ExceptionCheck()) { return -1; } } @@ -638,7 +640,7 @@ static jint socket_read (JNIEnv *env, jobject object, jobject fileDescriptor) fd = jniGetFDFromFileDescriptor(env, fileDescriptor); - if (env->ExceptionOccurred() != NULL) { + if (env->ExceptionCheck()) { return (jint)0; } @@ -683,7 +685,7 @@ static jint socket_readba (JNIEnv *env, jobject object, fd = jniGetFDFromFileDescriptor(env, fileDescriptor); - if (env->ExceptionOccurred() != NULL) { + if (env->ExceptionCheck()) { return (jint)-1; } @@ -717,12 +719,12 @@ static void socket_write (JNIEnv *env, jobject object, fd = jniGetFDFromFileDescriptor(env, fileDescriptor); - if (env->ExceptionOccurred() != NULL) { + if (env->ExceptionCheck()) { return; } err = socket_write_all(env, object, fd, &b, 1); - + UNUSED(err); // A return of -1 above means an exception is pending } @@ -745,7 +747,7 @@ static void socket_writeba (JNIEnv *env, jobject object, fd = jniGetFDFromFileDescriptor(env, fileDescriptor); - if (env->ExceptionOccurred() != NULL) { + if (env->ExceptionCheck()) { return; } @@ -758,7 +760,7 @@ static void socket_writeba (JNIEnv *env, jobject object, err = socket_write_all(env, object, fd, byteBuffer + off, len); - + UNUSED(err); // A return of -1 above means an exception is pending env->ReleaseByteArrayElements(buffer, byteBuffer, JNI_ABORT); @@ -777,7 +779,7 @@ static jobject socket_get_peer_credentials(JNIEnv *env, fd = jniGetFDFromFileDescriptor(env, fileDescriptor); - if (env->ExceptionOccurred() != NULL) { + if (env->ExceptionCheck()) { return NULL; } @@ -816,7 +818,7 @@ static jobject socket_getSockName(JNIEnv *env, fd = jniGetFDFromFileDescriptor(env, fileDescriptor); - if (env->ExceptionOccurred() != NULL) { + if (env->ExceptionCheck()) { return NULL; } diff --git a/core/jni/android_net_NetUtils.cpp b/core/jni/android_net_NetUtils.cpp index 8b9f574..9092512 100644 --- a/core/jni/android_net_NetUtils.cpp +++ b/core/jni/android_net_NetUtils.cpp @@ -19,13 +19,14 @@ #include "jni.h" #include "JNIHelp.h" #include "NetdClient.h" -#include "resolv_netid.h" #include <utils/misc.h> #include <android_runtime/AndroidRuntime.h> #include <utils/Log.h> #include <arpa/inet.h> #include <cutils/properties.h> +#include "core_jni_helpers.h" + extern "C" { int ifc_enable(const char *ifname); int ifc_disable(const char *ifname); @@ -269,27 +270,26 @@ static JNINativeMethod gNetworkUtilMethods[] = { int register_android_net_NetworkUtils(JNIEnv* env) { - jclass dhcpResultsClass = env->FindClass("android/net/DhcpResults"); - LOG_FATAL_IF(dhcpResultsClass == NULL, "Unable to find class android/net/DhcpResults"); - dhcpResultsFieldIds.clear = - env->GetMethodID(dhcpResultsClass, "clear", "()V"); - dhcpResultsFieldIds.setIpAddress = - env->GetMethodID(dhcpResultsClass, "setIpAddress", "(Ljava/lang/String;I)Z"); - dhcpResultsFieldIds.setGateway = - env->GetMethodID(dhcpResultsClass, "setGateway", "(Ljava/lang/String;)Z"); - dhcpResultsFieldIds.addDns = - env->GetMethodID(dhcpResultsClass, "addDns", "(Ljava/lang/String;)Z"); - dhcpResultsFieldIds.setDomains = - env->GetMethodID(dhcpResultsClass, "setDomains", "(Ljava/lang/String;)V"); - dhcpResultsFieldIds.setServerAddress = - env->GetMethodID(dhcpResultsClass, "setServerAddress", "(Ljava/lang/String;)Z"); - dhcpResultsFieldIds.setLeaseDuration = - env->GetMethodID(dhcpResultsClass, "setLeaseDuration", "(I)V"); - dhcpResultsFieldIds.setVendorInfo = - env->GetMethodID(dhcpResultsClass, "setVendorInfo", "(Ljava/lang/String;)V"); - - return AndroidRuntime::registerNativeMethods(env, - NETUTILS_PKG_NAME, gNetworkUtilMethods, NELEM(gNetworkUtilMethods)); + jclass dhcpResultsClass = FindClassOrDie(env, "android/net/DhcpResults"); + + dhcpResultsFieldIds.clear = GetMethodIDOrDie(env, dhcpResultsClass, "clear", "()V"); + dhcpResultsFieldIds.setIpAddress =GetMethodIDOrDie(env, dhcpResultsClass, "setIpAddress", + "(Ljava/lang/String;I)Z"); + dhcpResultsFieldIds.setGateway = GetMethodIDOrDie(env, dhcpResultsClass, "setGateway", + "(Ljava/lang/String;)Z"); + dhcpResultsFieldIds.addDns = GetMethodIDOrDie(env, dhcpResultsClass, "addDns", + "(Ljava/lang/String;)Z"); + dhcpResultsFieldIds.setDomains = GetMethodIDOrDie(env, dhcpResultsClass, "setDomains", + "(Ljava/lang/String;)V"); + dhcpResultsFieldIds.setServerAddress = GetMethodIDOrDie(env, dhcpResultsClass, + "setServerAddress", "(Ljava/lang/String;)Z"); + dhcpResultsFieldIds.setLeaseDuration = GetMethodIDOrDie(env, dhcpResultsClass, + "setLeaseDuration", "(I)V"); + dhcpResultsFieldIds.setVendorInfo = GetMethodIDOrDie(env, dhcpResultsClass, "setVendorInfo", + "(Ljava/lang/String;)V"); + + return RegisterMethodsOrDie(env, NETUTILS_PKG_NAME, gNetworkUtilMethods, + NELEM(gNetworkUtilMethods)); } }; // namespace android diff --git a/core/jni/android_net_TrafficStats.cpp b/core/jni/android_net_TrafficStats.cpp index 031637f..7354417 100644 --- a/core/jni/android_net_TrafficStats.cpp +++ b/core/jni/android_net_TrafficStats.cpp @@ -23,7 +23,7 @@ #include <sys/stat.h> #include <sys/types.h> -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" #include <jni.h> #include <ScopedUtfChars.h> #include <utils/misc.h> @@ -192,8 +192,7 @@ static JNINativeMethod gMethods[] = { }; int register_android_net_TrafficStats(JNIEnv* env) { - return AndroidRuntime::registerNativeMethods(env, "android/net/TrafficStats", - gMethods, NELEM(gMethods)); + return RegisterMethodsOrDie(env, "android/net/TrafficStats", gMethods, NELEM(gMethods)); } } diff --git a/core/jni/android_nfc.h b/core/jni/android_nfc.h deleted file mode 100644 index 36346e3..0000000 --- a/core/jni/android_nfc.h +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * Contains the bare minimum header so that framework NFC jni can link - * against NFC native library - */ - -#ifndef __ANDROID_NFC_H__ -#define __ANDROID_NFC_H__ - -#define LOG_TAG "NdefMessage" -#include <utils/Log.h> - -extern "C" { - -#if 0 - #define TRACE(...) ALOG(LOG_DEBUG, "NdefMessage", __VA_ARGS__) -#else - #define TRACE(...) -#endif - -typedef struct phFriNfc_NdefRecord { - uint8_t Flags; - uint8_t Tnf; - uint8_t TypeLength; - uint8_t *Type; - uint8_t IdLength; - uint8_t *Id; - uint32_t PayloadLength; - uint8_t *PayloadData; -} phFriNfc_NdefRecord_t; - -uint16_t phFriNfc_NdefRecord_GetRecords(uint8_t* pBuffer, - uint32_t BufferLength, - uint8_t* pRawRecords[ ], - uint8_t IsChunked[ ], - uint32_t* pNumberOfRawRecords - ); -uint16_t phFriNfc_NdefRecord_Parse(phFriNfc_NdefRecord_t* pRecord, - uint8_t* pRawRecord); - -uint16_t phFriNfc_NdefRecord_Generate(phFriNfc_NdefRecord_t* pRecord, - uint8_t* pBuffer, - uint32_t MaxBufferSize, - uint32_t* pBytesWritten - ); -} - -#endif diff --git a/core/jni/android_nio_utils.cpp b/core/jni/android_nio_utils.cpp index 59d6e41..ed8c603 100644 --- a/core/jni/android_nio_utils.cpp +++ b/core/jni/android_nio_utils.cpp @@ -16,6 +16,8 @@ #include "android_nio_utils.h" +#include "core_jni_helpers.h" + struct NioJNIData { jclass nioAccessClass; @@ -73,39 +75,19 @@ android::AutoBufferPointer::~AutoBufferPointer() { /////////////////////////////////////////////////////////////////////////////// -static jclass findClass(JNIEnv* env, const char name[]) { - jclass c = env->FindClass(name); - LOG_FATAL_IF(!c, "Unable to find class %s", name); - return c; -} - -static jmethodID findStaticMethod(JNIEnv* env, jclass c, const char method[], - const char params[]) { - jmethodID m = env->GetStaticMethodID(c, method, params); - LOG_FATAL_IF(!m, "Unable to find method %s", method); - return m; -} - -static jfieldID getFieldID(JNIEnv* env, jclass c, const char name[], - const char type[]) { - jfieldID f = env->GetFieldID(c, name, type); - LOG_FATAL_IF(!f, "Unable to find field %s", name); - return f; -} - namespace android { int register_android_nio_utils(JNIEnv* env) { - jclass localClass = findClass(env, "java/nio/NIOAccess"); - gNioJNI.getBasePointerID = findStaticMethod(env, localClass, - "getBasePointer", "(Ljava/nio/Buffer;)J"); - gNioJNI.getBaseArrayID = findStaticMethod(env, localClass, - "getBaseArray", "(Ljava/nio/Buffer;)Ljava/lang/Object;"); - gNioJNI.getBaseArrayOffsetID = findStaticMethod(env, localClass, - "getBaseArrayOffset", "(Ljava/nio/Buffer;)I"); + jclass localClass = FindClassOrDie(env, "java/nio/NIOAccess"); + gNioJNI.getBasePointerID = GetStaticMethodIDOrDie(env, localClass, "getBasePointer", + "(Ljava/nio/Buffer;)J"); + gNioJNI.getBaseArrayID = GetStaticMethodIDOrDie(env, localClass, "getBaseArray", + "(Ljava/nio/Buffer;)Ljava/lang/Object;"); + gNioJNI.getBaseArrayOffsetID = GetStaticMethodIDOrDie(env, localClass, "getBaseArrayOffset", + "(Ljava/nio/Buffer;)I"); // now record a permanent version of the class ID - gNioJNI.nioAccessClass = (jclass) env->NewGlobalRef(localClass); + gNioJNI.nioAccessClass = MakeGlobalRefOrDie(env, localClass); return 0; } diff --git a/core/jni/android_nio_utils.h b/core/jni/android_nio_utils.h index 69c360c..c634cb9 100644 --- a/core/jni/android_nio_utils.h +++ b/core/jni/android_nio_utils.h @@ -14,8 +14,8 @@ * limitations under the License. */ -#ifndef android_nio_utils_DEFINED -#define android_nio_utils_DEFINED +#ifndef _ANDROID_NIO_UTILS_H_ +#define _ANDROID_NIO_UTILS_H_ #include <android_runtime/AndroidRuntime.h> @@ -58,17 +58,16 @@ class AutoBufferPointer { public: AutoBufferPointer(JNIEnv* env, jobject nioBuffer, jboolean commit); ~AutoBufferPointer(); - + void* pointer() const { return fPointer; } - + private: JNIEnv* fEnv; void* fPointer; jarray fArray; - jint fRemaining; jboolean fCommit; }; } /* namespace android */ -#endif +#endif // _ANDROID_NIO_UTILS_H_ diff --git a/core/jni/android_opengl_EGL14.cpp b/core/jni/android_opengl_EGL14.cpp index 19e4d99..1afcf73 100644 --- a/core/jni/android_opengl_EGL14.cpp +++ b/core/jni/android_opengl_EGL14.cpp @@ -16,6 +16,10 @@ // This source file is automatically generated +#pragma GCC diagnostic ignored "-Wunused-variable" +#pragma GCC diagnostic ignored "-Wunused-but-set-variable" +#pragma GCC diagnostic ignored "-Wunused-function" + #include "jni.h" #include "JNIHelp.h" #include <android_runtime/AndroidRuntime.h> diff --git a/core/jni/android_opengl_EGLExt.cpp b/core/jni/android_opengl_EGLExt.cpp index 15899f5..60a3bf6 100644 --- a/core/jni/android_opengl_EGLExt.cpp +++ b/core/jni/android_opengl_EGLExt.cpp @@ -16,6 +16,10 @@ // This source file is automatically generated +#pragma GCC diagnostic ignored "-Wunused-variable" +#pragma GCC diagnostic ignored "-Wunused-but-set-variable" +#pragma GCC diagnostic ignored "-Wunused-function" + #include "jni.h" #include "JNIHelp.h" #include <android_runtime/AndroidRuntime.h> @@ -81,23 +85,19 @@ nativeClassInit(JNIEnv *_env, jclass glImplClass) eglsurfaceConstructor = _env->GetMethodID(eglsurfaceClass, "<init>", "(J)V"); eglconfigConstructor = _env->GetMethodID(eglconfigClass, "<init>", "(J)V"); - jobject localeglNoContextObject = _env->NewObject(eglcontextClass, eglcontextConstructor, reinterpret_cast<jlong>(EGL_NO_CONTEXT)); - eglNoContextObject = _env->NewGlobalRef(localeglNoContextObject); - jobject localeglNoDisplayObject = _env->NewObject(egldisplayClass, egldisplayConstructor, reinterpret_cast<jlong>(EGL_NO_DISPLAY)); - eglNoDisplayObject = _env->NewGlobalRef(localeglNoDisplayObject); - jobject localeglNoSurfaceObject = _env->NewObject(eglsurfaceClass, eglsurfaceConstructor, reinterpret_cast<jlong>(EGL_NO_SURFACE)); - eglNoSurfaceObject = _env->NewGlobalRef(localeglNoSurfaceObject); - jclass eglClass = _env->FindClass("android/opengl/EGL14"); jfieldID noContextFieldID = _env->GetStaticFieldID(eglClass, "EGL_NO_CONTEXT", "Landroid/opengl/EGLContext;"); - _env->SetStaticObjectField(eglClass, noContextFieldID, eglNoContextObject); + jobject localeglNoContextObject = _env->GetStaticObjectField(eglClass, noContextFieldID); + eglNoContextObject = _env->NewGlobalRef(localeglNoContextObject); jfieldID noDisplayFieldID = _env->GetStaticFieldID(eglClass, "EGL_NO_DISPLAY", "Landroid/opengl/EGLDisplay;"); - _env->SetStaticObjectField(eglClass, noDisplayFieldID, eglNoDisplayObject); + jobject localeglNoDisplayObject = _env->GetStaticObjectField(eglClass, noDisplayFieldID); + eglNoDisplayObject = _env->NewGlobalRef(localeglNoDisplayObject); jfieldID noSurfaceFieldID = _env->GetStaticFieldID(eglClass, "EGL_NO_SURFACE", "Landroid/opengl/EGLSurface;"); - _env->SetStaticObjectField(eglClass, noSurfaceFieldID, eglNoSurfaceObject); + jobject localeglNoSurfaceObject = _env->GetStaticObjectField(eglClass, noSurfaceFieldID); + eglNoSurfaceObject = _env->NewGlobalRef(localeglNoSurfaceObject); } static void * diff --git a/core/jni/android_opengl_GLES10.cpp b/core/jni/android_opengl_GLES10.cpp index 0a39a8e..c9b68bf 100644 --- a/core/jni/android_opengl_GLES10.cpp +++ b/core/jni/android_opengl_GLES10.cpp @@ -17,6 +17,10 @@ // This source file is automatically generated +#pragma GCC diagnostic ignored "-Wunused-variable" +#pragma GCC diagnostic ignored "-Wunused-but-set-variable" +#pragma GCC diagnostic ignored "-Wunused-function" + #include <GLES/gl.h> #include <GLES/glext.h> diff --git a/core/jni/android_opengl_GLES10Ext.cpp b/core/jni/android_opengl_GLES10Ext.cpp index 83d9bda..4f1eaa5 100644 --- a/core/jni/android_opengl_GLES10Ext.cpp +++ b/core/jni/android_opengl_GLES10Ext.cpp @@ -17,6 +17,10 @@ // This source file is automatically generated +#pragma GCC diagnostic ignored "-Wunused-variable" +#pragma GCC diagnostic ignored "-Wunused-but-set-variable" +#pragma GCC diagnostic ignored "-Wunused-function" + #include <GLES/gl.h> #include <GLES/glext.h> diff --git a/core/jni/android_opengl_GLES11.cpp b/core/jni/android_opengl_GLES11.cpp index a292cf2..08c4740 100644 --- a/core/jni/android_opengl_GLES11.cpp +++ b/core/jni/android_opengl_GLES11.cpp @@ -17,6 +17,10 @@ // This source file is automatically generated +#pragma GCC diagnostic ignored "-Wunused-variable" +#pragma GCC diagnostic ignored "-Wunused-but-set-variable" +#pragma GCC diagnostic ignored "-Wunused-function" + #include <GLES/gl.h> #include <GLES/glext.h> diff --git a/core/jni/android_opengl_GLES11Ext.cpp b/core/jni/android_opengl_GLES11Ext.cpp index 4ee5f15..21e5670f 100644 --- a/core/jni/android_opengl_GLES11Ext.cpp +++ b/core/jni/android_opengl_GLES11Ext.cpp @@ -17,6 +17,10 @@ // This source file is automatically generated +#pragma GCC diagnostic ignored "-Wunused-variable" +#pragma GCC diagnostic ignored "-Wunused-but-set-variable" +#pragma GCC diagnostic ignored "-Wunused-function" + #include <GLES/gl.h> #include <GLES/glext.h> diff --git a/core/jni/android_opengl_GLES20.cpp b/core/jni/android_opengl_GLES20.cpp index 60ab37b..cd0c135 100644 --- a/core/jni/android_opengl_GLES20.cpp +++ b/core/jni/android_opengl_GLES20.cpp @@ -17,6 +17,10 @@ // This source file is automatically generated +#pragma GCC diagnostic ignored "-Wunused-variable" +#pragma GCC diagnostic ignored "-Wunused-but-set-variable" +#pragma GCC diagnostic ignored "-Wunused-function" + #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> diff --git a/core/jni/android_opengl_GLES30.cpp b/core/jni/android_opengl_GLES30.cpp index ba324b0..713fff9 100644 --- a/core/jni/android_opengl_GLES30.cpp +++ b/core/jni/android_opengl_GLES30.cpp @@ -17,6 +17,10 @@ // This source file is automatically generated +#pragma GCC diagnostic ignored "-Wunused-variable" +#pragma GCC diagnostic ignored "-Wunused-but-set-variable" +#pragma GCC diagnostic ignored "-Wunused-function" + #include <GLES3/gl3.h> #include <GLES3/gl3ext.h> diff --git a/core/jni/android_opengl_GLES31.cpp b/core/jni/android_opengl_GLES31.cpp index bc9fc5d..e5ea950 100644 --- a/core/jni/android_opengl_GLES31.cpp +++ b/core/jni/android_opengl_GLES31.cpp @@ -16,6 +16,10 @@ // This source file is automatically generated +#pragma GCC diagnostic ignored "-Wunused-variable" +#pragma GCC diagnostic ignored "-Wunused-but-set-variable" +#pragma GCC diagnostic ignored "-Wunused-function" + #include <stdint.h> #include <GLES3/gl31.h> #include <jni.h> @@ -351,7 +355,7 @@ static void android_glDrawArraysIndirect(JNIEnv *_env, jobject, int mode, jlong // In OpenGL ES, 'indirect' is a byte offset into a buffer, not a raw pointer. // GL checks for too-large values. Here we only need to check for successful signed 64-bit // to unsigned 32-bit conversion. - if (sizeof(void*) != sizeof(jlong) && indirect > UINTPTR_MAX) { + if (sizeof(void*) != sizeof(jlong) && indirect > static_cast<jlong>(UINT32_MAX)) { jniThrowException(_env, "java/lang/IllegalArgumentException", "indirect offset too large"); return; } @@ -363,7 +367,7 @@ static void android_glDrawElementsIndirect(JNIEnv *_env, jobject, jint mode, jin // In OpenGL ES, 'indirect' is a byte offset into a buffer, not a raw pointer. // GL checks for too-large values. Here we only need to check for successful signed 64-bit // to unsigned 32-bit conversion. - if (sizeof(void*) != sizeof(jlong) && indirect > UINTPTR_MAX) { + if (sizeof(void*) != sizeof(jlong) && indirect > static_cast<jlong>(UINT32_MAX)) { jniThrowException(_env, "java/lang/IllegalArgumentException", "indirect offset too large"); return; } diff --git a/core/jni/android_opengl_GLES31Ext.cpp b/core/jni/android_opengl_GLES31Ext.cpp index d76c166..7317e9f 100644 --- a/core/jni/android_opengl_GLES31Ext.cpp +++ b/core/jni/android_opengl_GLES31Ext.cpp @@ -16,6 +16,10 @@ // This source file is automatically generated +#pragma GCC diagnostic ignored "-Wunused-variable" +#pragma GCC diagnostic ignored "-Wunused-but-set-variable" +#pragma GCC diagnostic ignored "-Wunused-function" + #include <GLES3/gl31.h> #include <GLES2/gl2ext.h> diff --git a/core/jni/android_os_Debug.cpp b/core/jni/android_os_Debug.cpp index d9e64c7..773d42e 100644 --- a/core/jni/android_os_Debug.cpp +++ b/core/jni/android_os_Debug.cpp @@ -227,13 +227,12 @@ static void read_mapinfo(FILE *fp, stats_t* stats) int len, nameLen; bool skip, done = false; - unsigned size = 0, resident = 0, pss = 0, swappable_pss = 0; + unsigned pss = 0, swappable_pss = 0; float sharing_proportion = 0.0; unsigned shared_clean = 0, shared_dirty = 0; unsigned private_clean = 0, private_dirty = 0; unsigned swapped_out = 0; bool is_swappable = false; - unsigned referenced = 0; unsigned temp; uint64_t start; @@ -362,9 +361,9 @@ static void read_mapinfo(FILE *fp, stats_t* stats) } if (line[0] == 'S' && sscanf(line, "Size: %d kB", &temp) == 1) { - size = temp; + /* size = temp; */ } else if (line[0] == 'R' && sscanf(line, "Rss: %d kB", &temp) == 1) { - resident = temp; + /* resident = temp; */ } else if (line[0] == 'P' && sscanf(line, "Pss: %d kB", &temp) == 1) { pss = temp; } else if (line[0] == 'S' && sscanf(line, "Shared_Clean: %d kB", &temp) == 1) { @@ -376,7 +375,7 @@ static void read_mapinfo(FILE *fp, stats_t* stats) } else if (line[0] == 'P' && sscanf(line, "Private_Dirty: %d kB", &temp) == 1) { private_dirty = temp; } else if (line[0] == 'R' && sscanf(line, "Referenced: %d kB", &temp) == 1) { - referenced = temp; + /* referenced = temp; */ } else if (line[0] == 'S' && sscanf(line, "Swap: %d kB", &temp) == 1) { swapped_out = temp; } else if (sscanf(line, "%" SCNx64 "-%" SCNx64 " %*s %*x %*x:%*x %*d", &start, &end) == 2) { @@ -502,7 +501,6 @@ static jlong android_os_Debug_getPssPid(JNIEnv *env, jobject clazz, jint pid, jl jlong pss = 0; jlong uss = 0; jlong memtrack = 0; - unsigned temp; char tmp[128]; FILE *fp; @@ -939,7 +937,8 @@ static void android_os_Debug_dumpNativeBacktraceToFile(JNIEnv* env, jobject claz const jchar* str = env->GetStringCritical(fileName, 0); String8 fileName8; if (str) { - fileName8 = String8(str, env->GetStringLength(fileName)); + fileName8 = String8(reinterpret_cast<const char16_t*>(str), + env->GetStringLength(fileName)); env->ReleaseStringCritical(fileName, str); } diff --git a/core/jni/android_os_MemoryFile.cpp b/core/jni/android_os_MemoryFile.cpp index 27b29bc..c198a73 100644 --- a/core/jni/android_os_MemoryFile.cpp +++ b/core/jni/android_os_MemoryFile.cpp @@ -18,7 +18,7 @@ #include <utils/Log.h> #include <cutils/ashmem.h> -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" #include "JNIHelp.h" #include <unistd.h> #include <sys/mman.h> @@ -151,9 +151,7 @@ static const JNINativeMethod methods[] = { int register_android_os_MemoryFile(JNIEnv* env) { - return AndroidRuntime::registerNativeMethods( - env, "android/os/MemoryFile", - methods, NELEM(methods)); + return RegisterMethodsOrDie(env, "android/os/MemoryFile", methods, NELEM(methods)); } } diff --git a/core/jni/android_os_MessageQueue.cpp b/core/jni/android_os_MessageQueue.cpp index a8ed895..5d7877b 100644 --- a/core/jni/android_os_MessageQueue.cpp +++ b/core/jni/android_os_MessageQueue.cpp @@ -23,6 +23,8 @@ #include <utils/Log.h> #include "android_os_MessageQueue.h" +#include "core_jni_helpers.h" + namespace android { static struct { @@ -54,8 +56,8 @@ MessageQueue::~MessageQueue() { } bool MessageQueue::raiseAndClearException(JNIEnv* env, const char* msg) { - jthrowable exceptionObj = env->ExceptionOccurred(); - if (exceptionObj) { + if (env->ExceptionCheck()) { + jthrowable exceptionObj = env->ExceptionOccurred(); env->ExceptionClear(); raiseException(env, msg, exceptionObj); env->DeleteLocalRef(exceptionObj); @@ -157,26 +159,15 @@ static JNINativeMethod gMessageQueueMethods[] = { { "nativeIsIdling", "(J)Z", (void*)android_os_MessageQueue_nativeIsIdling } }; -#define FIND_CLASS(var, className) \ - var = env->FindClass(className); \ - LOG_FATAL_IF(! var, "Unable to find class " className); - -#define GET_FIELD_ID(var, clazz, fieldName, fieldDescriptor) \ - var = env->GetFieldID(clazz, fieldName, fieldDescriptor); \ - LOG_FATAL_IF(! var, "Unable to find field " fieldName); - int register_android_os_MessageQueue(JNIEnv* env) { - int res = jniRegisterNativeMethods(env, "android/os/MessageQueue", - gMessageQueueMethods, NELEM(gMessageQueueMethods)); - LOG_FATAL_IF(res < 0, "Unable to register native methods."); + int res = RegisterMethodsOrDie(env, "android/os/MessageQueue", gMessageQueueMethods, + NELEM(gMessageQueueMethods)); + + jclass clazz = FindClassOrDie(env, "android/os/MessageQueue"); - jclass clazz; - FIND_CLASS(clazz, "android/os/MessageQueue"); + gMessageQueueClassInfo.mPtr = GetFieldIDOrDie(env, clazz, "mPtr", "J"); - GET_FIELD_ID(gMessageQueueClassInfo.mPtr, clazz, - "mPtr", "J"); - - return 0; + return res; } } // namespace android diff --git a/core/jni/android_os_Parcel.cpp b/core/jni/android_os_Parcel.cpp index 960acc0..4f29c50 100644 --- a/core/jni/android_os_Parcel.cpp +++ b/core/jni/android_os_Parcel.cpp @@ -46,6 +46,8 @@ #include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" + //#undef ALOGV //#define ALOGV(...) fprintf(stderr, __VA_ARGS__) @@ -275,7 +277,9 @@ static void android_os_Parcel_writeString(JNIEnv* env, jclass clazz, jlong nativ if (val) { const jchar* str = env->GetStringCritical(val, 0); if (str) { - err = parcel->writeString16(str, env->GetStringLength(val)); + err = parcel->writeString16( + reinterpret_cast<const char16_t*>(str), + env->GetStringLength(val)); env->ReleaseStringCritical(val, str); } } else { @@ -409,7 +413,7 @@ static jstring android_os_Parcel_readString(JNIEnv* env, jclass clazz, jlong nat size_t len; const char16_t* str = parcel->readString16Inplace(&len); if (str) { - return env->NewString(str, len); + return env->NewString(reinterpret_cast<const jchar*>(str), len); } return NULL; } @@ -451,7 +455,8 @@ static jobject android_os_Parcel_openFileDescriptor(JNIEnv* env, jclass clazz, jniThrowException(env, "java/lang/IllegalStateException", NULL); return NULL; } - String8 name8(str, env->GetStringLength(name)); + String8 name8(reinterpret_cast<const char16_t*>(str), + env->GetStringLength(name)); env->ReleaseStringCritical(name, str); int flags=0; switch (mode&0x30000000) { @@ -646,7 +651,9 @@ static void android_os_Parcel_writeInterfaceToken(JNIEnv* env, jclass clazz, jlo // the caller expects to be invoking const jchar* str = env->GetStringCritical(name, 0); if (str != NULL) { - parcel->writeInterfaceToken(String16(str, env->GetStringLength(name))); + parcel->writeInterfaceToken(String16( + reinterpret_cast<const char16_t*>(str), + env->GetStringLength(name))); env->ReleaseStringCritical(name, str); } } @@ -654,8 +661,6 @@ static void android_os_Parcel_writeInterfaceToken(JNIEnv* env, jclass clazz, jlo static void android_os_Parcel_enforceInterface(JNIEnv* env, jclass clazz, jlong nativePtr, jstring name) { - jboolean ret = JNI_FALSE; - Parcel* parcel = reinterpret_cast<Parcel*>(nativePtr); if (parcel != NULL) { const jchar* str = env->GetStringCritical(name, 0); @@ -663,7 +668,8 @@ static void android_os_Parcel_enforceInterface(JNIEnv* env, jclass clazz, jlong IPCThreadState* threadState = IPCThreadState::self(); const int32_t oldPolicy = threadState->getStrictModePolicy(); const bool isValid = parcel->enforceInterface( - String16(str, env->GetStringLength(name)), + String16(reinterpret_cast<const char16_t*>(str), + env->GetStringLength(name)), threadState); env->ReleaseStringCritical(name, str); if (isValid) { @@ -756,20 +762,14 @@ const char* const kParcelPathName = "android/os/Parcel"; int register_android_os_Parcel(JNIEnv* env) { - jclass clazz; - - clazz = env->FindClass(kParcelPathName); - LOG_FATAL_IF(clazz == NULL, "Unable to find class android.os.Parcel"); + jclass clazz = FindClassOrDie(env, kParcelPathName); - gParcelOffsets.clazz = (jclass) env->NewGlobalRef(clazz); - gParcelOffsets.mNativePtr = env->GetFieldID(clazz, "mNativePtr", "J"); - gParcelOffsets.obtain = env->GetStaticMethodID(clazz, "obtain", - "()Landroid/os/Parcel;"); - gParcelOffsets.recycle = env->GetMethodID(clazz, "recycle", "()V"); + gParcelOffsets.clazz = MakeGlobalRefOrDie(env, clazz); + gParcelOffsets.mNativePtr = GetFieldIDOrDie(env, clazz, "mNativePtr", "J"); + gParcelOffsets.obtain = GetStaticMethodIDOrDie(env, clazz, "obtain", "()Landroid/os/Parcel;"); + gParcelOffsets.recycle = GetMethodIDOrDie(env, clazz, "recycle", "()V"); - return AndroidRuntime::registerNativeMethods( - env, kParcelPathName, - gParcelMethods, NELEM(gParcelMethods)); + return RegisterMethodsOrDie(env, kParcelPathName, gParcelMethods, NELEM(gParcelMethods)); } }; diff --git a/core/jni/android_os_SELinux.cpp b/core/jni/android_os_SELinux.cpp index ffa569e..136e758 100644 --- a/core/jni/android_os_SELinux.cpp +++ b/core/jni/android_os_SELinux.cpp @@ -19,7 +19,7 @@ #include "JNIHelp.h" #include "jni.h" -#include "android_runtime/AndroidRuntime.h" +#include "core_jni_helpers.h" #include "selinux/selinux.h" #include "selinux/android.h" #include <errno.h> @@ -97,7 +97,7 @@ static jstring getPeerCon(JNIEnv *env, jobject, jobject fileDescriptor) { } int fd = jniGetFDFromFileDescriptor(env, fileDescriptor); - if (env->ExceptionOccurred() != NULL) { + if (env->ExceptionCheck()) { ALOGE("getPeerCon => getFD for %p failed", fileDescriptor); return NULL; } @@ -469,8 +469,7 @@ int register_android_os_SELinux(JNIEnv *env) { isSELinuxDisabled = (is_selinux_enabled() != 1) ? true : false; - return AndroidRuntime::registerNativeMethods(env, "android/os/SELinux", method_table, - NELEM(method_table)); + return RegisterMethodsOrDie(env, "android/os/SELinux", method_table, NELEM(method_table)); } } diff --git a/core/jni/android_os_SystemClock.cpp b/core/jni/android_os_SystemClock.cpp index 6247844..dfe024e 100644 --- a/core/jni/android_os_SystemClock.cpp +++ b/core/jni/android_os_SystemClock.cpp @@ -27,7 +27,7 @@ #include "JNIHelp.h" #include "jni.h" -#include "android_runtime/AndroidRuntime.h" +#include "core_jni_helpers.h" #include <sys/time.h> #include <time.h> @@ -60,18 +60,11 @@ static jlong android_os_SystemClock_elapsedRealtime(JNIEnv* env, static jlong android_os_SystemClock_currentThreadTimeMillis(JNIEnv* env, jobject clazz) { -#if defined(HAVE_POSIX_CLOCKS) struct timespec tm; clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tm); return tm.tv_sec * 1000LL + tm.tv_nsec / 1000000; -#else - struct timeval tv; - - gettimeofday(&tv, NULL); - return tv.tv_sec * 1000LL + tv.tv_usec / 1000; -#endif } /* @@ -80,18 +73,11 @@ static jlong android_os_SystemClock_currentThreadTimeMillis(JNIEnv* env, static jlong android_os_SystemClock_currentThreadTimeMicro(JNIEnv* env, jobject clazz) { -#if defined(HAVE_POSIX_CLOCKS) struct timespec tm; clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tm); return tm.tv_sec * 1000000LL + tm.tv_nsec / 1000; -#else - struct timeval tv; - - gettimeofday(&tv, NULL); - return tv.tv_sec * 1000000LL + tv.tv_nsec / 1000; -#endif } /* @@ -135,8 +121,7 @@ static JNINativeMethod gMethods[] = { }; int register_android_os_SystemClock(JNIEnv* env) { - return AndroidRuntime::registerNativeMethods(env, - "android/os/SystemClock", gMethods, NELEM(gMethods)); + return RegisterMethodsOrDie(env, "android/os/SystemClock", gMethods, NELEM(gMethods)); } }; // namespace android diff --git a/core/jni/android_os_SystemProperties.cpp b/core/jni/android_os_SystemProperties.cpp index 677396d1..554d304 100644 --- a/core/jni/android_os_SystemProperties.cpp +++ b/core/jni/android_os_SystemProperties.cpp @@ -21,7 +21,7 @@ #include "utils/misc.h" #include <utils/Log.h> #include "jni.h" -#include "android_runtime/AndroidRuntime.h" +#include "core_jni_helpers.h" #include <nativehelper/JNIHelp.h> namespace android @@ -239,9 +239,8 @@ static JNINativeMethod method_table[] = { int register_android_os_SystemProperties(JNIEnv *env) { - return AndroidRuntime::registerNativeMethods( - env, "android/os/SystemProperties", - method_table, NELEM(method_table)); + return RegisterMethodsOrDie(env, "android/os/SystemProperties", method_table, + NELEM(method_table)); } }; diff --git a/core/jni/android_os_Trace.cpp b/core/jni/android_os_Trace.cpp index b11c5bb..52fd111 100644 --- a/core/jni/android_os_Trace.cpp +++ b/core/jni/android_os_Trace.cpp @@ -17,6 +17,8 @@ #define LOG_TAG "Trace" // #define LOG_NDEBUG 0 +#include <inttypes.h> + #include <JNIHelp.h> #include <ScopedUtfChars.h> #include <ScopedStringChars.h> @@ -48,47 +50,44 @@ static void android_os_Trace_nativeTraceCounter(JNIEnv* env, jclass clazz, jlong tag, jstring nameStr, jint value) { ScopedUtfChars name(env, nameStr); - ALOGV("%s: %lld %s %d", __FUNCTION__, tag, name.c_str(), value); + ALOGV("%s: %" PRId64 " %s %d", __FUNCTION__, tag, name.c_str(), value); atrace_int(tag, name.c_str(), value); } static void android_os_Trace_nativeTraceBegin(JNIEnv* env, jclass clazz, jlong tag, jstring nameStr) { - const size_t MAX_SECTION_NAME_LEN = 127; ScopedStringChars jchars(env, nameStr); String8 utf8Chars(reinterpret_cast<const char16_t*>(jchars.get()), jchars.size()); sanitizeString(utf8Chars); - ALOGV("%s: %lld %s", __FUNCTION__, tag, utf8Chars.string()); + ALOGV("%s: %" PRId64 " %s", __FUNCTION__, tag, utf8Chars.string()); atrace_begin(tag, utf8Chars.string()); } static void android_os_Trace_nativeTraceEnd(JNIEnv* env, jclass clazz, jlong tag) { - ALOGV("%s: %lld", __FUNCTION__, tag); + ALOGV("%s: %" PRId64, __FUNCTION__, tag); atrace_end(tag); } static void android_os_Trace_nativeAsyncTraceBegin(JNIEnv* env, jclass clazz, jlong tag, jstring nameStr, jint cookie) { - const size_t MAX_SECTION_NAME_LEN = 127; ScopedStringChars jchars(env, nameStr); String8 utf8Chars(reinterpret_cast<const char16_t*>(jchars.get()), jchars.size()); sanitizeString(utf8Chars); - ALOGV("%s: %lld %s %d", __FUNCTION__, tag, utf8Chars.string(), cookie); + ALOGV("%s: %" PRId64 " %s %d", __FUNCTION__, tag, utf8Chars.string(), cookie); atrace_async_begin(tag, utf8Chars.string(), cookie); } static void android_os_Trace_nativeAsyncTraceEnd(JNIEnv* env, jclass clazz, jlong tag, jstring nameStr, jint cookie) { - const size_t MAX_SECTION_NAME_LEN = 127; ScopedStringChars jchars(env, nameStr); String8 utf8Chars(reinterpret_cast<const char16_t*>(jchars.get()), jchars.size()); sanitizeString(utf8Chars); - ALOGV("%s: %lld %s %d", __FUNCTION__, tag, utf8Chars.string(), cookie); + ALOGV("%s: %" PRId64 " %s %d", __FUNCTION__, tag, utf8Chars.string(), cookie); atrace_async_end(tag, utf8Chars.string(), cookie); } @@ -137,7 +136,7 @@ static JNINativeMethod gTraceMethods[] = { int register_android_os_Trace(JNIEnv* env) { int res = jniRegisterNativeMethods(env, "android/os/Trace", gTraceMethods, NELEM(gTraceMethods)); - LOG_FATAL_IF(res < 0, "Unable to register native methods."); + LOG_ALWAYS_FATAL_IF(res < 0, "Unable to register native methods."); return 0; } diff --git a/core/jni/android_os_UEventObserver.cpp b/core/jni/android_os_UEventObserver.cpp index 3f7c7d2..eb36f85 100644 --- a/core/jni/android_os_UEventObserver.cpp +++ b/core/jni/android_os_UEventObserver.cpp @@ -22,7 +22,7 @@ #include "hardware_legacy/uevent.h" #include "jni.h" #include "JNIHelp.h" -#include "android_runtime/AndroidRuntime.h" +#include "core_jni_helpers.h" #include <utils/Mutex.h> #include <utils/Vector.h> @@ -117,16 +117,9 @@ static JNINativeMethod gMethods[] = { int register_android_os_UEventObserver(JNIEnv *env) { - jclass clazz; + FindClassOrDie(env, "android/os/UEventObserver"); - clazz = env->FindClass("android/os/UEventObserver"); - if (clazz == NULL) { - ALOGE("Can't find android/os/UEventObserver"); - return -1; - } - - return AndroidRuntime::registerNativeMethods(env, - "android/os/UEventObserver", gMethods, NELEM(gMethods)); + return RegisterMethodsOrDie(env, "android/os/UEventObserver", gMethods, NELEM(gMethods)); } } // namespace android diff --git a/core/jni/android_server_FingerprintManager.cpp b/core/jni/android_server_FingerprintManager.cpp index b174d1b..c8aa22f 100644 --- a/core/jni/android_server_FingerprintManager.cpp +++ b/core/jni/android_server_FingerprintManager.cpp @@ -24,22 +24,7 @@ #include <hardware/fingerprint.h> #include <utils/Log.h> -#define FIND_CLASS(var, className) \ - var = env->FindClass(className); \ - LOG_FATAL_IF(! var, "Unable to find class " className); \ - var = jclass(env->NewGlobalRef(var)); - -#define GET_STATIC_METHOD_ID(var, clazz, methodName, fieldDescriptor) \ - var = env->GetStaticMethodID(clazz, methodName, fieldDescriptor); \ - LOG_FATAL_IF(! var, "Unable to find static method" methodName); - -#define GET_METHOD_ID(var, clazz, methodName, fieldDescriptor) \ - var = env->GetMethodID(clazz, methodName, fieldDescriptor); \ - LOG_FATAL_IF(! var, "Unable to find method" methodName); - -#define GET_FIELD_ID(var, clazz, fieldName, fieldDescriptor) \ - var = env->GetFieldID(clazz, fieldName, fieldDescriptor); \ - LOG_FATAL_IF(! var, "Unable to find field " fieldName); +#include "core_jni_helpers.h" namespace android { @@ -84,6 +69,7 @@ static void hal_notify_callback(fingerprint_msg_t msg) { ALOGE("fingerprint: invalid msg: %d", msg.type); return; } + (void)arg3; //ALOG(LOG_VERBOSE, LOG_TAG, "hal_notify(msg=%d, arg1=%d, arg2=%d)\n", msg.type, arg1, arg2); // TODO: fix gross hack to attach JNI to calling thread @@ -103,10 +89,12 @@ static void hal_notify_callback(fingerprint_msg_t msg) { static void nativeInit(JNIEnv *env, jobject clazz, jobject callbackObj) { ALOG(LOG_VERBOSE, LOG_TAG, "nativeInit()\n"); - FIND_CLASS(gFingerprintServiceClassInfo.clazz, FINGERPRINT_SERVICE); - GET_METHOD_ID(gFingerprintServiceClassInfo.notify, gFingerprintServiceClassInfo.clazz, + gFingerprintServiceClassInfo.clazz = FindClassOrDie(env, FINGERPRINT_SERVICE); + gFingerprintServiceClassInfo.clazz = MakeGlobalRefOrDie(env, + gFingerprintServiceClassInfo.clazz); + gFingerprintServiceClassInfo.notify = GetMethodIDOrDie(env, gFingerprintServiceClassInfo.clazz, "notify", "(III)V"); - gFingerprintServiceClassInfo.callbackObject = env->NewGlobalRef(callbackObj); + gFingerprintServiceClassInfo.callbackObject = MakeGlobalRefOrDie(env, callbackObj); } static jint nativeEnroll(JNIEnv* env, jobject clazz, jint timeout) { @@ -184,7 +172,7 @@ static jint nativeCloseHal(JNIEnv* env, jobject clazz) { // TODO: clean up void methods static const JNINativeMethod g_methods[] = { { "nativeEnroll", "(I)I", (void*)nativeEnroll }, - { "nativeEnrollCancel", "()I", (void*)nativeEnroll }, + { "nativeEnrollCancel", "()I", (void*)nativeEnrollCancel }, { "nativeRemove", "(I)I", (void*)nativeRemove }, { "nativeOpenHal", "()I", (void*)nativeOpenHal }, { "nativeCloseHal", "()I", (void*)nativeCloseHal }, @@ -192,11 +180,11 @@ static const JNINativeMethod g_methods[] = { }; int register_android_server_fingerprint_FingerprintService(JNIEnv* env) { - FIND_CLASS(gFingerprintServiceClassInfo.clazz, FINGERPRINT_SERVICE); - GET_METHOD_ID(gFingerprintServiceClassInfo.notify, gFingerprintServiceClassInfo.clazz, "notify", - "(III)V"); - int result = AndroidRuntime::registerNativeMethods( - env, FINGERPRINT_SERVICE, g_methods, NELEM(g_methods)); + jclass clazz = FindClassOrDie(env, FINGERPRINT_SERVICE); + gFingerprintServiceClassInfo.clazz = MakeGlobalRefOrDie(env, clazz); + gFingerprintServiceClassInfo.notify = GetMethodIDOrDie(env, gFingerprintServiceClassInfo.clazz, + "notify", "(III)V"); + int result = RegisterMethodsOrDie(env, FINGERPRINT_SERVICE, g_methods, NELEM(g_methods)); ALOG(LOG_VERBOSE, LOG_TAG, "FingerprintManager JNI ready.\n"); return result; } diff --git a/core/jni/android_server_NetworkManagementSocketTagger.cpp b/core/jni/android_server_NetworkManagementSocketTagger.cpp index 7e12b1e..ca21fd7 100644 --- a/core/jni/android_server_NetworkManagementSocketTagger.cpp +++ b/core/jni/android_server_NetworkManagementSocketTagger.cpp @@ -35,7 +35,7 @@ static jint QTagUid_tagSocketFd(JNIEnv* env, jclass, jint tagNum, jint uid) { int userFd = jniGetFDFromFileDescriptor(env, fileDescriptor); - if (env->ExceptionOccurred() != NULL) { + if (env->ExceptionCheck()) { ALOGE("Can't get FileDescriptor num"); return (jint)-1; } @@ -51,7 +51,7 @@ static jint QTagUid_untagSocketFd(JNIEnv* env, jclass, jobject fileDescriptor) { int userFd = jniGetFDFromFileDescriptor(env, fileDescriptor); - if (env->ExceptionOccurred() != NULL) { + if (env->ExceptionCheck()) { ALOGE("Can't get FileDescriptor num"); return (jint)-1; } diff --git a/core/jni/android_server_Watchdog.cpp b/core/jni/android_server_Watchdog.cpp index 6726c14..d1f9434 100644 --- a/core/jni/android_server_Watchdog.cpp +++ b/core/jni/android_server_Watchdog.cpp @@ -26,7 +26,7 @@ #include "jni.h" #include "JNIHelp.h" -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" static void dumpOneStack(int tid, int outFd) { char buf[64]; @@ -106,8 +106,7 @@ static const JNINativeMethod g_methods[] = { }; int register_android_server_Watchdog(JNIEnv* env) { - return AndroidRuntime::registerNativeMethods(env, "com/android/server/Watchdog", - g_methods, NELEM(g_methods)); + return RegisterMethodsOrDie(env, "com/android/server/Watchdog", g_methods, NELEM(g_methods)); } } diff --git a/core/jni/android_text_AndroidBidi.cpp b/core/jni/android_text_AndroidBidi.cpp index 6f7ee49..3285429 100644 --- a/core/jni/android_text_AndroidBidi.cpp +++ b/core/jni/android_text_AndroidBidi.cpp @@ -18,7 +18,7 @@ #define LOG_TAG "AndroidUnicode" #include "JNIHelp.h" -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" #include "utils/misc.h" #include "utils/Log.h" #include "unicode/ubidi.h" @@ -57,14 +57,12 @@ static jint runBidi(JNIEnv* env, jobject obj, jint dir, jcharArray chsArray, } static JNINativeMethod gMethods[] = { - { "runBidi", "(I[C[BIZ)I", - (void*) runBidi } + { "runBidi", "(I[C[BIZ)I", (void*) runBidi } }; int register_android_text_AndroidBidi(JNIEnv* env) { - return AndroidRuntime::registerNativeMethods(env, "android/text/AndroidBidi", - gMethods, NELEM(gMethods)); + return RegisterMethodsOrDie(env, "android/text/AndroidBidi", gMethods, NELEM(gMethods)); } } diff --git a/core/jni/android_text_AndroidCharacter.cpp b/core/jni/android_text_AndroidCharacter.cpp index 94bd40f..9258248 100644 --- a/core/jni/android_text_AndroidCharacter.cpp +++ b/core/jni/android_text_AndroidCharacter.cpp @@ -19,7 +19,7 @@ #include "JNIHelp.h" #include "ScopedPrimitiveArray.h" -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" #include "utils/misc.h" #include "utils/Log.h" #include "unicode/uchar.h" @@ -193,8 +193,7 @@ static JNINativeMethod gMethods[] = { int register_android_text_AndroidCharacter(JNIEnv* env) { - return AndroidRuntime::registerNativeMethods(env, "android/text/AndroidCharacter", - gMethods, NELEM(gMethods)); + return RegisterMethodsOrDie(env, "android/text/AndroidCharacter", gMethods, NELEM(gMethods)); } } diff --git a/core/jni/android_text_StaticLayout.cpp b/core/jni/android_text_StaticLayout.cpp index 9e20d18..0c2ebf4 100644 --- a/core/jni/android_text_StaticLayout.cpp +++ b/core/jni/android_text_StaticLayout.cpp @@ -23,7 +23,7 @@ #include "utils/Log.h" #include "ScopedPrimitiveArray.h" #include "JNIHelp.h" -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" #include <vector> namespace android { @@ -103,8 +103,7 @@ static JNINativeMethod gMethods[] = { int register_android_text_StaticLayout(JNIEnv* env) { - return AndroidRuntime::registerNativeMethods(env, "android/text/StaticLayout", - gMethods, NELEM(gMethods)); + return RegisterMethodsOrDie(env, "android/text/StaticLayout", gMethods, NELEM(gMethods)); } } diff --git a/core/jni/android_util_AssetManager.cpp b/core/jni/android_util_AssetManager.cpp index fba7255..daf5a61 100644 --- a/core/jni/android_util_AssetManager.cpp +++ b/core/jni/android_util_AssetManager.cpp @@ -17,38 +17,39 @@ #define LOG_TAG "asset" -#define DEBUG_STYLES(x) //x -#define THROW_ON_BAD_ID 0 - #include <android_runtime/android_util_AssetManager.h> +#include <inttypes.h> +#include <linux/capability.h> +#include <stdio.h> +#include <sys/types.h> +#include <sys/wait.h> + +#include <private/android_filesystem_config.h> // for AID_SYSTEM + +#include "androidfw/Asset.h" +#include "androidfw/AssetManager.h" +#include "androidfw/AttributeFinder.h" +#include "androidfw/ResourceTypes.h" +#include "android_runtime/AndroidRuntime.h" +#include "android_util_Binder.h" +#include "core_jni_helpers.h" #include "jni.h" #include "JNIHelp.h" #include "ScopedStringChars.h" #include "ScopedUtfChars.h" -#include "android_util_Binder.h" -#include <utils/misc.h> -#include <android_runtime/AndroidRuntime.h> -#include <utils/Log.h> - -#include <androidfw/Asset.h> -#include <androidfw/AssetManager.h> -#include <androidfw/AttributeFinder.h> -#include <androidfw/ResourceTypes.h> +#include "utils/Log.h" +#include "utils/misc.h" -#include <private/android_filesystem_config.h> // for AID_SYSTEM - -#include <stdio.h> -#include <sys/types.h> -#include <sys/wait.h> - -#include <linux/capability.h> extern "C" int capget(cap_user_header_t hdrp, cap_user_data_t datap); extern "C" int capset(cap_user_header_t hdrp, const cap_user_data_t datap); namespace android { +static const bool kThrowOnBadId = false; +static const bool kDebugStyles = false; + // ---------------------------------------------------------------------------- static struct typedvalue_offsets_t @@ -651,23 +652,29 @@ static jint android_content_AssetManager_getResourceIdentifier(JNIEnv* env, jobj return 0; } - const char16_t* defType16 = defType - ? env->GetStringChars(defType, NULL) : NULL; + const char16_t* defType16 = reinterpret_cast<const char16_t*>(defType) + ? reinterpret_cast<const char16_t*>(env->GetStringChars(defType, NULL)) + : NULL; jsize defTypeLen = defType ? env->GetStringLength(defType) : 0; - const char16_t* defPackage16 = defPackage - ? env->GetStringChars(defPackage, NULL) : NULL; + const char16_t* defPackage16 = reinterpret_cast<const char16_t*>(defPackage) + ? reinterpret_cast<const char16_t*>(env->GetStringChars(defPackage, + NULL)) + : NULL; jsize defPackageLen = defPackage ? env->GetStringLength(defPackage) : 0; jint ident = am->getResources().identifierForName( - name16.get(), name16.size(), defType16, defTypeLen, defPackage16, defPackageLen); + reinterpret_cast<const char16_t*>(name16.get()), name16.size(), + defType16, defTypeLen, defPackage16, defPackageLen); if (defPackage16) { - env->ReleaseStringChars(defPackage, defPackage16); + env->ReleaseStringChars(defPackage, + reinterpret_cast<const jchar*>(defPackage16)); } if (defType16) { - env->ReleaseStringChars(defType, defType16); + env->ReleaseStringChars(defType, + reinterpret_cast<const jchar*>(defType16)); } return ident; @@ -804,21 +811,21 @@ static jint android_content_AssetManager_loadResourceValue(JNIEnv* env, jobject ResTable_config config; uint32_t typeSpecFlags; ssize_t block = res.getResource(ident, &value, false, density, &typeSpecFlags, &config); -#if THROW_ON_BAD_ID - if (block == BAD_INDEX) { - jniThrowException(env, "java/lang/IllegalStateException", "Bad resource!"); - return 0; + if (kThrowOnBadId) { + if (block == BAD_INDEX) { + jniThrowException(env, "java/lang/IllegalStateException", "Bad resource!"); + return 0; + } } -#endif uint32_t ref = ident; if (resolve) { block = res.resolveReference(&value, block, &ref, &typeSpecFlags, &config); -#if THROW_ON_BAD_ID - if (block == BAD_INDEX) { - jniThrowException(env, "java/lang/IllegalStateException", "Bad resource!"); - return 0; + if (kThrowOnBadId) { + if (block == BAD_INDEX) { + jniThrowException(env, "java/lang/IllegalStateException", "Bad resource!"); + return 0; + } } -#endif } if (block >= 0) { return copyValue(env, outValue, &res, value, ref, block, typeSpecFlags, &config); @@ -864,12 +871,12 @@ static jint android_content_AssetManager_loadResourceBagValue(JNIEnv* env, jobje uint32_t ref = ident; if (resolve) { block = res.resolveReference(&value, block, &ref, &typeSpecFlags); -#if THROW_ON_BAD_ID - if (block == BAD_INDEX) { - jniThrowException(env, "java/lang/IllegalStateException", "Bad resource!"); - return 0; + if (kThrowOnBadId) { + if (block == BAD_INDEX) { + jniThrowException(env, "java/lang/IllegalStateException", "Bad resource!"); + return 0; + } } -#endif } if (block >= 0) { return copyValue(env, outValue, &res, value, ref, block, typeSpecFlags); @@ -927,8 +934,11 @@ static jobject android_content_AssetManager_getAssignedPackageIdentifiers(JNIEnv const size_t N = res.getBasePackageCount(); for (size_t i = 0; i < N; i++) { const String16 name = res.getBasePackageName(i); - env->CallVoidMethod(sparseArray, gSparseArrayOffsets.put, (jint) res.getBasePackageId(i), - env->NewString(name, name.size())); + env->CallVoidMethod( + sparseArray, gSparseArrayOffsets.put, + static_cast<jint>(res.getBasePackageId(i)), + env->NewString(reinterpret_cast<const jchar*>(name.string()), + name.size())); } return sparseArray; } @@ -979,12 +989,12 @@ static jint android_content_AssetManager_loadThemeAttributeValue( uint32_t ref = 0; if (resolve) { block = res.resolveReference(&value, block, &ref, &typeSpecFlags); -#if THROW_ON_BAD_ID - if (block == BAD_INDEX) { - jniThrowException(env, "java/lang/IllegalStateException", "Bad resource!"); - return 0; + if (kThrowOnBadId) { + if (block == BAD_INDEX) { + jniThrowException(env, "java/lang/IllegalStateException", "Bad resource!"); + return 0; + } } -#endif } return block >= 0 ? copyValue(env, outValue, &res, value, ref, block, typeSpecFlags) : block; } @@ -995,6 +1005,7 @@ static void android_content_AssetManager_dumpTheme(JNIEnv* env, jobject clazz, { ResTable::Theme* theme = reinterpret_cast<ResTable::Theme*>(themeHandle); const ResTable& res(theme->getResTable()); + (void)res; // XXX Need to use params. theme->dumpToLog(); @@ -1046,8 +1057,10 @@ static jboolean android_content_AssetManager_resolveAttrs(JNIEnv* env, jobject c return JNI_FALSE; } - DEBUG_STYLES(ALOGI("APPLY STYLE: theme=0x%x defStyleAttr=0x%x defStyleRes=0x%x", - themeToken, defStyleAttr, defStyleRes)); + if (kDebugStyles) { + ALOGI("APPLY STYLE: theme=0x%" PRIx64 " defStyleAttr=0x%x " + "defStyleRes=0x%x", themeToken, defStyleAttr, defStyleRes); + } ResTable::Theme* theme = reinterpret_cast<ResTable::Theme*>(themeToken); const ResTable& res = theme->getResTable(); @@ -1114,7 +1127,9 @@ static jboolean android_content_AssetManager_resolveAttrs(JNIEnv* env, jobject c for (jsize ii=0; ii<NI; ii++) { const uint32_t curIdent = (uint32_t)src[ii]; - DEBUG_STYLES(ALOGI("RETRIEVING ATTR 0x%08x...", curIdent)); + if (kDebugStyles) { + ALOGI("RETRIEVING ATTR 0x%08x...", curIdent); + } // Try to find a value for this attribute... we prioritize values // coming from, first XML attributes, then XML style, then default @@ -1129,8 +1144,9 @@ static jboolean android_content_AssetManager_resolveAttrs(JNIEnv* env, jobject c block = -1; value.dataType = Res_value::TYPE_ATTRIBUTE; value.data = srcValues[ii]; - DEBUG_STYLES(ALOGI("-> From values: type=0x%x, data=0x%08x", - value.dataType, value.data)); + if (kDebugStyles) { + ALOGI("-> From values: type=0x%x, data=0x%08x", value.dataType, value.data); + } } if (value.dataType == Res_value::TYPE_NULL) { @@ -1139,8 +1155,9 @@ static jboolean android_content_AssetManager_resolveAttrs(JNIEnv* env, jobject c block = defStyleEntry->stringBlock; typeSetFlags = defStyleTypeSetFlags; value = defStyleEntry->map.value; - DEBUG_STYLES(ALOGI("-> From def style: type=0x%x, data=0x%08x", - value.dataType, value.data)); + if (kDebugStyles) { + ALOGI("-> From def style: type=0x%x, data=0x%08x", value.dataType, value.data); + } } } @@ -1150,39 +1167,46 @@ static jboolean android_content_AssetManager_resolveAttrs(JNIEnv* env, jobject c ssize_t newBlock = theme->resolveAttributeReference(&value, block, &resid, &typeSetFlags, &config); if (newBlock >= 0) block = newBlock; - DEBUG_STYLES(ALOGI("-> Resolved attr: type=0x%x, data=0x%08x", - value.dataType, value.data)); + if (kDebugStyles) { + ALOGI("-> Resolved attr: type=0x%x, data=0x%08x", value.dataType, value.data); + } } else { // If we still don't have a value for this attribute, try to find // it in the theme! ssize_t newBlock = theme->getAttribute(curIdent, &value, &typeSetFlags); if (newBlock >= 0) { - DEBUG_STYLES(ALOGI("-> From theme: type=0x%x, data=0x%08x", - value.dataType, value.data)); + if (kDebugStyles) { + ALOGI("-> From theme: type=0x%x, data=0x%08x", value.dataType, value.data); + } newBlock = res.resolveReference(&value, block, &resid, &typeSetFlags, &config); -#if THROW_ON_BAD_ID - if (newBlock == BAD_INDEX) { - jniThrowException(env, "java/lang/IllegalStateException", "Bad resource!"); - return JNI_FALSE; + if (kThrowOnBadId) { + if (newBlock == BAD_INDEX) { + jniThrowException(env, "java/lang/IllegalStateException", "Bad resource!"); + return JNI_FALSE; + } } -#endif if (newBlock >= 0) block = newBlock; - DEBUG_STYLES(ALOGI("-> Resolved theme: type=0x%x, data=0x%08x", - value.dataType, value.data)); + if (kDebugStyles) { + ALOGI("-> Resolved theme: type=0x%x, data=0x%08x", value.dataType, value.data); + } } } // Deal with the special @null value -- it turns back to TYPE_NULL. if (value.dataType == Res_value::TYPE_REFERENCE && value.data == 0) { - DEBUG_STYLES(ALOGI("-> Setting to @null!")); + if (kDebugStyles) { + ALOGI("-> Setting to @null!"); + } value.dataType = Res_value::TYPE_NULL; value.data = Res_value::DATA_NULL_UNDEFINED; block = -1; } - DEBUG_STYLES(ALOGI("Attribute 0x%08x: type=0x%x, data=0x%08x", - curIdent, value.dataType, value.data)); + if (kDebugStyles) { + ALOGI("Attribute 0x%08x: type=0x%x, data=0x%08x", curIdent, value.dataType, + value.data); + } // Write the final value back to Java. dest[STYLE_TYPE] = value.dataType; @@ -1236,8 +1260,11 @@ static jboolean android_content_AssetManager_applyStyle(JNIEnv* env, jobject cla return JNI_FALSE; } - DEBUG_STYLES(ALOGI("APPLY STYLE: theme=0x%x defStyleAttr=0x%x defStyleRes=0x%x xml=0x%x", - themeToken, defStyleAttr, defStyleRes, xmlParserToken)); + if (kDebugStyles) { + ALOGI("APPLY STYLE: theme=0x%" PRIx64 " defStyleAttr=0x%x defStyleRes=0x%x " + "xml=0x%" PRIx64, themeToken, defStyleAttr, defStyleRes, + xmlParserToken); + } ResTable::Theme* theme = reinterpret_cast<ResTable::Theme*>(themeToken); const ResTable& res = theme->getResTable(); @@ -1332,7 +1359,9 @@ static jboolean android_content_AssetManager_applyStyle(JNIEnv* env, jobject cla for (jsize ii = 0; ii < NI; ii++) { const uint32_t curIdent = (uint32_t)src[ii]; - DEBUG_STYLES(ALOGI("RETRIEVING ATTR 0x%08x...", curIdent)); + if (kDebugStyles) { + ALOGI("RETRIEVING ATTR 0x%08x...", curIdent); + } // Try to find a value for this attribute... we prioritize values // coming from, first XML attributes, then XML style, then default @@ -1348,8 +1377,9 @@ static jboolean android_content_AssetManager_applyStyle(JNIEnv* env, jobject cla // We found the attribute we were looking for. block = kXmlBlock; xmlParser->getAttributeValue(xmlAttrIdx, &value); - DEBUG_STYLES(ALOGI("-> From XML: type=0x%x, data=0x%08x", - value.dataType, value.data)); + if (kDebugStyles) { + ALOGI("-> From XML: type=0x%x, data=0x%08x", value.dataType, value.data); + } } if (value.dataType == Res_value::TYPE_NULL) { @@ -1360,8 +1390,9 @@ static jboolean android_content_AssetManager_applyStyle(JNIEnv* env, jobject cla block = styleAttrEntry->stringBlock; typeSetFlags = styleTypeSetFlags; value = styleAttrEntry->map.value; - DEBUG_STYLES(ALOGI("-> From style: type=0x%x, data=0x%08x", - value.dataType, value.data)); + if (kDebugStyles) { + ALOGI("-> From style: type=0x%x, data=0x%08x", value.dataType, value.data); + } } } @@ -1373,8 +1404,9 @@ static jboolean android_content_AssetManager_applyStyle(JNIEnv* env, jobject cla block = defStyleAttrEntry->stringBlock; typeSetFlags = styleTypeSetFlags; value = defStyleAttrEntry->map.value; - DEBUG_STYLES(ALOGI("-> From def style: type=0x%x, data=0x%08x", - value.dataType, value.data)); + if (kDebugStyles) { + ALOGI("-> From def style: type=0x%x, data=0x%08x", value.dataType, value.data); + } } } @@ -1386,41 +1418,50 @@ static jboolean android_content_AssetManager_applyStyle(JNIEnv* env, jobject cla if (newBlock >= 0) { block = newBlock; } - DEBUG_STYLES(ALOGI("-> Resolved attr: type=0x%x, data=0x%08x", - value.dataType, value.data)); + + if (kDebugStyles) { + ALOGI("-> Resolved attr: type=0x%x, data=0x%08x", value.dataType, value.data); + } } else { // If we still don't have a value for this attribute, try to find // it in the theme! ssize_t newBlock = theme->getAttribute(curIdent, &value, &typeSetFlags); if (newBlock >= 0) { - DEBUG_STYLES(ALOGI("-> From theme: type=0x%x, data=0x%08x", - value.dataType, value.data)); + if (kDebugStyles) { + ALOGI("-> From theme: type=0x%x, data=0x%08x", value.dataType, value.data); + } newBlock = res.resolveReference(&value, block, &resid, &typeSetFlags, &config); -#if THROW_ON_BAD_ID - if (newBlock == BAD_INDEX) { - jniThrowException(env, "java/lang/IllegalStateException", "Bad resource!"); - return JNI_FALSE; + if (kThrowOnBadId) { + if (newBlock == BAD_INDEX) { + jniThrowException(env, "java/lang/IllegalStateException", "Bad resource!"); + return JNI_FALSE; + } } -#endif + if (newBlock >= 0) { block = newBlock; } - DEBUG_STYLES(ALOGI("-> Resolved theme: type=0x%x, data=0x%08x", - value.dataType, value.data)); + + if (kDebugStyles) { + ALOGI("-> Resolved theme: type=0x%x, data=0x%08x", value.dataType, value.data); + } } } // Deal with the special @null value -- it turns back to TYPE_NULL. if (value.dataType == Res_value::TYPE_REFERENCE && value.data == 0) { - DEBUG_STYLES(ALOGI("-> Setting to @null!")); + if (kDebugStyles) { + ALOGI("-> Setting to @null!"); + } value.dataType = Res_value::TYPE_NULL; value.data = Res_value::DATA_NULL_UNDEFINED; block = kXmlBlock; } - DEBUG_STYLES(ALOGI("Attribute 0x%08x: type=0x%x, data=0x%08x", - curIdent, value.dataType, value.data)); + if (kDebugStyles) { + ALOGI("Attribute 0x%08x: type=0x%x, data=0x%08x", curIdent, value.dataType, value.data); + } // Write the final value back to Java. dest[STYLE_TYPE] = value.dataType; @@ -1549,12 +1590,12 @@ static jboolean android_content_AssetManager_retrieveAttributes(JNIEnv* env, job //printf("Resolving attribute reference\n"); ssize_t newBlock = res.resolveReference(&value, block, &resid, &typeSetFlags, &config); -#if THROW_ON_BAD_ID - if (newBlock == BAD_INDEX) { - jniThrowException(env, "java/lang/IllegalStateException", "Bad resource!"); - return JNI_FALSE; + if (kThrowOnBadId) { + if (newBlock == BAD_INDEX) { + jniThrowException(env, "java/lang/IllegalStateException", "Bad resource!"); + return JNI_FALSE; + } } -#endif if (newBlock >= 0) block = newBlock; } @@ -1663,12 +1704,12 @@ static jint android_content_AssetManager_retrieveArray(JNIEnv* env, jobject claz //printf("Resolving attribute reference\n"); ssize_t newBlock = res.resolveReference(&value, block, &resid, &typeSetFlags, &config); -#if THROW_ON_BAD_ID - if (newBlock == BAD_INDEX) { - jniThrowException(env, "java/lang/IllegalStateException", "Bad resource!"); - return JNI_FALSE; + if (kThrowOnBadId) { + if (newBlock == BAD_INDEX) { + jniThrowException(env, "java/lang/IllegalStateException", "Bad resource!"); + return JNI_FALSE; + } } -#endif if (newBlock >= 0) block = newBlock; } @@ -1776,12 +1817,12 @@ static jintArray android_content_AssetManager_getArrayStringInfo(JNIEnv* env, jo stringIndex = value.data; } -#if THROW_ON_BAD_ID - if (stringBlock == BAD_INDEX) { - jniThrowException(env, "java/lang/IllegalStateException", "Bad resource!"); - return array; + if (kThrowOnBadId) { + if (stringBlock == BAD_INDEX) { + jniThrowException(env, "java/lang/IllegalStateException", "Bad resource!"); + return array; + } } -#endif //todo: It might be faster to allocate a C array to contain // the blocknums and indices, put them in there and then @@ -1824,12 +1865,12 @@ static jobjectArray android_content_AssetManager_getArrayStringResource(JNIEnv* // Take care of resolving the found resource to its final value. ssize_t block = res.resolveReference(&value, bag->stringBlock, NULL); -#if THROW_ON_BAD_ID - if (block == BAD_INDEX) { - jniThrowException(env, "java/lang/IllegalStateException", "Bad resource!"); - return array; + if (kThrowOnBadId) { + if (block == BAD_INDEX) { + jniThrowException(env, "java/lang/IllegalStateException", "Bad resource!"); + return array; + } } -#endif if (value.dataType == Res_value::TYPE_STRING) { const ResStringPool* pool = res.getTableStringBlock(block); const char* str8 = pool->string8At(value.data, &strLen); @@ -1837,7 +1878,8 @@ static jobjectArray android_content_AssetManager_getArrayStringResource(JNIEnv* str = env->NewStringUTF(str8); } else { const char16_t* str16 = pool->stringAt(value.data, &strLen); - str = env->NewString(str16, strLen); + str = env->NewString(reinterpret_cast<const jchar*>(str16), + strLen); } // If one of our NewString{UTF} calls failed due to memory, an @@ -1887,12 +1929,12 @@ static jintArray android_content_AssetManager_getArrayIntResource(JNIEnv* env, j // Take care of resolving the found resource to its final value. ssize_t block = res.resolveReference(&value, bag->stringBlock, NULL); -#if THROW_ON_BAD_ID - if (block == BAD_INDEX) { - jniThrowException(env, "java/lang/IllegalStateException", "Bad resource!"); - return array; + if (kThrowOnBadId) { + if (block == BAD_INDEX) { + jniThrowException(env, "java/lang/IllegalStateException", "Bad resource!"); + return array; + } } -#endif if (value.dataType >= Res_value::TYPE_FIRST_INT && value.dataType <= Res_value::TYPE_LAST_INT) { int intVal = value.data; @@ -1924,7 +1966,6 @@ static jintArray android_content_AssetManager_getStyleAttributes(JNIEnv* env, jo return NULL; } - Res_value value; const ResTable::bag_entry* bag = startOfBag; for (size_t i=0; ((ssize_t)i)<N; i++, bag++) { int resourceId = bag->map.name.ident; @@ -2016,7 +2057,7 @@ static JNINativeMethod gAssetManagerMethods[] = { (void*) android_content_AssetManager_getAssetRemainingLength }, { "addAssetPathNative", "(Ljava/lang/String;)I", (void*) android_content_AssetManager_addAssetPath }, - { "addOverlayPath", "(Ljava/lang/String;)I", + { "addOverlayPathNative", "(Ljava/lang/String;)I", (void*) android_content_AssetManager_addOverlayPath }, { "isUpToDate", "()Z", (void*) android_content_AssetManager_isUpToDate }, @@ -2099,69 +2140,43 @@ static JNINativeMethod gAssetManagerMethods[] = { { "getAssetAllocations", "()Ljava/lang/String;", (void*) android_content_AssetManager_getAssetAllocations }, { "getGlobalAssetManagerCount", "()I", - (void*) android_content_AssetManager_getGlobalAssetCount }, + (void*) android_content_AssetManager_getGlobalAssetManagerCount }, }; int register_android_content_AssetManager(JNIEnv* env) { - jclass typedValue = env->FindClass("android/util/TypedValue"); - LOG_FATAL_IF(typedValue == NULL, "Unable to find class android/util/TypedValue"); - gTypedValueOffsets.mType - = env->GetFieldID(typedValue, "type", "I"); - LOG_FATAL_IF(gTypedValueOffsets.mType == NULL, "Unable to find TypedValue.type"); - gTypedValueOffsets.mData - = env->GetFieldID(typedValue, "data", "I"); - LOG_FATAL_IF(gTypedValueOffsets.mData == NULL, "Unable to find TypedValue.data"); - gTypedValueOffsets.mString - = env->GetFieldID(typedValue, "string", "Ljava/lang/CharSequence;"); - LOG_FATAL_IF(gTypedValueOffsets.mString == NULL, "Unable to find TypedValue.string"); - gTypedValueOffsets.mAssetCookie - = env->GetFieldID(typedValue, "assetCookie", "I"); - LOG_FATAL_IF(gTypedValueOffsets.mAssetCookie == NULL, "Unable to find TypedValue.assetCookie"); - gTypedValueOffsets.mResourceId - = env->GetFieldID(typedValue, "resourceId", "I"); - LOG_FATAL_IF(gTypedValueOffsets.mResourceId == NULL, "Unable to find TypedValue.resourceId"); - gTypedValueOffsets.mChangingConfigurations - = env->GetFieldID(typedValue, "changingConfigurations", "I"); - LOG_FATAL_IF(gTypedValueOffsets.mChangingConfigurations == NULL, "Unable to find TypedValue.changingConfigurations"); - gTypedValueOffsets.mDensity = env->GetFieldID(typedValue, "density", "I"); - LOG_FATAL_IF(gTypedValueOffsets.mDensity == NULL, "Unable to find TypedValue.density"); - - jclass assetFd = env->FindClass("android/content/res/AssetFileDescriptor"); - LOG_FATAL_IF(assetFd == NULL, "Unable to find class android/content/res/AssetFileDescriptor"); - gAssetFileDescriptorOffsets.mFd - = env->GetFieldID(assetFd, "mFd", "Landroid/os/ParcelFileDescriptor;"); - LOG_FATAL_IF(gAssetFileDescriptorOffsets.mFd == NULL, "Unable to find AssetFileDescriptor.mFd"); - gAssetFileDescriptorOffsets.mStartOffset - = env->GetFieldID(assetFd, "mStartOffset", "J"); - LOG_FATAL_IF(gAssetFileDescriptorOffsets.mStartOffset == NULL, "Unable to find AssetFileDescriptor.mStartOffset"); - gAssetFileDescriptorOffsets.mLength - = env->GetFieldID(assetFd, "mLength", "J"); - LOG_FATAL_IF(gAssetFileDescriptorOffsets.mLength == NULL, "Unable to find AssetFileDescriptor.mLength"); - - jclass assetManager = env->FindClass("android/content/res/AssetManager"); - LOG_FATAL_IF(assetManager == NULL, "Unable to find class android/content/res/AssetManager"); - gAssetManagerOffsets.mObject - = env->GetFieldID(assetManager, "mObject", "J"); - LOG_FATAL_IF(gAssetManagerOffsets.mObject == NULL, "Unable to find AssetManager.mObject"); - - jclass stringClass = env->FindClass("java/lang/String"); - LOG_FATAL_IF(stringClass == NULL, "Unable to find class java/lang/String"); - g_stringClass = (jclass)env->NewGlobalRef(stringClass); - LOG_FATAL_IF(g_stringClass == NULL, "Unable to create global reference for class java/lang/String"); - - jclass sparseArrayClass = env->FindClass("android/util/SparseArray"); - LOG_FATAL_IF(sparseArrayClass == NULL, "Unable to find class android/util/SparseArray"); - gSparseArrayOffsets.classObject = (jclass) env->NewGlobalRef(sparseArrayClass); - gSparseArrayOffsets.constructor = - env->GetMethodID(gSparseArrayOffsets.classObject, "<init>", "()V"); - LOG_FATAL_IF(gSparseArrayOffsets.constructor == NULL, "Unable to find SparseArray.<init>()"); - gSparseArrayOffsets.put = - env->GetMethodID(gSparseArrayOffsets.classObject, "put", "(ILjava/lang/Object;)V"); - LOG_FATAL_IF(gSparseArrayOffsets.put == NULL, "Unable to find SparseArray.put(int, V)"); - - return AndroidRuntime::registerNativeMethods(env, - "android/content/res/AssetManager", gAssetManagerMethods, NELEM(gAssetManagerMethods)); + jclass typedValue = FindClassOrDie(env, "android/util/TypedValue"); + gTypedValueOffsets.mType = GetFieldIDOrDie(env, typedValue, "type", "I"); + gTypedValueOffsets.mData = GetFieldIDOrDie(env, typedValue, "data", "I"); + gTypedValueOffsets.mString = GetFieldIDOrDie(env, typedValue, "string", + "Ljava/lang/CharSequence;"); + gTypedValueOffsets.mAssetCookie = GetFieldIDOrDie(env, typedValue, "assetCookie", "I"); + gTypedValueOffsets.mResourceId = GetFieldIDOrDie(env, typedValue, "resourceId", "I"); + gTypedValueOffsets.mChangingConfigurations = GetFieldIDOrDie(env, typedValue, + "changingConfigurations", "I"); + gTypedValueOffsets.mDensity = GetFieldIDOrDie(env, typedValue, "density", "I"); + + jclass assetFd = FindClassOrDie(env, "android/content/res/AssetFileDescriptor"); + gAssetFileDescriptorOffsets.mFd = GetFieldIDOrDie(env, assetFd, "mFd", + "Landroid/os/ParcelFileDescriptor;"); + gAssetFileDescriptorOffsets.mStartOffset = GetFieldIDOrDie(env, assetFd, "mStartOffset", "J"); + gAssetFileDescriptorOffsets.mLength = GetFieldIDOrDie(env, assetFd, "mLength", "J"); + + jclass assetManager = FindClassOrDie(env, "android/content/res/AssetManager"); + gAssetManagerOffsets.mObject = GetFieldIDOrDie(env, assetManager, "mObject", "J"); + + jclass stringClass = FindClassOrDie(env, "java/lang/String"); + g_stringClass = MakeGlobalRefOrDie(env, stringClass); + + jclass sparseArrayClass = FindClassOrDie(env, "android/util/SparseArray"); + gSparseArrayOffsets.classObject = MakeGlobalRefOrDie(env, sparseArrayClass); + gSparseArrayOffsets.constructor = GetMethodIDOrDie(env, gSparseArrayOffsets.classObject, + "<init>", "()V"); + gSparseArrayOffsets.put = GetMethodIDOrDie(env, gSparseArrayOffsets.classObject, "put", + "(ILjava/lang/Object;)V"); + + return RegisterMethodsOrDie(env, "android/content/res/AssetManager", gAssetManagerMethods, + NELEM(gAssetManagerMethods)); } }; // namespace android diff --git a/core/jni/android_util_Binder.cpp b/core/jni/android_util_Binder.cpp index e400698..5f42c3d 100644 --- a/core/jni/android_util_Binder.cpp +++ b/core/jni/android_util_Binder.cpp @@ -46,7 +46,7 @@ #include <ScopedUtfChars.h> #include <ScopedLocalRef.h> -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" //#undef ALOGV //#define ALOGV(...) fprintf(stderr, __VA_ARGS__) @@ -85,15 +85,6 @@ static struct binderinternal_offsets_t // ---------------------------------------------------------------------------- -static struct debug_offsets_t -{ - // Class state. - jclass mClass; - -} gDebugOffsets; - -// ---------------------------------------------------------------------------- - static struct error_offsets_t { jclass mClass; @@ -215,7 +206,6 @@ static void report_exception(JNIEnv* env, jthrowable excep, const char* msg) sleep(60); ALOGE("Forcefully exiting"); exit(1); - *((int *) 1) = 1; } bail: @@ -271,9 +261,9 @@ protected: //printf("\n"); jboolean res = env->CallBooleanMethod(mObject, gBinderOffsets.mExecTransact, code, reinterpret_cast<jlong>(&data), reinterpret_cast<jlong>(reply), flags); - jthrowable excep = env->ExceptionOccurred(); - if (excep) { + if (env->ExceptionCheck()) { + jthrowable excep = env->ExceptionOccurred(); report_exception(env, excep, "*** Uncaught remote exception! " "(Exceptions are not yet supported across processes.)"); @@ -291,12 +281,12 @@ protected: set_dalvik_blockguard_policy(env, strict_policy_before); } - jthrowable excep2 = env->ExceptionOccurred(); - if (excep2) { - report_exception(env, excep2, + if (env->ExceptionCheck()) { + jthrowable excep = env->ExceptionOccurred(); + report_exception(env, excep, "*** Uncaught exception in onBinderStrictModePolicyChange"); /* clean up JNI local ref -- we don't return to Java code */ - env->DeleteLocalRef(excep2); + env->DeleteLocalRef(excep); } // Need to always call through the native implementation of @@ -398,8 +388,8 @@ public: env->CallStaticVoidMethod(gBinderProxyOffsets.mClass, gBinderProxyOffsets.mSendDeathNotice, mObject); - jthrowable excep = env->ExceptionOccurred(); - if (excep) { + if (env->ExceptionCheck()) { + jthrowable excep = env->ExceptionOccurred(); report_exception(env, excep, "*** Uncaught exception returned from death notification!"); } @@ -836,21 +826,13 @@ const char* const kBinderPathName = "android/os/Binder"; static int int_register_android_os_Binder(JNIEnv* env) { - jclass clazz; + jclass clazz = FindClassOrDie(env, kBinderPathName); - clazz = env->FindClass(kBinderPathName); - LOG_FATAL_IF(clazz == NULL, "Unable to find class android.os.Binder"); + gBinderOffsets.mClass = MakeGlobalRefOrDie(env, clazz); + gBinderOffsets.mExecTransact = GetMethodIDOrDie(env, clazz, "execTransact", "(IJJI)Z"); + gBinderOffsets.mObject = GetFieldIDOrDie(env, clazz, "mObject", "J"); - gBinderOffsets.mClass = (jclass) env->NewGlobalRef(clazz); - gBinderOffsets.mExecTransact - = env->GetMethodID(clazz, "execTransact", "(IJJI)Z"); - assert(gBinderOffsets.mExecTransact); - - gBinderOffsets.mObject - = env->GetFieldID(clazz, "mObject", "J"); - assert(gBinderOffsets.mObject); - - return AndroidRuntime::registerNativeMethods( + return RegisterMethodsOrDie( env, kBinderPathName, gBinderMethods, NELEM(gBinderMethods)); } @@ -920,17 +902,12 @@ const char* const kBinderInternalPathName = "com/android/internal/os/BinderInter static int int_register_android_os_BinderInternal(JNIEnv* env) { - jclass clazz; + jclass clazz = FindClassOrDie(env, kBinderInternalPathName); - clazz = env->FindClass(kBinderInternalPathName); - LOG_FATAL_IF(clazz == NULL, "Unable to find class com.android.internal.os.BinderInternal"); + gBinderInternalOffsets.mClass = MakeGlobalRefOrDie(env, clazz); + gBinderInternalOffsets.mForceGc = GetStaticMethodIDOrDie(env, clazz, "forceBinderGc", "()V"); - gBinderInternalOffsets.mClass = (jclass) env->NewGlobalRef(clazz); - gBinderInternalOffsets.mForceGc - = env->GetStaticMethodID(clazz, "forceBinderGc", "()V"); - assert(gBinderInternalOffsets.mForceGc); - - return AndroidRuntime::registerNativeMethods( + return RegisterMethodsOrDie( env, kBinderInternalPathName, gBinderInternalMethods, NELEM(gBinderInternalMethods)); } @@ -955,7 +932,8 @@ static jstring android_os_BinderProxy_getInterfaceDescriptor(JNIEnv* env, jobjec IBinder* target = (IBinder*) env->GetLongField(obj, gBinderProxyOffsets.mObject); if (target != NULL) { const String16& desc = target->getInterfaceDescriptor(); - return env->NewString(desc.string(), desc.size()); + return env->NewString(reinterpret_cast<const jchar*>(desc.string()), + desc.size()); } jniThrowException(env, "java/lang/RuntimeException", "No binder found for object"); @@ -1024,7 +1002,9 @@ static bool push_eventlog_int(char** pos, const char* end, jint val) { } // From frameworks/base/core/java/android/content/EventLogTags.logtags: -#define ENABLE_BINDER_SAMPLE 0 + +static const bool kEnableBinderSample = false; + #define LOGTAG_BINDER_OPERATION 52004 static void conditionally_log_binder_call(int64_t start_millis, @@ -1063,16 +1043,9 @@ static void conditionally_log_binder_call(int64_t start_millis, } // We only measure binder call durations to potentially log them if -// we're on the main thread. Unfortunately sim-eng doesn't seem to -// have gettid, so we just ignore this and don't log if we can't -// get the thread id. +// we're on the main thread. static bool should_time_binder_calls() { -#ifdef HAVE_GETTID - return (getpid() == androidGetTid()); -#else -#warning no gettid(), so not logging Binder calls... - return false; -#endif + return (getpid() == gettid()); } static jboolean android_os_BinderProxy_transact(JNIEnv* env, jobject obj, @@ -1102,24 +1075,28 @@ static jboolean android_os_BinderProxy_transact(JNIEnv* env, jobject obj, ALOGV("Java code calling transact on %p in Java object %p with code %" PRId32 "\n", target, obj, code); -#if ENABLE_BINDER_SAMPLE - // Only log the binder call duration for things on the Java-level main thread. - // But if we don't - const bool time_binder_calls = should_time_binder_calls(); + bool time_binder_calls; int64_t start_millis; - if (time_binder_calls) { - start_millis = uptimeMillis(); + if (kEnableBinderSample) { + // Only log the binder call duration for things on the Java-level main thread. + // But if we don't + time_binder_calls = should_time_binder_calls(); + + if (time_binder_calls) { + start_millis = uptimeMillis(); + } } -#endif + //printf("Transact from Java code to %p sending: ", target); data->print(); status_t err = target->transact(code, *data, reply, flags); //if (reply) printf("Transact from Java code to %p received: ", target); reply->print(); -#if ENABLE_BINDER_SAMPLE - if (time_binder_calls) { - conditionally_log_binder_call(start_millis, target, code); + + if (kEnableBinderSample) { + if (time_binder_calls) { + conditionally_log_binder_call(start_millis, target, code); + } } -#endif if (err == NO_ERROR) { return JNI_TRUE; @@ -1244,39 +1221,24 @@ const char* const kBinderProxyPathName = "android/os/BinderProxy"; static int int_register_android_os_BinderProxy(JNIEnv* env) { - jclass clazz; - - clazz = env->FindClass("java/lang/Error"); - LOG_FATAL_IF(clazz == NULL, "Unable to find class java.lang.Error"); - gErrorOffsets.mClass = (jclass) env->NewGlobalRef(clazz); - - clazz = env->FindClass(kBinderProxyPathName); - LOG_FATAL_IF(clazz == NULL, "Unable to find class android.os.BinderProxy"); - - gBinderProxyOffsets.mClass = (jclass) env->NewGlobalRef(clazz); - gBinderProxyOffsets.mConstructor - = env->GetMethodID(clazz, "<init>", "()V"); - assert(gBinderProxyOffsets.mConstructor); - gBinderProxyOffsets.mSendDeathNotice - = env->GetStaticMethodID(clazz, "sendDeathNotice", "(Landroid/os/IBinder$DeathRecipient;)V"); - assert(gBinderProxyOffsets.mSendDeathNotice); - - gBinderProxyOffsets.mObject - = env->GetFieldID(clazz, "mObject", "J"); - assert(gBinderProxyOffsets.mObject); - gBinderProxyOffsets.mSelf - = env->GetFieldID(clazz, "mSelf", "Ljava/lang/ref/WeakReference;"); - assert(gBinderProxyOffsets.mSelf); - gBinderProxyOffsets.mOrgue - = env->GetFieldID(clazz, "mOrgue", "J"); - assert(gBinderProxyOffsets.mOrgue); - - clazz = env->FindClass("java/lang/Class"); - LOG_FATAL_IF(clazz == NULL, "Unable to find java.lang.Class"); - gClassOffsets.mGetName = env->GetMethodID(clazz, "getName", "()Ljava/lang/String;"); - assert(gClassOffsets.mGetName); - - return AndroidRuntime::registerNativeMethods( + jclass clazz = FindClassOrDie(env, "java/lang/Error"); + gErrorOffsets.mClass = MakeGlobalRefOrDie(env, clazz); + + clazz = FindClassOrDie(env, kBinderProxyPathName); + gBinderProxyOffsets.mClass = MakeGlobalRefOrDie(env, clazz); + gBinderProxyOffsets.mConstructor = GetMethodIDOrDie(env, clazz, "<init>", "()V"); + gBinderProxyOffsets.mSendDeathNotice = GetStaticMethodIDOrDie(env, clazz, "sendDeathNotice", + "(Landroid/os/IBinder$DeathRecipient;)V"); + + gBinderProxyOffsets.mObject = GetFieldIDOrDie(env, clazz, "mObject", "J"); + gBinderProxyOffsets.mSelf = GetFieldIDOrDie(env, clazz, "mSelf", + "Ljava/lang/ref/WeakReference;"); + gBinderProxyOffsets.mOrgue = GetFieldIDOrDie(env, clazz, "mOrgue", "J"); + + clazz = FindClassOrDie(env, "java/lang/Class"); + gClassOffsets.mGetName = GetMethodIDOrDie(env, clazz, "getName", "()Ljava/lang/String;"); + + return RegisterMethodsOrDie( env, kBinderProxyPathName, gBinderProxyMethods, NELEM(gBinderProxyMethods)); } @@ -1294,28 +1256,20 @@ int register_android_os_Binder(JNIEnv* env) if (int_register_android_os_BinderProxy(env) < 0) return -1; - jclass clazz; - - clazz = env->FindClass("android/util/Log"); - LOG_FATAL_IF(clazz == NULL, "Unable to find class android.util.Log"); - gLogOffsets.mClass = (jclass) env->NewGlobalRef(clazz); - gLogOffsets.mLogE = env->GetStaticMethodID( - clazz, "e", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I"); - assert(gLogOffsets.mLogE); - - clazz = env->FindClass("android/os/ParcelFileDescriptor"); - LOG_FATAL_IF(clazz == NULL, "Unable to find class android.os.ParcelFileDescriptor"); - gParcelFileDescriptorOffsets.mClass = (jclass) env->NewGlobalRef(clazz); - gParcelFileDescriptorOffsets.mConstructor - = env->GetMethodID(clazz, "<init>", "(Ljava/io/FileDescriptor;)V"); - - clazz = env->FindClass("android/os/StrictMode"); - LOG_FATAL_IF(clazz == NULL, "Unable to find class android.os.StrictMode"); - gStrictModeCallbackOffsets.mClass = (jclass) env->NewGlobalRef(clazz); - gStrictModeCallbackOffsets.mCallback = env->GetStaticMethodID( - clazz, "onBinderStrictModePolicyChange", "(I)V"); - LOG_FATAL_IF(gStrictModeCallbackOffsets.mCallback == NULL, - "Unable to find strict mode callback."); + jclass clazz = FindClassOrDie(env, "android/util/Log"); + gLogOffsets.mClass = MakeGlobalRefOrDie(env, clazz); + gLogOffsets.mLogE = GetStaticMethodIDOrDie(env, clazz, "e", + "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I"); + + clazz = FindClassOrDie(env, "android/os/ParcelFileDescriptor"); + gParcelFileDescriptorOffsets.mClass = MakeGlobalRefOrDie(env, clazz); + gParcelFileDescriptorOffsets.mConstructor = GetMethodIDOrDie(env, clazz, "<init>", + "(Ljava/io/FileDescriptor;)V"); + + clazz = FindClassOrDie(env, "android/os/StrictMode"); + gStrictModeCallbackOffsets.mClass = MakeGlobalRefOrDie(env, clazz); + gStrictModeCallbackOffsets.mCallback = GetStaticMethodIDOrDie(env, clazz, + "onBinderStrictModePolicyChange", "(I)V"); return 0; } diff --git a/core/jni/android_util_EventLog.cpp b/core/jni/android_util_EventLog.cpp index 8a0eaa2..2df13b7 100644 --- a/core/jni/android_util_EventLog.cpp +++ b/core/jni/android_util_EventLog.cpp @@ -17,7 +17,7 @@ #include <fcntl.h> #include "JNIHelp.h" -#include "android_runtime/AndroidRuntime.h" +#include "core_jni_helpers.h" #include "jni.h" #include "log/logger.h" @@ -263,33 +263,21 @@ static struct { jclass *c; const char *name, *mt; jmethodID *id; } gMethods[] = int register_android_util_EventLog(JNIEnv* env) { for (int i = 0; i < NELEM(gClasses); ++i) { - jclass clazz = env->FindClass(gClasses[i].name); - if (clazz == NULL) { - ALOGE("Can't find class: %s\n", gClasses[i].name); - return -1; - } - *gClasses[i].clazz = (jclass) env->NewGlobalRef(clazz); + jclass clazz = FindClassOrDie(env, gClasses[i].name); + *gClasses[i].clazz = MakeGlobalRefOrDie(env, clazz); } for (int i = 0; i < NELEM(gFields); ++i) { - *gFields[i].id = env->GetFieldID( + *gFields[i].id = GetFieldIDOrDie(env, *gFields[i].c, gFields[i].name, gFields[i].ft); - if (*gFields[i].id == NULL) { - ALOGE("Can't find field: %s\n", gFields[i].name); - return -1; - } } for (int i = 0; i < NELEM(gMethods); ++i) { - *gMethods[i].id = env->GetMethodID( + *gMethods[i].id = GetMethodIDOrDie(env, *gMethods[i].c, gMethods[i].name, gMethods[i].mt); - if (*gMethods[i].id == NULL) { - ALOGE("Can't find method: %s\n", gMethods[i].name); - return -1; - } } - return AndroidRuntime::registerNativeMethods( + return RegisterMethodsOrDie( env, "android/util/EventLog", gRegisterMethods, NELEM(gRegisterMethods)); diff --git a/core/jni/android_util_FileObserver.cpp b/core/jni/android_util_FileObserver.cpp index 0327d8c..067d298 100644 --- a/core/jni/android_util_FileObserver.cpp +++ b/core/jni/android_util_FileObserver.cpp @@ -19,7 +19,7 @@ #include "jni.h" #include "utils/Log.h" #include "utils/misc.h" -#include "android_runtime/AndroidRuntime.h" +#include "core_jni_helpers.h" #include <stdio.h> #include <stdlib.h> @@ -29,7 +29,7 @@ #include <sys/ioctl.h> #include <errno.h> -#ifdef HAVE_INOTIFY +#if defined(__linux__) #include <sys/inotify.h> #endif @@ -39,29 +39,25 @@ static jmethodID method_onEvent; static jint android_os_fileobserver_init(JNIEnv* env, jobject object) { -#ifdef HAVE_INOTIFY - - return (jint)inotify_init(); - -#else // HAVE_INOTIFY - +#if defined(__linux__) + return (jint)inotify_init(); +#else return -1; - -#endif // HAVE_INOTIFY +#endif } static void android_os_fileobserver_observe(JNIEnv* env, jobject object, jint fd) { -#ifdef HAVE_INOTIFY - +#if defined(__linux__) + char event_buf[512]; struct inotify_event* event; - + while (1) { int event_pos = 0; int num_bytes = read(fd, event_buf, sizeof(event_buf)); - + if (num_bytes < (int)sizeof(*event)) { if (errno == EINTR) @@ -70,14 +66,14 @@ static void android_os_fileobserver_observe(JNIEnv* env, jobject object, jint fd ALOGE("***** ERROR! android_os_fileobserver_observe() got a short event!"); return; } - + while (num_bytes >= (int)sizeof(*event)) { int event_size; event = (struct inotify_event *)(event_buf + event_pos); jstring path = NULL; - + if (event->len > 0) { path = env->NewStringUTF(event->name); @@ -98,37 +94,37 @@ static void android_os_fileobserver_observe(JNIEnv* env, jobject object, jint fd event_pos += event_size; } } - -#endif // HAVE_INOTIFY + +#endif } static jint android_os_fileobserver_startWatching(JNIEnv* env, jobject object, jint fd, jstring pathString, jint mask) { int res = -1; - -#ifdef HAVE_INOTIFY - + +#if defined(__linux__) + if (fd >= 0) { const char* path = env->GetStringUTFChars(pathString, NULL); - + res = inotify_add_watch(fd, path, mask); - + env->ReleaseStringUTFChars(pathString, path); } -#endif // HAVE_INOTIFY - +#endif + return res; } static void android_os_fileobserver_stopWatching(JNIEnv* env, jobject object, jint fd, jint wfd) { -#ifdef HAVE_INOTIFY +#if defined(__linux__) inotify_rm_watch((int)fd, (uint32_t)wfd); -#endif // HAVE_INOTIFY +#endif } static JNINativeMethod sMethods[] = { @@ -137,29 +133,17 @@ static JNINativeMethod sMethods[] = { { "observe", "(I)V", (void*)android_os_fileobserver_observe }, { "startWatching", "(ILjava/lang/String;I)I", (void*)android_os_fileobserver_startWatching }, { "stopWatching", "(II)V", (void*)android_os_fileobserver_stopWatching } - + }; int register_android_os_FileObserver(JNIEnv* env) { - jclass clazz; - - clazz = env->FindClass("android/os/FileObserver$ObserverThread"); - - if (clazz == NULL) - { - ALOGE("Can't find android/os/FileObserver$ObserverThread"); - return -1; - } + jclass clazz = FindClassOrDie(env, "android/os/FileObserver$ObserverThread"); - method_onEvent = env->GetMethodID(clazz, "onEvent", "(IILjava/lang/String;)V"); - if (method_onEvent == NULL) - { - ALOGE("Can't find FileObserver.onEvent(int, int, String)"); - return -1; - } + method_onEvent = GetMethodIDOrDie(env, clazz, "onEvent", "(IILjava/lang/String;)V"); - return AndroidRuntime::registerNativeMethods(env, "android/os/FileObserver$ObserverThread", sMethods, NELEM(sMethods)); + return RegisterMethodsOrDie(env, "android/os/FileObserver$ObserverThread", sMethods, + NELEM(sMethods)); } } /* namespace android */ diff --git a/core/jni/android_util_FloatMath.cpp b/core/jni/android_util_FloatMath.cpp deleted file mode 100644 index 73b7a6f..0000000 --- a/core/jni/android_util_FloatMath.cpp +++ /dev/null @@ -1,61 +0,0 @@ -#include "jni.h" -#include <android_runtime/AndroidRuntime.h> -#include <math.h> -#include <float.h> -#include "SkTypes.h" - -class MathUtilsGlue { -public: - static float FloorF(JNIEnv* env, jobject clazz, float x) { - return floorf(x); - } - - static float CeilF(JNIEnv* env, jobject clazz, float x) { - return ceilf(x); - } - - static float SinF(JNIEnv* env, jobject clazz, float x) { - return sinf(x); - } - - static float CosF(JNIEnv* env, jobject clazz, float x) { - return cosf(x); - } - - static float SqrtF(JNIEnv* env, jobject clazz, float x) { - return sqrtf(x); - } - - static float ExpF(JNIEnv* env, jobject clazz, float x) { - return expf(x); - } - - static float PowF(JNIEnv* env, jobject clazz, float x, float y) { - return powf(x, y); - } - - static float HypotF(JNIEnv* env, jobject clazz, float x, float y) { - return hypotf(x, y); - } -}; - -static JNINativeMethod gMathUtilsMethods[] = { - {"floor", "(F)F", (void*) MathUtilsGlue::FloorF}, - {"ceil", "(F)F", (void*) MathUtilsGlue::CeilF}, - {"sin", "(F)F", (void*) MathUtilsGlue::SinF}, - {"cos", "(F)F", (void*) MathUtilsGlue::CosF}, - {"sqrt", "(F)F", (void*) MathUtilsGlue::SqrtF}, - {"exp", "(F)F", (void*) MathUtilsGlue::ExpF}, - {"pow", "(FF)F", (void*) MathUtilsGlue::PowF}, - {"hypot", "(FF)F", (void*) MathUtilsGlue::HypotF}, -}; - -int register_android_util_FloatMath(JNIEnv* env) -{ - int result = android::AndroidRuntime::registerNativeMethods(env, - "android/util/FloatMath", - gMathUtilsMethods, - SK_ARRAY_COUNT(gMathUtilsMethods)); - return result; -} - diff --git a/core/jni/android_util_Log.cpp b/core/jni/android_util_Log.cpp index 93dcbef..9a80f1d 100644 --- a/core/jni/android_util_Log.cpp +++ b/core/jni/android_util_Log.cpp @@ -26,11 +26,9 @@ #include "jni.h" #include "JNIHelp.h" #include "utils/misc.h" -#include "android_runtime/AndroidRuntime.h" +#include "core_jni_helpers.h" #include "android_util_Log.h" -#define MIN(a,b) ((a<b)?a:b) - namespace android { struct levels_t { @@ -145,21 +143,16 @@ static JNINativeMethod gMethods[] = { int register_android_util_Log(JNIEnv* env) { - jclass clazz = env->FindClass("android/util/Log"); - - if (clazz == NULL) { - ALOGE("Can't find android/util/Log"); - return -1; - } + jclass clazz = FindClassOrDie(env, "android/util/Log"); - levels.verbose = env->GetStaticIntField(clazz, env->GetStaticFieldID(clazz, "VERBOSE", "I")); - levels.debug = env->GetStaticIntField(clazz, env->GetStaticFieldID(clazz, "DEBUG", "I")); - levels.info = env->GetStaticIntField(clazz, env->GetStaticFieldID(clazz, "INFO", "I")); - levels.warn = env->GetStaticIntField(clazz, env->GetStaticFieldID(clazz, "WARN", "I")); - levels.error = env->GetStaticIntField(clazz, env->GetStaticFieldID(clazz, "ERROR", "I")); - levels.assert = env->GetStaticIntField(clazz, env->GetStaticFieldID(clazz, "ASSERT", "I")); + levels.verbose = env->GetStaticIntField(clazz, GetStaticFieldIDOrDie(env, clazz, "VERBOSE", "I")); + levels.debug = env->GetStaticIntField(clazz, GetStaticFieldIDOrDie(env, clazz, "DEBUG", "I")); + levels.info = env->GetStaticIntField(clazz, GetStaticFieldIDOrDie(env, clazz, "INFO", "I")); + levels.warn = env->GetStaticIntField(clazz, GetStaticFieldIDOrDie(env, clazz, "WARN", "I")); + levels.error = env->GetStaticIntField(clazz, GetStaticFieldIDOrDie(env, clazz, "ERROR", "I")); + levels.assert = env->GetStaticIntField(clazz, GetStaticFieldIDOrDie(env, clazz, "ASSERT", "I")); - return AndroidRuntime::registerNativeMethods(env, "android/util/Log", gMethods, NELEM(gMethods)); + return RegisterMethodsOrDie(env, "android/util/Log", gMethods, NELEM(gMethods)); } }; // namespace android diff --git a/core/jni/android_util_Process.cpp b/core/jni/android_util_Process.cpp index aaa680f..2830724 100644 --- a/core/jni/android_util_Process.cpp +++ b/core/jni/android_util_Process.cpp @@ -26,7 +26,7 @@ #include <utils/Vector.h> #include <processgroup/processgroup.h> -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" #include "android_util_Binder.h" #include "JNIHelp.h" @@ -43,13 +43,13 @@ #include <sys/types.h> #include <unistd.h> -#define POLICY_DEBUG 0 #define GUARD_THREAD_PRIORITY 0 -#define DEBUG_PROC(x) //x - using namespace android; +static const bool kDebugPolicy = false; +static const bool kDebugProc = false; + #if GUARD_THREAD_PRIORITY Mutex gKeyCreateMutex; static pthread_key_t gBgKey = -1; @@ -109,7 +109,8 @@ jint android_os_Process_getUidForName(JNIEnv* env, jobject clazz, jstring name) const jchar* str16 = env->GetStringCritical(name, 0); String8 name8; if (str16) { - name8 = String8(str16, env->GetStringLength(name)); + name8 = String8(reinterpret_cast<const char16_t*>(str16), + env->GetStringLength(name)); env->ReleaseStringCritical(name, str16); } @@ -140,7 +141,8 @@ jint android_os_Process_getGidForName(JNIEnv* env, jobject clazz, jstring name) const jchar* str16 = env->GetStringCritical(name, 0); String8 name8; if (str16) { - name8 = String8(str16, env->GetStringLength(name)); + name8 = String8(reinterpret_cast<const char16_t*>(str16), + env->GetStringLength(name)); env->ReleaseStringCritical(name, str16); } @@ -175,7 +177,6 @@ void android_os_Process_setProcessGroup(JNIEnv* env, jobject clazz, int pid, jin { ALOGV("%s pid=%d grp=%" PRId32, __func__, pid, grp); DIR *d; - FILE *fp; char proc_path[255]; struct dirent *de; @@ -191,26 +192,27 @@ void android_os_Process_setProcessGroup(JNIEnv* env, jobject clazz, int pid, jin } SchedPolicy sp = (SchedPolicy) grp; -#if POLICY_DEBUG - char cmdline[32]; - int fd; + if (kDebugPolicy) { + char cmdline[32]; + int fd; - strcpy(cmdline, "unknown"); + strcpy(cmdline, "unknown"); - sprintf(proc_path, "/proc/%d/cmdline", pid); - fd = open(proc_path, O_RDONLY); - if (fd >= 0) { - int rc = read(fd, cmdline, sizeof(cmdline)-1); - cmdline[rc] = 0; - close(fd); - } + sprintf(proc_path, "/proc/%d/cmdline", pid); + fd = open(proc_path, O_RDONLY); + if (fd >= 0) { + int rc = read(fd, cmdline, sizeof(cmdline)-1); + cmdline[rc] = 0; + close(fd); + } - if (sp == SP_BACKGROUND) { - ALOGD("setProcessGroup: vvv pid %d (%s)", pid, cmdline); - } else { - ALOGD("setProcessGroup: ^^^ pid %d (%s)", pid, cmdline); + if (sp == SP_BACKGROUND) { + ALOGD("setProcessGroup: vvv pid %d (%s)", pid, cmdline); + } else { + ALOGD("setProcessGroup: ^^^ pid %d (%s)", pid, cmdline); + } } -#endif + sprintf(proc_path, "/proc/%d/task", pid); if (!(d = opendir(proc_path))) { // If the process exited on us, don't generate an exception @@ -271,7 +273,7 @@ static void android_os_Process_setCanSelfBackground(JNIEnv* env, jobject clazz, // Establishes the calling thread as illegal to put into the background. // Typically used only for the system process's main looper. #if GUARD_THREAD_PRIORITY - ALOGV("Process.setCanSelfBackground(%d) : tid=%d", bgOk, androidGetTid()); + ALOGV("Process.setCanSelfBackground(%d) : tid=%d", bgOk, gettid()); { Mutex::Autolock _l(gKeyCreateMutex); if (gBgKey == -1) { @@ -287,7 +289,8 @@ static void android_os_Process_setCanSelfBackground(JNIEnv* env, jobject clazz, void android_os_Process_setThreadScheduler(JNIEnv* env, jclass clazz, jint tid, jint policy, jint pri) { -#ifdef HAVE_SCHED_SETSCHEDULER +// linux has sched_setscheduler(), others don't. +#if defined(__linux__) struct sched_param param; param.sched_priority = pri; int rc = sched_setscheduler(tid, policy, ¶m); @@ -306,7 +309,7 @@ void android_os_Process_setThreadPriority(JNIEnv* env, jobject clazz, // if we're putting the current thread into the background, check the TLS // to make sure this thread isn't guarded. If it is, raise an exception. if (pri >= ANDROID_PRIORITY_BACKGROUND) { - if (pid == androidGetTid()) { + if (pid == gettid()) { void* bgOk = pthread_getspecific(gBgKey); if (bgOk == ((void*)0xbaad)) { ALOGE("Thread marked fg-only put self in background!"); @@ -333,7 +336,7 @@ void android_os_Process_setThreadPriority(JNIEnv* env, jobject clazz, void android_os_Process_setCallingThreadPriority(JNIEnv* env, jobject clazz, jint pri) { - android_os_Process_setThreadPriority(env, clazz, androidGetTid(), pri); + android_os_Process_setThreadPriority(env, clazz, gettid(), pri); } jint android_os_Process_getThreadPriority(JNIEnv* env, jobject clazz, @@ -384,7 +387,8 @@ void android_os_Process_setArgV0(JNIEnv* env, jobject clazz, jstring name) const jchar* str = env->GetStringCritical(name, 0); String8 name8; if (str) { - name8 = String8(str, env->GetStringLength(name)); + name8 = String8(reinterpret_cast<const char16_t*>(str), + env->GetStringLength(name)); env->ReleaseStringCritical(name, str); } @@ -718,7 +722,7 @@ jboolean android_os_Process_parseProcLineArray(JNIEnv* env, jobject clazz, jint mode = formatData[fi]; if ((mode&PROC_PARENS) != 0) { i++; - } else if ((mode&PROC_QUOTES != 0)) { + } else if ((mode&PROC_QUOTES) != 0) { if (buffer[i] == '"') { i++; } else { @@ -728,7 +732,9 @@ jboolean android_os_Process_parseProcLineArray(JNIEnv* env, jobject clazz, const char term = (char)(mode&PROC_TERM_MASK); const jsize start = i; if (i >= endIndex) { - DEBUG_PROC(ALOGW("Ran off end of data @%d", i)); + if (kDebugProc) { + ALOGW("Ran off end of data @%d", i); + } res = JNI_FALSE; break; } @@ -828,7 +834,9 @@ jboolean android_os_Process_readProcFile(JNIEnv* env, jobject clazz, int fd = open(file8, O_RDONLY); if (fd < 0) { - DEBUG_PROC(ALOGW("Unable to open process file: %s\n", file8)); + if (kDebugProc) { + ALOGW("Unable to open process file: %s\n", file8); + } env->ReleaseStringUTFChars(file, file8); return JNI_FALSE; } @@ -839,7 +847,9 @@ jboolean android_os_Process_readProcFile(JNIEnv* env, jobject clazz, close(fd); if (len < 0) { - DEBUG_PROC(ALOGW("Unable to open process file: %s fd=%d\n", file8, fd)); + if (kDebugProc) { + ALOGW("Unable to open process file: %s fd=%d\n", file8, fd); + } return JNI_FALSE; } buffer[len] = 0; @@ -1044,11 +1054,7 @@ static const JNINativeMethod methods[] = { {"removeAllProcessGroups", "()V", (void*)android_os_Process_removeAllProcessGroups}, }; -const char* const kProcessPathName = "android/os/Process"; - int register_android_os_Process(JNIEnv* env) { - return AndroidRuntime::registerNativeMethods( - env, kProcessPathName, - methods, NELEM(methods)); + return RegisterMethodsOrDie(env, "android/os/Process", methods, NELEM(methods)); } diff --git a/core/jni/android_util_StringBlock.cpp b/core/jni/android_util_StringBlock.cpp index f29250f..f83eaec 100644 --- a/core/jni/android_util_StringBlock.cpp +++ b/core/jni/android_util_StringBlock.cpp @@ -20,7 +20,7 @@ #include "jni.h" #include "JNIHelp.h" #include <utils/misc.h> -#include <android_runtime/AndroidRuntime.h> +#include <core_jni_helpers.h> #include <utils/Log.h> #include <androidfw/ResourceTypes.h> @@ -171,7 +171,7 @@ static JNINativeMethod gStringBlockMethods[] = { int register_android_content_StringBlock(JNIEnv* env) { - return AndroidRuntime::registerNativeMethods(env, + return RegisterMethodsOrDie(env, "android/content/res/StringBlock", gStringBlockMethods, NELEM(gStringBlockMethods)); } diff --git a/core/jni/android_util_XmlBlock.cpp b/core/jni/android_util_XmlBlock.cpp index 2cccb83..375710e 100644 --- a/core/jni/android_util_XmlBlock.cpp +++ b/core/jni/android_util_XmlBlock.cpp @@ -19,7 +19,7 @@ #include "jni.h" #include "JNIHelp.h" -#include <android_runtime/AndroidRuntime.h> +#include <core_jni_helpers.h> #include <androidfw/AssetManager.h> #include <androidfw/ResourceTypes.h> #include <utils/Log.h> @@ -267,19 +267,20 @@ static jint android_content_XmlBlock_nativeGetAttributeIndex(JNIEnv* env, jobjec const char16_t* ns16 = NULL; jsize nsLen = 0; if (ns) { - ns16 = env->GetStringChars(ns, NULL); + ns16 = reinterpret_cast<const char16_t*>(env->GetStringChars(ns, NULL)); nsLen = env->GetStringLength(ns); } - const char16_t* name16 = env->GetStringChars(name, NULL); + const char16_t* name16 = reinterpret_cast<const char16_t*>( + env->GetStringChars(name, NULL)); jsize nameLen = env->GetStringLength(name); jint idx = static_cast<jint>(st->indexOfAttribute(ns16, nsLen, name16, nameLen)); if (ns) { - env->ReleaseStringChars(ns, ns16); + env->ReleaseStringChars(ns, reinterpret_cast<const jchar*>(ns16)); } - env->ReleaseStringChars(name, name16); + env->ReleaseStringChars(name, reinterpret_cast<const jchar*>(name16)); return idx; } @@ -411,7 +412,7 @@ static JNINativeMethod gXmlBlockMethods[] = { int register_android_content_XmlBlock(JNIEnv* env) { - return AndroidRuntime::registerNativeMethods(env, + return RegisterMethodsOrDie(env, "android/content/res/XmlBlock", gXmlBlockMethods, NELEM(gXmlBlockMethods)); } diff --git a/core/jni/android_view_DisplayEventReceiver.cpp b/core/jni/android_view_DisplayEventReceiver.cpp index d4cc159..0d54953 100644 --- a/core/jni/android_view_DisplayEventReceiver.cpp +++ b/core/jni/android_view_DisplayEventReceiver.cpp @@ -18,9 +18,10 @@ //#define LOG_NDEBUG 0 - #include "JNIHelp.h" +#include <inttypes.h> + #include <android_runtime/AndroidRuntime.h> #include <utils/Log.h> #include <utils/Looper.h> @@ -28,6 +29,8 @@ #include <gui/DisplayEventReceiver.h> #include "android_os_MessageQueue.h" +#include "core_jni_helpers.h" + namespace android { // Number of events to read at a time from the DisplayEventReceiver pipe. @@ -142,7 +145,7 @@ int NativeDisplayEventReceiver::handleEvent(int receiveFd, int events, void* dat int32_t vsyncDisplayId; uint32_t vsyncCount; if (processPendingEvents(&vsyncTimestamp, &vsyncDisplayId, &vsyncCount)) { - ALOGV("receiver %p ~ Vsync pulse: timestamp=%lld, id=%d, count=%d", + ALOGV("receiver %p ~ Vsync pulse: timestamp=%" PRId64 ", id=%d, count=%d", this, vsyncTimestamp, vsyncDisplayId, vsyncCount); mWaitingForVsync = false; dispatchVsync(vsyncTimestamp, vsyncDisplayId, vsyncCount); @@ -260,29 +263,19 @@ static JNINativeMethod gMethods[] = { (void*)nativeScheduleVsync } }; -#define FIND_CLASS(var, className) \ - var = env->FindClass(className); \ - LOG_FATAL_IF(! var, "Unable to find class " className); \ - var = jclass(env->NewGlobalRef(var)); +int register_android_view_DisplayEventReceiver(JNIEnv* env) { + int res = RegisterMethodsOrDie(env, "android/view/DisplayEventReceiver", gMethods, + NELEM(gMethods)); -#define GET_METHOD_ID(var, clazz, methodName, methodDescriptor) \ - var = env->GetMethodID(clazz, methodName, methodDescriptor); \ - LOG_FATAL_IF(! var, "Unable to find method " methodName); + jclass clazz = FindClassOrDie(env, "android/view/DisplayEventReceiver"); + gDisplayEventReceiverClassInfo.clazz = MakeGlobalRefOrDie(env, clazz); -int register_android_view_DisplayEventReceiver(JNIEnv* env) { - int res = jniRegisterNativeMethods(env, "android/view/DisplayEventReceiver", - gMethods, NELEM(gMethods)); - LOG_FATAL_IF(res < 0, "Unable to register native methods."); - - FIND_CLASS(gDisplayEventReceiverClassInfo.clazz, "android/view/DisplayEventReceiver"); - - GET_METHOD_ID(gDisplayEventReceiverClassInfo.dispatchVsync, - gDisplayEventReceiverClassInfo.clazz, - "dispatchVsync", "(JII)V"); - GET_METHOD_ID(gDisplayEventReceiverClassInfo.dispatchHotplug, - gDisplayEventReceiverClassInfo.clazz, - "dispatchHotplug", "(JIZ)V"); - return 0; + gDisplayEventReceiverClassInfo.dispatchVsync = GetMethodIDOrDie(env, + gDisplayEventReceiverClassInfo.clazz, "dispatchVsync", "(JII)V"); + gDisplayEventReceiverClassInfo.dispatchHotplug = GetMethodIDOrDie(env, + gDisplayEventReceiverClassInfo.clazz, "dispatchHotplug", "(JIZ)V"); + + return res; } } // namespace android diff --git a/core/jni/android_view_GLES20Canvas.cpp b/core/jni/android_view_GLES20Canvas.cpp index 9bbd4fc..da8a9ed 100644 --- a/core/jni/android_view_GLES20Canvas.cpp +++ b/core/jni/android_view_GLES20Canvas.cpp @@ -47,10 +47,16 @@ #include "MinikinUtils.h" +#include "core_jni_helpers.h" + namespace android { using namespace uirenderer; +static struct { + jmethodID set; +} gRectClassInfo; + /** * Note: DisplayListRenderer JNI layer is generated and compiled only on supported * devices. This means all the logic must be compiled only when the @@ -62,21 +68,7 @@ using namespace uirenderer; // Defines // ---------------------------------------------------------------------------- -// Debug -#define DEBUG_RENDERER 0 - -// Debug -#if DEBUG_RENDERER - #define RENDERER_LOGD(...) ALOGD(__VA_ARGS__) -#else - #define RENDERER_LOGD(...) -#endif - -// ---------------------------------------------------------------------------- - -static struct { - jmethodID set; -} gRectClassInfo; +static const bool kDebugRenderer = false; // ---------------------------------------------------------------------------- // Constructors @@ -85,7 +77,9 @@ static struct { static void android_view_GLES20Canvas_destroyRenderer(JNIEnv* env, jobject clazz, jlong rendererPtr) { DisplayListRenderer* renderer = reinterpret_cast<DisplayListRenderer*>(rendererPtr); - RENDERER_LOGD("Destroy DisplayListRenderer"); + if (kDebugRenderer) { + ALOGD("Destroy DisplayListRenderer"); + } delete renderer; } @@ -821,24 +815,30 @@ static void android_view_GLES20Canvas_drawLayer(JNIEnv* env, jobject clazz, #endif // USE_OPENGL_RENDERER +#ifdef USE_OPENGL_RENDERER +static const bool kUseOpenGLRenderer = true; +#else +static const bool kUseOpenGLRenderer = false; +#endif + // ---------------------------------------------------------------------------- // Common // ---------------------------------------------------------------------------- static jboolean android_view_GLES20Canvas_isAvailable(JNIEnv* env, jobject clazz) { -#ifdef USE_OPENGL_RENDERER - char prop[PROPERTY_VALUE_MAX]; - if (property_get("ro.kernel.qemu", prop, NULL) == 0) { - // not in the emulator - return JNI_TRUE; + if (kUseOpenGLRenderer) { + char prop[PROPERTY_VALUE_MAX]; + if (property_get("ro.kernel.qemu", prop, NULL) == 0) { + // not in the emulator + return JNI_TRUE; + } + // In the emulator this property will be set to 1 when hardware GLES is + // enabled, 0 otherwise. On old emulator versions it will be undefined. + property_get("ro.kernel.qemu.gles", prop, "0"); + return atoi(prop) == 1 ? JNI_TRUE : JNI_FALSE; + } else { + return JNI_FALSE; } - // In the emulator this property will be set to 1 when hardware GLES is - // enabled, 0 otherwise. On old emulator versions it will be undefined. - property_get("ro.kernel.qemu.gles", prop, "0"); - return atoi(prop) == 1 ? JNI_TRUE : JNI_FALSE; -#else - return JNI_FALSE; -#endif } // ---------------------------------------------------------------------------- @@ -847,10 +847,10 @@ static jboolean android_view_GLES20Canvas_isAvailable(JNIEnv* env, jobject clazz static void android_app_ActivityThread_dumpGraphics(JNIEnv* env, jobject clazz, jobject javaFileDescriptor) { -#ifdef USE_OPENGL_RENDERER - int fd = jniGetFDFromFileDescriptor(env, javaFileDescriptor); - android::uirenderer::renderthread::RenderProxy::outputLogBuffer(fd); -#endif // USE_OPENGL_RENDERER + if (kUseOpenGLRenderer) { + int fd = jniGetFDFromFileDescriptor(env, javaFileDescriptor); + android::uirenderer::renderthread::RenderProxy::outputLogBuffer(fd); + } } // ---------------------------------------------------------------------------- @@ -959,32 +959,17 @@ static JNINativeMethod gActivityThreadMethods[] = { (void*) android_app_ActivityThread_dumpGraphics } }; - -#ifdef USE_OPENGL_RENDERER - #define FIND_CLASS(var, className) \ - var = env->FindClass(className); \ - LOG_FATAL_IF(! var, "Unable to find class " className); - - #define GET_METHOD_ID(var, clazz, methodName, methodDescriptor) \ - var = env->GetMethodID(clazz, methodName, methodDescriptor); \ - LOG_FATAL_IF(! var, "Unable to find method " methodName); -#else - #define FIND_CLASS(var, className) - #define GET_METHOD_ID(var, clazz, methodName, methodDescriptor) -#endif - int register_android_view_GLES20Canvas(JNIEnv* env) { - jclass clazz; - FIND_CLASS(clazz, "android/graphics/Rect"); - GET_METHOD_ID(gRectClassInfo.set, clazz, "set", "(IIII)V"); + if (kUseOpenGLRenderer) { + jclass clazz = FindClassOrDie(env, "android/graphics/Rect"); + gRectClassInfo.set = GetMethodIDOrDie(env, clazz, "set", "(IIII)V"); + } - return AndroidRuntime::registerNativeMethods(env, kClassPathName, gMethods, NELEM(gMethods)); + return RegisterMethodsOrDie(env, kClassPathName, gMethods, NELEM(gMethods)); } -const char* const kActivityThreadPathName = "android/app/ActivityThread"; - int register_android_app_ActivityThread(JNIEnv* env) { - return AndroidRuntime::registerNativeMethods(env, kActivityThreadPathName, + return RegisterMethodsOrDie(env, "android/app/ActivityThread", gActivityThreadMethods, NELEM(gActivityThreadMethods)); } diff --git a/core/jni/android_view_GraphicBuffer.cpp b/core/jni/android_view_GraphicBuffer.cpp index 5ebed9c..a12629f 100644 --- a/core/jni/android_view_GraphicBuffer.cpp +++ b/core/jni/android_view_GraphicBuffer.cpp @@ -38,6 +38,8 @@ #include <private/gui/ComposerService.h> +#include "core_jni_helpers.h" + namespace android { // ---------------------------------------------------------------------------- @@ -45,16 +47,7 @@ namespace android { // ---------------------------------------------------------------------------- // Debug -#define DEBUG_GRAPHIC_BUFFER 0 - -// Debug -#if DEBUG_GRAPHIC_BUFFER - #define GB_LOGD(...) ALOGD(__VA_ARGS__) - #define GB_LOGW(...) ALOGW(__VA_ARGS__) -#else - #define GB_LOGD(...) - #define GB_LOGW(...) -#endif +static const bool kDebugGraphicBuffer = false; #define LOCK_CANVAS_USAGE GraphicBuffer::USAGE_SW_READ_OFTEN | GraphicBuffer::USAGE_SW_WRITE_OFTEN @@ -116,14 +109,18 @@ static jlong android_view_GraphiceBuffer_create(JNIEnv* env, jobject clazz, sp<ISurfaceComposer> composer(ComposerService::getComposerService()); sp<IGraphicBufferAlloc> alloc(composer->createGraphicBufferAlloc()); if (alloc == NULL) { - GB_LOGW("createGraphicBufferAlloc() failed in GraphicBuffer.create()"); + if (kDebugGraphicBuffer) { + ALOGW("createGraphicBufferAlloc() failed in GraphicBuffer.create()"); + } return NULL; } status_t error; sp<GraphicBuffer> buffer(alloc->createGraphicBuffer(width, height, format, usage, &error)); if (buffer == NULL) { - GB_LOGW("createGraphicBuffer() failed in GraphicBuffer.create()"); + if (kDebugGraphicBuffer) { + ALOGW("createGraphicBuffer() failed in GraphicBuffer.create()"); + } return NULL; } @@ -277,18 +274,6 @@ sp<GraphicBuffer> graphicBufferForJavaObject(JNIEnv* env, jobject obj) { // JNI Glue // ---------------------------------------------------------------------------- -#define FIND_CLASS(var, className) \ - var = env->FindClass(className); \ - LOG_FATAL_IF(! var, "Unable to find class " className); - -#define GET_FIELD_ID(var, clazz, fieldName, fieldDescriptor) \ - var = env->GetFieldID(clazz, fieldName, fieldDescriptor); \ - LOG_FATAL_IF(! var, "Unable to find field " fieldName); - -#define GET_METHOD_ID(var, clazz, methodName, methodDescriptor) \ - var = env->GetMethodID(clazz, methodName, methodDescriptor); \ - LOG_FATAL_IF(!var, "Unable to find method " methodName); - const char* const kClassPathName = "android/view/GraphicBuffer"; static JNINativeMethod gMethods[] = { @@ -307,22 +292,21 @@ static JNINativeMethod gMethods[] = { }; int register_android_view_GraphicBuffer(JNIEnv* env) { - jclass clazz; - FIND_CLASS(clazz, "android/view/GraphicBuffer"); - GET_FIELD_ID(gGraphicBufferClassInfo.mNativeObject, clazz, "mNativeObject", "J"); - - FIND_CLASS(clazz, "android/graphics/Rect"); - GET_METHOD_ID(gRectClassInfo.set, clazz, "set", "(IIII)V"); - GET_FIELD_ID(gRectClassInfo.left, clazz, "left", "I"); - GET_FIELD_ID(gRectClassInfo.top, clazz, "top", "I"); - GET_FIELD_ID(gRectClassInfo.right, clazz, "right", "I"); - GET_FIELD_ID(gRectClassInfo.bottom, clazz, "bottom", "I"); - - FIND_CLASS(clazz, "android/graphics/Canvas"); - GET_FIELD_ID(gCanvasClassInfo.mSurfaceFormat, clazz, "mSurfaceFormat", "I"); - GET_METHOD_ID(gCanvasClassInfo.setNativeBitmap, clazz, "setNativeBitmap", "(J)V"); - - return AndroidRuntime::registerNativeMethods(env, kClassPathName, gMethods, NELEM(gMethods)); + jclass clazz = FindClassOrDie(env, "android/view/GraphicBuffer"); + gGraphicBufferClassInfo.mNativeObject = GetFieldIDOrDie(env, clazz, "mNativeObject", "J"); + + clazz = FindClassOrDie(env, "android/graphics/Rect"); + gRectClassInfo.set = GetMethodIDOrDie(env, clazz, "set", "(IIII)V"); + gRectClassInfo.left = GetFieldIDOrDie(env, clazz, "left", "I"); + gRectClassInfo.top = GetFieldIDOrDie(env, clazz, "top", "I"); + gRectClassInfo.right = GetFieldIDOrDie(env, clazz, "right", "I"); + gRectClassInfo.bottom = GetFieldIDOrDie(env, clazz, "bottom", "I"); + + clazz = FindClassOrDie(env, "android/graphics/Canvas"); + gCanvasClassInfo.mSurfaceFormat = GetFieldIDOrDie(env, clazz, "mSurfaceFormat", "I"); + gCanvasClassInfo.setNativeBitmap = GetMethodIDOrDie(env, clazz, "setNativeBitmap", "(J)V"); + + return RegisterMethodsOrDie(env, kClassPathName, gMethods, NELEM(gMethods)); } }; diff --git a/core/jni/android_view_HardwareLayer.cpp b/core/jni/android_view_HardwareLayer.cpp index 1ffff03..cefb3da 100644 --- a/core/jni/android_view_HardwareLayer.cpp +++ b/core/jni/android_view_HardwareLayer.cpp @@ -20,7 +20,7 @@ #include "GraphicsJNI.h" #include <nativehelper/JNIHelp.h> -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" #include <android_runtime/android_graphics_SurfaceTexture.h> #include <gui/GLConsumer.h> @@ -110,7 +110,7 @@ static JNINativeMethod gMethods[] = { }; int register_android_view_HardwareLayer(JNIEnv* env) { - return AndroidRuntime::registerNativeMethods(env, kClassPathName, gMethods, NELEM(gMethods)); + return RegisterMethodsOrDie(env, kClassPathName, gMethods, NELEM(gMethods)); } }; diff --git a/core/jni/android_view_InputChannel.cpp b/core/jni/android_view_InputChannel.cpp index d667920..4b42ab5 100644 --- a/core/jni/android_view_InputChannel.cpp +++ b/core/jni/android_view_InputChannel.cpp @@ -26,6 +26,8 @@ #include "android_os_Parcel.h" #include "android_util_Binder.h" +#include "core_jni_helpers.h" + namespace android { // ---------------------------------------------------------------------------- @@ -275,33 +277,19 @@ static JNINativeMethod gInputChannelMethods[] = { (void*)android_view_InputChannel_nativeDup }, }; -#define FIND_CLASS(var, className) \ - var = env->FindClass(className); \ - LOG_FATAL_IF(! var, "Unable to find class " className); \ - var = jclass(env->NewGlobalRef(var)); - -#define GET_METHOD_ID(var, clazz, methodName, methodDescriptor) \ - var = env->GetMethodID(clazz, methodName, methodDescriptor); \ - LOG_FATAL_IF(! var, "Unable to find method " methodName); - -#define GET_FIELD_ID(var, clazz, fieldName, fieldDescriptor) \ - var = env->GetFieldID(clazz, fieldName, fieldDescriptor); \ - LOG_FATAL_IF(! var, "Unable to find field " fieldName); - int register_android_view_InputChannel(JNIEnv* env) { - int res = jniRegisterNativeMethods(env, "android/view/InputChannel", - gInputChannelMethods, NELEM(gInputChannelMethods)); - LOG_FATAL_IF(res < 0, "Unable to register native methods."); + int res = RegisterMethodsOrDie(env, "android/view/InputChannel", gInputChannelMethods, + NELEM(gInputChannelMethods)); + + jclass clazz = FindClassOrDie(env, "android/view/InputChannel"); + gInputChannelClassInfo.clazz = MakeGlobalRefOrDie(env, clazz); - FIND_CLASS(gInputChannelClassInfo.clazz, "android/view/InputChannel"); + gInputChannelClassInfo.mPtr = GetFieldIDOrDie(env, gInputChannelClassInfo.clazz, "mPtr", "J"); - GET_FIELD_ID(gInputChannelClassInfo.mPtr, gInputChannelClassInfo.clazz, - "mPtr", "J"); - - GET_METHOD_ID(gInputChannelClassInfo.ctor, gInputChannelClassInfo.clazz, - "<init>", "()V"); + gInputChannelClassInfo.ctor = GetMethodIDOrDie(env, gInputChannelClassInfo.clazz, "<init>", + "()V"); - return 0; + return res; } } // namespace android diff --git a/core/jni/android_view_InputDevice.cpp b/core/jni/android_view_InputDevice.cpp index bef0f84..2323f43 100644 --- a/core/jni/android_view_InputDevice.cpp +++ b/core/jni/android_view_InputDevice.cpp @@ -25,6 +25,8 @@ #include "android_view_InputDevice.h" #include "android_view_KeyCharacterMap.h" +#include "core_jni_helpers.h" + namespace android { static struct { @@ -77,24 +79,15 @@ jobject android_view_InputDevice_create(JNIEnv* env, const InputDeviceInfo& devi } -#define FIND_CLASS(var, className) \ - var = env->FindClass(className); \ - LOG_FATAL_IF(! var, "Unable to find class " className); - -#define GET_METHOD_ID(var, clazz, methodName, methodDescriptor) \ - var = env->GetMethodID(clazz, methodName, methodDescriptor); \ - LOG_FATAL_IF(! var, "Unable to find method " methodName); - int register_android_view_InputDevice(JNIEnv* env) { - FIND_CLASS(gInputDeviceClassInfo.clazz, "android/view/InputDevice"); - gInputDeviceClassInfo.clazz = jclass(env->NewGlobalRef(gInputDeviceClassInfo.clazz)); + gInputDeviceClassInfo.clazz = FindClassOrDie(env, "android/view/InputDevice"); + gInputDeviceClassInfo.clazz = MakeGlobalRefOrDie(env, gInputDeviceClassInfo.clazz); - GET_METHOD_ID(gInputDeviceClassInfo.ctor, gInputDeviceClassInfo.clazz, - "<init>", + gInputDeviceClassInfo.ctor = GetMethodIDOrDie(env, gInputDeviceClassInfo.clazz, "<init>", "(IIILjava/lang/String;IILjava/lang/String;ZIILandroid/view/KeyCharacterMap;ZZ)V"); - GET_METHOD_ID(gInputDeviceClassInfo.addMotionRange, gInputDeviceClassInfo.clazz, + gInputDeviceClassInfo.addMotionRange = GetMethodIDOrDie(env, gInputDeviceClassInfo.clazz, "addMotionRange", "(IIFFFFF)V"); return 0; diff --git a/core/jni/android_view_InputEventReceiver.cpp b/core/jni/android_view_InputEventReceiver.cpp index f36bf31..43b8471 100644 --- a/core/jni/android_view_InputEventReceiver.cpp +++ b/core/jni/android_view_InputEventReceiver.cpp @@ -18,10 +18,6 @@ //#define LOG_NDEBUG 0 -// Log debug messages about the dispatch cycle. -#define DEBUG_DISPATCH_CYCLE 0 - - #include "JNIHelp.h" #include <android_runtime/AndroidRuntime.h> @@ -37,8 +33,12 @@ #include <ScopedLocalRef.h> +#include "core_jni_helpers.h" + namespace android { +static const bool kDebugDispatchCycle = false; + static struct { jclass clazz; @@ -92,9 +92,9 @@ NativeInputEventReceiver::NativeInputEventReceiver(JNIEnv* env, mReceiverWeakGlobal(env->NewGlobalRef(receiverWeak)), mInputConsumer(inputChannel), mMessageQueue(messageQueue), mBatchedInputEventPending(false), mFdEvents(0) { -#if DEBUG_DISPATCH_CYCLE - ALOGD("channel '%s' ~ Initializing input event receiver.", getInputChannelName()); -#endif + if (kDebugDispatchCycle) { + ALOGD("channel '%s' ~ Initializing input event receiver.", getInputChannelName()); + } } NativeInputEventReceiver::~NativeInputEventReceiver() { @@ -108,25 +108,25 @@ status_t NativeInputEventReceiver::initialize() { } void NativeInputEventReceiver::dispose() { -#if DEBUG_DISPATCH_CYCLE - ALOGD("channel '%s' ~ Disposing input event receiver.", getInputChannelName()); -#endif + if (kDebugDispatchCycle) { + ALOGD("channel '%s' ~ Disposing input event receiver.", getInputChannelName()); + } setFdEvents(0); } status_t NativeInputEventReceiver::finishInputEvent(uint32_t seq, bool handled) { -#if DEBUG_DISPATCH_CYCLE - ALOGD("channel '%s' ~ Finished input event.", getInputChannelName()); -#endif + if (kDebugDispatchCycle) { + ALOGD("channel '%s' ~ Finished input event.", getInputChannelName()); + } status_t status = mInputConsumer.sendFinishedSignal(seq, handled); if (status) { if (status == WOULD_BLOCK) { -#if DEBUG_DISPATCH_CYCLE - ALOGD("channel '%s' ~ Could not send finished signal immediately. " - "Enqueued for later.", getInputChannelName()); -#endif + if (kDebugDispatchCycle) { + ALOGD("channel '%s' ~ Could not send finished signal immediately. " + "Enqueued for later.", getInputChannelName()); + } Finish finish; finish.seq = seq; finish.handled = handled; @@ -156,13 +156,13 @@ void NativeInputEventReceiver::setFdEvents(int events) { int NativeInputEventReceiver::handleEvent(int receiveFd, int events, void* data) { if (events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP)) { -#if DEBUG_DISPATCH_CYCLE // This error typically occurs when the publisher has closed the input channel // as part of removing a window or finishing an IME session, in which case // the consumer will soon be disposed as well. - ALOGD("channel '%s' ~ Publisher closed input channel or an error occurred. " - "events=0x%x", getInputChannelName(), events); -#endif + if (kDebugDispatchCycle) { + ALOGD("channel '%s' ~ Publisher closed input channel or an error occurred. " + "events=0x%x", getInputChannelName(), events); + } return 0; // remove the callback } @@ -181,10 +181,10 @@ int NativeInputEventReceiver::handleEvent(int receiveFd, int events, void* data) mFinishQueue.removeItemsAt(0, i); if (status == WOULD_BLOCK) { -#if DEBUG_DISPATCH_CYCLE - ALOGD("channel '%s' ~ Sent %u queued finish events; %u left.", - getInputChannelName(), i, mFinishQueue.size()); -#endif + if (kDebugDispatchCycle) { + ALOGD("channel '%s' ~ Sent %zu queued finish events; %zu left.", + getInputChannelName(), i, mFinishQueue.size()); + } return 1; // keep the callback, try again later } @@ -200,10 +200,10 @@ int NativeInputEventReceiver::handleEvent(int receiveFd, int events, void* data) return 0; // remove the callback } } -#if DEBUG_DISPATCH_CYCLE - ALOGD("channel '%s' ~ Sent %u queued finish events; none left.", - getInputChannelName(), mFinishQueue.size()); -#endif + if (kDebugDispatchCycle) { + ALOGD("channel '%s' ~ Sent %zu queued finish events; none left.", + getInputChannelName(), mFinishQueue.size()); + } mFinishQueue.clear(); setFdEvents(ALOOPER_EVENT_INPUT); return 1; @@ -216,10 +216,10 @@ int NativeInputEventReceiver::handleEvent(int receiveFd, int events, void* data) status_t NativeInputEventReceiver::consumeEvents(JNIEnv* env, bool consumeBatches, nsecs_t frameTime, bool* outConsumedBatch) { -#if DEBUG_DISPATCH_CYCLE - ALOGD("channel '%s' ~ Consuming input events, consumeBatches=%s, frameTime=%lld.", - getInputChannelName(), consumeBatches ? "true" : "false", frameTime); -#endif + if (kDebugDispatchCycle) { + ALOGD("channel '%s' ~ Consuming input events, consumeBatches=%s, frameTime=%lld.", + getInputChannelName(), consumeBatches ? "true" : "false", (long long)frameTime); + } if (consumeBatches) { mBatchedInputEventPending = false; @@ -250,10 +250,10 @@ status_t NativeInputEventReceiver::consumeEvents(JNIEnv* env, } mBatchedInputEventPending = true; -#if DEBUG_DISPATCH_CYCLE - ALOGD("channel '%s' ~ Dispatching batched input event pending notification.", - getInputChannelName()); -#endif + if (kDebugDispatchCycle) { + ALOGD("channel '%s' ~ Dispatching batched input event pending notification.", + getInputChannelName()); + } env->CallVoidMethod(receiverObj.get(), gInputEventReceiverClassInfo.dispatchBatchedInputEventPending); if (env->ExceptionCheck()) { @@ -282,17 +282,17 @@ status_t NativeInputEventReceiver::consumeEvents(JNIEnv* env, jobject inputEventObj; switch (inputEvent->getType()) { case AINPUT_EVENT_TYPE_KEY: -#if DEBUG_DISPATCH_CYCLE - ALOGD("channel '%s' ~ Received key event.", getInputChannelName()); -#endif + if (kDebugDispatchCycle) { + ALOGD("channel '%s' ~ Received key event.", getInputChannelName()); + } inputEventObj = android_view_KeyEvent_fromNative(env, static_cast<KeyEvent*>(inputEvent)); break; case AINPUT_EVENT_TYPE_MOTION: { -#if DEBUG_DISPATCH_CYCLE - ALOGD("channel '%s' ~ Received motion event.", getInputChannelName()); -#endif + if (kDebugDispatchCycle) { + ALOGD("channel '%s' ~ Received motion event.", getInputChannelName()); + } MotionEvent* motionEvent = static_cast<MotionEvent*>(inputEvent); if ((motionEvent->getAction() & AMOTION_EVENT_ACTION_MOVE) && outConsumedBatch) { *outConsumedBatch = true; @@ -307,9 +307,9 @@ status_t NativeInputEventReceiver::consumeEvents(JNIEnv* env, } if (inputEventObj) { -#if DEBUG_DISPATCH_CYCLE - ALOGD("channel '%s' ~ Dispatching input event.", getInputChannelName()); -#endif + if (kDebugDispatchCycle) { + ALOGD("channel '%s' ~ Dispatching input event.", getInputChannelName()); + } env->CallVoidMethod(receiverObj.get(), gInputEventReceiverClassInfo.dispatchInputEvent, seq, inputEventObj); if (env->ExceptionCheck()) { @@ -408,29 +408,20 @@ static JNINativeMethod gMethods[] = { (void*)nativeConsumeBatchedInputEvents }, }; -#define FIND_CLASS(var, className) \ - var = env->FindClass(className); \ - LOG_FATAL_IF(! var, "Unable to find class " className); \ - var = jclass(env->NewGlobalRef(var)); - -#define GET_METHOD_ID(var, clazz, methodName, methodDescriptor) \ - var = env->GetMethodID(clazz, methodName, methodDescriptor); \ - LOG_FATAL_IF(! var, "Unable to find method " methodName); - int register_android_view_InputEventReceiver(JNIEnv* env) { - int res = jniRegisterNativeMethods(env, "android/view/InputEventReceiver", + int res = RegisterMethodsOrDie(env, "android/view/InputEventReceiver", gMethods, NELEM(gMethods)); - LOG_FATAL_IF(res < 0, "Unable to register native methods."); - FIND_CLASS(gInputEventReceiverClassInfo.clazz, "android/view/InputEventReceiver"); + jclass clazz = FindClassOrDie(env, "android/view/InputEventReceiver"); + gInputEventReceiverClassInfo.clazz = MakeGlobalRefOrDie(env, clazz); - GET_METHOD_ID(gInputEventReceiverClassInfo.dispatchInputEvent, + gInputEventReceiverClassInfo.dispatchInputEvent = GetMethodIDOrDie(env, gInputEventReceiverClassInfo.clazz, "dispatchInputEvent", "(ILandroid/view/InputEvent;)V"); - GET_METHOD_ID(gInputEventReceiverClassInfo.dispatchBatchedInputEventPending, - gInputEventReceiverClassInfo.clazz, - "dispatchBatchedInputEventPending", "()V"); - return 0; + gInputEventReceiverClassInfo.dispatchBatchedInputEventPending = GetMethodIDOrDie(env, + gInputEventReceiverClassInfo.clazz, "dispatchBatchedInputEventPending", "()V"); + + return res; } } // namespace android diff --git a/core/jni/android_view_InputEventSender.cpp b/core/jni/android_view_InputEventSender.cpp index f156b9a..265daeb 100644 --- a/core/jni/android_view_InputEventSender.cpp +++ b/core/jni/android_view_InputEventSender.cpp @@ -18,10 +18,6 @@ //#define LOG_NDEBUG 0 -// Log debug messages about the dispatch cycle. -#define DEBUG_DISPATCH_CYCLE 0 - - #include "JNIHelp.h" #include <android_runtime/AndroidRuntime.h> @@ -37,8 +33,13 @@ #include <ScopedLocalRef.h> +#include "core_jni_helpers.h" + namespace android { +// Log debug messages about the dispatch cycle. +static const bool kDebugDispatchCycle = false; + static struct { jclass clazz; @@ -82,9 +83,9 @@ NativeInputEventSender::NativeInputEventSender(JNIEnv* env, mSenderWeakGlobal(env->NewGlobalRef(senderWeak)), mInputPublisher(inputChannel), mMessageQueue(messageQueue), mNextPublishedSeq(1) { -#if DEBUG_DISPATCH_CYCLE - ALOGD("channel '%s' ~ Initializing input event sender.", getInputChannelName()); -#endif + if (kDebugDispatchCycle) { + ALOGD("channel '%s' ~ Initializing input event sender.", getInputChannelName()); + } } NativeInputEventSender::~NativeInputEventSender() { @@ -99,17 +100,17 @@ status_t NativeInputEventSender::initialize() { } void NativeInputEventSender::dispose() { -#if DEBUG_DISPATCH_CYCLE - ALOGD("channel '%s' ~ Disposing input event sender.", getInputChannelName()); -#endif + if (kDebugDispatchCycle) { + ALOGD("channel '%s' ~ Disposing input event sender.", getInputChannelName()); + } mMessageQueue->getLooper()->removeFd(mInputPublisher.getChannel()->getFd()); } status_t NativeInputEventSender::sendKeyEvent(uint32_t seq, const KeyEvent* event) { -#if DEBUG_DISPATCH_CYCLE - ALOGD("channel '%s' ~ Sending key event, seq=%u.", getInputChannelName(), seq); -#endif + if (kDebugDispatchCycle) { + ALOGD("channel '%s' ~ Sending key event, seq=%u.", getInputChannelName(), seq); + } uint32_t publishedSeq = mNextPublishedSeq++; status_t status = mInputPublisher.publishKeyEvent(publishedSeq, @@ -126,9 +127,9 @@ status_t NativeInputEventSender::sendKeyEvent(uint32_t seq, const KeyEvent* even } status_t NativeInputEventSender::sendMotionEvent(uint32_t seq, const MotionEvent* event) { -#if DEBUG_DISPATCH_CYCLE - ALOGD("channel '%s' ~ Sending motion event, seq=%u.", getInputChannelName(), seq); -#endif + if (kDebugDispatchCycle) { + ALOGD("channel '%s' ~ Sending motion event, seq=%u.", getInputChannelName(), seq); + } uint32_t publishedSeq; for (size_t i = 0; i <= event->getHistorySize(); i++) { @@ -153,13 +154,14 @@ status_t NativeInputEventSender::sendMotionEvent(uint32_t seq, const MotionEvent int NativeInputEventSender::handleEvent(int receiveFd, int events, void* data) { if (events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP)) { -#if DEBUG_DISPATCH_CYCLE // This error typically occurs when the consumer has closed the input channel // as part of finishing an IME session, in which case the publisher will // soon be disposed as well. - ALOGD("channel '%s' ~ Consumer closed input channel or an error occurred. " - "events=0x%x", getInputChannelName(), events); -#endif + if (kDebugDispatchCycle) { + ALOGD("channel '%s' ~ Consumer closed input channel or an error occurred. " + "events=0x%x", getInputChannelName(), events); + } + return 0; // remove the callback } @@ -176,9 +178,9 @@ int NativeInputEventSender::handleEvent(int receiveFd, int events, void* data) { } status_t NativeInputEventSender::receiveFinishedSignals(JNIEnv* env) { -#if DEBUG_DISPATCH_CYCLE - ALOGD("channel '%s' ~ Receiving finished signals.", getInputChannelName()); -#endif + if (kDebugDispatchCycle) { + ALOGD("channel '%s' ~ Receiving finished signals.", getInputChannelName()); + } ScopedLocalRef<jobject> senderObj(env, NULL); bool skipCallbacks = false; @@ -200,12 +202,12 @@ status_t NativeInputEventSender::receiveFinishedSignals(JNIEnv* env) { uint32_t seq = mPublishedSeqMap.valueAt(index); mPublishedSeqMap.removeItemsAt(index); -#if DEBUG_DISPATCH_CYCLE - ALOGD("channel '%s' ~ Received finished signal, seq=%u, handled=%s, " - "pendingEvents=%u.", - getInputChannelName(), seq, handled ? "true" : "false", - mPublishedSeqMap.size()); -#endif + if (kDebugDispatchCycle) { + ALOGD("channel '%s' ~ Received finished signal, seq=%u, handled=%s, " + "pendingEvents=%zu.", + getInputChannelName(), seq, handled ? "true" : "false", + mPublishedSeqMap.size()); + } if (!skipCallbacks) { if (!senderObj.get()) { @@ -299,26 +301,16 @@ static JNINativeMethod gMethods[] = { (void*)nativeSendMotionEvent }, }; -#define FIND_CLASS(var, className) \ - var = env->FindClass(className); \ - LOG_FATAL_IF(! var, "Unable to find class " className); \ - var = jclass(env->NewGlobalRef(var)); - -#define GET_METHOD_ID(var, clazz, methodName, methodDescriptor) \ - var = env->GetMethodID(clazz, methodName, methodDescriptor); \ - LOG_FATAL_IF(! var, "Unable to find method " methodName); - int register_android_view_InputEventSender(JNIEnv* env) { - int res = jniRegisterNativeMethods(env, "android/view/InputEventSender", - gMethods, NELEM(gMethods)); - LOG_FATAL_IF(res < 0, "Unable to register native methods."); + int res = RegisterMethodsOrDie(env, "android/view/InputEventSender", gMethods, NELEM(gMethods)); + + jclass clazz = FindClassOrDie(env, "android/view/InputEventSender"); + gInputEventSenderClassInfo.clazz = MakeGlobalRefOrDie(env, clazz); - FIND_CLASS(gInputEventSenderClassInfo.clazz, "android/view/InputEventSender"); + gInputEventSenderClassInfo.dispatchInputEventFinished = GetMethodIDOrDie( + env, gInputEventSenderClassInfo.clazz, "dispatchInputEventFinished", "(IZ)V"); - GET_METHOD_ID(gInputEventSenderClassInfo.dispatchInputEventFinished, - gInputEventSenderClassInfo.clazz, - "dispatchInputEventFinished", "(IZ)V"); - return 0; + return res; } } // namespace android diff --git a/core/jni/android_view_InputQueue.cpp b/core/jni/android_view_InputQueue.cpp index 21b73b1..96ccdee 100644 --- a/core/jni/android_view_InputQueue.cpp +++ b/core/jni/android_view_InputQueue.cpp @@ -33,6 +33,8 @@ #include "android_view_KeyEvent.h" #include "android_view_MotionEvent.h" +#include "core_jni_helpers.h" + namespace android { static struct { @@ -256,27 +258,13 @@ static const JNINativeMethod g_methods[] = { static const char* const kInputQueuePathName = "android/view/InputQueue"; -#define FIND_CLASS(var, className) \ - do { \ - var = env->FindClass(className); \ - LOG_FATAL_IF(! var, "Unable to find class %s", className); \ - } while(0) - -#define GET_METHOD_ID(var, clazz, methodName, fieldDescriptor) \ - do { \ - var = env->GetMethodID(clazz, methodName, fieldDescriptor); \ - LOG_FATAL_IF(! var, "Unable to find method" methodName); \ - } while(0) - int register_android_view_InputQueue(JNIEnv* env) { - jclass clazz; - FIND_CLASS(clazz, kInputQueuePathName); - GET_METHOD_ID(gInputQueueClassInfo.finishInputEvent, clazz, "finishInputEvent", "(JZ)V"); + jclass clazz = FindClassOrDie(env, kInputQueuePathName); + gInputQueueClassInfo.finishInputEvent = GetMethodIDOrDie(env, clazz, "finishInputEvent", + "(JZ)V"); - return AndroidRuntime::registerNativeMethods( - env, kInputQueuePathName, - g_methods, NELEM(g_methods)); + return RegisterMethodsOrDie(env, kInputQueuePathName, g_methods, NELEM(g_methods)); } } // namespace android diff --git a/core/jni/android_view_KeyCharacterMap.cpp b/core/jni/android_view_KeyCharacterMap.cpp index 62d5129..7653f58 100644 --- a/core/jni/android_view_KeyCharacterMap.cpp +++ b/core/jni/android_view_KeyCharacterMap.cpp @@ -26,6 +26,8 @@ #include "android_os_Parcel.h" #include "android_view_KeyEvent.h" +#include "core_jni_helpers.h" + namespace android { static struct { @@ -148,7 +150,9 @@ static jchar nativeGetMatch(JNIEnv *env, jobject clazz, jlong ptr, jint keyCode, return 0; } - char16_t result = map->getMap()->getMatch(keyCode, chars, size_t(numChars), metaState); + char16_t result = map->getMap()->getMatch( + keyCode, reinterpret_cast<char16_t*>(chars), size_t(numChars), + metaState); env->ReleasePrimitiveArrayCritical(charsArray, chars, JNI_ABORT); return result; @@ -176,7 +180,9 @@ static jobjectArray nativeGetEvents(JNIEnv *env, jobject clazz, jlong ptr, Vector<KeyEvent> events; jobjectArray result = NULL; - if (map->getMap()->getEvents(map->getDeviceId(), chars, size_t(numChars), events)) { + if (map->getMap()->getEvents(map->getDeviceId(), + reinterpret_cast<char16_t*>(chars), + size_t(numChars), events)) { result = env->NewObjectArray(jsize(events.size()), gKeyEventClassInfo.clazz, NULL); if (result) { for (size_t i = 0; i < events.size(); i++) { @@ -221,40 +227,23 @@ static JNINativeMethod g_methods[] = { (void*)nativeGetEvents }, }; -#define FIND_CLASS(var, className) \ - var = env->FindClass(className); \ - LOG_FATAL_IF(! var, "Unable to find class " className); - -#define GET_METHOD_ID(var, clazz, methodName, methodDescriptor) \ - var = env->GetMethodID(clazz, methodName, methodDescriptor); \ - LOG_FATAL_IF(! var, "Unable to find method " methodName); - -#define GET_FIELD_ID(var, clazz, fieldName, fieldDescriptor) \ - var = env->GetFieldID(clazz, fieldName, fieldDescriptor); \ - LOG_FATAL_IF(! var, "Unable to find field " fieldName); - int register_android_view_KeyCharacterMap(JNIEnv* env) { - FIND_CLASS(gKeyCharacterMapClassInfo.clazz, "android/view/KeyCharacterMap"); - gKeyCharacterMapClassInfo.clazz = jclass(env->NewGlobalRef(gKeyCharacterMapClassInfo.clazz)); + gKeyCharacterMapClassInfo.clazz = FindClassOrDie(env, "android/view/KeyCharacterMap"); + gKeyCharacterMapClassInfo.clazz = MakeGlobalRefOrDie(env, gKeyCharacterMapClassInfo.clazz); - GET_METHOD_ID(gKeyCharacterMapClassInfo.ctor, gKeyCharacterMapClassInfo.clazz, + gKeyCharacterMapClassInfo.ctor = GetMethodIDOrDie(env, gKeyCharacterMapClassInfo.clazz, "<init>", "(J)V"); - FIND_CLASS(gKeyEventClassInfo.clazz, "android/view/KeyEvent"); - gKeyEventClassInfo.clazz = jclass(env->NewGlobalRef(gKeyEventClassInfo.clazz)); - - jclass clazz; - FIND_CLASS(clazz, "android/view/KeyCharacterMap$FallbackAction"); + gKeyEventClassInfo.clazz = FindClassOrDie(env, "android/view/KeyEvent"); + gKeyEventClassInfo.clazz = MakeGlobalRefOrDie(env, gKeyEventClassInfo.clazz); - GET_FIELD_ID(gFallbackActionClassInfo.keyCode, clazz, - "keyCode", "I"); + jclass clazz = FindClassOrDie(env, "android/view/KeyCharacterMap$FallbackAction"); - GET_FIELD_ID(gFallbackActionClassInfo.metaState, clazz, - "metaState", "I"); + gFallbackActionClassInfo.keyCode = GetFieldIDOrDie(env, clazz, "keyCode", "I"); + gFallbackActionClassInfo.metaState = GetFieldIDOrDie(env, clazz, "metaState", "I"); - return AndroidRuntime::registerNativeMethods(env, - "android/view/KeyCharacterMap", g_methods, NELEM(g_methods)); + return RegisterMethodsOrDie(env, "android/view/KeyCharacterMap", g_methods, NELEM(g_methods)); } }; // namespace android diff --git a/core/jni/android_view_KeyEvent.cpp b/core/jni/android_view_KeyEvent.cpp index 7ae21a7..216e6f6 100644 --- a/core/jni/android_view_KeyEvent.cpp +++ b/core/jni/android_view_KeyEvent.cpp @@ -25,6 +25,8 @@ #include <ScopedUtfChars.h> #include "android_view_KeyEvent.h" +#include "core_jni_helpers.h" + namespace android { // ---------------------------------------------------------------------------- @@ -124,56 +126,32 @@ static const JNINativeMethod g_methods[] = { (void*)android_view_KeyEvent_nativeKeyCodeFromString}, }; -#define FIND_CLASS(var, className) \ - var = env->FindClass(className); \ - LOG_FATAL_IF(! var, "Unable to find class " className); \ - var = jclass(env->NewGlobalRef(var)); - -#define GET_STATIC_METHOD_ID(var, clazz, methodName, fieldDescriptor) \ - var = env->GetStaticMethodID(clazz, methodName, fieldDescriptor); \ - LOG_FATAL_IF(! var, "Unable to find static method" methodName); - -#define GET_METHOD_ID(var, clazz, methodName, fieldDescriptor) \ - var = env->GetMethodID(clazz, methodName, fieldDescriptor); \ - LOG_FATAL_IF(! var, "Unable to find method" methodName); - -#define GET_FIELD_ID(var, clazz, fieldName, fieldDescriptor) \ - var = env->GetFieldID(clazz, fieldName, fieldDescriptor); \ - LOG_FATAL_IF(! var, "Unable to find field " fieldName); - int register_android_view_KeyEvent(JNIEnv* env) { - FIND_CLASS(gKeyEventClassInfo.clazz, "android/view/KeyEvent"); + jclass clazz = FindClassOrDie(env, "android/view/KeyEvent"); + gKeyEventClassInfo.clazz = MakeGlobalRefOrDie(env, clazz); - GET_STATIC_METHOD_ID(gKeyEventClassInfo.obtain, gKeyEventClassInfo.clazz, + gKeyEventClassInfo.obtain = GetStaticMethodIDOrDie(env, gKeyEventClassInfo.clazz, "obtain", "(JJIIIIIIIILjava/lang/String;)Landroid/view/KeyEvent;"); - GET_METHOD_ID(gKeyEventClassInfo.recycle, gKeyEventClassInfo.clazz, + gKeyEventClassInfo.recycle = GetMethodIDOrDie(env, gKeyEventClassInfo.clazz, "recycle", "()V"); - GET_FIELD_ID(gKeyEventClassInfo.mDeviceId, gKeyEventClassInfo.clazz, - "mDeviceId", "I"); - GET_FIELD_ID(gKeyEventClassInfo.mSource, gKeyEventClassInfo.clazz, - "mSource", "I"); - GET_FIELD_ID(gKeyEventClassInfo.mMetaState, gKeyEventClassInfo.clazz, - "mMetaState", "I"); - GET_FIELD_ID(gKeyEventClassInfo.mAction, gKeyEventClassInfo.clazz, - "mAction", "I"); - GET_FIELD_ID(gKeyEventClassInfo.mKeyCode, gKeyEventClassInfo.clazz, - "mKeyCode", "I"); - GET_FIELD_ID(gKeyEventClassInfo.mScanCode, gKeyEventClassInfo.clazz, - "mScanCode", "I"); - GET_FIELD_ID(gKeyEventClassInfo.mRepeatCount, gKeyEventClassInfo.clazz, - "mRepeatCount", "I"); - GET_FIELD_ID(gKeyEventClassInfo.mFlags, gKeyEventClassInfo.clazz, - "mFlags", "I"); - GET_FIELD_ID(gKeyEventClassInfo.mDownTime, gKeyEventClassInfo.clazz, - "mDownTime", "J"); - GET_FIELD_ID(gKeyEventClassInfo.mEventTime, gKeyEventClassInfo.clazz, - "mEventTime", "J"); - GET_FIELD_ID(gKeyEventClassInfo.mCharacters, gKeyEventClassInfo.clazz, - "mCharacters", "Ljava/lang/String;"); - - return AndroidRuntime::registerNativeMethods( - env, "android/view/KeyEvent", g_methods, NELEM(g_methods)); + gKeyEventClassInfo.mDeviceId = GetFieldIDOrDie(env, gKeyEventClassInfo.clazz, "mDeviceId", "I"); + gKeyEventClassInfo.mSource = GetFieldIDOrDie(env, gKeyEventClassInfo.clazz, "mSource", "I"); + gKeyEventClassInfo.mMetaState = GetFieldIDOrDie(env, gKeyEventClassInfo.clazz, "mMetaState", + "I"); + gKeyEventClassInfo.mAction = GetFieldIDOrDie(env, gKeyEventClassInfo.clazz, "mAction", "I"); + gKeyEventClassInfo.mKeyCode = GetFieldIDOrDie(env, gKeyEventClassInfo.clazz, "mKeyCode", "I"); + gKeyEventClassInfo.mScanCode = GetFieldIDOrDie(env, gKeyEventClassInfo.clazz, "mScanCode", "I"); + gKeyEventClassInfo.mRepeatCount = GetFieldIDOrDie(env, gKeyEventClassInfo.clazz, "mRepeatCount", + "I"); + gKeyEventClassInfo.mFlags = GetFieldIDOrDie(env, gKeyEventClassInfo.clazz, "mFlags", "I"); + gKeyEventClassInfo.mDownTime = GetFieldIDOrDie(env, gKeyEventClassInfo.clazz, "mDownTime", "J"); + gKeyEventClassInfo.mEventTime = GetFieldIDOrDie(env, gKeyEventClassInfo.clazz, "mEventTime", + "J"); + gKeyEventClassInfo.mCharacters = GetFieldIDOrDie(env, gKeyEventClassInfo.clazz, "mCharacters", + "Ljava/lang/String;"); + + return RegisterMethodsOrDie(env, "android/view/KeyEvent", g_methods, NELEM(g_methods)); } } // namespace android diff --git a/core/jni/android_view_MotionEvent.cpp b/core/jni/android_view_MotionEvent.cpp index a590dbf..e622768 100644 --- a/core/jni/android_view_MotionEvent.cpp +++ b/core/jni/android_view_MotionEvent.cpp @@ -29,6 +29,8 @@ #include "android_util_Binder.h" #include "android/graphics/Matrix.h" +#include "core_jni_helpers.h" + namespace android { // ---------------------------------------------------------------------------- @@ -296,7 +298,6 @@ static void pointerCoordsFromNative(JNIEnv* env, const PointerCoords* rawPointer jfloat* outValues = static_cast<jfloat*>(env->GetPrimitiveArrayCritical( outValuesArray, NULL)); - const float* values = rawPointerCoords->values; uint32_t index = 0; do { uint32_t axis = bits.clearFirstMarkedBit(); @@ -853,71 +854,41 @@ static JNINativeMethod gMotionEventMethods[] = { (void*)android_view_MotionEvent_nativeAxisFromString }, }; -#define FIND_CLASS(var, className) \ - var = env->FindClass(className); \ - LOG_FATAL_IF(! var, "Unable to find class " className); - -#define GET_STATIC_METHOD_ID(var, clazz, methodName, fieldDescriptor) \ - var = env->GetStaticMethodID(clazz, methodName, fieldDescriptor); \ - LOG_FATAL_IF(! var, "Unable to find static method" methodName); - -#define GET_METHOD_ID(var, clazz, methodName, fieldDescriptor) \ - var = env->GetMethodID(clazz, methodName, fieldDescriptor); \ - LOG_FATAL_IF(! var, "Unable to find method" methodName); - -#define GET_FIELD_ID(var, clazz, fieldName, fieldDescriptor) \ - var = env->GetFieldID(clazz, fieldName, fieldDescriptor); \ - LOG_FATAL_IF(! var, "Unable to find field " fieldName); - int register_android_view_MotionEvent(JNIEnv* env) { - int res = jniRegisterNativeMethods(env, "android/view/MotionEvent", - gMotionEventMethods, NELEM(gMotionEventMethods)); - LOG_FATAL_IF(res < 0, "Unable to register native methods."); + int res = RegisterMethodsOrDie(env, "android/view/MotionEvent", gMotionEventMethods, + NELEM(gMotionEventMethods)); - FIND_CLASS(gMotionEventClassInfo.clazz, "android/view/MotionEvent"); - gMotionEventClassInfo.clazz = jclass(env->NewGlobalRef(gMotionEventClassInfo.clazz)); + gMotionEventClassInfo.clazz = FindClassOrDie(env, "android/view/MotionEvent"); + gMotionEventClassInfo.clazz = MakeGlobalRefOrDie(env, gMotionEventClassInfo.clazz); - GET_STATIC_METHOD_ID(gMotionEventClassInfo.obtain, gMotionEventClassInfo.clazz, + gMotionEventClassInfo.obtain = GetStaticMethodIDOrDie(env, gMotionEventClassInfo.clazz, "obtain", "()Landroid/view/MotionEvent;"); - GET_METHOD_ID(gMotionEventClassInfo.recycle, gMotionEventClassInfo.clazz, + gMotionEventClassInfo.recycle = GetMethodIDOrDie(env, gMotionEventClassInfo.clazz, "recycle", "()V"); - GET_FIELD_ID(gMotionEventClassInfo.mNativePtr, gMotionEventClassInfo.clazz, + gMotionEventClassInfo.mNativePtr = GetFieldIDOrDie(env, gMotionEventClassInfo.clazz, "mNativePtr", "J"); - jclass clazz; - FIND_CLASS(clazz, "android/view/MotionEvent$PointerCoords"); - - GET_FIELD_ID(gPointerCoordsClassInfo.mPackedAxisBits, clazz, - "mPackedAxisBits", "J"); - GET_FIELD_ID(gPointerCoordsClassInfo.mPackedAxisValues, clazz, - "mPackedAxisValues", "[F"); - GET_FIELD_ID(gPointerCoordsClassInfo.x, clazz, - "x", "F"); - GET_FIELD_ID(gPointerCoordsClassInfo.y, clazz, - "y", "F"); - GET_FIELD_ID(gPointerCoordsClassInfo.pressure, clazz, - "pressure", "F"); - GET_FIELD_ID(gPointerCoordsClassInfo.size, clazz, - "size", "F"); - GET_FIELD_ID(gPointerCoordsClassInfo.touchMajor, clazz, - "touchMajor", "F"); - GET_FIELD_ID(gPointerCoordsClassInfo.touchMinor, clazz, - "touchMinor", "F"); - GET_FIELD_ID(gPointerCoordsClassInfo.toolMajor, clazz, - "toolMajor", "F"); - GET_FIELD_ID(gPointerCoordsClassInfo.toolMinor, clazz, - "toolMinor", "F"); - GET_FIELD_ID(gPointerCoordsClassInfo.orientation, clazz, - "orientation", "F"); - - FIND_CLASS(clazz, "android/view/MotionEvent$PointerProperties"); - - GET_FIELD_ID(gPointerPropertiesClassInfo.id, clazz, - "id", "I"); - GET_FIELD_ID(gPointerPropertiesClassInfo.toolType, clazz, - "toolType", "I"); + jclass clazz = FindClassOrDie(env, "android/view/MotionEvent$PointerCoords"); - return 0; + gPointerCoordsClassInfo.mPackedAxisBits = GetFieldIDOrDie(env, clazz, "mPackedAxisBits", "J"); + gPointerCoordsClassInfo.mPackedAxisValues = GetFieldIDOrDie(env, clazz, "mPackedAxisValues", + "[F"); + gPointerCoordsClassInfo.x = GetFieldIDOrDie(env, clazz, "x", "F"); + gPointerCoordsClassInfo.y = GetFieldIDOrDie(env, clazz, "y", "F"); + gPointerCoordsClassInfo.pressure = GetFieldIDOrDie(env, clazz, "pressure", "F"); + gPointerCoordsClassInfo.size = GetFieldIDOrDie(env, clazz, "size", "F"); + gPointerCoordsClassInfo.touchMajor = GetFieldIDOrDie(env, clazz, "touchMajor", "F"); + gPointerCoordsClassInfo.touchMinor = GetFieldIDOrDie(env, clazz, "touchMinor", "F"); + gPointerCoordsClassInfo.toolMajor = GetFieldIDOrDie(env, clazz, "toolMajor", "F"); + gPointerCoordsClassInfo.toolMinor = GetFieldIDOrDie(env, clazz, "toolMinor", "F"); + gPointerCoordsClassInfo.orientation = GetFieldIDOrDie(env, clazz, "orientation", "F"); + + clazz = FindClassOrDie(env, "android/view/MotionEvent$PointerProperties"); + + gPointerPropertiesClassInfo.id = GetFieldIDOrDie(env, clazz, "id", "I"); + gPointerPropertiesClassInfo.toolType = GetFieldIDOrDie(env, clazz, "toolType", "I"); + + return res; } } // namespace android diff --git a/core/jni/android_view_PointerIcon.cpp b/core/jni/android_view_PointerIcon.cpp index 5e29213..bbd031e 100644 --- a/core/jni/android_view_PointerIcon.cpp +++ b/core/jni/android_view_PointerIcon.cpp @@ -25,6 +25,8 @@ #include <utils/Log.h> #include <android/graphics/GraphicsJNI.h> +#include "core_jni_helpers.h" + namespace android { static struct { @@ -106,42 +108,26 @@ status_t android_view_PointerIcon_loadSystemIcon(JNIEnv* env, jobject contextObj // --- JNI Registration --- -#define FIND_CLASS(var, className) \ - var = env->FindClass(className); \ - LOG_FATAL_IF(! var, "Unable to find class " className); \ - var = jclass(env->NewGlobalRef(var)); - -#define GET_STATIC_METHOD_ID(var, clazz, methodName, methodDescriptor) \ - var = env->GetStaticMethodID(clazz, methodName, methodDescriptor); \ - LOG_FATAL_IF(! var, "Unable to find method " methodName); - -#define GET_METHOD_ID(var, clazz, methodName, methodDescriptor) \ - var = env->GetMethodID(clazz, methodName, methodDescriptor); \ - LOG_FATAL_IF(! var, "Unable to find method " methodName); - -#define GET_FIELD_ID(var, clazz, fieldName, fieldDescriptor) \ - var = env->GetFieldID(clazz, fieldName, fieldDescriptor); \ - LOG_FATAL_IF(! var, "Unable to find field " fieldName); - int register_android_view_PointerIcon(JNIEnv* env) { - FIND_CLASS(gPointerIconClassInfo.clazz, "android/view/PointerIcon"); + jclass clazz = FindClassOrDie(env, "android/view/PointerIcon"); + gPointerIconClassInfo.clazz = MakeGlobalRefOrDie(env, clazz); - GET_FIELD_ID(gPointerIconClassInfo.mBitmap, gPointerIconClassInfo.clazz, + gPointerIconClassInfo.mBitmap = GetFieldIDOrDie(env, gPointerIconClassInfo.clazz, "mBitmap", "Landroid/graphics/Bitmap;"); - GET_FIELD_ID(gPointerIconClassInfo.mStyle, gPointerIconClassInfo.clazz, + gPointerIconClassInfo.mStyle = GetFieldIDOrDie(env, gPointerIconClassInfo.clazz, "mStyle", "I"); - GET_FIELD_ID(gPointerIconClassInfo.mHotSpotX, gPointerIconClassInfo.clazz, + gPointerIconClassInfo.mHotSpotX = GetFieldIDOrDie(env, gPointerIconClassInfo.clazz, "mHotSpotX", "F"); - GET_FIELD_ID(gPointerIconClassInfo.mHotSpotY, gPointerIconClassInfo.clazz, + gPointerIconClassInfo.mHotSpotY = GetFieldIDOrDie(env, gPointerIconClassInfo.clazz, "mHotSpotY", "F"); - GET_STATIC_METHOD_ID(gPointerIconClassInfo.getSystemIcon, gPointerIconClassInfo.clazz, + gPointerIconClassInfo.getSystemIcon = GetStaticMethodIDOrDie(env, gPointerIconClassInfo.clazz, "getSystemIcon", "(Landroid/content/Context;I)Landroid/view/PointerIcon;"); - GET_METHOD_ID(gPointerIconClassInfo.load, gPointerIconClassInfo.clazz, + gPointerIconClassInfo.load = GetMethodIDOrDie(env, gPointerIconClassInfo.clazz, "load", "(Landroid/content/Context;)Landroid/view/PointerIcon;"); return 0; diff --git a/core/jni/android_view_RenderNode.cpp b/core/jni/android_view_RenderNode.cpp index 621df72..a1d3bc6 100644 --- a/core/jni/android_view_RenderNode.cpp +++ b/core/jni/android_view_RenderNode.cpp @@ -28,6 +28,8 @@ #include <RenderNode.h> #include <Paint.h> +#include "core_jni_helpers.h" + namespace android { using namespace uirenderer; @@ -551,21 +553,8 @@ static JNINativeMethod gMethods[] = { #endif }; -#ifdef USE_OPENGL_RENDERER - #define FIND_CLASS(var, className) \ - var = env->FindClass(className); \ - LOG_FATAL_IF(! var, "Unable to find class " className); - - #define GET_METHOD_ID(var, clazz, methodName, methodDescriptor) \ - var = env->GetMethodID(clazz, methodName, methodDescriptor); \ - LOG_FATAL_IF(! var, "Unable to find method " methodName); -#else - #define FIND_CLASS(var, className) - #define GET_METHOD_ID(var, clazz, methodName, methodDescriptor) -#endif - int register_android_view_RenderNode(JNIEnv* env) { - return AndroidRuntime::registerNativeMethods(env, kClassPathName, gMethods, NELEM(gMethods)); + return RegisterMethodsOrDie(env, kClassPathName, gMethods, NELEM(gMethods)); } }; diff --git a/core/jni/android_view_RenderNodeAnimator.cpp b/core/jni/android_view_RenderNodeAnimator.cpp index eb56639..0978ebb 100644 --- a/core/jni/android_view_RenderNodeAnimator.cpp +++ b/core/jni/android_view_RenderNodeAnimator.cpp @@ -25,6 +25,8 @@ #include <Interpolator.h> #include <RenderProperties.h> +#include "core_jni_helpers.h" + namespace android { using namespace uirenderer; @@ -161,11 +163,6 @@ static void setStartDelay(JNIEnv* env, jobject clazz, jlong animatorPtr, jlong s animator->setStartDelay(startDelay); } -static jlong getStartDelay(JNIEnv* env, jobject clazz, jlong animatorPtr) { - BaseRenderNodeAnimator* animator = reinterpret_cast<BaseRenderNodeAnimator*>(animatorPtr); - return static_cast<jlong>(animator->startDelay()); -} - static void setInterpolator(JNIEnv* env, jobject clazz, jlong animatorPtr, jlong interpolatorPtr) { BaseRenderNodeAnimator* animator = reinterpret_cast<BaseRenderNodeAnimator*>(animatorPtr); Interpolator* interpolator = reinterpret_cast<Interpolator*>(interpolatorPtr); @@ -218,25 +215,19 @@ static JNINativeMethod gMethods[] = { #endif }; -#define FIND_CLASS(var, className) \ - var = env->FindClass(className); \ - LOG_FATAL_IF(! var, "Unable to find class " className); - -#define GET_STATIC_METHOD_ID(var, clazz, methodName, methodDescriptor) \ - var = env->GetStaticMethodID(clazz, methodName, methodDescriptor); \ - LOG_FATAL_IF(! var, "Unable to find method " methodName); - int register_android_view_RenderNodeAnimator(JNIEnv* env) { #ifdef USE_OPENGL_RENDERER sLifecycleChecker.incStrong(0); #endif - FIND_CLASS(gRenderNodeAnimatorClassInfo.clazz, kClassPathName); - gRenderNodeAnimatorClassInfo.clazz = jclass(env->NewGlobalRef(gRenderNodeAnimatorClassInfo.clazz)); + gRenderNodeAnimatorClassInfo.clazz = FindClassOrDie(env, kClassPathName); + gRenderNodeAnimatorClassInfo.clazz = MakeGlobalRefOrDie(env, + gRenderNodeAnimatorClassInfo.clazz); - GET_STATIC_METHOD_ID(gRenderNodeAnimatorClassInfo.callOnFinished, gRenderNodeAnimatorClassInfo.clazz, - "callOnFinished", "(Landroid/view/RenderNodeAnimator;)V"); + gRenderNodeAnimatorClassInfo.callOnFinished = GetStaticMethodIDOrDie( + env, gRenderNodeAnimatorClassInfo.clazz, "callOnFinished", + "(Landroid/view/RenderNodeAnimator;)V"); - return AndroidRuntime::registerNativeMethods(env, kClassPathName, gMethods, NELEM(gMethods)); + return RegisterMethodsOrDie(env, kClassPathName, gMethods, NELEM(gMethods)); } diff --git a/core/jni/android_view_Surface.cpp b/core/jni/android_view_Surface.cpp index a39ff8e..7f6c50f 100644 --- a/core/jni/android_view_Surface.cpp +++ b/core/jni/android_view_Surface.cpp @@ -23,7 +23,7 @@ #include "android_os_Parcel.h" #include "android/graphics/GraphicsJNI.h" -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" #include <android_runtime/android_view_Surface.h> #include <android_runtime/android_graphics_SurfaceTexture.h> #include <android_runtime/Log.h> @@ -324,7 +324,7 @@ static jlong nativeReadFromParcel(JNIEnv* env, jclass clazz, // update the Surface only if the underlying IGraphicBufferProducer // has changed. if (self != NULL - && (self->getIGraphicBufferProducer()->asBinder() == binder)) { + && (IInterface::asBinder(self->getIGraphicBufferProducer()) == binder)) { // same IGraphicBufferProducer, return ourselves return jlong(self.get()); } @@ -354,7 +354,7 @@ static void nativeWriteToParcel(JNIEnv* env, jclass clazz, return; } sp<Surface> self(reinterpret_cast<Surface *>(nativeObject)); - parcel->writeStrongBinder( self != 0 ? self->getIGraphicBufferProducer()->asBinder() : NULL); + parcel->writeStrongBinder( self != 0 ? IInterface::asBinder(self->getIGraphicBufferProducer()) : NULL); } static jint nativeGetWidth(JNIEnv* env, jclass clazz, jlong nativeObject) { @@ -454,26 +454,26 @@ static JNINativeMethod gSurfaceMethods[] = { int register_android_view_Surface(JNIEnv* env) { - int err = AndroidRuntime::registerNativeMethods(env, "android/view/Surface", + int err = RegisterMethodsOrDie(env, "android/view/Surface", gSurfaceMethods, NELEM(gSurfaceMethods)); - jclass clazz = env->FindClass("android/view/Surface"); - gSurfaceClassInfo.clazz = jclass(env->NewGlobalRef(clazz)); - gSurfaceClassInfo.mNativeObject = - env->GetFieldID(gSurfaceClassInfo.clazz, "mNativeObject", "J"); - gSurfaceClassInfo.mLock = - env->GetFieldID(gSurfaceClassInfo.clazz, "mLock", "Ljava/lang/Object;"); - gSurfaceClassInfo.ctor = env->GetMethodID(gSurfaceClassInfo.clazz, "<init>", "(J)V"); - - clazz = env->FindClass("android/graphics/Canvas"); - gCanvasClassInfo.mSurfaceFormat = env->GetFieldID(clazz, "mSurfaceFormat", "I"); - gCanvasClassInfo.setNativeBitmap = env->GetMethodID(clazz, "setNativeBitmap", "(J)V"); - - clazz = env->FindClass("android/graphics/Rect"); - gRectClassInfo.left = env->GetFieldID(clazz, "left", "I"); - gRectClassInfo.top = env->GetFieldID(clazz, "top", "I"); - gRectClassInfo.right = env->GetFieldID(clazz, "right", "I"); - gRectClassInfo.bottom = env->GetFieldID(clazz, "bottom", "I"); + jclass clazz = FindClassOrDie(env, "android/view/Surface"); + gSurfaceClassInfo.clazz = MakeGlobalRefOrDie(env, clazz); + gSurfaceClassInfo.mNativeObject = GetFieldIDOrDie(env, + gSurfaceClassInfo.clazz, "mNativeObject", "J"); + gSurfaceClassInfo.mLock = GetFieldIDOrDie(env, + gSurfaceClassInfo.clazz, "mLock", "Ljava/lang/Object;"); + gSurfaceClassInfo.ctor = GetMethodIDOrDie(env, gSurfaceClassInfo.clazz, "<init>", "(J)V"); + + clazz = FindClassOrDie(env, "android/graphics/Canvas"); + gCanvasClassInfo.mSurfaceFormat = GetFieldIDOrDie(env, clazz, "mSurfaceFormat", "I"); + gCanvasClassInfo.setNativeBitmap = GetMethodIDOrDie(env, clazz, "setNativeBitmap", "(J)V"); + + clazz = FindClassOrDie(env, "android/graphics/Rect"); + gRectClassInfo.left = GetFieldIDOrDie(env, clazz, "left", "I"); + gRectClassInfo.top = GetFieldIDOrDie(env, clazz, "top", "I"); + gRectClassInfo.right = GetFieldIDOrDie(env, clazz, "right", "I"); + gRectClassInfo.bottom = GetFieldIDOrDie(env, clazz, "bottom", "I"); return err; } diff --git a/core/jni/android_view_SurfaceControl.cpp b/core/jni/android_view_SurfaceControl.cpp index 06c22ae..13c373f 100644 --- a/core/jni/android_view_SurfaceControl.cpp +++ b/core/jni/android_view_SurfaceControl.cpp @@ -26,7 +26,7 @@ #include "android/graphics/GraphicsJNI.h" #include "android/graphics/Region.h" -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" #include <android_runtime/android_view_Surface.h> #include <android_runtime/android_view_SurfaceSession.h> @@ -134,7 +134,7 @@ static jobject nativeScreenshotBitmap(JNIEnv* env, jclass clazz, status_t res; if (allLayers) { minLayer = 0; - maxLayer = -1UL; + maxLayer = -1; } res = screenshot->update(displayToken, sourceCrop, width, height, @@ -647,41 +647,44 @@ static JNINativeMethod sSurfaceControlMethods[] = { int register_android_view_SurfaceControl(JNIEnv* env) { - int err = AndroidRuntime::registerNativeMethods(env, "android/view/SurfaceControl", + int err = RegisterMethodsOrDie(env, "android/view/SurfaceControl", sSurfaceControlMethods, NELEM(sSurfaceControlMethods)); - jclass clazz = env->FindClass("android/view/SurfaceControl$PhysicalDisplayInfo"); - gPhysicalDisplayInfoClassInfo.clazz = static_cast<jclass>(env->NewGlobalRef(clazz)); - gPhysicalDisplayInfoClassInfo.ctor = env->GetMethodID(gPhysicalDisplayInfoClassInfo.clazz, - "<init>", "()V"); - gPhysicalDisplayInfoClassInfo.width = env->GetFieldID(clazz, "width", "I"); - gPhysicalDisplayInfoClassInfo.height = env->GetFieldID(clazz, "height", "I"); - gPhysicalDisplayInfoClassInfo.refreshRate = env->GetFieldID(clazz, "refreshRate", "F"); - gPhysicalDisplayInfoClassInfo.density = env->GetFieldID(clazz, "density", "F"); - gPhysicalDisplayInfoClassInfo.xDpi = env->GetFieldID(clazz, "xDpi", "F"); - gPhysicalDisplayInfoClassInfo.yDpi = env->GetFieldID(clazz, "yDpi", "F"); - gPhysicalDisplayInfoClassInfo.secure = env->GetFieldID(clazz, "secure", "Z"); - gPhysicalDisplayInfoClassInfo.appVsyncOffsetNanos = env->GetFieldID(clazz, - "appVsyncOffsetNanos", "J"); - gPhysicalDisplayInfoClassInfo.presentationDeadlineNanos = env->GetFieldID(clazz, - "presentationDeadlineNanos", "J"); - - jclass rectClazz = env->FindClass("android/graphics/Rect"); - gRectClassInfo.bottom = env->GetFieldID(rectClazz, "bottom", "I"); - gRectClassInfo.left = env->GetFieldID(rectClazz, "left", "I"); - gRectClassInfo.right = env->GetFieldID(rectClazz, "right", "I"); - gRectClassInfo.top = env->GetFieldID(rectClazz, "top", "I"); - - jclass frameStatsClazz = env->FindClass("android/view/FrameStats"); - jfieldID undefined_time_nano_field = env->GetStaticFieldID(frameStatsClazz, "UNDEFINED_TIME_NANO", "J"); + jclass clazz = FindClassOrDie(env, "android/view/SurfaceControl$PhysicalDisplayInfo"); + gPhysicalDisplayInfoClassInfo.clazz = MakeGlobalRefOrDie(env, clazz); + gPhysicalDisplayInfoClassInfo.ctor = GetMethodIDOrDie(env, + gPhysicalDisplayInfoClassInfo.clazz, "<init>", "()V"); + gPhysicalDisplayInfoClassInfo.width = GetFieldIDOrDie(env, clazz, "width", "I"); + gPhysicalDisplayInfoClassInfo.height = GetFieldIDOrDie(env, clazz, "height", "I"); + gPhysicalDisplayInfoClassInfo.refreshRate = GetFieldIDOrDie(env, clazz, "refreshRate", "F"); + gPhysicalDisplayInfoClassInfo.density = GetFieldIDOrDie(env, clazz, "density", "F"); + gPhysicalDisplayInfoClassInfo.xDpi = GetFieldIDOrDie(env, clazz, "xDpi", "F"); + gPhysicalDisplayInfoClassInfo.yDpi = GetFieldIDOrDie(env, clazz, "yDpi", "F"); + gPhysicalDisplayInfoClassInfo.secure = GetFieldIDOrDie(env, clazz, "secure", "Z"); + gPhysicalDisplayInfoClassInfo.appVsyncOffsetNanos = GetFieldIDOrDie(env, + clazz, "appVsyncOffsetNanos", "J"); + gPhysicalDisplayInfoClassInfo.presentationDeadlineNanos = GetFieldIDOrDie(env, + clazz, "presentationDeadlineNanos", "J"); + + jclass rectClazz = FindClassOrDie(env, "android/graphics/Rect"); + gRectClassInfo.bottom = GetFieldIDOrDie(env, rectClazz, "bottom", "I"); + gRectClassInfo.left = GetFieldIDOrDie(env, rectClazz, "left", "I"); + gRectClassInfo.right = GetFieldIDOrDie(env, rectClazz, "right", "I"); + gRectClassInfo.top = GetFieldIDOrDie(env, rectClazz, "top", "I"); + + jclass frameStatsClazz = FindClassOrDie(env, "android/view/FrameStats"); + jfieldID undefined_time_nano_field = GetStaticFieldIDOrDie(env, + frameStatsClazz, "UNDEFINED_TIME_NANO", "J"); nsecs_t undefined_time_nano = env->GetStaticLongField(frameStatsClazz, undefined_time_nano_field); - jclass contFrameStatsClazz = env->FindClass("android/view/WindowContentFrameStats"); - gWindowContentFrameStatsClassInfo.init = env->GetMethodID(contFrameStatsClazz, "init", "(J[J[J[J)V"); + jclass contFrameStatsClazz = FindClassOrDie(env, "android/view/WindowContentFrameStats"); + gWindowContentFrameStatsClassInfo.init = GetMethodIDOrDie(env, + contFrameStatsClazz, "init", "(J[J[J[J)V"); gWindowContentFrameStatsClassInfo.UNDEFINED_TIME_NANO = undefined_time_nano; - jclass animFrameStatsClazz = env->FindClass("android/view/WindowAnimationFrameStats"); - gWindowAnimationFrameStatsClassInfo.init = env->GetMethodID(animFrameStatsClazz, "init", "(J[J)V"); + jclass animFrameStatsClazz = FindClassOrDie(env, "android/view/WindowAnimationFrameStats"); + gWindowAnimationFrameStatsClassInfo.init = GetMethodIDOrDie(env, + animFrameStatsClazz, "init", "(J[J)V"); gWindowAnimationFrameStatsClassInfo.UNDEFINED_TIME_NANO = undefined_time_nano; return err; diff --git a/core/jni/android_view_TextureView.cpp b/core/jni/android_view_TextureView.cpp index 5c04a78..011c326 100644 --- a/core/jni/android_view_TextureView.cpp +++ b/core/jni/android_view_TextureView.cpp @@ -31,6 +31,8 @@ #include "android/graphics/GraphicsJNI.h" +#include "core_jni_helpers.h" + namespace android { // ---------------------------------------------------------------------------- @@ -212,35 +214,22 @@ static JNINativeMethod gMethods[] = { (void*) android_view_TextureView_unlockCanvasAndPost }, }; -#define FIND_CLASS(var, className) \ - var = env->FindClass(className); \ - LOG_FATAL_IF(!var, "Unable to find class " className); +int register_android_view_TextureView(JNIEnv* env) { + jclass clazz = FindClassOrDie(env, "android/graphics/Rect"); + gRectClassInfo.set = GetMethodIDOrDie(env, clazz, "set", "(IIII)V"); + gRectClassInfo.left = GetFieldIDOrDie(env, clazz, "left", "I"); + gRectClassInfo.top = GetFieldIDOrDie(env, clazz, "top", "I"); + gRectClassInfo.right = GetFieldIDOrDie(env, clazz, "right", "I"); + gRectClassInfo.bottom = GetFieldIDOrDie(env, clazz, "bottom", "I"); -#define GET_METHOD_ID(var, clazz, methodName, methodDescriptor) \ - var = env->GetMethodID(clazz, methodName, methodDescriptor); \ - LOG_FATAL_IF(!var, "Unable to find method " methodName); + clazz = FindClassOrDie(env, "android/graphics/Canvas"); + gCanvasClassInfo.mSurfaceFormat = GetFieldIDOrDie(env, clazz, "mSurfaceFormat", "I"); + gCanvasClassInfo.setNativeBitmap = GetMethodIDOrDie(env, clazz, "setNativeBitmap", "(J)V"); -#define GET_FIELD_ID(var, clazz, fieldName, fieldDescriptor) \ - var = env->GetFieldID(clazz, fieldName, fieldDescriptor); \ - LOG_FATAL_IF(!var, "Unable to find field" fieldName); + clazz = FindClassOrDie(env, "android/view/TextureView"); + gTextureViewClassInfo.nativeWindow = GetFieldIDOrDie(env, clazz, "mNativeWindow", "J"); -int register_android_view_TextureView(JNIEnv* env) { - jclass clazz; - FIND_CLASS(clazz, "android/graphics/Rect"); - GET_METHOD_ID(gRectClassInfo.set, clazz, "set", "(IIII)V"); - GET_FIELD_ID(gRectClassInfo.left, clazz, "left", "I"); - GET_FIELD_ID(gRectClassInfo.top, clazz, "top", "I"); - GET_FIELD_ID(gRectClassInfo.right, clazz, "right", "I"); - GET_FIELD_ID(gRectClassInfo.bottom, clazz, "bottom", "I"); - - FIND_CLASS(clazz, "android/graphics/Canvas"); - GET_FIELD_ID(gCanvasClassInfo.mSurfaceFormat, clazz, "mSurfaceFormat", "I"); - GET_METHOD_ID(gCanvasClassInfo.setNativeBitmap, clazz, "setNativeBitmap", "(J)V"); - - FIND_CLASS(clazz, "android/view/TextureView"); - GET_FIELD_ID(gTextureViewClassInfo.nativeWindow, clazz, "mNativeWindow", "J"); - - return AndroidRuntime::registerNativeMethods(env, kClassPathName, gMethods, NELEM(gMethods)); + return RegisterMethodsOrDie(env, kClassPathName, gMethods, NELEM(gMethods)); } }; diff --git a/core/jni/android_view_ThreadedRenderer.cpp b/core/jni/android_view_ThreadedRenderer.cpp index b9d849c..9b06293 100644 --- a/core/jni/android_view_ThreadedRenderer.cpp +++ b/core/jni/android_view_ThreadedRenderer.cpp @@ -20,7 +20,7 @@ #include "jni.h" #include <nativehelper/JNIHelp.h> -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" #include <EGL/egl.h> #include <EGL/eglext.h> @@ -454,7 +454,7 @@ static JNINativeMethod gMethods[] = { }; int register_android_view_ThreadedRenderer(JNIEnv* env) { - return AndroidRuntime::registerNativeMethods(env, kClassPathName, gMethods, NELEM(gMethods)); + return RegisterMethodsOrDie(env, kClassPathName, gMethods, NELEM(gMethods)); } }; // namespace android diff --git a/core/jni/android_view_VelocityTracker.cpp b/core/jni/android_view_VelocityTracker.cpp index 1e36932..ddd5fc8 100644 --- a/core/jni/android_view_VelocityTracker.cpp +++ b/core/jni/android_view_VelocityTracker.cpp @@ -26,6 +26,7 @@ #include <ScopedUtfChars.h> +#include "core_jni_helpers.h" namespace android { @@ -242,31 +243,18 @@ static JNINativeMethod gVelocityTrackerMethods[] = { (void*)android_view_VelocityTracker_nativeGetEstimator }, }; -#define FIND_CLASS(var, className) \ - var = env->FindClass(className); \ - LOG_FATAL_IF(! var, "Unable to find class " className); +int register_android_view_VelocityTracker(JNIEnv* env) { + int res = RegisterMethodsOrDie(env, "android/view/VelocityTracker", gVelocityTrackerMethods, + NELEM(gVelocityTrackerMethods)); -#define GET_FIELD_ID(var, clazz, fieldName, fieldDescriptor) \ - var = env->GetFieldID(clazz, fieldName, fieldDescriptor); \ - LOG_FATAL_IF(! var, "Unable to find field " fieldName); + jclass clazz = FindClassOrDie(env, "android/view/VelocityTracker$Estimator"); -int register_android_view_VelocityTracker(JNIEnv* env) { - int res = jniRegisterNativeMethods(env, "android/view/VelocityTracker", - gVelocityTrackerMethods, NELEM(gVelocityTrackerMethods)); - LOG_FATAL_IF(res < 0, "Unable to register native methods."); - - jclass clazz; - FIND_CLASS(clazz, "android/view/VelocityTracker$Estimator"); - - GET_FIELD_ID(gEstimatorClassInfo.xCoeff, clazz, - "xCoeff", "[F"); - GET_FIELD_ID(gEstimatorClassInfo.yCoeff, clazz, - "yCoeff", "[F"); - GET_FIELD_ID(gEstimatorClassInfo.degree, clazz, - "degree", "I"); - GET_FIELD_ID(gEstimatorClassInfo.confidence, clazz, - "confidence", "F"); - return 0; + gEstimatorClassInfo.xCoeff = GetFieldIDOrDie(env, clazz, "xCoeff", "[F"); + gEstimatorClassInfo.yCoeff = GetFieldIDOrDie(env, clazz, "yCoeff", "[F"); + gEstimatorClassInfo.degree = GetFieldIDOrDie(env, clazz, "degree", "I"); + gEstimatorClassInfo.confidence = GetFieldIDOrDie(env, clazz, "confidence", "F"); + + return res; } } // namespace android diff --git a/core/jni/com_android_internal_content_NativeLibraryHelper.cpp b/core/jni/com_android_internal_content_NativeLibraryHelper.cpp index 226b764..3c1993e 100644 --- a/core/jni/com_android_internal_content_NativeLibraryHelper.cpp +++ b/core/jni/com_android_internal_content_NativeLibraryHelper.cpp @@ -17,7 +17,7 @@ #define LOG_TAG "NativeLibraryHelper" //#define LOG_NDEBUG 0 -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" #include <ScopedUtfChars.h> #include <UniquePtr.h> @@ -117,7 +117,7 @@ isFileDifferent(const char* filePath, size_t fileSize, time_t modifiedTime, return true; } - if (st->st_size != fileSize) { + if (static_cast<uint64_t>(st->st_size) != static_cast<uint64_t>(fileSize)) { return true; } @@ -430,7 +430,6 @@ static int findSupportedAbi(JNIEnv *env, jlong apkHandle, jobjectArray supported } ZipEntryRO entry = NULL; - char fileName[PATH_MAX]; int status = NO_NATIVE_LIBRARIES; while ((entry = it->next()) != NULL) { // We're currently in the lib/ directory of the APK, so it does have some native @@ -564,8 +563,8 @@ static JNINativeMethod gMethods[] = { int register_com_android_internal_content_NativeLibraryHelper(JNIEnv *env) { - return AndroidRuntime::registerNativeMethods(env, - "com/android/internal/content/NativeLibraryHelper", gMethods, NELEM(gMethods)); + return RegisterMethodsOrDie(env, + "com/android/internal/content/NativeLibraryHelper", gMethods, NELEM(gMethods)); } }; diff --git a/core/jni/com_android_internal_net_NetworkStatsFactory.cpp b/core/jni/com_android_internal_net_NetworkStatsFactory.cpp index 2e2d0c7..6c0b756 100644 --- a/core/jni/com_android_internal_net_NetworkStatsFactory.cpp +++ b/core/jni/com_android_internal_net_NetworkStatsFactory.cpp @@ -17,10 +17,11 @@ #define LOG_TAG "NetworkStats" #include <errno.h> +#include <inttypes.h> #include <sys/stat.h> #include <sys/types.h> -#include <android_runtime/AndroidRuntime.h> +#include <core_jni_helpers.h> #include <jni.h> #include <ScopedUtfChars.h> @@ -187,7 +188,7 @@ static int readNetworkStatsDetail(JNIEnv* env, jclass clazz, jobject stats, if (endPos - pos == 3) { rawTag = 0; } else { - if (sscanf(pos, "%llx", &rawTag) != 1) { + if (sscanf(pos, "%" PRIx64, &rawTag) != 1) { ALOGE("bad tag: %s", pos); fclose(fp); return -1; @@ -204,7 +205,7 @@ static int readNetworkStatsDetail(JNIEnv* env, jclass clazz, jobject stats, while (*pos == ' ') pos++; // Parse remaining fields. - if (sscanf(pos, "%u %u %llu %llu %llu %llu", + if (sscanf(pos, "%u %u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, &s.uid, &s.set, &s.rxBytes, &s.rxPackets, &s.txBytes, &s.txPackets) == 6) { if (limitUid != -1 && limitUid != s.uid) { @@ -283,16 +284,6 @@ static int readNetworkStatsDetail(JNIEnv* env, jclass clazz, jobject stats, return 0; } -static jclass findClass(JNIEnv* env, const char* name) { - ScopedLocalRef<jclass> localClass(env, env->FindClass(name)); - jclass result = reinterpret_cast<jclass>(env->NewGlobalRef(localClass.get())); - if (result == NULL) { - ALOGE("failed to find class '%s'", name); - abort(); - } - return result; -} - static JNINativeMethod gMethods[] = { { "nativeReadNetworkStatsDetail", "(Landroid/net/NetworkStats;Ljava/lang/String;I[Ljava/lang/String;I)I", @@ -300,24 +291,25 @@ static JNINativeMethod gMethods[] = { }; int register_com_android_internal_net_NetworkStatsFactory(JNIEnv* env) { - int err = AndroidRuntime::registerNativeMethods(env, + int err = RegisterMethodsOrDie(env, "com/android/internal/net/NetworkStatsFactory", gMethods, NELEM(gMethods)); - gStringClass = findClass(env, "java/lang/String"); - - jclass clazz = env->FindClass("android/net/NetworkStats"); - gNetworkStatsClassInfo.size = env->GetFieldID(clazz, "size", "I"); - gNetworkStatsClassInfo.capacity = env->GetFieldID(clazz, "capacity", "I"); - gNetworkStatsClassInfo.iface = env->GetFieldID(clazz, "iface", "[Ljava/lang/String;"); - gNetworkStatsClassInfo.uid = env->GetFieldID(clazz, "uid", "[I"); - gNetworkStatsClassInfo.set = env->GetFieldID(clazz, "set", "[I"); - gNetworkStatsClassInfo.tag = env->GetFieldID(clazz, "tag", "[I"); - gNetworkStatsClassInfo.rxBytes = env->GetFieldID(clazz, "rxBytes", "[J"); - gNetworkStatsClassInfo.rxPackets = env->GetFieldID(clazz, "rxPackets", "[J"); - gNetworkStatsClassInfo.txBytes = env->GetFieldID(clazz, "txBytes", "[J"); - gNetworkStatsClassInfo.txPackets = env->GetFieldID(clazz, "txPackets", "[J"); - gNetworkStatsClassInfo.operations = env->GetFieldID(clazz, "operations", "[J"); + gStringClass = FindClassOrDie(env, "java/lang/String"); + gStringClass = MakeGlobalRefOrDie(env, gStringClass); + + jclass clazz = FindClassOrDie(env, "android/net/NetworkStats"); + gNetworkStatsClassInfo.size = GetFieldIDOrDie(env, clazz, "size", "I"); + gNetworkStatsClassInfo.capacity = GetFieldIDOrDie(env, clazz, "capacity", "I"); + gNetworkStatsClassInfo.iface = GetFieldIDOrDie(env, clazz, "iface", "[Ljava/lang/String;"); + gNetworkStatsClassInfo.uid = GetFieldIDOrDie(env, clazz, "uid", "[I"); + gNetworkStatsClassInfo.set = GetFieldIDOrDie(env, clazz, "set", "[I"); + gNetworkStatsClassInfo.tag = GetFieldIDOrDie(env, clazz, "tag", "[I"); + gNetworkStatsClassInfo.rxBytes = GetFieldIDOrDie(env, clazz, "rxBytes", "[J"); + gNetworkStatsClassInfo.rxPackets = GetFieldIDOrDie(env, clazz, "rxPackets", "[J"); + gNetworkStatsClassInfo.txBytes = GetFieldIDOrDie(env, clazz, "txBytes", "[J"); + gNetworkStatsClassInfo.txPackets = GetFieldIDOrDie(env, clazz, "txPackets", "[J"); + gNetworkStatsClassInfo.operations = GetFieldIDOrDie(env, clazz, "operations", "[J"); return err; } diff --git a/core/jni/com_android_internal_os_Zygote.cpp b/core/jni/com_android_internal_os_Zygote.cpp index 4f5e08b..2bfeadb 100644 --- a/core/jni/com_android_internal_os_Zygote.cpp +++ b/core/jni/com_android_internal_os_Zygote.cpp @@ -20,12 +20,12 @@ #include <sys/mount.h> #include <linux/fs.h> -#include <grp.h> #include <fcntl.h> +#include <grp.h> +#include <inttypes.h> #include <paths.h> #include <signal.h> #include <stdlib.h> -#include <unistd.h> #include <sys/capability.h> #include <sys/personality.h> #include <sys/prctl.h> @@ -34,7 +34,7 @@ #include <sys/types.h> #include <sys/utsname.h> #include <sys/wait.h> - +#include <unistd.h> #include <cutils/fs.h> #include <cutils/multiuser.h> @@ -43,9 +43,8 @@ #include <utils/String8.h> #include <selinux/android.h> #include <processgroup/processgroup.h> -#include <inttypes.h> -#include "android_runtime/AndroidRuntime.h" +#include "core_jni_helpers.h" #include "JNIHelp.h" #include "ScopedLocalRef.h" #include "ScopedPrimitiveArray.h" @@ -105,7 +104,7 @@ static void SigChldHandler(int /*signal_number*/) { // so that it is restarted by init and system server will be restarted // from there. if (pid == gSystemServerPid) { - ALOGE("Exit zygote because system server (%d) has terminated"); + ALOGE("Exit zygote because system server (%d) has terminated", pid); kill(getpid(), SIGKILL); } } @@ -131,7 +130,7 @@ static void SetSigChldHandler() { int err = sigaction(SIGCHLD, &sa, NULL); if (err < 0) { - ALOGW("Error setting SIGCHLD handler: %d", errno); + ALOGW("Error setting SIGCHLD handler: %s", strerror(errno)); } } @@ -143,7 +142,7 @@ static void UnsetSigChldHandler() { int err = sigaction(SIGCHLD, &sa, NULL); if (err < 0) { - ALOGW("Error unsetting SIGCHLD handler: %d", errno); + ALOGW("Error unsetting SIGCHLD handler: %s", strerror(errno)); } } @@ -190,7 +189,8 @@ static void SetRLimits(JNIEnv* env, jobjectArray javaRlimits) { int rc = setrlimit(javaRlimit[0], &rlim); if (rc == -1) { - ALOGE("setrlimit(%d, {%d, %d}) failed", javaRlimit[0], rlim.rlim_cur, rlim.rlim_max); + ALOGE("setrlimit(%d, {%ld, %ld}) failed", javaRlimit[0], rlim.rlim_cur, + rlim.rlim_max); RuntimeAbort(env); } } @@ -236,7 +236,7 @@ static void SetCapabilities(JNIEnv* env, int64_t permitted, int64_t effective) { capdata[1].permitted = permitted >> 32; if (capset(&capheader, &capdata[0]) == -1) { - ALOGE("capset(%lld, %lld) failed", permitted, effective); + ALOGE("capset(%" PRId64 ", %" PRId64 ") failed", permitted, effective); RuntimeAbort(env); } } @@ -258,7 +258,7 @@ static bool MountEmulatedStorage(uid_t uid, jint mount_mode, bool force_mount_na // Create a second private mount namespace for our process if (unshare(CLONE_NEWNS) == -1) { - ALOGW("Failed to unshare(): %d", errno); + ALOGW("Failed to unshare(): %s", strerror(errno)); return false; } @@ -295,14 +295,15 @@ static bool MountEmulatedStorage(uid_t uid, jint mount_mode, bool force_mount_na if (mount_mode == MOUNT_EXTERNAL_MULTIUSER_ALL) { // Mount entire external storage tree for all users if (TEMP_FAILURE_RETRY(mount(source, target, NULL, MS_BIND, NULL)) == -1) { - ALOGW("Failed to mount %s to %s :%d", source, target, errno); + ALOGW("Failed to mount %s to %s: %s", source, target, strerror(errno)); return false; } } else { // Only mount user-specific external storage - if (TEMP_FAILURE_RETRY( - mount(source_user.string(), target_user.string(), NULL, MS_BIND, NULL)) == -1) { - ALOGW("Failed to mount %s to %s: %d", source_user.string(), target_user.string(), errno); + if (TEMP_FAILURE_RETRY(mount(source_user.string(), target_user.string(), NULL, + MS_BIND, NULL)) == -1) { + ALOGW("Failed to mount %s to %s: %s", source_user.string(), target_user.string(), + strerror(errno)); return false; } } @@ -314,7 +315,7 @@ static bool MountEmulatedStorage(uid_t uid, jint mount_mode, bool force_mount_na // Finally, mount user-specific path into place for legacy users if (TEMP_FAILURE_RETRY( mount(target_user.string(), legacy, NULL, MS_BIND | MS_REC, NULL)) == -1) { - ALOGW("Failed to mount %s to %s: %d", target_user.string(), legacy, errno); + ALOGW("Failed to mount %s to %s: %s", target_user.string(), legacy, strerror(errno)); return false; } } else { @@ -365,13 +366,13 @@ static void DetachDescriptors(JNIEnv* env, jintArray fdsToClose) { for (i = 0; i < count; i++) { devnull = open("/dev/null", O_RDWR); if (devnull < 0) { - ALOGE("Failed to open /dev/null"); + ALOGE("Failed to open /dev/null: %s", strerror(errno)); RuntimeAbort(env); continue; } - ALOGV("Switching descriptor %d to /dev/null: %d", ar[i], errno); + ALOGV("Switching descriptor %d to /dev/null: %s", ar[i], strerror(errno)); if (dup2(devnull, ar[i]) < 0) { - ALOGE("Failed dup2() on descriptor %d", ar[i]); + ALOGE("Failed dup2() on descriptor %d: %s", ar[i], strerror(errno)); RuntimeAbort(env); } close(devnull); @@ -401,23 +402,7 @@ void SetThreadName(const char* thread_name) { strlcpy(buf, s, sizeof(buf)-1); errno = pthread_setname_np(pthread_self(), buf); if (errno != 0) { - ALOGW("Unable to set the name of current thread to '%s'", buf); - } -} - - // Temporary timing check. -uint64_t MsTime() { - timespec now; - clock_gettime(CLOCK_MONOTONIC, &now); - return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000) + now.tv_nsec / UINT64_C(1000000); -} - - -void ckTime(uint64_t start, const char* where) { - uint64_t now = MsTime(); - if ((now-start) > 1000) { - // If we are taking more than a second, log about it. - ALOGW("Slow operation: %"PRIu64" ms in %s", (uint64_t)(now-start), where); + ALOGW("Unable to set the name of current thread to '%s': %s", buf, strerror(errno)); } } @@ -429,9 +414,7 @@ static pid_t ForkAndSpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArra jstring java_se_info, jstring java_se_name, bool is_system_server, jintArray fdsToClose, jstring instructionSet, jstring dataDir) { - uint64_t start = MsTime(); SetSigChldHandler(); - ckTime(start, "ForkAndSpecializeCommon:SetSigChldHandler"); pid_t pid = fork(); @@ -439,12 +422,9 @@ static pid_t ForkAndSpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArra // The child process. gMallocLeakZygoteChild = 1; - // Clean up any descriptors which must be closed immediately DetachDescriptors(env, fdsToClose); - ckTime(start, "ForkAndSpecializeCommon:Fork and detach"); - // Keep capabilities across UID change, unless we're staying root. if (uid != 0) { EnableKeepCapabilities(env); @@ -504,13 +484,13 @@ static pid_t ForkAndSpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArra int rc = setresgid(gid, gid, gid); if (rc == -1) { - ALOGE("setresgid(%d) failed", gid); + ALOGE("setresgid(%d) failed: %s", gid, strerror(errno)); RuntimeAbort(env); } rc = setresuid(uid, uid, uid); if (rc == -1) { - ALOGE("setresuid(%d) failed", uid); + ALOGE("setresuid(%d) failed: %s", uid, strerror(errno)); RuntimeAbort(env); } @@ -519,7 +499,7 @@ static pid_t ForkAndSpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArra int old_personality = personality(0xffffffff); int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE); if (new_personality == -1) { - ALOGW("personality(%d) failed", new_personality); + ALOGW("personality(%d) failed: %s", new_personality, strerror(errno)); } } @@ -568,11 +548,8 @@ static pid_t ForkAndSpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArra UnsetSigChldHandler(); - ckTime(start, "ForkAndSpecializeCommon:child process setup"); - env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, debug_flags, is_system_server ? NULL : instructionSet); - ckTime(start, "ForkAndSpecializeCommon:PostForkChildHooks returns"); if (env->ExceptionCheck()) { ALOGE("Error calling post fork hooks."); RuntimeAbort(env); @@ -636,15 +613,11 @@ static JNINativeMethod gMethods[] = { }; int register_com_android_internal_os_Zygote(JNIEnv* env) { - gZygoteClass = (jclass) env->NewGlobalRef(env->FindClass(kZygoteClassName)); - if (gZygoteClass == NULL) { - RuntimeAbort(env); - } - gCallPostForkChildHooks = env->GetStaticMethodID(gZygoteClass, "callPostForkChildHooks", + gZygoteClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteClassName)); + gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks", "(ILjava/lang/String;)V"); - return AndroidRuntime::registerNativeMethods(env, "com/android/internal/os/Zygote", - gMethods, NELEM(gMethods)); + return RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods)); } } // namespace android diff --git a/core/jni/com_android_internal_os_ZygoteInit.cpp b/core/jni/com_android_internal_os_ZygoteInit.cpp deleted file mode 100644 index 2233ee3..0000000 --- a/core/jni/com_android_internal_os_ZygoteInit.cpp +++ /dev/null @@ -1,265 +0,0 @@ -/* - * Copyright (C) 2007 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#define LOG_TAG "Zygote" - -#include <sys/types.h> -#include <unistd.h> -#include <fcntl.h> -#include <utils/misc.h> -#include <errno.h> -#include <sys/select.h> - -#include "jni.h" -#include <JNIHelp.h> -#include "android_runtime/AndroidRuntime.h" - -#include <sys/capability.h> -#include <sys/prctl.h> - -namespace android { - -/* - * In class com.android.internal.os.ZygoteInit: - * private static native boolean setreuid(int ruid, int euid) - */ -static jint com_android_internal_os_ZygoteInit_setreuid( - JNIEnv* env, jobject clazz, jint ruid, jint euid) -{ - if (setreuid(ruid, euid) < 0) { - return errno; - } - return 0; -} - -/* - * In class com.android.internal.os.ZygoteInit: - * private static native int setregid(int rgid, int egid) - */ -static jint com_android_internal_os_ZygoteInit_setregid( - JNIEnv* env, jobject clazz, jint rgid, jint egid) -{ - if (setregid(rgid, egid) < 0) { - return errno; - } - return 0; -} - -/* - * In class com.android.internal.os.ZygoteInit: - * private static native int setpgid(int rgid, int egid) - */ -static jint com_android_internal_os_ZygoteInit_setpgid( - JNIEnv* env, jobject clazz, jint pid, jint pgid) -{ - if (setpgid(pid, pgid) < 0) { - return errno; - } - return 0; -} - -/* - * In class com.android.internal.os.ZygoteInit: - * private static native int getpgid(int pid) - */ -static jint com_android_internal_os_ZygoteInit_getpgid( - JNIEnv* env, jobject clazz, jint pid) -{ - pid_t ret; - ret = getpgid(pid); - - if (ret < 0) { - jniThrowIOException(env, errno); - } - - return ret; -} - -static void com_android_internal_os_ZygoteInit_reopenStdio(JNIEnv* env, - jobject clazz, jobject in, jobject out, jobject errfd) -{ - int fd; - int err; - - fd = jniGetFDFromFileDescriptor(env, in); - - if (env->ExceptionOccurred() != NULL) { - return; - } - - do { - err = dup2(fd, STDIN_FILENO); - } while (err < 0 && errno == EINTR); - - fd = jniGetFDFromFileDescriptor(env, out); - - if (env->ExceptionOccurred() != NULL) { - return; - } - - do { - err = dup2(fd, STDOUT_FILENO); - } while (err < 0 && errno == EINTR); - - fd = jniGetFDFromFileDescriptor(env, errfd); - - if (env->ExceptionOccurred() != NULL) { - return; - } - - do { - err = dup2(fd, STDERR_FILENO); - } while (err < 0 && errno == EINTR); -} - -static void com_android_internal_os_ZygoteInit_setCloseOnExec (JNIEnv *env, - jobject clazz, jobject descriptor, jboolean flag) -{ - int fd; - int err; - int fdFlags; - - fd = jniGetFDFromFileDescriptor(env, descriptor); - - if (env->ExceptionOccurred() != NULL) { - return; - } - - fdFlags = fcntl(fd, F_GETFD); - - if (fdFlags < 0) { - jniThrowIOException(env, errno); - return; - } - - if (flag) { - fdFlags |= FD_CLOEXEC; - } else { - fdFlags &= ~FD_CLOEXEC; - } - - err = fcntl(fd, F_SETFD, fdFlags); - - if (err < 0) { - jniThrowIOException(env, errno); - return; - } -} - -static jint com_android_internal_os_ZygoteInit_selectReadable ( - JNIEnv *env, jobject clazz, jobjectArray fds) -{ - if (fds == NULL) { - jniThrowNullPointerException(env, "fds == null"); - return -1; - } - - jsize length = env->GetArrayLength(fds); - fd_set fdset; - - if (env->ExceptionOccurred() != NULL) { - return -1; - } - - FD_ZERO(&fdset); - - int nfds = 0; - for (jsize i = 0; i < length; i++) { - jobject fdObj = env->GetObjectArrayElement(fds, i); - if (env->ExceptionOccurred() != NULL) { - return -1; - } - if (fdObj == NULL) { - continue; - } - int fd = jniGetFDFromFileDescriptor(env, fdObj); - if (env->ExceptionOccurred() != NULL) { - return -1; - } - - FD_SET(fd, &fdset); - - if (fd >= nfds) { - nfds = fd + 1; - } - } - - int err; - do { - err = select (nfds, &fdset, NULL, NULL, NULL); - } while (err < 0 && errno == EINTR); - - if (err < 0) { - jniThrowIOException(env, errno); - return -1; - } - - for (jsize i = 0; i < length; i++) { - jobject fdObj = env->GetObjectArrayElement(fds, i); - if (env->ExceptionOccurred() != NULL) { - return -1; - } - if (fdObj == NULL) { - continue; - } - int fd = jniGetFDFromFileDescriptor(env, fdObj); - if (env->ExceptionOccurred() != NULL) { - return -1; - } - if (FD_ISSET(fd, &fdset)) { - return (jint)i; - } - } - return -1; -} - -static jobject com_android_internal_os_ZygoteInit_createFileDescriptor ( - JNIEnv *env, jobject clazz, jint fd) -{ - return jniCreateFileDescriptor(env, fd); -} - -/* - * JNI registration. - */ -static JNINativeMethod gMethods[] = { - /* name, signature, funcPtr */ - { "setreuid", "(II)I", - (void*) com_android_internal_os_ZygoteInit_setreuid }, - { "setregid", "(II)I", - (void*) com_android_internal_os_ZygoteInit_setregid }, - { "setpgid", "(II)I", - (void *) com_android_internal_os_ZygoteInit_setpgid }, - { "getpgid", "(I)I", - (void *) com_android_internal_os_ZygoteInit_getpgid }, - { "reopenStdio", - "(Ljava/io/FileDescriptor;Ljava/io/FileDescriptor;" - "Ljava/io/FileDescriptor;)V", - (void *) com_android_internal_os_ZygoteInit_reopenStdio}, - { "setCloseOnExec", "(Ljava/io/FileDescriptor;Z)V", - (void *) com_android_internal_os_ZygoteInit_setCloseOnExec}, - { "selectReadable", "([Ljava/io/FileDescriptor;)I", - (void *) com_android_internal_os_ZygoteInit_selectReadable }, - { "createFileDescriptor", "(I)Ljava/io/FileDescriptor;", - (void *) com_android_internal_os_ZygoteInit_createFileDescriptor } -}; -int register_com_android_internal_os_ZygoteInit(JNIEnv* env) -{ - return AndroidRuntime::registerNativeMethods(env, - "com/android/internal/os/ZygoteInit", gMethods, NELEM(gMethods)); -} - -}; // namespace android diff --git a/core/jni/com_android_internal_util_VirtualRefBasePtr.cpp b/core/jni/com_android_internal_util_VirtualRefBasePtr.cpp index ce6f207..7a18c2d 100644 --- a/core/jni/com_android_internal_util_VirtualRefBasePtr.cpp +++ b/core/jni/com_android_internal_util_VirtualRefBasePtr.cpp @@ -16,7 +16,7 @@ #include "jni.h" #include <nativehelper/JNIHelp.h> -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" namespace android { @@ -42,7 +42,7 @@ static JNINativeMethod gMethods[] = { }; int register_com_android_internal_util_VirtualRefBasePtr(JNIEnv* env) { - return AndroidRuntime::registerNativeMethods(env, kClassPathName, gMethods, NELEM(gMethods)); + return RegisterMethodsOrDie(env, kClassPathName, gMethods, NELEM(gMethods)); } diff --git a/core/jni/com_android_internal_view_animation_NativeInterpolatorFactoryHelper.cpp b/core/jni/com_android_internal_view_animation_NativeInterpolatorFactoryHelper.cpp index 704e1be..c5c2e9d 100644 --- a/core/jni/com_android_internal_view_animation_NativeInterpolatorFactoryHelper.cpp +++ b/core/jni/com_android_internal_view_animation_NativeInterpolatorFactoryHelper.cpp @@ -18,7 +18,7 @@ #include "jni.h" #include <nativehelper/JNIHelp.h> -#include <android_runtime/AndroidRuntime.h> +#include "core_jni_helpers.h" #include <Interpolator.h> @@ -98,7 +98,7 @@ static JNINativeMethod gMethods[] = { }; int register_com_android_internal_view_animation_NativeInterpolatorFactoryHelper(JNIEnv* env) { - return AndroidRuntime::registerNativeMethods(env, kClassPathName, gMethods, NELEM(gMethods)); + return RegisterMethodsOrDie(env, kClassPathName, gMethods, NELEM(gMethods)); } diff --git a/core/jni/com_google_android_gles_jni_GLImpl.cpp b/core/jni/com_google_android_gles_jni_GLImpl.cpp index 7975987..c5f330e 100644 --- a/core/jni/com_google_android_gles_jni_GLImpl.cpp +++ b/core/jni/com_google_android_gles_jni_GLImpl.cpp @@ -17,6 +17,10 @@ // This source file is automatically generated +#pragma GCC diagnostic ignored "-Wunused-variable" +#pragma GCC diagnostic ignored "-Wunused-but-set-variable" +#pragma GCC diagnostic ignored "-Wunused-function" + #include "jni.h" #include "JNIHelp.h" #include <android_runtime/AndroidRuntime.h> diff --git a/core/jni/core_jni_helpers.h b/core/jni/core_jni_helpers.h new file mode 100644 index 0000000..3f169c3 --- /dev/null +++ b/core/jni/core_jni_helpers.h @@ -0,0 +1,77 @@ +/* + * Copyright (C) 2014 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CORE_JNI_HELPERS +#define CORE_JNI_HELPERS + +#include "JNIHelp.h" +#include <android_runtime/AndroidRuntime.h> + +namespace android { + +// Defines some helpful functions. + +static inline jclass FindClassOrDie(JNIEnv* env, const char* class_name) { + jclass clazz = env->FindClass(class_name); + LOG_ALWAYS_FATAL_IF(clazz == NULL, "Unable to find class %s", class_name); + return clazz; +} + +static inline jfieldID GetFieldIDOrDie(JNIEnv* env, jclass clazz, const char* field_name, + const char* field_signature) { + jfieldID res = env->GetFieldID(clazz, field_name, field_signature); + LOG_ALWAYS_FATAL_IF(res == NULL, "Unable to find static field %s", field_name); + return res; +} + +static inline jmethodID GetMethodIDOrDie(JNIEnv* env, jclass clazz, const char* method_name, + const char* method_signature) { + jmethodID res = env->GetMethodID(clazz, method_name, method_signature); + LOG_ALWAYS_FATAL_IF(res == NULL, "Unable to find method %s", method_name); + return res; +} + +static inline jfieldID GetStaticFieldIDOrDie(JNIEnv* env, jclass clazz, const char* field_name, + const char* field_signature) { + jfieldID res = env->GetStaticFieldID(clazz, field_name, field_signature); + LOG_ALWAYS_FATAL_IF(res == NULL, "Unable to find static field %s", field_name); + return res; +} + +static inline jmethodID GetStaticMethodIDOrDie(JNIEnv* env, jclass clazz, const char* method_name, + const char* method_signature) { + jmethodID res = env->GetStaticMethodID(clazz, method_name, method_signature); + LOG_ALWAYS_FATAL_IF(res == NULL, "Unable to find static method %s", method_name); + return res; +} + +template <typename T> +static inline T MakeGlobalRefOrDie(JNIEnv* env, T in) { + jobject res = env->NewGlobalRef(in); + LOG_ALWAYS_FATAL_IF(res == NULL, "Unable to create global reference."); + return static_cast<T>(res); +} + +static inline int RegisterMethodsOrDie(JNIEnv* env, const char* className, + const JNINativeMethod* gMethods, int numMethods) { + int res = AndroidRuntime::registerNativeMethods(env, className, gMethods, numMethods); + LOG_ALWAYS_FATAL_IF(res < 0, "Unable to register native methods."); + return res; +} + +} // namespace android + +#endif // CORE_JNI_HELPERS |