Merge "Race-condition in SoundPool during release"
diff --git a/Android.mk b/Android.mk
index 22cc27b..5d9c5b3 100644
--- a/Android.mk
+++ b/Android.mk
@@ -400,9 +400,6 @@
 
 LOCAL_RMTYPEDEFS := true
 
-# List of classes and interfaces which should be loaded by the Zygote.
-LOCAL_JAVA_RESOURCE_FILES += $(LOCAL_PATH)/preloaded-classes
-
 include $(BUILD_JAVA_LIBRARY)
 framework_module := $(LOCAL_INSTALLED_MODULE)
 
@@ -1001,13 +998,9 @@
 	../../external/nist-sip/java \
 	../../external/apache-http/src \
 	../../external/tagsoup/src \
-	../../external/libphonenumber/java/src
 
 ext_src_files := $(call all-java-files-under,$(ext_dirs))
 
-ext_res_dirs := \
-	../../external/libphonenumber/java/src
-
 # ====  the library  =========================================
 include $(CLEAR_VARS)
 
@@ -1015,7 +1008,7 @@
 
 LOCAL_NO_STANDARD_LIBRARIES := true
 LOCAL_JAVA_LIBRARIES := core-libart
-LOCAL_JAVA_RESOURCE_DIRS := $(ext_res_dirs)
+LOCAL_STATIC_JAVA_LIBRARIES := libphonenumber-platform
 LOCAL_MODULE_TAGS := optional
 LOCAL_MODULE := ext
 
diff --git a/api/current.txt b/api/current.txt
index fe0c209..a6a9e27 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -35803,24 +35803,25 @@
     enum_constant public static final android.webkit.ConsoleMessage.MessageLevel WARNING;
   }
 
-  public class CookieManager {
-    method public synchronized boolean acceptCookie();
-    method public boolean acceptThirdPartyCookies(android.webkit.WebView);
+  public abstract class CookieManager {
+    ctor public CookieManager();
+    method public abstract boolean acceptCookie();
+    method public abstract boolean acceptThirdPartyCookies(android.webkit.WebView);
     method public static boolean allowFileSchemeCookies();
-    method public void flush();
-    method public java.lang.String getCookie(java.lang.String);
+    method public abstract void flush();
+    method public abstract java.lang.String getCookie(java.lang.String);
     method public static synchronized android.webkit.CookieManager getInstance();
-    method public synchronized boolean hasCookies();
-    method public deprecated void removeAllCookie();
-    method public void removeAllCookies(android.webkit.ValueCallback<java.lang.Boolean>);
-    method public deprecated void removeExpiredCookie();
-    method public deprecated void removeSessionCookie();
-    method public void removeSessionCookies(android.webkit.ValueCallback<java.lang.Boolean>);
-    method public synchronized void setAcceptCookie(boolean);
+    method public abstract boolean hasCookies();
+    method public abstract deprecated void removeAllCookie();
+    method public abstract void removeAllCookies(android.webkit.ValueCallback<java.lang.Boolean>);
+    method public abstract deprecated void removeExpiredCookie();
+    method public abstract deprecated void removeSessionCookie();
+    method public abstract void removeSessionCookies(android.webkit.ValueCallback<java.lang.Boolean>);
+    method public abstract void setAcceptCookie(boolean);
     method public static void setAcceptFileSchemeCookies(boolean);
-    method public void setAcceptThirdPartyCookies(android.webkit.WebView, boolean);
-    method public void setCookie(java.lang.String, java.lang.String);
-    method public void setCookie(java.lang.String, java.lang.String, android.webkit.ValueCallback<java.lang.Boolean>);
+    method public abstract void setAcceptThirdPartyCookies(android.webkit.WebView, boolean);
+    method public abstract void setCookie(java.lang.String, java.lang.String);
+    method public abstract void setCookie(java.lang.String, java.lang.String, android.webkit.ValueCallback<java.lang.Boolean>);
   }
 
   public final deprecated class CookieSyncManager extends android.webkit.WebSyncManager {
@@ -35929,11 +35930,13 @@
     method public abstract void onReceiveValue(T);
   }
 
-  public class WebBackForwardList implements java.lang.Cloneable java.io.Serializable {
-    method public synchronized int getCurrentIndex();
-    method public synchronized android.webkit.WebHistoryItem getCurrentItem();
-    method public synchronized android.webkit.WebHistoryItem getItemAtIndex(int);
-    method public synchronized int getSize();
+  public abstract class WebBackForwardList implements java.lang.Cloneable java.io.Serializable {
+    ctor public WebBackForwardList();
+    method protected abstract android.webkit.WebBackForwardList clone();
+    method public abstract int getCurrentIndex();
+    method public abstract android.webkit.WebHistoryItem getCurrentItem();
+    method public abstract android.webkit.WebHistoryItem getItemAtIndex(int);
+    method public abstract int getSize();
   }
 
   public class WebChromeClient {
@@ -35985,21 +35988,24 @@
     field public static final int MODE_SAVE = 3; // 0x3
   }
 
-  public class WebHistoryItem implements java.lang.Cloneable {
-    method public android.graphics.Bitmap getFavicon();
-    method public java.lang.String getOriginalUrl();
-    method public java.lang.String getTitle();
-    method public java.lang.String getUrl();
+  public abstract class WebHistoryItem implements java.lang.Cloneable {
+    ctor public WebHistoryItem();
+    method protected abstract android.webkit.WebHistoryItem clone();
+    method public abstract android.graphics.Bitmap getFavicon();
+    method public abstract java.lang.String getOriginalUrl();
+    method public abstract java.lang.String getTitle();
+    method public abstract java.lang.String getUrl();
   }
 
-  public deprecated class WebIconDatabase {
-    method public void close();
+  public abstract deprecated class WebIconDatabase {
+    ctor public WebIconDatabase();
+    method public abstract void close();
     method public static android.webkit.WebIconDatabase getInstance();
-    method public void open(java.lang.String);
-    method public void releaseIconForPageUrl(java.lang.String);
-    method public void removeAllIcons();
-    method public void requestIconForPageUrl(java.lang.String, android.webkit.WebIconDatabase.IconListener);
-    method public void retainIconForPageUrl(java.lang.String);
+    method public abstract void open(java.lang.String);
+    method public abstract void releaseIconForPageUrl(java.lang.String);
+    method public abstract void removeAllIcons();
+    method public abstract void requestIconForPageUrl(java.lang.String, android.webkit.WebIconDatabase.IconListener);
+    method public abstract void retainIconForPageUrl(java.lang.String);
   }
 
   public static abstract deprecated interface WebIconDatabase.IconListener {
@@ -36031,98 +36037,99 @@
   }
 
   public abstract class WebSettings {
-    method public deprecated boolean enableSmoothTransition();
-    method public boolean getAllowContentAccess();
-    method public boolean getAllowFileAccess();
+    ctor public WebSettings();
+    method public abstract deprecated boolean enableSmoothTransition();
+    method public abstract boolean getAllowContentAccess();
+    method public abstract boolean getAllowFileAccess();
     method public abstract boolean getAllowFileAccessFromFileURLs();
     method public abstract boolean getAllowUniversalAccessFromFileURLs();
-    method public synchronized boolean getBlockNetworkImage();
-    method public synchronized boolean getBlockNetworkLoads();
-    method public boolean getBuiltInZoomControls();
-    method public int getCacheMode();
-    method public synchronized java.lang.String getCursiveFontFamily();
-    method public synchronized boolean getDatabaseEnabled();
-    method public deprecated synchronized java.lang.String getDatabasePath();
-    method public synchronized int getDefaultFixedFontSize();
-    method public synchronized int getDefaultFontSize();
-    method public synchronized java.lang.String getDefaultTextEncodingName();
+    method public abstract boolean getBlockNetworkImage();
+    method public abstract boolean getBlockNetworkLoads();
+    method public abstract boolean getBuiltInZoomControls();
+    method public abstract int getCacheMode();
+    method public abstract java.lang.String getCursiveFontFamily();
+    method public abstract boolean getDatabaseEnabled();
+    method public abstract deprecated java.lang.String getDatabasePath();
+    method public abstract int getDefaultFixedFontSize();
+    method public abstract int getDefaultFontSize();
+    method public abstract java.lang.String getDefaultTextEncodingName();
     method public static java.lang.String getDefaultUserAgent(android.content.Context);
-    method public deprecated android.webkit.WebSettings.ZoomDensity getDefaultZoom();
-    method public boolean getDisplayZoomControls();
-    method public synchronized boolean getDomStorageEnabled();
-    method public synchronized java.lang.String getFantasyFontFamily();
-    method public synchronized java.lang.String getFixedFontFamily();
-    method public synchronized boolean getJavaScriptCanOpenWindowsAutomatically();
-    method public synchronized boolean getJavaScriptEnabled();
-    method public synchronized android.webkit.WebSettings.LayoutAlgorithm getLayoutAlgorithm();
-    method public deprecated boolean getLightTouchEnabled();
-    method public boolean getLoadWithOverviewMode();
-    method public synchronized boolean getLoadsImagesAutomatically();
-    method public boolean getMediaPlaybackRequiresUserGesture();
-    method public synchronized int getMinimumFontSize();
-    method public synchronized int getMinimumLogicalFontSize();
+    method public abstract deprecated android.webkit.WebSettings.ZoomDensity getDefaultZoom();
+    method public abstract boolean getDisplayZoomControls();
+    method public abstract boolean getDomStorageEnabled();
+    method public abstract java.lang.String getFantasyFontFamily();
+    method public abstract java.lang.String getFixedFontFamily();
+    method public abstract boolean getJavaScriptCanOpenWindowsAutomatically();
+    method public abstract boolean getJavaScriptEnabled();
+    method public abstract android.webkit.WebSettings.LayoutAlgorithm getLayoutAlgorithm();
+    method public abstract deprecated boolean getLightTouchEnabled();
+    method public abstract boolean getLoadWithOverviewMode();
+    method public abstract boolean getLoadsImagesAutomatically();
+    method public abstract boolean getMediaPlaybackRequiresUserGesture();
+    method public abstract int getMinimumFontSize();
+    method public abstract int getMinimumLogicalFontSize();
     method public abstract int getMixedContentMode();
-    method public deprecated synchronized android.webkit.WebSettings.PluginState getPluginState();
-    method public synchronized java.lang.String getSansSerifFontFamily();
-    method public boolean getSaveFormData();
-    method public deprecated boolean getSavePassword();
-    method public synchronized java.lang.String getSerifFontFamily();
-    method public synchronized java.lang.String getStandardFontFamily();
+    method public abstract deprecated android.webkit.WebSettings.PluginState getPluginState();
+    method public abstract java.lang.String getSansSerifFontFamily();
+    method public abstract boolean getSaveFormData();
+    method public abstract deprecated boolean getSavePassword();
+    method public abstract java.lang.String getSerifFontFamily();
+    method public abstract java.lang.String getStandardFontFamily();
     method public deprecated synchronized android.webkit.WebSettings.TextSize getTextSize();
-    method public synchronized int getTextZoom();
-    method public synchronized boolean getUseWideViewPort();
-    method public synchronized java.lang.String getUserAgentString();
-    method public void setAllowContentAccess(boolean);
-    method public void setAllowFileAccess(boolean);
+    method public abstract int getTextZoom();
+    method public abstract boolean getUseWideViewPort();
+    method public abstract java.lang.String getUserAgentString();
+    method public abstract void setAllowContentAccess(boolean);
+    method public abstract void setAllowFileAccess(boolean);
     method public abstract void setAllowFileAccessFromFileURLs(boolean);
     method public abstract void setAllowUniversalAccessFromFileURLs(boolean);
-    method public synchronized void setAppCacheEnabled(boolean);
-    method public deprecated synchronized void setAppCacheMaxSize(long);
-    method public synchronized void setAppCachePath(java.lang.String);
-    method public synchronized void setBlockNetworkImage(boolean);
-    method public synchronized void setBlockNetworkLoads(boolean);
-    method public void setBuiltInZoomControls(boolean);
-    method public void setCacheMode(int);
-    method public synchronized void setCursiveFontFamily(java.lang.String);
-    method public synchronized void setDatabaseEnabled(boolean);
-    method public deprecated synchronized void setDatabasePath(java.lang.String);
-    method public synchronized void setDefaultFixedFontSize(int);
-    method public synchronized void setDefaultFontSize(int);
-    method public synchronized void setDefaultTextEncodingName(java.lang.String);
-    method public deprecated void setDefaultZoom(android.webkit.WebSettings.ZoomDensity);
-    method public void setDisplayZoomControls(boolean);
-    method public synchronized void setDomStorageEnabled(boolean);
-    method public deprecated void setEnableSmoothTransition(boolean);
-    method public synchronized void setFantasyFontFamily(java.lang.String);
-    method public synchronized void setFixedFontFamily(java.lang.String);
-    method public synchronized void setGeolocationDatabasePath(java.lang.String);
-    method public synchronized void setGeolocationEnabled(boolean);
-    method public synchronized void setJavaScriptCanOpenWindowsAutomatically(boolean);
-    method public synchronized void setJavaScriptEnabled(boolean);
-    method public synchronized void setLayoutAlgorithm(android.webkit.WebSettings.LayoutAlgorithm);
-    method public deprecated void setLightTouchEnabled(boolean);
-    method public void setLoadWithOverviewMode(boolean);
-    method public synchronized void setLoadsImagesAutomatically(boolean);
-    method public void setMediaPlaybackRequiresUserGesture(boolean);
-    method public synchronized void setMinimumFontSize(int);
-    method public synchronized void setMinimumLogicalFontSize(int);
+    method public abstract void setAppCacheEnabled(boolean);
+    method public abstract deprecated void setAppCacheMaxSize(long);
+    method public abstract void setAppCachePath(java.lang.String);
+    method public abstract void setBlockNetworkImage(boolean);
+    method public abstract void setBlockNetworkLoads(boolean);
+    method public abstract void setBuiltInZoomControls(boolean);
+    method public abstract void setCacheMode(int);
+    method public abstract void setCursiveFontFamily(java.lang.String);
+    method public abstract void setDatabaseEnabled(boolean);
+    method public abstract deprecated void setDatabasePath(java.lang.String);
+    method public abstract void setDefaultFixedFontSize(int);
+    method public abstract void setDefaultFontSize(int);
+    method public abstract void setDefaultTextEncodingName(java.lang.String);
+    method public abstract deprecated void setDefaultZoom(android.webkit.WebSettings.ZoomDensity);
+    method public abstract void setDisplayZoomControls(boolean);
+    method public abstract void setDomStorageEnabled(boolean);
+    method public abstract deprecated void setEnableSmoothTransition(boolean);
+    method public abstract void setFantasyFontFamily(java.lang.String);
+    method public abstract void setFixedFontFamily(java.lang.String);
+    method public abstract void setGeolocationDatabasePath(java.lang.String);
+    method public abstract void setGeolocationEnabled(boolean);
+    method public abstract void setJavaScriptCanOpenWindowsAutomatically(boolean);
+    method public abstract void setJavaScriptEnabled(boolean);
+    method public abstract void setLayoutAlgorithm(android.webkit.WebSettings.LayoutAlgorithm);
+    method public abstract deprecated void setLightTouchEnabled(boolean);
+    method public abstract void setLoadWithOverviewMode(boolean);
+    method public abstract void setLoadsImagesAutomatically(boolean);
+    method public abstract void setMediaPlaybackRequiresUserGesture(boolean);
+    method public abstract void setMinimumFontSize(int);
+    method public abstract void setMinimumLogicalFontSize(int);
     method public abstract void setMixedContentMode(int);
-    method public void setNeedInitialFocus(boolean);
-    method public deprecated synchronized void setPluginState(android.webkit.WebSettings.PluginState);
-    method public deprecated synchronized void setRenderPriority(android.webkit.WebSettings.RenderPriority);
-    method public synchronized void setSansSerifFontFamily(java.lang.String);
-    method public void setSaveFormData(boolean);
-    method public deprecated void setSavePassword(boolean);
-    method public synchronized void setSerifFontFamily(java.lang.String);
-    method public synchronized void setStandardFontFamily(java.lang.String);
-    method public synchronized void setSupportMultipleWindows(boolean);
-    method public void setSupportZoom(boolean);
+    method public abstract void setNeedInitialFocus(boolean);
+    method public abstract deprecated void setPluginState(android.webkit.WebSettings.PluginState);
+    method public abstract deprecated void setRenderPriority(android.webkit.WebSettings.RenderPriority);
+    method public abstract void setSansSerifFontFamily(java.lang.String);
+    method public abstract void setSaveFormData(boolean);
+    method public abstract deprecated void setSavePassword(boolean);
+    method public abstract void setSerifFontFamily(java.lang.String);
+    method public abstract void setStandardFontFamily(java.lang.String);
+    method public abstract void setSupportMultipleWindows(boolean);
+    method public abstract void setSupportZoom(boolean);
     method public deprecated synchronized void setTextSize(android.webkit.WebSettings.TextSize);
-    method public synchronized void setTextZoom(int);
-    method public synchronized void setUseWideViewPort(boolean);
-    method public synchronized void setUserAgentString(java.lang.String);
-    method public synchronized boolean supportMultipleWindows();
-    method public boolean supportZoom();
+    method public abstract void setTextZoom(int);
+    method public abstract void setUseWideViewPort(boolean);
+    method public abstract void setUserAgentString(java.lang.String);
+    method public abstract boolean supportMultipleWindows();
+    method public abstract boolean supportZoom();
     field public static final int LOAD_CACHE_ELSE_NETWORK = 1; // 0x1
     field public static final int LOAD_CACHE_ONLY = 3; // 0x3
     field public static final int LOAD_DEFAULT = -1; // 0xffffffff
@@ -36372,14 +36379,15 @@
     field public static final int ERROR_UNSUPPORTED_SCHEME = -10; // 0xfffffff6
   }
 
-  public class WebViewDatabase {
-    method public void clearFormData();
-    method public void clearHttpAuthUsernamePassword();
-    method public deprecated void clearUsernamePassword();
+  public abstract class WebViewDatabase {
+    ctor public WebViewDatabase();
+    method public abstract void clearFormData();
+    method public abstract void clearHttpAuthUsernamePassword();
+    method public abstract deprecated void clearUsernamePassword();
     method public static android.webkit.WebViewDatabase getInstance(android.content.Context);
-    method public boolean hasFormData();
-    method public boolean hasHttpAuthUsernamePassword();
-    method public deprecated boolean hasUsernamePassword();
+    method public abstract boolean hasFormData();
+    method public abstract boolean hasHttpAuthUsernamePassword();
+    method public abstract deprecated boolean hasUsernamePassword();
   }
 
   public class WebViewFragment extends android.app.Fragment {
diff --git a/cmds/app_process/app_main.cpp b/cmds/app_process/app_main.cpp
index fbdbb25..c86fd53 100644
--- a/cmds/app_process/app_main.cpp
+++ b/cmds/app_process/app_main.cpp
@@ -146,8 +146,10 @@
     static const char kInstructionSet[] = "arm";
 #elif defined(__i386__)
     static const char kInstructionSet[] = "x86";
-#elif defined (__mips__)
+#elif defined (__mips__) && !defined(__LP64__)
     static const char kInstructionSet[] = "mips";
+#elif defined (__mips__) && defined(__LP64__)
+    static const char kInstructionSet[] = "mips64";
 #else
 #error "Unknown instruction set"
 #endif
diff --git a/cmds/bootanimation/AudioPlayer.cpp b/cmds/bootanimation/AudioPlayer.cpp
index 459190f..81fe5f8 100644
--- a/cmds/bootanimation/AudioPlayer.cpp
+++ b/cmds/bootanimation/AudioPlayer.cpp
@@ -98,16 +98,16 @@
                         ALOGE("mixer_ctl_set_value failed for %s %d", name, intValue);
                     }
                 } else {
-                    ALOGE("Could not parse %s as int for %d", intValue, name);
+                    ALOGE("Could not parse %s as int for %s", values, name);
                 }
                 break;
             case MIXER_CTL_TYPE_ENUM:
                 if (sscanf(values, "%s", stringValue) == 1) {
                     if (mixer_ctl_set_enum_by_string(ctl, stringValue) != 0) {
-                        ALOGE("mixer_ctl_set_enum_by_string failed for %s %%s", name, stringValue);
+                        ALOGE("mixer_ctl_set_enum_by_string failed for %s %s", name, stringValue);
                     }
                 } else {
-                    ALOGE("Could not parse %s as enum for %d", stringValue, name);
+                    ALOGE("Could not parse %s as enum for %s", values, name);
                 }
                 break;
             default:
@@ -193,7 +193,7 @@
     return false;
 }
 
-void AudioPlayer::playFile(struct FileMap* fileMap) {
+void AudioPlayer::playFile(FileMap* fileMap) {
     // stop any currently playing sound
     requestExitAndWait();
 
diff --git a/cmds/bootanimation/AudioPlayer.h b/cmds/bootanimation/AudioPlayer.h
index 7e82a07..1def0ae 100644
--- a/cmds/bootanimation/AudioPlayer.h
+++ b/cmds/bootanimation/AudioPlayer.h
@@ -18,6 +18,7 @@
 #define _BOOTANIMATION_AUDIOPLAYER_H
 
 #include <utils/Thread.h>
+#include <utils/FileMap.h>
 
 namespace android {
 
@@ -28,7 +29,7 @@
     virtual     ~AudioPlayer();
     bool        init(const char* config);
 
-    void        playFile(struct FileMap* fileMap);
+    void        playFile(FileMap* fileMap);
 
 private:
     virtual bool        threadLoop();
@@ -39,7 +40,7 @@
     int                 mPeriodSize;
     int                 mPeriodCount;
 
-    struct FileMap*     mCurrentFile;
+    FileMap*            mCurrentFile;
 };
 
 } // namespace android
diff --git a/cmds/idmap/scan.cpp b/cmds/idmap/scan.cpp
index 4f19a74..bbe6eef2 100644
--- a/cmds/idmap/scan.cpp
+++ b/cmds/idmap/scan.cpp
@@ -73,7 +73,7 @@
             size_t len;
             String16 key(parser.getAttributeName(i, &len));
             if (key == String16("targetPackage")) {
-                const uint16_t *p = parser.getAttributeStringValue(i, &len);
+                const char16_t *p = parser.getAttributeStringValue(i, &len);
                 if (p != NULL) {
                     target = String16(p, len);
                 }
@@ -146,13 +146,13 @@
         }
         char *buf = new char[uncompLen];
         if (NULL == buf) {
-            ALOGW("%s: failed to allocate %d byte\n", __FUNCTION__, uncompLen);
+            ALOGW("%s: failed to allocate %zd byte\n", __FUNCTION__, uncompLen);
             dataMap->release();
             return -1;
         }
         StreamingZipInflater inflater(dataMap, uncompLen);
         if (inflater.read(buf, uncompLen) < 0) {
-            ALOGW("%s: failed to inflate %d byte\n", __FUNCTION__, uncompLen);
+            ALOGW("%s: failed to inflate %zd byte\n", __FUNCTION__, uncompLen);
             delete[] buf;
             dataMap->release();
             return -1;
diff --git a/cmds/pm/src/com/android/commands/pm/Pm.java b/cmds/pm/src/com/android/commands/pm/Pm.java
index 5e9d8f7..5249065 100644
--- a/cmds/pm/src/com/android/commands/pm/Pm.java
+++ b/cmds/pm/src/com/android/commands/pm/Pm.java
@@ -563,7 +563,10 @@
         if (res != 0) {
             Resources r = getResources(pii);
             if (r != null) {
-                return r.getString(res);
+                try {
+                    return r.getString(res);
+                } catch (Resources.NotFoundException e) {
+                }
             }
         }
         return null;
diff --git a/core/java/android/app/ActivityThread.java b/core/java/android/app/ActivityThread.java
index 17a31f3..6233676 100644
--- a/core/java/android/app/ActivityThread.java
+++ b/core/java/android/app/ActivityThread.java
@@ -4161,22 +4161,24 @@
     final void handleDispatchPackageBroadcast(int cmd, String[] packages) {
         boolean hasPkgInfo = false;
         if (packages != null) {
-            for (int i=packages.length-1; i>=0; i--) {
-                //Slog.i(TAG, "Cleaning old package: " + packages[i]);
-                if (!hasPkgInfo) {
-                    WeakReference<LoadedApk> ref;
-                    ref = mPackages.get(packages[i]);
-                    if (ref != null && ref.get() != null) {
-                        hasPkgInfo = true;
-                    } else {
-                        ref = mResourcePackages.get(packages[i]);
+            synchronized (mResourcesManager) {
+                for (int i=packages.length-1; i>=0; i--) {
+                    //Slog.i(TAG, "Cleaning old package: " + packages[i]);
+                    if (!hasPkgInfo) {
+                        WeakReference<LoadedApk> ref;
+                        ref = mPackages.get(packages[i]);
                         if (ref != null && ref.get() != null) {
                             hasPkgInfo = true;
+                        } else {
+                            ref = mResourcePackages.get(packages[i]);
+                            if (ref != null && ref.get() != null) {
+                                hasPkgInfo = true;
+                            }
                         }
                     }
+                    mPackages.remove(packages[i]);
+                    mResourcePackages.remove(packages[i]);
                 }
-                mPackages.remove(packages[i]);
-                mResourcePackages.remove(packages[i]);
             }
         }
         ApplicationPackageManager.handlePackageBroadcast(cmd, packages,
diff --git a/core/java/android/app/ApplicationErrorReport.java b/core/java/android/app/ApplicationErrorReport.java
index 49ab7c1..6c2511e 100644
--- a/core/java/android/app/ApplicationErrorReport.java
+++ b/core/java/android/app/ApplicationErrorReport.java
@@ -168,10 +168,20 @@
         PackageManager pm = context.getPackageManager();
 
         // look for receiver in the installer package
-        String candidate = pm.getInstallerPackageName(packageName);
-        ComponentName result = getErrorReportReceiver(pm, packageName, candidate);
-        if (result != null) {
-            return result;
+        String candidate = null;
+        ComponentName result = null;
+
+        try {
+            candidate = pm.getInstallerPackageName(packageName);
+        } catch (IllegalArgumentException e) {
+            // the package could already removed
+        }
+
+        if (candidate != null) {
+            result = getErrorReportReceiver(pm, packageName, candidate);
+            if (result != null) {
+                return result;
+            }
         }
 
         // if the error app is on the system image, look for system apps
diff --git a/core/java/android/app/Notification.java b/core/java/android/app/Notification.java
index fb10e17..a363503 100644
--- a/core/java/android/app/Notification.java
+++ b/core/java/android/app/Notification.java
@@ -1646,6 +1646,7 @@
         builder.setSound(this.sound, this.audioStreamType);
         builder.setDefaults(this.defaults);
         builder.setVibrate(this.vibrate);
+        builder.setDeleteIntent(this.deleteIntent);
 
         // now apply the latestEventInfo fields
         if (contentTitle != null) {
diff --git a/core/java/android/app/backup/BackupAgent.java b/core/java/android/app/backup/BackupAgent.java
index 87d785a..1b1e600 100644
--- a/core/java/android/app/backup/BackupAgent.java
+++ b/core/java/android/app/backup/BackupAgent.java
@@ -105,7 +105,7 @@
  */
 public abstract class BackupAgent extends ContextWrapper {
     private static final String TAG = "BackupAgent";
-    private static final boolean DEBUG = true;
+    private static final boolean DEBUG = false;
 
     /** @hide */
     public static final int TYPE_EOF = 0;
diff --git a/core/java/android/bluetooth/BluetoothA2dp.java b/core/java/android/bluetooth/BluetoothA2dp.java
index 5175490..0450150 100644
--- a/core/java/android/bluetooth/BluetoothA2dp.java
+++ b/core/java/android/bluetooth/BluetoothA2dp.java
@@ -199,7 +199,8 @@
     }
 
     public void finalize() {
-        close();
+        // The empty finalize needs to be kept or the
+        // cts signature tests would fail.
     }
     /**
      * Initiate connection to a profile of the remote bluetooth device.
diff --git a/core/java/android/content/res/AssetManager.java b/core/java/android/content/res/AssetManager.java
index e578822..72f24d3 100644
--- a/core/java/android/content/res/AssetManager.java
+++ b/core/java/android/content/res/AssetManager.java
@@ -627,7 +627,21 @@
      *
      * {@hide}
      */
-    public native final int addOverlayPath(String idmapPath);
+
+    public final int addOverlayPath(String idmapPath) {
+        synchronized (this) {
+            int res = addOverlayPathNative(idmapPath);
+            makeStringBlocks(mStringBlocks);
+            return res;
+        }
+    }
+
+    /**
+     * See addOverlayPath.
+     *
+     * {@hide}
+     */
+    public native final int addOverlayPathNative(String idmapPath);
 
     /**
      * Add multiple sets of assets to the asset manager at once.  See
diff --git a/core/java/android/content/res/StringBlock.java b/core/java/android/content/res/StringBlock.java
index 77b8a33..9652db7 100644
--- a/core/java/android/content/res/StringBlock.java
+++ b/core/java/android/content/res/StringBlock.java
@@ -311,13 +311,13 @@
      * the color black is returned instead.
      *
      * @param color The color as a string. Can be a resource reference,
-     *              HTML hexadecimal, octal or a name
+     *              hexadecimal, octal or a name
      * @param foreground True if the color will be used as the foreground color,
      *                   false otherwise
      *
      * @return A CharacterStyle
      *
-     * @see Color#getHtmlColor(String)
+     * @see Color#parseColor(String)
      */
     private static CharacterStyle getColor(String color, boolean foreground) {
         int c = 0xff000000;
@@ -336,7 +336,11 @@
                     }
                 }
             } else {
-                c = Color.getHtmlColor(color);
+                try {
+                    c = Color.parseColor(color);
+                } catch (IllegalArgumentException e) {
+                    c = Color.BLACK;
+                }
             }
         }
 
diff --git a/core/java/android/net/LocalServerSocket.java b/core/java/android/net/LocalServerSocket.java
index a36203b..9464222 100644
--- a/core/java/android/net/LocalServerSocket.java
+++ b/core/java/android/net/LocalServerSocket.java
@@ -20,12 +20,8 @@
 import java.io.FileDescriptor;
 
 /**
- * non-standard class for creating inbound UNIX-domain socket
- * on the Android platform, this is created in the Linux non-filesystem
- * namespace.
- *
- * On simulator platforms, this may be created in a temporary directory on
- * the filesystem
+ * Non-standard class for creating an inbound UNIX-domain socket
+ * in the Linux abstract namespace.
  */
 public class LocalServerSocket {
     private final LocalSocketImpl impl;
@@ -35,7 +31,7 @@
     private static final int LISTEN_BACKLOG = 50;
 
     /**
-     * Crewates a new server socket listening at specified name.
+     * Creates a new server socket listening at specified name.
      * On the Android platform, the name is created in the Linux
      * abstract namespace (instead of on the filesystem).
      * 
diff --git a/core/java/android/net/WebAddress.java b/core/java/android/net/WebAddress.java
index 8126b75..24d4eb8 100644
--- a/core/java/android/net/WebAddress.java
+++ b/core/java/android/net/WebAddress.java
@@ -18,6 +18,8 @@
 
 import static android.util.Patterns.GOOD_IRI_CHAR;
 
+import android.annotation.SystemApi;
+
 import java.util.Locale;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
@@ -38,6 +40,9 @@
  * If given an https scheme but no port, fills in port
  *
  */
+// TODO(igsolla): remove WebAddress from the system SDK once the WebView apk does not
+// longer need to be binary compatible with the API 21 version of the framework.
+@SystemApi
 public class WebAddress {
 
     private String mScheme;
@@ -136,42 +141,52 @@
         return mScheme + "://" + authInfo + mHost + port + mPath;
     }
 
+    /** {@hide} */
     public void setScheme(String scheme) {
       mScheme = scheme;
     }
 
+    /** {@hide} */
     public String getScheme() {
       return mScheme;
     }
 
+    /** {@hide} */
     public void setHost(String host) {
       mHost = host;
     }
 
+    /** {@hide} */
     public String getHost() {
       return mHost;
     }
 
+    /** {@hide} */
     public void setPort(int port) {
       mPort = port;
     }
 
+    /** {@hide} */
     public int getPort() {
       return mPort;
     }
 
+    /** {@hide} */
     public void setPath(String path) {
       mPath = path;
     }
 
+    /** {@hide} */
     public String getPath() {
       return mPath;
     }
 
+    /** {@hide} */
     public void setAuthInfo(String authInfo) {
       mAuthInfo = authInfo;
     }
 
+    /** {@hide} */
     public String getAuthInfo() {
       return mAuthInfo;
     }
diff --git a/core/java/android/net/http/CharArrayBuffers.java b/core/java/android/net/http/CharArrayBuffers.java
deleted file mode 100644
index 77d45f6..0000000
--- a/core/java/android/net/http/CharArrayBuffers.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Copyright (C) 2008 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.
- */
-
-package android.net.http;
-
-import org.apache.http.util.CharArrayBuffer;
-import org.apache.http.protocol.HTTP;
-
-/**
- * Utility methods for working on CharArrayBuffers.
- * 
- * {@hide}
- */
-class CharArrayBuffers {
-
-    static final char uppercaseAddon = 'a' - 'A';
-
-    /**
-     * Returns true if the buffer contains the given string. Ignores leading
-     * whitespace and case.
-     *
-     * @param buffer to search
-     * @param beginIndex index at which we should start
-     * @param str to search for
-     */
-    static boolean containsIgnoreCaseTrimmed(CharArrayBuffer buffer,
-            int beginIndex, final String str) {
-        int len = buffer.length();
-        char[] chars = buffer.buffer();
-        while (beginIndex < len && HTTP.isWhitespace(chars[beginIndex])) {
-            beginIndex++;
-        }
-        int size = str.length();
-        boolean ok = len >= beginIndex + size;
-        for (int j=0; ok && (j<size); j++) {
-            char a = chars[beginIndex+j];
-            char b = str.charAt(j);
-            if (a != b) {
-                a = toLower(a);
-                b = toLower(b);
-                ok = a == b;
-            }
-        }
-        return ok;
-    }
-
-    /**
-     * Returns index of first occurence ch. Lower cases characters leading up
-     * to first occurrence of ch.
-     */
-    static int setLowercaseIndexOf(CharArrayBuffer buffer, final int ch) {
-
-        int beginIndex = 0;
-        int endIndex = buffer.length();
-        char[] chars = buffer.buffer();
-
-        for (int i = beginIndex; i < endIndex; i++) {
-            char current = chars[i];
-            if (current == ch) {
-                return i;
-            } else if (current >= 'A' && current <= 'Z'){
-                // make lower case
-                current += uppercaseAddon;
-                chars[i] = current;
-            }
-        }
-        return -1;
-    }
-
-    private static char toLower(char c) {
-        if (c >= 'A' && c <= 'Z'){
-            c += uppercaseAddon;
-        }
-        return c;
-    }
-}
diff --git a/core/java/android/net/http/Connection.java b/core/java/android/net/http/Connection.java
index 834ad69..831bd0e 100644
--- a/core/java/android/net/http/Connection.java
+++ b/core/java/android/net/http/Connection.java
@@ -436,7 +436,7 @@
             ret = false;
             String error;
             if (errorId < 0) {
-                error = ErrorStrings.getString(errorId, mContext);
+                error = getEventHandlerErrorString(errorId);
             } else {
                 Throwable cause = e.getCause();
                 error = cause != null ? cause.toString() : e.getMessage();
@@ -451,6 +451,61 @@
         return ret;
     }
 
+    private static String getEventHandlerErrorString(int errorId) {
+        switch (errorId) {
+            case EventHandler.OK:
+                return "OK";
+
+            case EventHandler.ERROR:
+                return "ERROR";
+
+            case EventHandler.ERROR_LOOKUP:
+                return "ERROR_LOOKUP";
+
+            case EventHandler.ERROR_UNSUPPORTED_AUTH_SCHEME:
+                return "ERROR_UNSUPPORTED_AUTH_SCHEME";
+
+            case EventHandler.ERROR_AUTH:
+                return "ERROR_AUTH";
+
+            case EventHandler.ERROR_PROXYAUTH:
+                return "ERROR_PROXYAUTH";
+
+            case EventHandler.ERROR_CONNECT:
+                return "ERROR_CONNECT";
+
+            case EventHandler.ERROR_IO:
+                return "ERROR_IO";
+
+            case EventHandler.ERROR_TIMEOUT:
+                return "ERROR_TIMEOUT";
+
+            case EventHandler.ERROR_REDIRECT_LOOP:
+                return "ERROR_REDIRECT_LOOP";
+
+            case EventHandler.ERROR_UNSUPPORTED_SCHEME:
+                return "ERROR_UNSUPPORTED_SCHEME";
+
+            case EventHandler.ERROR_FAILED_SSL_HANDSHAKE:
+                return "ERROR_FAILED_SSL_HANDSHAKE";
+
+            case EventHandler.ERROR_BAD_URL:
+                return "ERROR_BAD_URL";
+
+            case EventHandler.FILE_ERROR:
+                return "FILE_ERROR";
+
+            case EventHandler.FILE_NOT_FOUND_ERROR:
+                return "FILE_NOT_FOUND_ERROR";
+
+            case EventHandler.TOO_MANY_REQUESTS_ERROR:
+                return "TOO_MANY_REQUESTS_ERROR";
+
+            default:
+                return "UNKNOWN_ERROR";
+        }
+    }
+
     HttpContext getHttpContext() {
         return mHttpContext;
     }
diff --git a/core/java/android/net/http/Headers.java b/core/java/android/net/http/Headers.java
index 657e071..0f8b105 100644
--- a/core/java/android/net/http/Headers.java
+++ b/core/java/android/net/http/Headers.java
@@ -158,7 +158,7 @@
     }
 
     public void parseHeader(CharArrayBuffer buffer) {
-        int pos = CharArrayBuffers.setLowercaseIndexOf(buffer, ':');
+        int pos = setLowercaseIndexOf(buffer, ':');
         if (pos == -1) {
             return;
         }
@@ -459,12 +459,63 @@
     }
 
     private void setConnectionType(CharArrayBuffer buffer, int pos) {
-        if (CharArrayBuffers.containsIgnoreCaseTrimmed(
-                buffer, pos, HTTP.CONN_CLOSE)) {
+        if (containsIgnoreCaseTrimmed(buffer, pos, HTTP.CONN_CLOSE)) {
             connectionType = CONN_CLOSE;
-        } else if (CharArrayBuffers.containsIgnoreCaseTrimmed(
+        } else if (containsIgnoreCaseTrimmed(
                 buffer, pos, HTTP.CONN_KEEP_ALIVE)) {
             connectionType = CONN_KEEP_ALIVE;
         }
     }
+
+
+    /**
+     * Returns true if the buffer contains the given string. Ignores leading
+     * whitespace and case.
+     *
+     * @param buffer to search
+     * @param beginIndex index at which we should start
+     * @param str to search for
+     */
+    static boolean containsIgnoreCaseTrimmed(CharArrayBuffer buffer,
+            int beginIndex, final String str) {
+        int len = buffer.length();
+        char[] chars = buffer.buffer();
+        while (beginIndex < len && HTTP.isWhitespace(chars[beginIndex])) {
+            beginIndex++;
+        }
+        int size = str.length();
+        boolean ok = len >= (beginIndex + size);
+        for (int j=0; ok && (j < size); j++) {
+            char a = chars[beginIndex + j];
+            char b = str.charAt(j);
+            if (a != b) {
+                a = Character.toLowerCase(a);
+                b = Character.toLowerCase(b);
+                ok = a == b;
+            }
+        }
+
+        return true;
+    }
+
+    /**
+     * Returns index of first occurence ch. Lower cases characters leading up
+     * to first occurrence of ch.
+     */
+    static int setLowercaseIndexOf(CharArrayBuffer buffer, final int ch) {
+
+        int beginIndex = 0;
+        int endIndex = buffer.length();
+        char[] chars = buffer.buffer();
+
+        for (int i = beginIndex; i < endIndex; i++) {
+            char current = chars[i];
+            if (current == ch) {
+                return i;
+            } else {
+                chars[i] = Character.toLowerCase(current);
+            }
+        }
+        return -1;
+    }
 }
diff --git a/core/java/android/net/http/Timer.java b/core/java/android/net/http/Timer.java
deleted file mode 100644
index cc15a30..0000000
--- a/core/java/android/net/http/Timer.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (C) 2006 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.
- */
-
-package android.net.http;
-
-import android.os.SystemClock;
-
-/**
- * {@hide}
- * Debugging tool
- */
-class Timer {
-
-    private long mStart;
-    private long mLast;
-
-    public Timer() {
-        mStart = mLast = SystemClock.uptimeMillis();
-    }
-
-    public void mark(String message) {
-        long now = SystemClock.uptimeMillis();
-        if (HttpLog.LOGV) {
-            HttpLog.v(message + " " + (now - mLast) + " total " + (now - mStart));
-        }
-        mLast = now;
-    }
-}
diff --git a/core/java/android/net/http/X509TrustManagerExtensions.java b/core/java/android/net/http/X509TrustManagerExtensions.java
index 6a63a0c..bb36c20 100644
--- a/core/java/android/net/http/X509TrustManagerExtensions.java
+++ b/core/java/android/net/http/X509TrustManagerExtensions.java
@@ -36,7 +36,7 @@
  */
 public class X509TrustManagerExtensions {
 
-    TrustManagerImpl mDelegate;
+    final TrustManagerImpl mDelegate;
 
     /**
      * Constructs a new X509TrustManagerExtensions wrapper.
@@ -48,6 +48,7 @@
         if (tm instanceof TrustManagerImpl) {
             mDelegate = (TrustManagerImpl) tm;
         } else {
+            mDelegate = null;
             throw new IllegalArgumentException("tm is an instance of " + tm.getClass().getName() +
                     " which is not a supported type of X509TrustManager");
         }
diff --git a/core/java/android/nfc/tech/Ndef.java b/core/java/android/nfc/tech/Ndef.java
index 5852ce4..fdccaae 100644
--- a/core/java/android/nfc/tech/Ndef.java
+++ b/core/java/android/nfc/tech/Ndef.java
@@ -51,7 +51,7 @@
  * {@link Ndef} on NFC Forum Tag Types 1-4, and implement all NDEF operations
  * as defined in this class.
  *
- * <p>Some vendors have there own well defined specifications for storing NDEF data
+ * <p>Some vendors have their own well defined specifications for storing NDEF data
  * on tags that do not fall into the above categories. Android devices with NFC
  * should enumerate and implement {@link Ndef} under these vendor specifications
  * where possible, but it is not mandatory. {@link #getType} returns a String
diff --git a/core/java/android/os/Debug.java b/core/java/android/os/Debug.java
index 18730b6..9377def 100644
--- a/core/java/android/os/Debug.java
+++ b/core/java/android/os/Debug.java
@@ -104,7 +104,7 @@
 
     /**
      * This class is used to retrieved various statistics about the memory mappings for this
-     * process. The returns info broken down by dalvik, native, and other. All results are in kB.
+     * process. The returned info is broken down by dalvik, native, and other. All results are in kB.
      */
     public static class MemoryInfo implements Parcelable {
         /** The proportional set size for dalvik heap.  (Doesn't include other Dalvik overhead.) */
@@ -168,7 +168,7 @@
         public static final int NUM_OTHER_STATS = 16;
 
         /** @hide */
-        public static final int NUM_DVK_STATS = 5;
+        public static final int NUM_DVK_STATS = 8;
 
         /** @hide */
         public static final int NUM_CATEGORIES = 7;
@@ -313,6 +313,9 @@
                 case 18: return ".LinearAlloc";
                 case 19: return ".GC";
                 case 20: return ".JITCache";
+                case 21: return ".Zygote";
+                case 22: return ".NonMoving";
+                case 23: return ".IndirectRef";
                 default: return "????";
             }
         }
diff --git a/core/java/android/os/Process.java b/core/java/android/os/Process.java
index 3ada9bb..21a9904 100644
--- a/core/java/android/os/Process.java
+++ b/core/java/android/os/Process.java
@@ -689,6 +689,20 @@
     }
 
     /**
+     * Tries to establish a connection to the zygote that handles a given {@code abi}. Might block and retry if the
+     * zygote is unresponsive. This method is a no-op if a connection is already open.
+     *
+     * @hide
+     */
+    public static void establishZygoteConnectionForAbi(String abi) {
+        try {
+            openZygoteSocketIfNeeded(abi);
+        } catch (ZygoteStartFailedEx ex) {
+            throw new RuntimeException("Unable to connect to zygote for abi: " + abi, ex);
+        }
+    }
+
+    /**
      * Tries to open socket to Zygote process if not already open. If
      * already open, does nothing.  May block and retry.
      */
diff --git a/core/java/android/printservice/PrintService.java b/core/java/android/printservice/PrintService.java
index c5aee7b..ae95854 100644
--- a/core/java/android/printservice/PrintService.java
+++ b/core/java/android/printservice/PrintService.java
@@ -386,7 +386,7 @@
 
             @Override
             public void setClient(IPrintServiceClient client) {
-                mHandler.obtainMessage(ServiceHandler.MSG_SET_CLEINT, client)
+                mHandler.obtainMessage(ServiceHandler.MSG_SET_CLIENT, client)
                         .sendToTarget();
             }
 
@@ -414,7 +414,7 @@
         public static final int MSG_STOP_PRINTER_STATE_TRACKING = 7;
         public static final int MSG_ON_PRINTJOB_QUEUED = 8;
         public static final int MSG_ON_REQUEST_CANCEL_PRINTJOB = 9;
-        public static final int MSG_SET_CLEINT = 10;
+        public static final int MSG_SET_CLIENT = 10;
 
         public ServiceHandler(Looper looper) {
             super(looper, null, true);
@@ -528,9 +528,9 @@
                     onPrintJobQueued(new PrintJob(printJobInfo, mClient));
                 } break;
 
-                case MSG_SET_CLEINT: {
+                case MSG_SET_CLIENT: {
                     if (DEBUG) {
-                        Log.i(LOG_TAG, "MSG_SET_CLEINT "
+                        Log.i(LOG_TAG, "MSG_SET_CLIENT "
                                 + getPackageName());
                     }
                     mClient = (IPrintServiceClient) message.obj;
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index 79e84d9..d08758b 100644
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -6343,14 +6343,7 @@
         public static final String CALL_AUTO_RETRY = "call_auto_retry";
 
         /**
-         * The preferred network mode   7 = Global
-         *                              6 = EvDo only
-         *                              5 = CDMA w/o EvDo
-         *                              4 = CDMA / EvDo auto
-         *                              3 = GSM / WCDMA auto
-         *                              2 = WCDMA only
-         *                              1 = GSM only
-         *                              0 = GSM / WCDMA preferred
+         * See RIL_PreferredNetworkType in ril.h
          * @hide
          */
         public static final String PREFERRED_NETWORK_MODE =
diff --git a/core/java/android/text/format/DateFormat.java b/core/java/android/text/format/DateFormat.java
index d48f551..d515e21 100755
--- a/core/java/android/text/format/DateFormat.java
+++ b/core/java/android/text/format/DateFormat.java
@@ -221,68 +221,13 @@
 
     /**
      * Returns a {@link java.text.DateFormat} object that can format the date
-     * in short form (such as 12/31/1999) according
-     * to the current locale and the user's date-order preference.
+     * in short form according to the current locale.
+     *
      * @param context the application context
      * @return the {@link java.text.DateFormat} object that properly formats the date.
      */
     public static java.text.DateFormat getDateFormat(Context context) {
-        String value = Settings.System.getString(context.getContentResolver(),
-                Settings.System.DATE_FORMAT);
-
-        return getDateFormatForSetting(context, value);
-    }
-
-    /**
-     * Returns a {@link java.text.DateFormat} object to format the date
-     * as if the date format setting were set to <code>value</code>,
-     * including null to use the locale's default format.
-     * @param context the application context
-     * @param value the date format setting string to interpret for
-     *              the current locale
-     * @hide
-     */
-    public static java.text.DateFormat getDateFormatForSetting(Context context,
-                                                               String value) {
-        String format = getDateFormatStringForSetting(context, value);
-        return new java.text.SimpleDateFormat(format);
-    }
-
-    private static String getDateFormatStringForSetting(Context context, String value) {
-        if (value != null) {
-            int month = value.indexOf('M');
-            int day = value.indexOf('d');
-            int year = value.indexOf('y');
-
-            if (month >= 0 && day >= 0 && year >= 0) {
-                String template = context.getString(R.string.numeric_date_template);
-                if (year < month && year < day) {
-                    if (month < day) {
-                        value = String.format(template, "yyyy", "MM", "dd");
-                    } else {
-                        value = String.format(template, "yyyy", "dd", "MM");
-                    }
-                } else if (month < day) {
-                    if (day < year) {
-                        value = String.format(template, "MM", "dd", "yyyy");
-                    } else { // unlikely
-                        value = String.format(template, "MM", "yyyy", "dd");
-                    }
-                } else { // day < month
-                    if (month < year) {
-                        value = String.format(template, "dd", "MM", "yyyy");
-                    } else { // unlikely
-                        value = String.format(template, "dd", "yyyy", "MM");
-                    }
-                }
-
-                return value;
-            }
-        }
-
-        // The setting is not set; use the locale's default.
-        LocaleData d = LocaleData.get(context.getResources().getConfiguration().locale);
-        return d.shortDateFormat4;
+        return java.text.DateFormat.getDateInstance(java.text.DateFormat.SHORT);
     }
 
     /**
@@ -315,14 +260,16 @@
      * order returned here.
      */
     public static char[] getDateFormatOrder(Context context) {
-        return ICU.getDateFormatOrder(getDateFormatString(context));
+        return ICU.getDateFormatOrder(getDateFormatString());
     }
 
-    private static String getDateFormatString(Context context) {
-        String value = Settings.System.getString(context.getContentResolver(),
-                Settings.System.DATE_FORMAT);
+    private static String getDateFormatString() {
+        java.text.DateFormat df = java.text.DateFormat.getDateInstance(java.text.DateFormat.SHORT);
+        if (df instanceof SimpleDateFormat) {
+            return ((SimpleDateFormat) df).toPattern();
+        }
 
-        return getDateFormatStringForSetting(context, value);
+        throw new AssertionError("!(df instanceof SimpleDateFormat)");
     }
 
     /**
diff --git a/core/java/android/webkit/CookieManager.java b/core/java/android/webkit/CookieManager.java
index 20ef646..eca96f9 100644
--- a/core/java/android/webkit/CookieManager.java
+++ b/core/java/android/webkit/CookieManager.java
@@ -16,18 +16,14 @@
 
 package android.webkit;
 
+import android.annotation.SystemApi;
 import android.net.WebAddress;
 
 /**
  * Manages the cookies used by an application's {@link WebView} instances.
  * Cookies are manipulated according to RFC2109.
  */
-public class CookieManager {
-    /**
-     * @hide Only for use by WebViewProvider implementations
-     */
-    protected CookieManager() {
-    }
+public abstract class CookieManager {
 
     @Override
     protected Object clone() throws CloneNotSupportedException {
@@ -59,9 +55,7 @@
      * @param accept whether {@link WebView} instances should send and accept
      *               cookies
      */
-    public synchronized void setAcceptCookie(boolean accept) {
-        throw new MustOverrideException();
-    }
+    public abstract void setAcceptCookie(boolean accept);
 
     /**
      * Gets whether the application's {@link WebView} instances send and accept
@@ -69,9 +63,7 @@
      *
      * @return true if {@link WebView} instances send and accept cookies
      */
-    public synchronized boolean acceptCookie() {
-        throw new MustOverrideException();
-    }
+    public abstract boolean acceptCookie();
 
    /**
      * Sets whether the {@link WebView} should allow third party cookies to be set.
@@ -87,9 +79,7 @@
      * @param accept whether the {@link WebView} instance should accept
      *               third party cookies
      */
-    public void setAcceptThirdPartyCookies(WebView webview, boolean accept) {
-        throw new MustOverrideException();
-    }
+    public abstract void setAcceptThirdPartyCookies(WebView webview, boolean accept);
 
     /**
      * Gets whether the {@link WebView} should allow third party cookies to be set.
@@ -97,9 +87,7 @@
      * @param webview the {@link WebView} instance to get the cookie policy for
      * @return true if the {@link WebView} accepts third party cookies
      */
-    public boolean acceptThirdPartyCookies(WebView webview) {
-        throw new MustOverrideException();
-    }
+    public abstract boolean acceptThirdPartyCookies(WebView webview);
 
     /**
      * Sets a cookie for the given URL. Any existing cookie with the same host,
@@ -110,9 +98,7 @@
      * @param value the cookie as a string, using the format of the 'Set-Cookie'
      *              HTTP response header
      */
-    public void setCookie(String url, String value) {
-        throw new MustOverrideException();
-    }
+    public abstract void setCookie(String url, String value);
 
     /**
      * Sets a cookie for the given URL. Any existing cookie with the same host,
@@ -133,9 +119,7 @@
      *              HTTP response header
      * @param callback a callback to be executed when the cookie has been set
      */
-    public void setCookie(String url, String value, ValueCallback<Boolean> callback) {
-        throw new MustOverrideException();
-    }
+    public abstract void setCookie(String url, String value, ValueCallback<Boolean> callback);
 
     /**
      * Gets the cookies for the given URL.
@@ -144,9 +128,7 @@
      * @return value the cookies as a string, using the format of the 'Cookie'
      *               HTTP request header
      */
-    public String getCookie(String url) {
-        throw new MustOverrideException();
-    }
+    public abstract String getCookie(String url);
 
     /**
      * See {@link #getCookie(String)}.
@@ -155,11 +137,10 @@
      * @param privateBrowsing whether to use the private browsing cookie jar
      * @return value the cookies as a string, using the format of the 'Cookie'
      *               HTTP request header
-     * @hide Used by Browser, no intention to publish.
+     * @hide Used by Browser and by WebViewProvider implementations.
      */
-    public String getCookie(String url, boolean privateBrowsing) {
-        throw new MustOverrideException();
-    }
+    @SystemApi
+    public abstract String getCookie(String url, boolean privateBrowsing);
 
     /**
      * Gets cookie(s) for a given uri so that it can be set to "cookie:" in http
@@ -168,10 +149,11 @@
      * @param uri the WebAddress for which the cookies are requested
      * @return value the cookies as a string, using the format of the 'Cookie'
      *               HTTP request header
-     * @hide Used by RequestHandle, no intention to publish.
+     * @hide Used by RequestHandle and by WebViewProvider implementations.
      */
+    @SystemApi
     public synchronized String getCookie(WebAddress uri) {
-        throw new MustOverrideException();
+        return getCookie(uri.toString());
     }
 
     /**
@@ -179,9 +161,7 @@
      * date.
      * @deprecated use {@link #removeSessionCookies(ValueCallback)} instead.
      */
-    public void removeSessionCookie() {
-        throw new MustOverrideException();
-    }
+    public abstract void removeSessionCookie();
 
     /**
      * Removes all session cookies, which are cookies without an expiration
@@ -197,18 +177,14 @@
      * method from a thread without a Looper.
      * @param callback a callback which is executed when the session cookies have been removed
      */
-    public void removeSessionCookies(ValueCallback<Boolean> callback) {
-        throw new MustOverrideException();
-    }
+    public abstract void removeSessionCookies(ValueCallback<Boolean> callback);
 
     /**
      * Removes all cookies.
      * @deprecated Use {@link #removeAllCookies(ValueCallback)} instead.
      */
     @Deprecated
-    public void removeAllCookie() {
-        throw new MustOverrideException();
-    }
+    public abstract void removeAllCookie();
 
     /**
      * Removes all cookies.
@@ -223,54 +199,37 @@
      * method from a thread without a Looper.
      * @param callback a callback which is executed when the cookies have been removed
      */
-    public void removeAllCookies(ValueCallback<Boolean> callback) {
-        throw new MustOverrideException();
-    }
+    public abstract void removeAllCookies(ValueCallback<Boolean> callback);
 
     /**
      * Gets whether there are stored cookies.
      *
      * @return true if there are stored cookies
      */
-    public synchronized boolean hasCookies() {
-        throw new MustOverrideException();
-    }
+    public abstract boolean hasCookies();
 
     /**
      * See {@link #hasCookies()}.
      *
      * @param privateBrowsing whether to use the private browsing cookie jar
-     * @hide Used by Browser, no intention to publish.
+     * @hide Used by Browser and WebViewProvider implementations.
      */
-    public synchronized boolean hasCookies(boolean privateBrowsing) {
-        throw new MustOverrideException();
-    }
+    @SystemApi
+    public abstract boolean hasCookies(boolean privateBrowsing);
 
     /**
      * Removes all expired cookies.
      * @deprecated The WebView handles removing expired cookies automatically.
      */
     @Deprecated
-    public void removeExpiredCookie() {
-        throw new MustOverrideException();
-    }
+    public abstract void removeExpiredCookie();
 
     /**
      * Ensures all cookies currently accessible through the getCookie API are
      * written to persistent storage.
      * This call will block the caller until it is done and may perform I/O.
      */
-    public void flush() {
-        flushCookieStore();
-    }
-
-    /**
-     * Flushes all cookies managed by the Chrome HTTP stack to flash.
-     *
-     * @hide Package level api, called from CookieSyncManager
-     */
-    protected void flushCookieStore() {
-    }
+    public abstract void flush();
 
     /**
      * Gets whether the application's {@link WebView} instances send and accept
@@ -289,9 +248,8 @@
      *
      * @hide Only for use by WebViewProvider implementations
      */
-    protected boolean allowFileSchemeCookiesImpl() {
-        throw new MustOverrideException();
-    }
+    @SystemApi
+    protected abstract boolean allowFileSchemeCookiesImpl();
 
     /**
      * Sets whether the application's {@link WebView} instances should send and
@@ -314,7 +272,6 @@
      *
      * @hide Only for use by WebViewProvider implementations
      */
-    protected void setAcceptFileSchemeCookiesImpl(boolean accept) {
-        throw new MustOverrideException();
-    }
+    @SystemApi
+    protected abstract void setAcceptFileSchemeCookiesImpl(boolean accept);
 }
diff --git a/core/java/android/webkit/DebugFlags.java b/core/java/android/webkit/DebugFlags.java
deleted file mode 100644
index 7b3cb1b..0000000
--- a/core/java/android/webkit/DebugFlags.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (C) 2009 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.
- */
-
-package android.webkit;
-
-/**
- * This class is a container for all of the debug flags used in the Java
- * components of webkit.  These flags must be final in order to ensure that
- * the compiler optimizes the code that uses them out of the final executable.
- *
- * The name of each flags maps directly to the name of the class in which that
- * flag is used.
- *
- * @hide Only used by WebView implementations.
- */
-public class DebugFlags {
-
-    public static final boolean COOKIE_SYNC_MANAGER = false;
-    public static final boolean TRACE_API = false;
-    public static final boolean TRACE_CALLBACK = false;
-    public static final boolean URL_UTIL = false;
-    public static final boolean WEB_SYNC_MANAGER = false;
-
-}
diff --git a/core/java/android/webkit/FindActionModeCallback.java b/core/java/android/webkit/FindActionModeCallback.java
index c68b450..ab6a2f9 100644
--- a/core/java/android/webkit/FindActionModeCallback.java
+++ b/core/java/android/webkit/FindActionModeCallback.java
@@ -16,6 +16,7 @@
 
 package android.webkit;
 
+import android.annotation.SystemApi;
 import android.content.Context;
 import android.content.res.Resources;
 import android.graphics.Point;
@@ -36,6 +37,7 @@
 /**
  * @hide
  */
+@SystemApi
 public class FindActionModeCallback implements ActionMode.Callback, TextWatcher,
         View.OnClickListener, WebView.FindListener {
     private View mCustomView;
diff --git a/core/java/android/webkit/GeolocationPermissions.java b/core/java/android/webkit/GeolocationPermissions.java
index bc3d035..7187f22 100644
--- a/core/java/android/webkit/GeolocationPermissions.java
+++ b/core/java/android/webkit/GeolocationPermissions.java
@@ -16,6 +16,8 @@
 
 package android.webkit;
 
+import android.annotation.SystemApi;
+
 import java.util.Set;
 
 /**
@@ -136,5 +138,6 @@
      * way to call createHandler() and createUIHandler(), so it would not work).
      * @hide Only for use by WebViewProvider implementations
      */
+    @SystemApi
     public GeolocationPermissions() {}
 }
diff --git a/core/java/android/webkit/HttpAuthHandler.java b/core/java/android/webkit/HttpAuthHandler.java
index ee3b3698..45fc1f5 100644
--- a/core/java/android/webkit/HttpAuthHandler.java
+++ b/core/java/android/webkit/HttpAuthHandler.java
@@ -16,6 +16,7 @@
 
 package android.webkit;
 
+import android.annotation.SystemApi;
 import android.os.Handler;
 
 /**
@@ -30,6 +31,7 @@
     /**
      * @hide Only for use by WebViewProvider implementations.
      */
+    @SystemApi
     public HttpAuthHandler() {
     }
 
diff --git a/core/java/android/webkit/JsDialogHelper.java b/core/java/android/webkit/JsDialogHelper.java
index bb0339e..cc475c3 100644
--- a/core/java/android/webkit/JsDialogHelper.java
+++ b/core/java/android/webkit/JsDialogHelper.java
@@ -16,6 +16,7 @@
 
 package android.webkit;
 
+import android.annotation.SystemApi;
 import android.app.Activity;
 import android.app.AlertDialog;
 import android.content.Context;
@@ -34,8 +35,9 @@
  * Helper class to create JavaScript dialogs. It is used by
  * different WebView implementations.
  *
- * @hide Helper class for internal use
+ * @hide
  */
+@SystemApi
 public class JsDialogHelper {
 
     private static final String TAG = "JsDialogHelper";
diff --git a/core/java/android/webkit/JsPromptResult.java b/core/java/android/webkit/JsPromptResult.java
index a1bf124..771cc32 100644
--- a/core/java/android/webkit/JsPromptResult.java
+++ b/core/java/android/webkit/JsPromptResult.java
@@ -16,6 +16,8 @@
 
 package android.webkit;
 
+import android.annotation.SystemApi;
+
 
 /**
  * Public class for handling JavaScript prompt requests. The WebChromeClient will receive a
@@ -39,6 +41,7 @@
     /**
      * @hide Only for use by WebViewProvider implementations
      */
+    @SystemApi
     public JsPromptResult(ResultReceiver receiver) {
         super(receiver);
     }
@@ -46,6 +49,7 @@
     /**
      * @hide Only for use by WebViewProvider implementations
      */
+    @SystemApi
     public String getStringResult() {
         return mStringResult;
     }
diff --git a/core/java/android/webkit/JsResult.java b/core/java/android/webkit/JsResult.java
index e4e6851..d36ab418 100644
--- a/core/java/android/webkit/JsResult.java
+++ b/core/java/android/webkit/JsResult.java
@@ -16,6 +16,8 @@
 
 package android.webkit;
 
+import android.annotation.SystemApi;
+
 /**
  * An instance of this class is passed as a parameter in various {@link WebChromeClient} action
  * notifications. The object is used as a handle onto the underlying JavaScript-originated request,
@@ -27,6 +29,7 @@
      * notifications when the JavaScript result represented by a JsResult instance has
      * @hide Only for use by WebViewProvider implementations
      */
+    @SystemApi
     public interface ResultReceiver {
         public void onJsResultComplete(JsResult result);
     }
@@ -54,6 +57,7 @@
     /**
      * @hide Only for use by WebViewProvider implementations
      */
+    @SystemApi
     public JsResult(ResultReceiver receiver) {
         mReceiver = receiver;
     }
@@ -61,6 +65,7 @@
     /**
      * @hide Only for use by WebViewProvider implementations
      */
+    @SystemApi
     public final boolean getResult() {
         return mResult;
     }
diff --git a/core/java/android/net/http/ErrorStrings.java b/core/java/android/webkit/LegacyErrorStrings.java
similarity index 91%
rename from core/java/android/net/http/ErrorStrings.java
rename to core/java/android/webkit/LegacyErrorStrings.java
index 8383681..11fc05d 100644
--- a/core/java/android/net/http/ErrorStrings.java
+++ b/core/java/android/webkit/LegacyErrorStrings.java
@@ -14,9 +14,10 @@
  * limitations under the License.
  */
 
-package android.net.http;
+package android.webkit;
 
 import android.content.Context;
+import android.net.http.EventHandler;
 import android.util.Log;
 
 /**
@@ -24,8 +25,8 @@
  *
  * {@hide}
  */
-public class ErrorStrings {
-    private ErrorStrings() { /* Utility class, don't instantiate. */ }
+class LegacyErrorStrings {
+    private LegacyErrorStrings() { /* Utility class, don't instantiate. */ }
 
     private static final String LOGTAG = "Http";
 
@@ -33,7 +34,7 @@
      * Get the localized error message resource for the given error code.
      * If the code is unknown, we'll return a generic error message.
      */
-    public static String getString(int errorCode, Context context) {
+    static String getString(int errorCode, Context context) {
         return context.getText(getResource(errorCode)).toString();
     }
 
@@ -41,7 +42,7 @@
      * Get the localized error message resource for the given error code.
      * If the code is unknown, we'll return a generic error message.
      */
-    public static int getResource(int errorCode) {
+    private static int getResource(int errorCode) {
         switch(errorCode) {
             case EventHandler.OK:
                 return com.android.internal.R.string.httpErrorOk;
diff --git a/core/java/android/webkit/SslErrorHandler.java b/core/java/android/webkit/SslErrorHandler.java
index af31544..537065d 100644
--- a/core/java/android/webkit/SslErrorHandler.java
+++ b/core/java/android/webkit/SslErrorHandler.java
@@ -16,6 +16,7 @@
 
 package android.webkit;
 
+import android.annotation.SystemApi;
 import android.os.Handler;
 
 /**
@@ -30,6 +31,7 @@
     /**
      * @hide Only for use by WebViewProvider implementations.
      */
+    @SystemApi
     public SslErrorHandler() {}
 
     /**
diff --git a/core/java/android/webkit/URLUtil.java b/core/java/android/webkit/URLUtil.java
index d115984..f5233b6 100644
--- a/core/java/android/webkit/URLUtil.java
+++ b/core/java/android/webkit/URLUtil.java
@@ -29,6 +29,7 @@
 public final class URLUtil {
 
     private static final String LOGTAG = "webkit";
+    private static final boolean TRACE = false;
 
     // to refer to bar.png under your package's asset/foo/ directory, use
     // "file:///android_asset/foo/bar.png".
@@ -49,7 +50,7 @@
         String retVal = inUrl;
         WebAddress webAddress;
 
-        if (DebugFlags.URL_UTIL) Log.v(LOGTAG, "guessURL before queueRequest: " + inUrl);
+        if (TRACE) Log.v(LOGTAG, "guessURL before queueRequest: " + inUrl);
 
         if (inUrl.length() == 0) return inUrl;
         if (inUrl.startsWith("about:")) return inUrl;
@@ -69,7 +70,7 @@
             webAddress = new WebAddress(inUrl);
         } catch (ParseException ex) {
 
-            if (DebugFlags.URL_UTIL) {
+            if (TRACE) {
                 Log.v(LOGTAG, "smartUrlFilter: failed to parse url = " + inUrl);
             }
             return retVal;
@@ -286,7 +287,7 @@
         }
         return url;
     }
-    
+
     /**
      * Guesses canonical filename that a download would have, using
      * the URL and contentDisposition. File extension, if not defined,
@@ -294,7 +295,7 @@
      * @param url Url to the content
      * @param contentDisposition Content-Disposition HTTP header or null
      * @param mimeType Mime-type of the content or null
-     * 
+     *
      * @return suggested filename
      */
     public static final String guessFileName(
diff --git a/core/java/android/webkit/WebBackForwardList.java b/core/java/android/webkit/WebBackForwardList.java
index bfef2e7..e671376 100644
--- a/core/java/android/webkit/WebBackForwardList.java
+++ b/core/java/android/webkit/WebBackForwardList.java
@@ -16,6 +16,7 @@
 
 package android.webkit;
 
+import android.annotation.SystemApi;
 import java.io.Serializable;
 
 /**
@@ -23,56 +24,38 @@
  * WebView.copyBackForwardList() will return a copy of this class used to
  * inspect the entries in the list.
  */
-public class WebBackForwardList implements Cloneable, Serializable {
-
-    /**
-     *  @hide
-     */
-    public WebBackForwardList() {
-    }
-
+public abstract class WebBackForwardList implements Cloneable, Serializable {
     /**
      * Return the current history item. This method returns null if the list is
      * empty.
      * @return The current history item.
      */
-    public synchronized WebHistoryItem getCurrentItem() {
-        throw new MustOverrideException();
-    }
+    public abstract WebHistoryItem getCurrentItem();
 
     /**
      * Get the index of the current history item. This index can be used to
      * directly index into the array list.
      * @return The current index from 0...n or -1 if the list is empty.
      */
-    public synchronized int getCurrentIndex() {
-        throw new MustOverrideException();
-    }
+    public abstract int getCurrentIndex();
 
     /**
      * Get the history item at the given index. The index range is from 0...n
      * where 0 is the first item and n is the last item.
      * @param index The index to retrieve.
      */
-    public synchronized WebHistoryItem getItemAtIndex(int index) {
-        throw new MustOverrideException();
-    }
+    public abstract WebHistoryItem getItemAtIndex(int index);
 
     /**
      * Get the total size of the back/forward list.
      * @return The size of the list.
      */
-    public synchronized int getSize() {
-        throw new MustOverrideException();
-    }
+    public abstract int getSize();
 
     /**
      * Clone the entire object to be used in the UI thread by clients of
      * WebView. This creates a copy that should never be modified by any of the
      * webkit package classes.
      */
-    protected synchronized WebBackForwardList clone() {
-        throw new MustOverrideException();
-    }
-
+    protected abstract WebBackForwardList clone();
 }
diff --git a/core/java/android/webkit/WebChromeClient.java b/core/java/android/webkit/WebChromeClient.java
index 46a7fd0..768dc9f 100644
--- a/core/java/android/webkit/WebChromeClient.java
+++ b/core/java/android/webkit/WebChromeClient.java
@@ -16,6 +16,7 @@
 
 package android.webkit;
 
+import android.annotation.SystemApi;
 import android.content.Intent;
 import android.content.pm.ActivityInfo;
 import android.graphics.Bitmap;
@@ -509,6 +510,7 @@
      * @deprecated Use {@link #showFileChooser} instead.
      * @hide This method was not published in any SDK version.
      */
+    @SystemApi
     @Deprecated
     public void openFileChooser(ValueCallback<Uri> uploadFile, String acceptType, String capture) {
         uploadFile.onReceiveValue(null);
diff --git a/core/java/android/webkit/WebHistoryItem.java b/core/java/android/webkit/WebHistoryItem.java
index 9a588e4..569fccd 100644
--- a/core/java/android/webkit/WebHistoryItem.java
+++ b/core/java/android/webkit/WebHistoryItem.java
@@ -16,6 +16,7 @@
 
 package android.webkit;
 
+import android.annotation.SystemApi;
 import android.graphics.Bitmap;
 
 /**
@@ -24,14 +25,7 @@
  * item. Each history item may be updated during the load of a page.
  * @see WebBackForwardList
  */
-public class WebHistoryItem implements Cloneable {
-
-    /**
-     * @hide
-     */
-    public WebHistoryItem() {
-    }
-
+public abstract class WebHistoryItem implements Cloneable {
     /**
      * Return an identifier for this history item. If an item is a copy of
      * another item, the identifiers will be the same even if they are not the
@@ -40,10 +34,9 @@
      * @deprecated This method is now obsolete.
      * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}
      */
+    @SystemApi
     @Deprecated
-    public int getId() {
-        throw new MustOverrideException();
-    }
+    public abstract int getId();
 
     /**
      * Return the url of this history item. The url is the base url of this
@@ -53,29 +46,23 @@
      * Note: The VM ensures 32-bit atomic read/write operations so we don't have
      * to synchronize this method.
      */
-    public String getUrl() {
-        throw new MustOverrideException();
-    }
+    public abstract String getUrl();
 
     /**
      * Return the original url of this history item. This was the requested
-     * url, the final url may be different as there might have been 
+     * url, the final url may be different as there might have been
      * redirects while loading the site.
      * @return The original url of this history item.
      */
-    public String getOriginalUrl() {
-        throw new MustOverrideException();
-    }
-    
+    public abstract String getOriginalUrl();
+
     /**
      * Return the document title of this history item.
      * @return The document title of this history item.
      * Note: The VM ensures 32-bit atomic read/write operations so we don't have
      * to synchronize this method.
      */
-    public String getTitle() {
-        throw new MustOverrideException();
-    }
+    public abstract String getTitle();
 
     /**
      * Return the favicon of this history item or null if no favicon was found.
@@ -83,15 +70,10 @@
      * Note: The VM ensures 32-bit atomic read/write operations so we don't have
      * to synchronize this method.
      */
-    public Bitmap getFavicon() {
-        throw new MustOverrideException();
-    }
+    public abstract Bitmap getFavicon();
 
     /**
      * Clone the history item for use by clients of WebView.
      */
-    protected synchronized WebHistoryItem clone() {
-        throw new MustOverrideException();
-    }
-
+    protected abstract WebHistoryItem clone();
 }
diff --git a/core/java/android/webkit/WebIconDatabase.java b/core/java/android/webkit/WebIconDatabase.java
index e574593..08956e0 100644
--- a/core/java/android/webkit/WebIconDatabase.java
+++ b/core/java/android/webkit/WebIconDatabase.java
@@ -16,6 +16,7 @@
 
 package android.webkit;
 
+import android.annotation.SystemApi;
 import android.content.ContentResolver;
 import android.graphics.Bitmap;
 
@@ -32,7 +33,7 @@
  *             up to {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}
  */
 @Deprecated
-public class WebIconDatabase {
+public abstract class WebIconDatabase {
     /**
      * Interface for receiving icons from the database.
      * @deprecated This interface is obsolete.
@@ -52,23 +53,17 @@
      * Open a the icon database and store the icons in the given path.
      * @param path The directory path where the icon database will be stored.
      */
-    public void open(String path) {
-        throw new MustOverrideException();
-    }
+    public abstract void open(String path);
 
     /**
      * Close the shared instance of the icon database.
      */
-    public void close() {
-        throw new MustOverrideException();
-    }
+    public abstract void close();
 
     /**
      * Removes all the icons in the database.
      */
-    public void removeAllIcons() {
-        throw new MustOverrideException();
-    }
+    public abstract void removeAllIcons();
 
     /**
      * Request the Bitmap representing the icon for the given page
@@ -76,32 +71,25 @@
      * @param url The page's url.
      * @param listener An implementation on IconListener to receive the result.
      */
-    public void requestIconForPageUrl(String url, IconListener listener) {
-        throw new MustOverrideException();
-    }
+    public abstract void requestIconForPageUrl(String url, IconListener listener);
 
     /** {@hide}
      */
-    public void bulkRequestIconForPageUrl(ContentResolver cr, String where,
-            IconListener listener) {
-        throw new MustOverrideException();
-    }
+    @SystemApi
+    public abstract void bulkRequestIconForPageUrl(ContentResolver cr, String where,
+            IconListener listener);
 
     /**
      * Retain the icon for the given page url.
      * @param url The page's url.
      */
-    public void retainIconForPageUrl(String url) {
-        throw new MustOverrideException();
-    }
+    public abstract void retainIconForPageUrl(String url);
 
     /**
      * Release the icon for the given page url.
      * @param url The page's url.
      */
-    public void releaseIconForPageUrl(String url) {
-        throw new MustOverrideException();
-    }
+    public abstract void releaseIconForPageUrl(String url);
 
     /**
      * Get the global instance of WebIconDatabase.
@@ -113,9 +101,4 @@
         // XXX: Must be created in the UI thread.
         return WebViewFactory.getProvider().getWebIconDatabase();
     }
-
-    /**
-     * @hide Only for use by WebViewProvider implementations
-     */
-    protected WebIconDatabase() {}
 }
diff --git a/core/java/android/webkit/WebSettings.java b/core/java/android/webkit/WebSettings.java
index 7cf3cb5..1d2c311 100644
--- a/core/java/android/webkit/WebSettings.java
+++ b/core/java/android/webkit/WebSettings.java
@@ -204,25 +204,15 @@
     public static final int MIXED_CONTENT_COMPATIBILITY_MODE = 2;
 
     /**
-     * Hidden constructor to prevent clients from creating a new settings
-     * instance or deriving the class.
-     *
-     * @hide
-     */
-    protected WebSettings() {
-    }
-
-    /**
      * Enables dumping the pages navigation cache to a text file. The default
      * is false.
      *
      * @deprecated This method is now obsolete.
      * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}
      */
+    @SystemApi
     @Deprecated
-    public void setNavDump(boolean enabled) {
-        throw new MustOverrideException();
-    }
+    public abstract void setNavDump(boolean enabled);
 
     /**
      * Gets whether dumping the navigation cache is enabled.
@@ -232,10 +222,9 @@
      * @deprecated This method is now obsolete.
      * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}
      */
+    @SystemApi
     @Deprecated
-    public boolean getNavDump() {
-        throw new MustOverrideException();
-    }
+    public abstract boolean getNavDump();
 
     /**
      * Sets whether the WebView should support zooming using its on-screen zoom
@@ -246,9 +235,7 @@
      *
      * @param support whether the WebView should support zoom
      */
-    public void setSupportZoom(boolean support) {
-        throw new MustOverrideException();
-    }
+    public abstract void setSupportZoom(boolean support);
 
     /**
      * Gets whether the WebView supports zoom.
@@ -256,9 +243,7 @@
      * @return true if the WebView supports zoom
      * @see #setSupportZoom
      */
-    public boolean supportZoom() {
-        throw new MustOverrideException();
-    }
+    public abstract boolean supportZoom();
 
     /**
      * Sets whether the WebView requires a user gesture to play media.
@@ -266,9 +251,7 @@
      *
      * @param require whether the WebView requires a user gesture to play media
      */
-    public void setMediaPlaybackRequiresUserGesture(boolean require) {
-        throw new MustOverrideException();
-    }
+    public abstract void setMediaPlaybackRequiresUserGesture(boolean require);
 
     /**
      * Gets whether the WebView requires a user gesture to play media.
@@ -276,9 +259,7 @@
      * @return true if the WebView requires a user gesture to play media
      * @see #setMediaPlaybackRequiresUserGesture
      */
-    public boolean getMediaPlaybackRequiresUserGesture() {
-        throw new MustOverrideException();
-    }
+    public abstract boolean getMediaPlaybackRequiresUserGesture();
 
     /**
      * Sets whether the WebView should use its built-in zoom mechanisms. The
@@ -295,9 +276,7 @@
     // This method was intended to select between the built-in zoom mechanisms
     // and the separate zoom controls. The latter were obtained using
     // {@link WebView#getZoomControls}, which is now hidden.
-    public void setBuiltInZoomControls(boolean enabled) {
-        throw new MustOverrideException();
-    }
+    public abstract void setBuiltInZoomControls(boolean enabled);
 
     /**
      * Gets whether the zoom mechanisms built into WebView are being used.
@@ -305,9 +284,7 @@
      * @return true if the zoom mechanisms built into WebView are being used
      * @see #setBuiltInZoomControls
      */
-    public boolean getBuiltInZoomControls() {
-        throw new MustOverrideException();
-    }
+    public abstract boolean getBuiltInZoomControls();
 
     /**
      * Sets whether the WebView should display on-screen zoom controls when
@@ -316,9 +293,7 @@
      *
      * @param enabled whether the WebView should display on-screen zoom controls
      */
-    public void setDisplayZoomControls(boolean enabled) {
-        throw new MustOverrideException();
-    }
+    public abstract void setDisplayZoomControls(boolean enabled);
 
     /**
      * Gets whether the WebView displays on-screen zoom controls when using
@@ -328,9 +303,7 @@
      *         the built-in zoom mechanisms
      * @see #setDisplayZoomControls
      */
-    public boolean getDisplayZoomControls() {
-        throw new MustOverrideException();
-    }
+    public abstract boolean getDisplayZoomControls();
 
     /**
      * Enables or disables file access within WebView. File access is enabled by
@@ -338,36 +311,28 @@
      * Assets and resources are still accessible using file:///android_asset and
      * file:///android_res.
      */
-    public void setAllowFileAccess(boolean allow) {
-        throw new MustOverrideException();
-    }
+    public abstract void setAllowFileAccess(boolean allow);
 
     /**
      * Gets whether this WebView supports file access.
      *
      * @see #setAllowFileAccess
      */
-    public boolean getAllowFileAccess() {
-        throw new MustOverrideException();
-    }
+    public abstract boolean getAllowFileAccess();
 
     /**
      * Enables or disables content URL access within WebView.  Content URL
      * access allows WebView to load content from a content provider installed
      * in the system. The default is enabled.
      */
-    public void setAllowContentAccess(boolean allow) {
-        throw new MustOverrideException();
-    }
+    public abstract void setAllowContentAccess(boolean allow);
 
     /**
      * Gets whether this WebView supports content URL access.
      *
      * @see #setAllowContentAccess
      */
-    public boolean getAllowContentAccess() {
-        throw new MustOverrideException();
-    }
+    public abstract boolean getAllowContentAccess();
 
     /**
      * Sets whether the WebView loads pages in overview mode, that is,
@@ -376,9 +341,7 @@
      * of the WebView control, for example, when {@link #getUseWideViewPort}
      * is enabled. The default is false.
      */
-    public void setLoadWithOverviewMode(boolean overview) {
-        throw new MustOverrideException();
-    }
+    public abstract void setLoadWithOverviewMode(boolean overview);
 
     /**
      * Gets whether this WebView loads pages in overview mode.
@@ -386,9 +349,7 @@
      * @return whether this WebView loads pages in overview mode
      * @see #setLoadWithOverviewMode
      */
-    public boolean getLoadWithOverviewMode() {
-        throw new MustOverrideException();
-    }
+    public abstract boolean getLoadWithOverviewMode();
 
     /**
      * Sets whether the WebView will enable smooth transition while panning or
@@ -400,9 +361,7 @@
      * @deprecated This method is now obsolete, and will become a no-op in future.
      */
     @Deprecated
-    public void setEnableSmoothTransition(boolean enable) {
-        throw new MustOverrideException();
-    }
+    public abstract void setEnableSmoothTransition(boolean enable);
 
     /**
      * Gets whether the WebView enables smooth transition while panning or
@@ -413,9 +372,7 @@
      * @deprecated This method is now obsolete, and will become a no-op in future.
      */
     @Deprecated
-    public boolean enableSmoothTransition() {
-        throw new MustOverrideException();
-    }
+    public abstract  boolean enableSmoothTransition();
 
     /**
      * Sets whether the WebView uses its background for over scroll background.
@@ -425,10 +382,9 @@
      * @deprecated This method is now obsolete.
      * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}
      */
+    @SystemApi
     @Deprecated
-    public void setUseWebViewBackgroundForOverscrollBackground(boolean view) {
-        throw new MustOverrideException();
-    }
+    public abstract  void setUseWebViewBackgroundForOverscrollBackground(boolean view);
 
     /**
      * Gets whether this WebView uses WebView's background instead of
@@ -438,17 +394,14 @@
      * @deprecated This method is now obsolete.
      * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}
      */
+    @SystemApi
     @Deprecated
-    public boolean getUseWebViewBackgroundForOverscrollBackground() {
-        throw new MustOverrideException();
-    }
+    public abstract  boolean getUseWebViewBackgroundForOverscrollBackground();
 
     /**
      * Sets whether the WebView should save form data. The default is true.
      */
-    public void setSaveFormData(boolean save) {
-        throw new MustOverrideException();
-    }
+    public abstract  void setSaveFormData(boolean save);
 
     /**
      * Gets whether the WebView saves form data.
@@ -456,18 +409,14 @@
      * @return whether the WebView saves form data
      * @see #setSaveFormData
      */
-    public boolean getSaveFormData() {
-        throw new MustOverrideException();
-    }
+    public abstract boolean getSaveFormData();
 
     /**
      * Sets whether the WebView should save passwords. The default is true.
      * @deprecated Saving passwords in WebView will not be supported in future versions.
      */
     @Deprecated
-    public void setSavePassword(boolean save) {
-        throw new MustOverrideException();
-    }
+    public abstract void setSavePassword(boolean save);
 
     /**
      * Gets whether the WebView saves passwords.
@@ -477,18 +426,14 @@
      * @deprecated Saving passwords in WebView will not be supported in future versions.
      */
     @Deprecated
-    public boolean getSavePassword() {
-        throw new MustOverrideException();
-    }
+    public abstract boolean getSavePassword();
 
     /**
      * Sets the text zoom of the page in percent. The default is 100.
      *
      * @param textZoom the text zoom in percent
      */
-    public synchronized void setTextZoom(int textZoom) {
-        throw new MustOverrideException();
-    }
+    public abstract void setTextZoom(int textZoom);
 
     /**
      * Gets the text zoom of the page in percent.
@@ -496,27 +441,23 @@
      * @return the text zoom of the page in percent
      * @see #setTextZoom
      */
-    public synchronized int getTextZoom() {
-        throw new MustOverrideException();
-    }
+    public abstract int getTextZoom();
 
     /**
      * Sets policy for third party cookies.
      * Developers should access this via {@link CookieManager#setShouldAcceptThirdPartyCookies}.
      * @hide Internal API.
      */
-    public void setAcceptThirdPartyCookies(boolean accept) {
-        throw new MustOverrideException();
-    }
+    @SystemApi
+    public abstract void setAcceptThirdPartyCookies(boolean accept);
 
     /**
      * Gets policy for third party cookies.
      * Developers should access this via {@link CookieManager#getShouldAcceptThirdPartyCookies}.
      * @hide Internal API
      */
-    public boolean getAcceptThirdPartyCookies() {
-        throw new MustOverrideException();
-    }
+    @SystemApi
+    public abstract boolean getAcceptThirdPartyCookies();
 
     /**
      * Sets the text size of the page. The default is {@link TextSize#NORMAL}.
@@ -569,9 +510,7 @@
      *             recommended alternatives.
      */
     @Deprecated
-    public void setDefaultZoom(ZoomDensity zoom) {
-        throw new MustOverrideException();
-    }
+    public abstract void setDefaultZoom(ZoomDensity zoom);
 
     /**
      * Gets the default zoom density of the page. This should be called from
@@ -583,9 +522,7 @@
      * @see #setDefaultZoom
      * @deprecated Will only return the default value.
      */
-    public ZoomDensity getDefaultZoom() {
-        throw new MustOverrideException();
-    }
+    public abstract ZoomDensity getDefaultZoom();
 
     /**
      * Enables using light touches to make a selection and activate mouseovers.
@@ -593,9 +530,7 @@
      *             setting is obsolete and has no effect.
      */
     @Deprecated
-    public void setLightTouchEnabled(boolean enabled) {
-        throw new MustOverrideException();
-    }
+    public abstract void setLightTouchEnabled(boolean enabled);
 
     /**
      * Gets whether light touches are enabled.
@@ -603,9 +538,7 @@
      * @deprecated This setting is obsolete.
      */
     @Deprecated
-    public boolean getLightTouchEnabled() {
-        throw new MustOverrideException();
-    }
+    public abstract boolean getLightTouchEnabled();
 
     /**
      * Controlled a rendering optimization that is no longer present. Setting
@@ -615,7 +548,7 @@
      * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}
      */
     @Deprecated
-    public synchronized void setUseDoubleTree(boolean use) {
+    public void setUseDoubleTree(boolean use) {
         // Specified to do nothing, so no need for derived classes to override.
     }
 
@@ -627,7 +560,7 @@
      * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}
      */
     @Deprecated
-    public synchronized boolean getUseDoubleTree() {
+    public boolean getUseDoubleTree() {
         // Returns false unconditionally, so no need for derived classes to override.
         return false;
     }
@@ -645,10 +578,9 @@
      * @deprecated Please use {@link #setUserAgentString} instead.
      * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}
      */
+    @SystemApi
     @Deprecated
-    public synchronized void setUserAgent(int ua) {
-        throw new MustOverrideException();
-    }
+    public abstract void setUserAgent(int ua);
 
     /**
      * Gets the user-agent as an integer code.
@@ -664,10 +596,9 @@
      * @deprecated Please use {@link #getUserAgentString} instead.
      * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}
      */
+    @SystemApi
     @Deprecated
-    public synchronized int getUserAgent() {
-        throw new MustOverrideException();
-    }
+    public abstract int getUserAgent();
 
     /**
      * Sets whether the WebView should enable support for the &quot;viewport&quot;
@@ -680,9 +611,7 @@
      *
      * @param use whether to enable support for the viewport meta tag
      */
-    public synchronized void setUseWideViewPort(boolean use) {
-        throw new MustOverrideException();
-    }
+    public abstract void setUseWideViewPort(boolean use);
 
     /**
      * Gets whether the WebView supports the &quot;viewport&quot;
@@ -691,9 +620,7 @@
      * @return true if the WebView supports the viewport meta tag
      * @see #setUseWideViewPort
      */
-    public synchronized boolean getUseWideViewPort() {
-        throw new MustOverrideException();
-    }
+    public abstract boolean getUseWideViewPort();
 
     /**
      * Sets whether the WebView whether supports multiple windows. If set to
@@ -702,9 +629,7 @@
      *
      * @param support whether to suport multiple windows
      */
-    public synchronized void setSupportMultipleWindows(boolean support) {
-        throw new MustOverrideException();
-    }
+    public abstract void setSupportMultipleWindows(boolean support);
 
     /**
      * Gets whether the WebView supports multiple windows.
@@ -712,9 +637,7 @@
      * @return true if the WebView supports multiple windows
      * @see #setSupportMultipleWindows
      */
-    public synchronized boolean supportMultipleWindows() {
-        throw new MustOverrideException();
-    }
+    public abstract boolean supportMultipleWindows();
 
     /**
      * Sets the underlying layout algorithm. This will cause a relayout of the
@@ -722,9 +645,7 @@
      *
      * @param l the layout algorithm to use, as a {@link LayoutAlgorithm} value
      */
-    public synchronized void setLayoutAlgorithm(LayoutAlgorithm l) {
-        throw new MustOverrideException();
-    }
+    public abstract void setLayoutAlgorithm(LayoutAlgorithm l);
 
     /**
      * Gets the current layout algorithm.
@@ -732,18 +653,14 @@
      * @return the layout algorithm in use, as a {@link LayoutAlgorithm} value
      * @see #setLayoutAlgorithm
      */
-    public synchronized LayoutAlgorithm getLayoutAlgorithm() {
-        throw new MustOverrideException();
-    }
+    public abstract LayoutAlgorithm getLayoutAlgorithm();
 
     /**
      * Sets the standard font family name. The default is "sans-serif".
      *
      * @param font a font family name
      */
-    public synchronized void setStandardFontFamily(String font) {
-        throw new MustOverrideException();
-    }
+    public abstract void setStandardFontFamily(String font);
 
     /**
      * Gets the standard font family name.
@@ -751,18 +668,14 @@
      * @return the standard font family name as a string
      * @see #setStandardFontFamily
      */
-    public synchronized String getStandardFontFamily() {
-        throw new MustOverrideException();
-    }
+    public abstract String getStandardFontFamily();
 
     /**
      * Sets the fixed font family name. The default is "monospace".
      *
      * @param font a font family name
      */
-    public synchronized void setFixedFontFamily(String font) {
-        throw new MustOverrideException();
-    }
+    public abstract void setFixedFontFamily(String font);
 
     /**
      * Gets the fixed font family name.
@@ -770,18 +683,14 @@
      * @return the fixed font family name as a string
      * @see #setFixedFontFamily
      */
-    public synchronized String getFixedFontFamily() {
-        throw new MustOverrideException();
-    }
+    public abstract String getFixedFontFamily();
 
     /**
      * Sets the sans-serif font family name. The default is "sans-serif".
      *
      * @param font a font family name
      */
-    public synchronized void setSansSerifFontFamily(String font) {
-        throw new MustOverrideException();
-    }
+    public abstract void setSansSerifFontFamily(String font);
 
     /**
      * Gets the sans-serif font family name.
@@ -789,18 +698,14 @@
      * @return the sans-serif font family name as a string
      * @see #setSansSerifFontFamily
      */
-    public synchronized String getSansSerifFontFamily() {
-        throw new MustOverrideException();
-    }
+    public abstract String getSansSerifFontFamily();
 
     /**
      * Sets the serif font family name. The default is "sans-serif".
      *
      * @param font a font family name
      */
-    public synchronized void setSerifFontFamily(String font) {
-        throw new MustOverrideException();
-    }
+    public abstract void setSerifFontFamily(String font);
 
     /**
      * Gets the serif font family name. The default is "serif".
@@ -808,18 +713,14 @@
      * @return the serif font family name as a string
      * @see #setSerifFontFamily
      */
-    public synchronized String getSerifFontFamily() {
-        throw new MustOverrideException();
-    }
+    public abstract String getSerifFontFamily();
 
     /**
      * Sets the cursive font family name. The default is "cursive".
      *
      * @param font a font family name
      */
-    public synchronized void setCursiveFontFamily(String font) {
-        throw new MustOverrideException();
-    }
+    public abstract void setCursiveFontFamily(String font);
 
     /**
      * Gets the cursive font family name.
@@ -827,18 +728,14 @@
      * @return the cursive font family name as a string
      * @see #setCursiveFontFamily
      */
-    public synchronized String getCursiveFontFamily() {
-        throw new MustOverrideException();
-    }
+    public abstract String getCursiveFontFamily();
 
     /**
      * Sets the fantasy font family name. The default is "fantasy".
      *
      * @param font a font family name
      */
-    public synchronized void setFantasyFontFamily(String font) {
-        throw new MustOverrideException();
-    }
+    public abstract void setFantasyFontFamily(String font);
 
     /**
      * Gets the fantasy font family name.
@@ -846,9 +743,7 @@
      * @return the fantasy font family name as a string
      * @see #setFantasyFontFamily
      */
-    public synchronized String getFantasyFontFamily() {
-        throw new MustOverrideException();
-    }
+    public abstract String getFantasyFontFamily();
 
     /**
      * Sets the minimum font size. The default is 8.
@@ -856,9 +751,7 @@
      * @param size a non-negative integer between 1 and 72. Any number outside
      *             the specified range will be pinned.
      */
-    public synchronized void setMinimumFontSize(int size) {
-        throw new MustOverrideException();
-    }
+    public abstract void setMinimumFontSize(int size);
 
     /**
      * Gets the minimum font size.
@@ -866,9 +759,7 @@
      * @return a non-negative integer between 1 and 72
      * @see #setMinimumFontSize
      */
-    public synchronized int getMinimumFontSize() {
-        throw new MustOverrideException();
-    }
+    public abstract int getMinimumFontSize();
 
     /**
      * Sets the minimum logical font size. The default is 8.
@@ -876,9 +767,7 @@
      * @param size a non-negative integer between 1 and 72. Any number outside
      *             the specified range will be pinned.
      */
-    public synchronized void setMinimumLogicalFontSize(int size) {
-        throw new MustOverrideException();
-    }
+    public abstract void setMinimumLogicalFontSize(int size);
 
     /**
      * Gets the minimum logical font size.
@@ -886,9 +775,7 @@
      * @return a non-negative integer between 1 and 72
      * @see #setMinimumLogicalFontSize
      */
-    public synchronized int getMinimumLogicalFontSize() {
-        throw new MustOverrideException();
-    }
+    public abstract int getMinimumLogicalFontSize();
 
     /**
      * Sets the default font size. The default is 16.
@@ -896,9 +783,7 @@
      * @param size a non-negative integer between 1 and 72. Any number outside
      *             the specified range will be pinned.
      */
-    public synchronized void setDefaultFontSize(int size) {
-        throw new MustOverrideException();
-    }
+    public abstract void setDefaultFontSize(int size);
 
     /**
      * Gets the default font size.
@@ -906,9 +791,7 @@
      * @return a non-negative integer between 1 and 72
      * @see #setDefaultFontSize
      */
-    public synchronized int getDefaultFontSize() {
-        throw new MustOverrideException();
-    }
+    public abstract int getDefaultFontSize();
 
     /**
      * Sets the default fixed font size. The default is 16.
@@ -916,9 +799,7 @@
      * @param size a non-negative integer between 1 and 72. Any number outside
      *             the specified range will be pinned.
      */
-    public synchronized void setDefaultFixedFontSize(int size) {
-        throw new MustOverrideException();
-    }
+    public abstract void setDefaultFixedFontSize(int size);
 
     /**
      * Gets the default fixed font size.
@@ -926,9 +807,7 @@
      * @return a non-negative integer between 1 and 72
      * @see #setDefaultFixedFontSize
      */
-    public synchronized int getDefaultFixedFontSize() {
-        throw new MustOverrideException();
-    }
+    public abstract int getDefaultFixedFontSize();
 
     /**
      * Sets whether the WebView should load image resources. Note that this method
@@ -941,9 +820,7 @@
      *
      * @param flag whether the WebView should load image resources
      */
-    public synchronized void setLoadsImagesAutomatically(boolean flag) {
-        throw new MustOverrideException();
-    }
+    public abstract void setLoadsImagesAutomatically(boolean flag);
 
     /**
      * Gets whether the WebView loads image resources. This includes
@@ -952,9 +829,7 @@
      * @return true if the WebView loads image resources
      * @see #setLoadsImagesAutomatically
      */
-    public synchronized boolean getLoadsImagesAutomatically() {
-        throw new MustOverrideException();
-    }
+    public abstract boolean getLoadsImagesAutomatically();
 
     /**
      * Sets whether the WebView should not load image resources from the
@@ -971,9 +846,7 @@
      *             network
      * @see #setBlockNetworkLoads
      */
-    public synchronized void setBlockNetworkImage(boolean flag) {
-        throw new MustOverrideException();
-    }
+    public abstract void setBlockNetworkImage(boolean flag);
 
     /**
      * Gets whether the WebView does not load image resources from the network.
@@ -981,9 +854,7 @@
      * @return true if the WebView does not load image resources from the network
      * @see #setBlockNetworkImage
      */
-    public synchronized boolean getBlockNetworkImage() {
-        throw new MustOverrideException();
-    }
+    public abstract boolean getBlockNetworkImage();
 
     /**
      * Sets whether the WebView should not load resources from the network.
@@ -1003,9 +874,7 @@
      *             network
      * @see android.webkit.WebView#reload
      */
-    public synchronized void setBlockNetworkLoads(boolean flag) {
-        throw new MustOverrideException();
-    }
+    public abstract void setBlockNetworkLoads(boolean flag);
 
     /**
      * Gets whether the WebView does not load any resources from the network.
@@ -1013,9 +882,7 @@
      * @return true if the WebView does not load any resources from the network
      * @see #setBlockNetworkLoads
      */
-    public synchronized boolean getBlockNetworkLoads() {
-        throw new MustOverrideException();
-    }
+    public abstract boolean getBlockNetworkLoads();
 
     /**
      * Tells the WebView to enable JavaScript execution.
@@ -1023,9 +890,7 @@
      *
      * @param flag true if the WebView should execute JavaScript
      */
-    public synchronized void setJavaScriptEnabled(boolean flag) {
-        throw new MustOverrideException();
-    }
+    public abstract void setJavaScriptEnabled(boolean flag);
 
     /**
      * Sets whether JavaScript running in the context of a file scheme URL
@@ -1076,10 +941,9 @@
      *             {@link #setPluginState}
      * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}
      */
+    @SystemApi
     @Deprecated
-    public synchronized void setPluginsEnabled(boolean flag) {
-        throw new MustOverrideException();
-    }
+    public abstract void setPluginsEnabled(boolean flag);
 
     /**
      * Tells the WebView to enable, disable, or have plugins on demand. On
@@ -1092,9 +956,7 @@
      * @deprecated Plugins will not be supported in future, and should not be used.
      */
     @Deprecated
-    public synchronized void setPluginState(PluginState state) {
-        throw new MustOverrideException();
-    }
+    public abstract void setPluginState(PluginState state);
 
     /**
      * Sets a custom path to plugins used by the WebView. This method is
@@ -1106,7 +968,7 @@
      * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}
      */
     @Deprecated
-    public synchronized void setPluginsPath(String pluginsPath) {
+    public void setPluginsPath(String pluginsPath) {
         // Specified to do nothing, so no need for derived classes to override.
     }
 
@@ -1125,9 +987,7 @@
     // Note that the WebCore Database Tracker only allows the path to be set
     // once.
     @Deprecated
-    public synchronized void setDatabasePath(String databasePath) {
-        throw new MustOverrideException();
-    }
+    public abstract void setDatabasePath(String databasePath);
 
     /**
      * Sets the path where the Geolocation databases should be saved. In order
@@ -1138,9 +998,7 @@
      *                     saved.
      */
     // This will update WebCore when the Sync runs in the C++ side.
-    public synchronized void setGeolocationDatabasePath(String databasePath) {
-        throw new MustOverrideException();
-    }
+    public abstract void setGeolocationDatabasePath(String databasePath);
 
     /**
      * Sets whether the Application Caches API should be enabled. The default
@@ -1150,9 +1008,7 @@
      *
      * @param flag true if the WebView should enable Application Caches
      */
-    public synchronized void setAppCacheEnabled(boolean flag) {
-        throw new MustOverrideException();
-    }
+    public abstract void setAppCacheEnabled(boolean flag);
 
     /**
      * Sets the path to the Application Caches files. In order for the
@@ -1164,9 +1020,7 @@
      *                     Application Caches files.
      * @see #setAppCacheEnabled
      */
-    public synchronized void setAppCachePath(String appCachePath) {
-        throw new MustOverrideException();
-    }
+    public abstract void setAppCachePath(String appCachePath);
 
     /**
      * Sets the maximum size for the Application Cache content. The passed size
@@ -1180,9 +1034,7 @@
      * @deprecated In future quota will be managed automatically.
      */
     @Deprecated
-    public synchronized void setAppCacheMaxSize(long appCacheMaxSize) {
-        throw new MustOverrideException();
-    }
+    public abstract void setAppCacheMaxSize(long appCacheMaxSize);
 
     /**
      * Sets whether the database storage API is enabled. The default value is
@@ -1196,18 +1048,14 @@
      *
      * @param flag true if the WebView should use the database storage API
      */
-    public synchronized void setDatabaseEnabled(boolean flag) {
-        throw new MustOverrideException();
-    }
+    public abstract void setDatabaseEnabled(boolean flag);
 
     /**
      * Sets whether the DOM storage API is enabled. The default value is false.
      *
      * @param flag true if the WebView should use the DOM storage API
      */
-    public synchronized void setDomStorageEnabled(boolean flag) {
-        throw new MustOverrideException();
-    }
+    public abstract void setDomStorageEnabled(boolean flag);
 
     /**
      * Gets whether the DOM Storage APIs are enabled.
@@ -1215,9 +1063,8 @@
      * @return true if the DOM Storage APIs are enabled
      * @see #setDomStorageEnabled
      */
-    public synchronized boolean getDomStorageEnabled() {
-        throw new MustOverrideException();
-    }
+    public abstract boolean getDomStorageEnabled();
+
     /**
      * Gets the path to where database storage API databases are saved.
      *
@@ -1226,9 +1073,7 @@
      * @deprecated Database paths are managed by the implementation this method is obsolete.
      */
     @Deprecated
-    public synchronized String getDatabasePath() {
-        throw new MustOverrideException();
-    }
+    public abstract String getDatabasePath();
 
     /**
      * Gets whether the database storage API is enabled.
@@ -1236,9 +1081,7 @@
      * @return true if the database storage API is enabled
      * @see #setDatabaseEnabled
      */
-    public synchronized boolean getDatabaseEnabled() {
-        throw new MustOverrideException();
-    }
+    public abstract boolean getDatabaseEnabled();
 
     /**
      * Sets whether Geolocation is enabled. The default is true.
@@ -1260,9 +1103,7 @@
      *
      * @param flag whether Geolocation should be enabled
      */
-    public synchronized void setGeolocationEnabled(boolean flag) {
-        throw new MustOverrideException();
-    }
+    public abstract void setGeolocationEnabled(boolean flag);
 
     /**
      * Gets whether JavaScript is enabled.
@@ -1270,9 +1111,7 @@
      * @return true if JavaScript is enabled
      * @see #setJavaScriptEnabled
      */
-    public synchronized boolean getJavaScriptEnabled() {
-        throw new MustOverrideException();
-    }
+    public abstract boolean getJavaScriptEnabled();
 
     /**
      * Gets whether JavaScript running in the context of a file scheme URL can
@@ -1303,10 +1142,9 @@
      * @deprecated This method has been replaced by {@link #getPluginState}
      * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}
      */
+    @SystemApi
     @Deprecated
-    public synchronized boolean getPluginsEnabled() {
-        throw new MustOverrideException();
-    }
+    public abstract boolean getPluginsEnabled();
 
     /**
      * Gets the current state regarding whether plugins are enabled.
@@ -1316,9 +1154,7 @@
      * @deprecated Plugins will not be supported in future, and should not be used.
      */
     @Deprecated
-    public synchronized PluginState getPluginState() {
-        throw new MustOverrideException();
-    }
+    public abstract PluginState getPluginState();
 
     /**
      * Gets the directory that contains the plugin libraries. This method is
@@ -1330,7 +1166,7 @@
      * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}
      */
     @Deprecated
-    public synchronized String getPluginsPath() {
+    public String getPluginsPath() {
         // Unconditionally returns empty string, so no need for derived classes to override.
         return "";
     }
@@ -1341,9 +1177,7 @@
      *
      * @param flag true if JavaScript can open windows automatically
      */
-    public synchronized void setJavaScriptCanOpenWindowsAutomatically(boolean flag) {
-        throw new MustOverrideException();
-    }
+    public abstract void setJavaScriptCanOpenWindowsAutomatically(boolean flag);
 
     /**
      * Gets whether JavaScript can open windows automatically.
@@ -1352,9 +1186,7 @@
      *         window.open()
      * @see #setJavaScriptCanOpenWindowsAutomatically
      */
-    public synchronized boolean getJavaScriptCanOpenWindowsAutomatically() {
-        throw new MustOverrideException();
-    }
+    public abstract boolean getJavaScriptCanOpenWindowsAutomatically();
 
     /**
      * Sets the default text encoding name to use when decoding html pages.
@@ -1362,9 +1194,7 @@
      *
      * @param encoding the text encoding name
      */
-    public synchronized void setDefaultTextEncodingName(String encoding) {
-        throw new MustOverrideException();
-    }
+    public abstract void setDefaultTextEncodingName(String encoding);
 
     /**
      * Gets the default text encoding name.
@@ -1372,17 +1202,13 @@
      * @return the default text encoding name as a string
      * @see #setDefaultTextEncodingName
      */
-    public synchronized String getDefaultTextEncodingName() {
-        throw new MustOverrideException();
-    }
+    public abstract String getDefaultTextEncodingName();
 
     /**
      * Sets the WebView's user-agent string. If the string is null or empty,
      * the system default value will be used.
      */
-    public synchronized void setUserAgentString(String ua) {
-        throw new MustOverrideException();
-    }
+    public abstract void setUserAgentString(String ua);
 
     /**
      * Gets the WebView's user-agent string.
@@ -1390,9 +1216,7 @@
      * @return the WebView's user-agent string
      * @see #setUserAgentString
      */
-    public synchronized String getUserAgentString() {
-        throw new MustOverrideException();
-    }
+    public abstract String getUserAgentString();
 
     /**
      * Returns the default User-Agent used by a WebView.
@@ -1412,9 +1236,7 @@
      *
      * @param flag whether the WebView needs to set a node
      */
-    public void setNeedInitialFocus(boolean flag) {
-        throw new MustOverrideException();
-    }
+    public abstract void setNeedInitialFocus(boolean flag);
 
     /**
      * Sets the priority of the Render thread. Unlike the other settings, this
@@ -1426,9 +1248,7 @@
      *             not be supported in future versions.
      */
     @Deprecated
-    public synchronized void setRenderPriority(RenderPriority priority) {
-        throw new MustOverrideException();
-    }
+    public abstract void setRenderPriority(RenderPriority priority);
 
     /**
      * Overrides the way the cache is used. The way the cache is used is based
@@ -1442,9 +1262,7 @@
      *
      * @param mode the mode to use
      */
-    public void setCacheMode(int mode) {
-        throw new MustOverrideException();
-    }
+    public abstract void setCacheMode(int mode);
 
     /**
      * Gets the current setting for overriding the cache mode.
@@ -1452,9 +1270,7 @@
      * @return the current setting for overriding the cache mode
      * @see #setCacheMode
      */
-    public int getCacheMode() {
-        throw new MustOverrideException();
-    }
+    public abstract int getCacheMode();
 
     /**
      * Configures the WebView's behavior when a secure origin attempts to load a resource from an
diff --git a/core/java/android/webkit/WebStorage.java b/core/java/android/webkit/WebStorage.java
index 3bfe9cf..947d0cb 100644
--- a/core/java/android/webkit/WebStorage.java
+++ b/core/java/android/webkit/WebStorage.java
@@ -16,6 +16,8 @@
 
 package android.webkit;
 
+import android.annotation.SystemApi;
+
 import java.util.Map;
 
 /**
@@ -65,23 +67,13 @@
         private long mUsage = 0;
 
         /** @hide */
+        @SystemApi
         protected Origin(String origin, long quota, long usage) {
             mOrigin = origin;
             mQuota = quota;
             mUsage = usage;
         }
 
-        /** @hide */
-        protected Origin(String origin, long quota) {
-            mOrigin = origin;
-            mQuota = quota;
-        }
-
-        /** @hide */
-        protected Origin(String origin) {
-            mOrigin = origin;
-        }
-
         /**
          * Gets the string representation of this origin.
          *
@@ -210,5 +202,6 @@
      * way to call createHandler() and createUIHandler(), so it would not work).
      * @hide
      */
+    @SystemApi
     public WebStorage() {}
 }
diff --git a/core/java/android/webkit/WebView.java b/core/java/android/webkit/WebView.java
index 592d6e2..6793634 100644
--- a/core/java/android/webkit/WebView.java
+++ b/core/java/android/webkit/WebView.java
@@ -16,6 +16,7 @@
 
 package android.webkit;
 
+import android.annotation.SystemApi;
 import android.annotation.Widget;
 import android.content.Context;
 import android.content.res.Configuration;
@@ -256,10 +257,12 @@
      * always stay as a hidden API.
      * @hide
      */
+    @SystemApi
     public static final String DATA_REDUCTION_PROXY_SETTING_CHANGED =
             "android.webkit.DATA_REDUCTION_PROXY_SETTING_CHANGED";
 
     private static final String LOGTAG = "WebView";
+    private static final boolean TRACE = false;
 
     // Throwing an exception for incorrect thread usage if the
     // build target is JB MR2 or newer. Defaults to false, and is
@@ -394,6 +397,7 @@
         /**
          * @hide Only for use by WebViewProvider implementations
          */
+        @SystemApi
         public HitTestResult() {
             mType = UNKNOWN_TYPE;
         }
@@ -401,6 +405,7 @@
         /**
          * @hide Only for use by WebViewProvider implementations
          */
+        @SystemApi
         public void setType(int type) {
             mType = type;
         }
@@ -408,6 +413,7 @@
         /**
          * @hide Only for use by WebViewProvider implementations
          */
+        @SystemApi
         public void setExtra(String extra) {
             mExtra = extra;
         }
@@ -542,7 +548,7 @@
         sEnforceThreadChecking = context.getApplicationInfo().targetSdkVersion >=
                 Build.VERSION_CODES.JELLY_BEAN_MR2;
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "WebView<init>");
+        if (TRACE) Log.d(LOGTAG, "WebView<init>");
 
         ensureProviderCreated();
         mProvider.init(javaScriptInterfaces, privateBrowsing);
@@ -557,7 +563,7 @@
      */
     public void setHorizontalScrollbarOverlay(boolean overlay) {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "setHorizontalScrollbarOverlay=" + overlay);
+        if (TRACE) Log.d(LOGTAG, "setHorizontalScrollbarOverlay=" + overlay);
         mProvider.setHorizontalScrollbarOverlay(overlay);
     }
 
@@ -568,7 +574,7 @@
      */
     public void setVerticalScrollbarOverlay(boolean overlay) {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "setVerticalScrollbarOverlay=" + overlay);
+        if (TRACE) Log.d(LOGTAG, "setVerticalScrollbarOverlay=" + overlay);
         mProvider.setVerticalScrollbarOverlay(overlay);
     }
 
@@ -623,7 +629,7 @@
     @Deprecated
     public void setCertificate(SslCertificate certificate) {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "setCertificate=" + certificate);
+        if (TRACE) Log.d(LOGTAG, "setCertificate=" + certificate);
         mProvider.setCertificate(certificate);
     }
 
@@ -647,7 +653,7 @@
     @Deprecated
     public void savePassword(String host, String username, String password) {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "savePassword=" + host);
+        if (TRACE) Log.d(LOGTAG, "savePassword=" + host);
         mProvider.savePassword(host, username, password);
     }
 
@@ -667,7 +673,7 @@
     public void setHttpAuthUsernamePassword(String host, String realm,
             String username, String password) {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "setHttpAuthUsernamePassword=" + host);
+        if (TRACE) Log.d(LOGTAG, "setHttpAuthUsernamePassword=" + host);
         mProvider.setHttpAuthUsernamePassword(host, realm, username, password);
     }
 
@@ -697,7 +703,7 @@
      */
     public void destroy() {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "destroy");
+        if (TRACE) Log.d(LOGTAG, "destroy");
         mProvider.destroy();
     }
 
@@ -743,7 +749,7 @@
      */
     public void setNetworkAvailable(boolean networkUp) {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "setNetworkAvailable=" + networkUp);
+        if (TRACE) Log.d(LOGTAG, "setNetworkAvailable=" + networkUp);
         mProvider.setNetworkAvailable(networkUp);
     }
 
@@ -760,7 +766,7 @@
      */
     public WebBackForwardList saveState(Bundle outState) {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "saveState");
+        if (TRACE) Log.d(LOGTAG, "saveState");
         return mProvider.saveState(outState);
     }
 
@@ -777,7 +783,7 @@
     @Deprecated
     public boolean savePicture(Bundle b, final File dest) {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "savePicture=" + dest.getName());
+        if (TRACE) Log.d(LOGTAG, "savePicture=" + dest.getName());
         return mProvider.savePicture(b, dest);
     }
 
@@ -795,7 +801,7 @@
     @Deprecated
     public boolean restorePicture(Bundle b, File src) {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "restorePicture=" + src.getName());
+        if (TRACE) Log.d(LOGTAG, "restorePicture=" + src.getName());
         return mProvider.restorePicture(b, src);
     }
 
@@ -813,7 +819,7 @@
      */
     public WebBackForwardList restoreState(Bundle inState) {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "restoreState");
+        if (TRACE) Log.d(LOGTAG, "restoreState");
         return mProvider.restoreState(inState);
     }
 
@@ -830,7 +836,7 @@
      */
     public void loadUrl(String url, Map<String, String> additionalHttpHeaders) {
         checkThread();
-        if (DebugFlags.TRACE_API) {
+        if (TRACE) {
             StringBuilder headers = new StringBuilder();
             if (additionalHttpHeaders != null) {
                 for (Map.Entry<String, String> entry : additionalHttpHeaders.entrySet()) {
@@ -849,7 +855,7 @@
      */
     public void loadUrl(String url) {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "loadUrl=" + url);
+        if (TRACE) Log.d(LOGTAG, "loadUrl=" + url);
         mProvider.loadUrl(url);
     }
 
@@ -864,7 +870,7 @@
      */
     public void postUrl(String url, byte[] postData) {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "postUrl=" + url);
+        if (TRACE) Log.d(LOGTAG, "postUrl=" + url);
         if (URLUtil.isNetworkUrl(url)) {
             mProvider.postUrl(url, postData);
         } else {
@@ -903,7 +909,7 @@
      */
     public void loadData(String data, String mimeType, String encoding) {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "loadData");
+        if (TRACE) Log.d(LOGTAG, "loadData");
         mProvider.loadData(data, mimeType, encoding);
     }
 
@@ -936,7 +942,7 @@
     public void loadDataWithBaseURL(String baseUrl, String data,
             String mimeType, String encoding, String historyUrl) {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "loadDataWithBaseURL=" + baseUrl);
+        if (TRACE) Log.d(LOGTAG, "loadDataWithBaseURL=" + baseUrl);
         mProvider.loadDataWithBaseURL(baseUrl, data, mimeType, encoding, historyUrl);
     }
 
@@ -953,7 +959,7 @@
      */
     public void evaluateJavascript(String script, ValueCallback<String> resultCallback) {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "evaluateJavascript=" + script);
+        if (TRACE) Log.d(LOGTAG, "evaluateJavascript=" + script);
         mProvider.evaluateJavaScript(script, resultCallback);
     }
 
@@ -964,7 +970,7 @@
      */
     public void saveWebArchive(String filename) {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "saveWebArchive=" + filename);
+        if (TRACE) Log.d(LOGTAG, "saveWebArchive=" + filename);
         mProvider.saveWebArchive(filename);
     }
 
@@ -982,7 +988,7 @@
      */
     public void saveWebArchive(String basename, boolean autoname, ValueCallback<String> callback) {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "saveWebArchive(auto)=" + basename);
+        if (TRACE) Log.d(LOGTAG, "saveWebArchive(auto)=" + basename);
         mProvider.saveWebArchive(basename, autoname, callback);
     }
 
@@ -991,7 +997,7 @@
      */
     public void stopLoading() {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "stopLoading");
+        if (TRACE) Log.d(LOGTAG, "stopLoading");
         mProvider.stopLoading();
     }
 
@@ -1000,7 +1006,7 @@
      */
     public void reload() {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "reload");
+        if (TRACE) Log.d(LOGTAG, "reload");
         mProvider.reload();
     }
 
@@ -1019,7 +1025,7 @@
      */
     public void goBack() {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "goBack");
+        if (TRACE) Log.d(LOGTAG, "goBack");
         mProvider.goBack();
     }
 
@@ -1038,7 +1044,7 @@
      */
     public void goForward() {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "goForward");
+        if (TRACE) Log.d(LOGTAG, "goForward");
         mProvider.goForward();
     }
 
@@ -1064,7 +1070,7 @@
      */
     public void goBackOrForward(int steps) {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "goBackOrForwad=" + steps);
+        if (TRACE) Log.d(LOGTAG, "goBackOrForwad=" + steps);
         mProvider.goBackOrForward(steps);
     }
 
@@ -1084,7 +1090,7 @@
      */
     public boolean pageUp(boolean top) {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "pageUp");
+        if (TRACE) Log.d(LOGTAG, "pageUp");
         return mProvider.pageUp(top);
     }
 
@@ -1096,7 +1102,7 @@
      */
     public boolean pageDown(boolean bottom) {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "pageDown");
+        if (TRACE) Log.d(LOGTAG, "pageDown");
         return mProvider.pageDown(bottom);
     }
 
@@ -1109,7 +1115,7 @@
     @Deprecated
     public void clearView() {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "clearView");
+        if (TRACE) Log.d(LOGTAG, "clearView");
         mProvider.clearView();
     }
 
@@ -1140,7 +1146,7 @@
     @Deprecated
     public Picture capturePicture() {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "capturePicture");
+        if (TRACE) Log.d(LOGTAG, "capturePicture");
         return mProvider.capturePicture();
     }
 
@@ -1151,7 +1157,7 @@
     @Deprecated
     public PrintDocumentAdapter createPrintDocumentAdapter() {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "createPrintDocumentAdapter");
+        if (TRACE) Log.d(LOGTAG, "createPrintDocumentAdapter");
         return mProvider.createPrintDocumentAdapter("default");
     }
 
@@ -1170,7 +1176,7 @@
      */
     public PrintDocumentAdapter createPrintDocumentAdapter(String documentName) {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "createPrintDocumentAdapter");
+        if (TRACE) Log.d(LOGTAG, "createPrintDocumentAdapter");
         return mProvider.createPrintDocumentAdapter(documentName);
     }
 
@@ -1210,7 +1216,7 @@
      */
     public void setInitialScale(int scaleInPercent) {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "setInitialScale=" + scaleInPercent);
+        if (TRACE) Log.d(LOGTAG, "setInitialScale=" + scaleInPercent);
         mProvider.setInitialScale(scaleInPercent);
     }
 
@@ -1221,7 +1227,7 @@
      */
     public void invokeZoomPicker() {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "invokeZoomPicker");
+        if (TRACE) Log.d(LOGTAG, "invokeZoomPicker");
         mProvider.invokeZoomPicker();
     }
 
@@ -1245,7 +1251,7 @@
      */
     public HitTestResult getHitTestResult() {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "getHitTestResult");
+        if (TRACE) Log.d(LOGTAG, "getHitTestResult");
         return mProvider.getHitTestResult();
     }
 
@@ -1264,7 +1270,7 @@
      */
     public void requestFocusNodeHref(Message hrefMsg) {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "requestFocusNodeHref");
+        if (TRACE) Log.d(LOGTAG, "requestFocusNodeHref");
         mProvider.requestFocusNodeHref(hrefMsg);
     }
 
@@ -1277,7 +1283,7 @@
      */
     public void requestImageRef(Message msg) {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "requestImageRef");
+        if (TRACE) Log.d(LOGTAG, "requestImageRef");
         mProvider.requestImageRef(msg);
     }
 
@@ -1382,7 +1388,7 @@
      */
     public void pauseTimers() {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "pauseTimers");
+        if (TRACE) Log.d(LOGTAG, "pauseTimers");
         mProvider.pauseTimers();
     }
 
@@ -1392,7 +1398,7 @@
      */
     public void resumeTimers() {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "resumeTimers");
+        if (TRACE) Log.d(LOGTAG, "resumeTimers");
         mProvider.resumeTimers();
     }
 
@@ -1405,7 +1411,7 @@
      */
     public void onPause() {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "onPause");
+        if (TRACE) Log.d(LOGTAG, "onPause");
         mProvider.onPause();
     }
 
@@ -1414,7 +1420,7 @@
      */
     public void onResume() {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "onResume");
+        if (TRACE) Log.d(LOGTAG, "onResume");
         mProvider.onResume();
     }
 
@@ -1437,7 +1443,7 @@
     @Deprecated
     public void freeMemory() {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "freeMemory");
+        if (TRACE) Log.d(LOGTAG, "freeMemory");
         mProvider.freeMemory();
     }
 
@@ -1449,7 +1455,7 @@
      */
     public void clearCache(boolean includeDiskFiles) {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "clearCache");
+        if (TRACE) Log.d(LOGTAG, "clearCache");
         mProvider.clearCache(includeDiskFiles);
     }
 
@@ -1461,7 +1467,7 @@
      */
     public void clearFormData() {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "clearFormData");
+        if (TRACE) Log.d(LOGTAG, "clearFormData");
         mProvider.clearFormData();
     }
 
@@ -1470,7 +1476,7 @@
      */
     public void clearHistory() {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "clearHistory");
+        if (TRACE) Log.d(LOGTAG, "clearHistory");
         mProvider.clearHistory();
     }
 
@@ -1480,7 +1486,7 @@
      */
     public void clearSslPreferences() {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "clearSslPreferences");
+        if (TRACE) Log.d(LOGTAG, "clearSslPreferences");
         mProvider.clearSslPreferences();
     }
 
@@ -1496,7 +1502,7 @@
      *                   callback. The runnable will be called in UI thread.
      */
     public static void clearClientCertPreferences(Runnable onCleared) {
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "clearClientCertPreferences");
+        if (TRACE) Log.d(LOGTAG, "clearClientCertPreferences");
         getFactory().getStatics().clearClientCertPreferences(onCleared);
     }
 
@@ -1538,7 +1544,7 @@
      */
     public void findNext(boolean forward) {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "findNext");
+        if (TRACE) Log.d(LOGTAG, "findNext");
         mProvider.findNext(forward);
     }
 
@@ -1554,7 +1560,7 @@
     @Deprecated
     public int findAll(String find) {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "findAll");
+        if (TRACE) Log.d(LOGTAG, "findAll");
         StrictMode.noteSlowCall("findAll blocks UI: prefer findAllAsync");
         return mProvider.findAll(find);
     }
@@ -1569,7 +1575,7 @@
      */
     public void findAllAsync(String find) {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "findAllAsync");
+        if (TRACE) Log.d(LOGTAG, "findAllAsync");
         mProvider.findAllAsync(find);
     }
 
@@ -1590,7 +1596,7 @@
     @Deprecated
     public boolean showFindDialog(String text, boolean showIme) {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "showFindDialog");
+        if (TRACE) Log.d(LOGTAG, "showFindDialog");
         return mProvider.showFindDialog(text, showIme);
     }
 
@@ -1646,7 +1652,7 @@
      */
     public void clearMatches() {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "clearMatches");
+        if (TRACE) Log.d(LOGTAG, "clearMatches");
         mProvider.clearMatches();
     }
 
@@ -1707,7 +1713,7 @@
     @Deprecated
     public void setPictureListener(PictureListener listener) {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "setPictureListener=" + listener);
+        if (TRACE) Log.d(LOGTAG, "setPictureListener=" + listener);
         mProvider.setPictureListener(listener);
     }
 
@@ -1764,7 +1770,7 @@
      */
     public void addJavascriptInterface(Object object, String name) {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "addJavascriptInterface=" + name);
+        if (TRACE) Log.d(LOGTAG, "addJavascriptInterface=" + name);
         mProvider.addJavascriptInterface(object, name);
     }
 
@@ -1777,7 +1783,7 @@
      */
     public void removeJavascriptInterface(String name) {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "removeJavascriptInterface=" + name);
+        if (TRACE) Log.d(LOGTAG, "removeJavascriptInterface=" + name);
         mProvider.removeJavascriptInterface(name);
     }
 
@@ -1881,7 +1887,7 @@
 
     public void flingScroll(int vx, int vy) {
         checkThread();
-        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "flingScroll");
+        if (TRACE) Log.d(LOGTAG, "flingScroll");
         mProvider.flingScroll(vx, vy);
     }
 
@@ -2006,6 +2012,7 @@
      *
      * @hide WebViewProvider is not public API.
      */
+    @SystemApi
     public WebViewProvider getWebViewProvider() {
         return mProvider;
     }
@@ -2015,6 +2022,7 @@
      * and fields, and make super-class calls in this WebView instance.
      * @hide Only for use by WebViewProvider implementations
      */
+    @SystemApi
     public class PrivateAccess {
         // ---- Access to super-class methods ----
         public int super_getScrollBarStyle() {
diff --git a/core/java/android/webkit/WebViewDatabase.java b/core/java/android/webkit/WebViewDatabase.java
index 99e0ffb..bfea481 100644
--- a/core/java/android/webkit/WebViewDatabase.java
+++ b/core/java/android/webkit/WebViewDatabase.java
@@ -16,6 +16,7 @@
 
 package android.webkit;
 
+import android.annotation.SystemApi;
 import android.content.Context;
 
 /**
@@ -28,18 +29,12 @@
  *  <li>Data entered into text fields (e.g. for autocomplete suggestions)</li>
  * </ul>
  */
-public class WebViewDatabase {
+public abstract class WebViewDatabase {
     /**
      * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}
      */
     protected static final String LOGTAG = "webviewdatabase";
 
-    /**
-     * @hide Only for use by WebViewProvider implementations.
-     */
-    protected WebViewDatabase() {
-    }
-
     public static WebViewDatabase getInstance(Context context) {
         return WebViewFactory.getProvider().getWebViewDatabase(context);
     }
@@ -54,9 +49,7 @@
      * @deprecated Saving passwords in WebView will not be supported in future versions.
      */
     @Deprecated
-    public boolean hasUsernamePassword() {
-        throw new MustOverrideException();
-    }
+    public abstract boolean hasUsernamePassword();
 
     /**
      * Clears any saved username/password pairs for web forms.
@@ -67,9 +60,7 @@
      * @deprecated Saving passwords in WebView will not be supported in future versions.
      */
     @Deprecated
-    public void clearUsernamePassword() {
-        throw new MustOverrideException();
-    }
+    public abstract void clearUsernamePassword();
 
     /**
      * Gets whether there are any saved credentials for HTTP authentication.
@@ -79,9 +70,7 @@
      * @see WebView#setHttpAuthUsernamePassword
      * @see #clearHttpAuthUsernamePassword
      */
-    public boolean hasHttpAuthUsernamePassword() {
-        throw new MustOverrideException();
-    }
+    public abstract boolean hasHttpAuthUsernamePassword();
 
     /**
      * Clears any saved credentials for HTTP authentication.
@@ -90,9 +79,7 @@
      * @see WebView#setHttpAuthUsernamePassword
      * @see #hasHttpAuthUsernamePassword
      */
-    public void clearHttpAuthUsernamePassword() {
-        throw new MustOverrideException();
-    }
+    public abstract void clearHttpAuthUsernamePassword();
 
     /**
      * Gets whether there is any saved data for web forms.
@@ -100,16 +87,12 @@
      * @return whether there is any saved data for web forms
      * @see #clearFormData
      */
-    public boolean hasFormData() {
-        throw new MustOverrideException();
-    }
+    public abstract boolean hasFormData();
 
     /**
      * Clears any saved data for web forms.
      *
      * @see #hasFormData
      */
-    public void clearFormData() {
-        throw new MustOverrideException();
-    }
+    public abstract void clearFormData();
 }
diff --git a/core/java/android/webkit/WebViewDelegate.java b/core/java/android/webkit/WebViewDelegate.java
new file mode 100644
index 0000000..a247c46
--- /dev/null
+++ b/core/java/android/webkit/WebViewDelegate.java
@@ -0,0 +1,162 @@
+/*
+ * 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.
+ */
+
+package android.webkit;
+
+import android.annotation.SystemApi;
+import android.app.ActivityThread;
+import android.app.Application;
+import android.content.Context;
+import android.content.res.Resources;
+import android.graphics.Canvas;
+import android.os.SystemProperties;
+import android.os.Trace;
+import android.util.SparseArray;
+import android.view.HardwareCanvas;
+import android.view.View;
+import android.view.ViewRootImpl;
+
+/**
+ * Delegate used by the WebView provider implementation to access
+ * the required framework functionality needed to implement a {@link WebView}.
+ *
+ * @hide
+ */
+@SystemApi
+public final class WebViewDelegate {
+
+    /* package */ WebViewDelegate() { }
+
+    /**
+     * Listener that gets notified whenever tracing has been enabled/disabled.
+     */
+    public interface OnTraceEnabledChangeListener {
+        void onTraceEnabledChange(boolean enabled);
+    }
+
+    /**
+     * Register a callback to be invoked when tracing for the WebView component has been
+     * enabled/disabled.
+     */
+    public void setOnTraceEnabledChangeListener(final OnTraceEnabledChangeListener listener) {
+        SystemProperties.addChangeCallback(new Runnable() {
+            @Override
+            public void run() {
+                listener.onTraceEnabledChange(isTraceTagEnabled());
+            }
+        });
+    }
+
+    /**
+     * Returns true if the WebView trace tag is enabled and false otherwise.
+     */
+    public boolean isTraceTagEnabled() {
+        return Trace.isTagEnabled(Trace.TRACE_TAG_WEBVIEW);
+    }
+
+    /**
+     * Returns true if the draw GL functor can be invoked (see {@link #invokeDrawGlFunctor})
+     * and false otherwise.
+     */
+    public boolean canInvokeDrawGlFunctor(View containerView) {
+        ViewRootImpl viewRootImpl = containerView.getViewRootImpl();
+         // viewRootImpl can be null during teardown when window is leaked.
+        return viewRootImpl != null;
+    }
+
+    /**
+     * Invokes the draw GL functor. If waitForCompletion is false the functor
+     * may be invoked asynchronously.
+     *
+     * @param nativeDrawGLFunctor the pointer to the native functor that implements
+     *        system/core/include/utils/Functor.h
+     */
+    public void invokeDrawGlFunctor(View containerView, long nativeDrawGLFunctor,
+            boolean waitForCompletion) {
+        ViewRootImpl viewRootImpl = containerView.getViewRootImpl();
+        viewRootImpl.invokeFunctor(nativeDrawGLFunctor, waitForCompletion);
+    }
+
+    /**
+     * Calls the function specified with the nativeDrawGLFunctor functor pointer. This
+     * functionality is used by the WebView for calling into their renderer from the
+     * framework display lists.
+     *
+     * @param canvas a hardware accelerated canvas (see {@link Canvas#isHardwareAccelerated()})
+     * @param nativeDrawGLFunctor the pointer to the native functor that implements
+     *        system/core/include/utils/Functor.h
+     * @throws IllegalArgumentException if the canvas is not hardware accelerated
+     */
+    public void callDrawGlFunction(Canvas canvas, long nativeDrawGLFunctor) {
+        if (!(canvas instanceof HardwareCanvas)) {
+            // Canvas#isHardwareAccelerated() is only true for subclasses of HardwareCanvas.
+            throw new IllegalArgumentException(canvas.getClass().getName()
+                    + " is not hardware accelerated");
+        }
+        ((HardwareCanvas) canvas).callDrawGLFunction(nativeDrawGLFunctor);
+    }
+
+    /**
+     * Detaches the draw GL functor.
+     *
+     * @param nativeDrawGLFunctor the pointer to the native functor that implements
+     *        system/core/include/utils/Functor.h
+     */
+    public void detachDrawGlFunctor(View containerView, long nativeDrawGLFunctor) {
+        ViewRootImpl viewRootImpl = containerView.getViewRootImpl();
+        if (nativeDrawGLFunctor != 0 && viewRootImpl != null) {
+            viewRootImpl.detachFunctor(nativeDrawGLFunctor);
+        }
+    }
+
+    /**
+     * Returns the package id of the given {@code packageName}.
+     */
+    public int getPackageId(Resources resources, String packageName) {
+        SparseArray<String> packageIdentifiers =
+                resources.getAssets().getAssignedPackageIdentifiers();
+        for (int i = 0; i < packageIdentifiers.size(); i++) {
+            final String name = packageIdentifiers.valueAt(i);
+
+            if (packageName.equals(name)) {
+                return packageIdentifiers.keyAt(i);
+            }
+        }
+        throw new RuntimeException("Package not found: " + packageName);
+    }
+
+    /**
+     * Returns the application which is embedding the WebView.
+     */
+    public Application getApplication() {
+        return ActivityThread.currentApplication();
+    }
+
+    /**
+     * Returns the error string for the given {@code errorCode}.
+     */
+    public String getErrorString(Context context, int errorCode) {
+        return LegacyErrorStrings.getString(errorCode, context);
+    }
+
+    /**
+     * Adds the WebView asset path to {@link AssetManager}.
+     */
+    public void addWebViewAssetPath(Context context) {
+        context.getAssets().addAssetPath(
+                WebViewFactory.getLoadedPackageInfo().applicationInfo.sourceDir);
+    }
+}
diff --git a/core/java/android/webkit/WebViewFactory.java b/core/java/android/webkit/WebViewFactory.java
index c7ffedc..7b23d8f 100644
--- a/core/java/android/webkit/WebViewFactory.java
+++ b/core/java/android/webkit/WebViewFactory.java
@@ -16,6 +16,7 @@
 
 package android.webkit;
 
+import android.annotation.SystemApi;
 import android.app.ActivityManagerInternal;
 import android.app.Application;
 import android.app.AppGlobals;
@@ -46,6 +47,7 @@
  *
  * @hide
  */
+@SystemApi
 public final class WebViewFactory {
 
     private static final String CHROMIUM_WEBVIEW_FACTORY =
@@ -109,7 +111,12 @@
                 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
                 Trace.traceBegin(Trace.TRACE_TAG_WEBVIEW, "providerClass.newInstance()");
                 try {
-                    sProviderInstance = providerClass.newInstance();
+                    try {
+                        sProviderInstance = providerClass.getConstructor(WebViewDelegate.class)
+                                .newInstance(new WebViewDelegate());
+                    } catch (Exception e) {
+                        sProviderInstance = providerClass.newInstance();
+                    }
                     if (DEBUG) Log.v(LOGTAG, "Loaded provider: " + sProviderInstance);
                     return sProviderInstance;
                 } catch (Exception e) {
diff --git a/core/java/android/webkit/WebViewFactoryProvider.java b/core/java/android/webkit/WebViewFactoryProvider.java
index d37d217..9105394 100644
--- a/core/java/android/webkit/WebViewFactoryProvider.java
+++ b/core/java/android/webkit/WebViewFactoryProvider.java
@@ -16,6 +16,7 @@
 
 package android.webkit;
 
+import android.annotation.SystemApi;
 import android.content.Context;
 import android.content.Intent;
 import android.net.Uri;
@@ -26,6 +27,7 @@
  * implementation of this interface, and make it available to the WebView via mechanism TBD.
  * @hide
  */
+@SystemApi
 public interface WebViewFactoryProvider {
     /**
      * This Interface provides glue for implementing the backend of WebView static methods which
diff --git a/core/java/android/webkit/WebViewProvider.java b/core/java/android/webkit/WebViewProvider.java
index fe18138..2aee57b 100644
--- a/core/java/android/webkit/WebViewProvider.java
+++ b/core/java/android/webkit/WebViewProvider.java
@@ -16,6 +16,7 @@
 
 package android.webkit;
 
+import android.annotation.SystemApi;
 import android.content.res.Configuration;
 import android.graphics.Bitmap;
 import android.graphics.Canvas;
@@ -53,6 +54,7 @@
  *
  * @hide Not part of the public API; only required by system implementors.
  */
+@SystemApi
 public interface WebViewProvider {
     //-------------------------------------------------------------------------
     // Main interface for backend provider of the WebView class.
diff --git a/core/java/android/widget/AbsSeekBar.java b/core/java/android/widget/AbsSeekBar.java
index b2cfdf7..6033c42 100644
--- a/core/java/android/widget/AbsSeekBar.java
+++ b/core/java/android/widget/AbsSeekBar.java
@@ -704,19 +704,20 @@
     @Override
     public boolean onKeyDown(int keyCode, KeyEvent event) {
         if (isEnabled()) {
-            int progress = getProgress();
+            int increment = mKeyProgressIncrement;
             switch (keyCode) {
                 case KeyEvent.KEYCODE_DPAD_LEFT:
-                    if (progress <= 0) break;
-                    animateSetProgress(progress - mKeyProgressIncrement);
-                    onKeyChange();
-                    return true;
-
+                    increment = -increment;
+                    // fallthrough
                 case KeyEvent.KEYCODE_DPAD_RIGHT:
-                    if (progress >= getMax()) break;
-                    animateSetProgress(progress + mKeyProgressIncrement);
-                    onKeyChange();
-                    return true;
+                    increment = isLayoutRtl() ? -increment : increment;
+                    int progress = getProgress() + increment;
+                    if (progress > -mKeyProgressIncrement &&
+                        progress < getMax() + mKeyProgressIncrement) {
+                        animateSetProgress(progress);
+                        onKeyChange();
+                        return true;
+                    }
             }
         }
 
diff --git a/core/java/android/widget/DateTimeView.java b/core/java/android/widget/DateTimeView.java
index 45d1403..86cd52f 100644
--- a/core/java/android/widget/DateTimeView.java
+++ b/core/java/android/widget/DateTimeView.java
@@ -149,7 +149,7 @@
                     format = getTimeFormat();
                     break;
                 case SHOW_MONTH_DAY_YEAR:
-                    format = getDateFormat();
+                    format = DateFormat.getDateInstance(DateFormat.SHORT);
                     break;
                 default:
                     throw new RuntimeException("unknown display value: " + display);
@@ -189,21 +189,6 @@
         return android.text.format.DateFormat.getTimeFormat(getContext());
     }
 
-    private DateFormat getDateFormat() {
-        String format = Settings.System.getString(getContext().getContentResolver(),
-                Settings.System.DATE_FORMAT);
-        if (format == null || "".equals(format)) {
-            return DateFormat.getDateInstance(DateFormat.SHORT);
-        } else {
-            try {
-                return new SimpleDateFormat(format);
-            } catch (IllegalArgumentException e) {
-                // If we tried to use a bad format string, fall back to a default.
-                return DateFormat.getDateInstance(DateFormat.SHORT);
-            }
-        }
-    }
-
     private void registerReceivers() {
         Context context = getContext();
 
@@ -213,15 +198,11 @@
         filter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
         filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
         context.registerReceiver(mBroadcastReceiver, filter);
-
-        Uri uri = Settings.System.getUriFor(Settings.System.DATE_FORMAT);
-        context.getContentResolver().registerContentObserver(uri, true, mContentObserver);
     }
 
     private void unregisterReceivers() {
         Context context = getContext();
         context.unregisterReceiver(mBroadcastReceiver);
-        context.getContentResolver().unregisterContentObserver(mContentObserver);
     }
 
     private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
@@ -241,12 +222,4 @@
             update();
         }
     };
-
-    private ContentObserver mContentObserver = new ContentObserver(new Handler()) {
-        @Override
-        public void onChange(boolean selfChange) {
-            mLastFormat = null;
-            update();
-        }
-    };
 }
diff --git a/core/java/android/widget/ListView.java b/core/java/android/widget/ListView.java
index 2e9858c..ba6f061 100644
--- a/core/java/android/widget/ListView.java
+++ b/core/java/android/widget/ListView.java
@@ -2420,10 +2420,15 @@
                         (ViewGroup) selectedView, currentFocus, direction);
                 if (nextFocus != null) {
                     // do the math to get interesting rect in next focus' coordinates
-                    currentFocus.getFocusedRect(mTempRect);
-                    offsetDescendantRectToMyCoords(currentFocus, mTempRect);
-                    offsetRectIntoDescendantCoords(nextFocus, mTempRect);
-                    if (nextFocus.requestFocus(direction, mTempRect)) {
+                    Rect focusedRect = mTempRect;
+                    if (currentFocus != null) {
+                        currentFocus.getFocusedRect(focusedRect);
+                        offsetDescendantRectToMyCoords(currentFocus, focusedRect);
+                        offsetRectIntoDescendantCoords(nextFocus, focusedRect);
+                    } else {
+                        focusedRect = null;
+                    }
+                    if (nextFocus.requestFocus(direction, focusedRect)) {
                         return true;
                     }
                 }
@@ -2556,8 +2561,10 @@
         if (mItemsCanFocus && (focusResult == null)
                 && selectedView != null && selectedView.hasFocus()) {
             final View focused = selectedView.findFocus();
-            if (!isViewAncestorOf(focused, this) || distanceToView(focused) > 0) {
-                focused.clearFocus();
+            if (focused != null) {
+                if (!isViewAncestorOf(focused, this) || distanceToView(focused) > 0) {
+                    focused.clearFocus();
+                }
             }
         }
 
diff --git a/core/java/android/widget/PopupWindow.java b/core/java/android/widget/PopupWindow.java
index 41d3e320..bde6201 100644
--- a/core/java/android/widget/PopupWindow.java
+++ b/core/java/android/widget/PopupWindow.java
@@ -375,9 +375,9 @@
     }
     
     /**
-     * Set the flag on popup to ignore cheek press eventt; by default this flag
+     * Set the flag on popup to ignore cheek press events; by default this flag
      * is set to false
-     * which means the pop wont ignore cheek press dispatch events.
+     * which means the popup will not ignore cheek press dispatch events.
      * 
      * <p>If the popup is showing, calling this method will take effect only
      * the next time the popup is shown or through a manual call to one of
diff --git a/core/java/android/widget/TextView.java b/core/java/android/widget/TextView.java
index 6345b79..dc4d214 100644
--- a/core/java/android/widget/TextView.java
+++ b/core/java/android/widget/TextView.java
@@ -3809,7 +3809,9 @@
             // Display the error later, after the first layout pass
             post(new Runnable() {
                 public void run() {
-                    setError(error);
+                    if (mEditor == null || !mEditor.mErrorWasChanged) {
+                        setError(error);
+                    }
                 }
             });
         }
diff --git a/core/java/com/android/internal/os/WrapperInit.java b/core/java/com/android/internal/os/WrapperInit.java
index 3301cbe..af821ba 100644
--- a/core/java/com/android/internal/os/WrapperInit.java
+++ b/core/java/com/android/internal/os/WrapperInit.java
@@ -62,7 +62,8 @@
             // wrapper that it directly forked).
             if (fdNum != 0) {
                 try {
-                    FileDescriptor fd = ZygoteInit.createFileDescriptor(fdNum);
+                    FileDescriptor fd = new FileDescriptor();
+                    fd.setInt$(fdNum);
                     DataOutputStream os = new DataOutputStream(new FileOutputStream(fd));
                     os.writeInt(Process.myPid());
                     os.close();
diff --git a/core/java/com/android/internal/os/ZygoteConnection.java b/core/java/com/android/internal/os/ZygoteConnection.java
index 24820bc..c03938a 100644
--- a/core/java/com/android/internal/os/ZygoteConnection.java
+++ b/core/java/com/android/internal/os/ZygoteConnection.java
@@ -16,6 +16,11 @@
 
 package com.android.internal.os;
 
+import static android.system.OsConstants.O_CLOEXEC;
+import static android.system.OsConstants.STDERR_FILENO;
+import static android.system.OsConstants.STDIN_FILENO;
+import static android.system.OsConstants.STDOUT_FILENO;
+
 import android.net.Credentials;
 import android.net.LocalSocket;
 import android.os.Process;
@@ -186,10 +191,9 @@
             }
 
             if (parsedArgs.runtimeInit && parsedArgs.invokeWith != null) {
-                FileDescriptor[] pipeFds = Os.pipe();
+                FileDescriptor[] pipeFds = Os.pipe2(O_CLOEXEC);
                 childPipeFd = pipeFds[1];
                 serverPipeFd = pipeFds[0];
-                ZygoteInit.setCloseOnExec(serverPipeFd, true);
             }
 
             /**
@@ -224,8 +228,6 @@
                     parsedArgs.debugFlags, rlimits, parsedArgs.mountExternal, parsedArgs.seInfo,
                     parsedArgs.niceName, fdsToClose, parsedArgs.instructionSet,
                     parsedArgs.appDataDir);
-        } catch (IOException ex) {
-            logAndPrintError(newStderr, "Exception creating pipe", ex);
         } catch (ErrnoException ex) {
             logAndPrintError(newStderr, "Exception creating pipe", ex);
         } catch (IllegalArgumentException ex) {
@@ -857,14 +859,15 @@
 
         if (descriptors != null) {
             try {
-                ZygoteInit.reopenStdio(descriptors[0],
-                        descriptors[1], descriptors[2]);
+                Os.dup2(descriptors[0], STDIN_FILENO);
+                Os.dup2(descriptors[1], STDOUT_FILENO);
+                Os.dup2(descriptors[2], STDERR_FILENO);
 
                 for (FileDescriptor fd: descriptors) {
                     IoUtils.closeQuietly(fd);
                 }
                 newStderr = System.err;
-            } catch (IOException ex) {
+            } catch (ErrnoException ex) {
                 Log.e(TAG, "Error reopening stdio", ex);
             }
         }
@@ -990,8 +993,8 @@
     private void setChildPgid(int pid) {
         // Try to move the new child into the peer's process group.
         try {
-            ZygoteInit.setpgid(pid, ZygoteInit.getpgid(peer.getPid()));
-        } catch (IOException ex) {
+            Os.setpgid(pid, Os.getpgid(peer.getPid()));
+        } catch (ErrnoException ex) {
             // This exception is expected in the case where
             // the peer is not in our session
             // TODO get rid of this log message in the case where
diff --git a/core/java/com/android/internal/os/ZygoteInit.java b/core/java/com/android/internal/os/ZygoteInit.java
index 46850da..0fa9a97 100644
--- a/core/java/com/android/internal/os/ZygoteInit.java
+++ b/core/java/com/android/internal/os/ZygoteInit.java
@@ -16,6 +16,8 @@
 
 package com.android.internal.os;
 
+import static android.system.OsConstants.POLLIN;
+import static android.system.OsConstants.POLLOUT;
 import static android.system.OsConstants.S_IRWXG;
 import static android.system.OsConstants.S_IRWXO;
 
@@ -32,6 +34,7 @@
 import android.system.ErrnoException;
 import android.system.Os;
 import android.system.OsConstants;
+import android.system.StructPollfd;
 import android.util.EventLog;
 import android.util.Log;
 import android.util.Slog;
@@ -45,6 +48,8 @@
 
 import java.io.BufferedReader;
 import java.io.FileDescriptor;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.InputStreamReader;
@@ -91,9 +96,9 @@
     private static Resources mResources;
 
     /**
-     * The name of a resource file that contains classes to preload.
+     * The path of a file that contains classes to preload.
      */
-    private static final String PRELOADED_CLASSES = "preloaded-classes";
+    private static final String PRELOADED_CLASSES = "/system/etc/preloaded-classes";
 
     /** Controls whether we should preload resources during zygote init. */
     private static final boolean PRELOAD_RESOURCES = true;
@@ -163,8 +168,9 @@
             }
 
             try {
-                sServerSocket = new LocalServerSocket(
-                        createFileDescriptor(fileDesc));
+                FileDescriptor fd = new FileDescriptor();
+                fd.setInt$(fileDesc);
+                sServerSocket = new LocalServerSocket(fd);
             } catch (IOException ex) {
                 throw new RuntimeException(
                         "Error binding to local socket '" + fileDesc + "'", ex);
@@ -223,26 +229,6 @@
     private static final int ROOT_UID = 0;
     private static final int ROOT_GID = 0;
 
-    /**
-     * Sets effective user ID.
-     */
-    private static void setEffectiveUser(int uid) {
-        int errno = setreuid(ROOT_UID, uid);
-        if (errno != 0) {
-            Log.e(TAG, "setreuid() failed. errno: " + errno);
-        }
-    }
-
-    /**
-     * Sets effective group ID.
-     */
-    private static void setEffectiveGroup(int gid) {
-        int errno = setregid(ROOT_GID, gid);
-        if (errno != 0) {
-            Log.e(TAG, "setregid() failed. errno: " + errno);
-        }
-    }
-
     static void preload() {
         Log.d(TAG, "begin preload");
         preloadClasses();
@@ -278,73 +264,83 @@
     private static void preloadClasses() {
         final VMRuntime runtime = VMRuntime.getRuntime();
 
-        InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream(
-                PRELOADED_CLASSES);
-        if (is == null) {
+        InputStream is;
+        try {
+            is = new FileInputStream(PRELOADED_CLASSES);
+        } catch (FileNotFoundException e) {
             Log.e(TAG, "Couldn't find " + PRELOADED_CLASSES + ".");
-        } else {
-            Log.i(TAG, "Preloading classes...");
-            long startTime = SystemClock.uptimeMillis();
+            return;
+        }
 
-            // Drop root perms while running static initializers.
-            setEffectiveGroup(UNPRIVILEGED_GID);
-            setEffectiveUser(UNPRIVILEGED_UID);
+        Log.i(TAG, "Preloading classes...");
+        long startTime = SystemClock.uptimeMillis();
 
-            // Alter the target heap utilization.  With explicit GCs this
-            // is not likely to have any effect.
-            float defaultUtilization = runtime.getTargetHeapUtilization();
-            runtime.setTargetHeapUtilization(0.8f);
+        // Drop root perms while running static initializers.
+        try {
+            Os.setregid(ROOT_GID, UNPRIVILEGED_GID);
+            Os.setreuid(ROOT_UID, UNPRIVILEGED_UID);
+        } catch (ErrnoException ex) {
+            throw new RuntimeException("Failed to drop root", ex);
+        }
 
-            try {
-                BufferedReader br
-                    = new BufferedReader(new InputStreamReader(is), 256);
+        // Alter the target heap utilization.  With explicit GCs this
+        // is not likely to have any effect.
+        float defaultUtilization = runtime.getTargetHeapUtilization();
+        runtime.setTargetHeapUtilization(0.8f);
 
-                int count = 0;
-                String line;
-                while ((line = br.readLine()) != null) {
-                    // Skip comments and blank lines.
-                    line = line.trim();
-                    if (line.startsWith("#") || line.equals("")) {
-                        continue;
-                    }
+        try {
+            BufferedReader br
+                = new BufferedReader(new InputStreamReader(is), 256);
 
-                    try {
-                        if (false) {
-                            Log.v(TAG, "Preloading " + line + "...");
-                        }
-                        Class.forName(line);
-                        count++;
-                    } catch (ClassNotFoundException e) {
-                        Log.w(TAG, "Class not found for preloading: " + line);
-                    } catch (UnsatisfiedLinkError e) {
-                        Log.w(TAG, "Problem preloading " + line + ": " + e);
-                    } catch (Throwable t) {
-                        Log.e(TAG, "Error preloading " + line + ".", t);
-                        if (t instanceof Error) {
-                            throw (Error) t;
-                        }
-                        if (t instanceof RuntimeException) {
-                            throw (RuntimeException) t;
-                        }
-                        throw new RuntimeException(t);
-                    }
+            int count = 0;
+            String line;
+            while ((line = br.readLine()) != null) {
+                // Skip comments and blank lines.
+                line = line.trim();
+                if (line.startsWith("#") || line.equals("")) {
+                    continue;
                 }
 
-                Log.i(TAG, "...preloaded " + count + " classes in "
-                        + (SystemClock.uptimeMillis()-startTime) + "ms.");
-            } catch (IOException e) {
-                Log.e(TAG, "Error reading " + PRELOADED_CLASSES + ".", e);
-            } finally {
-                IoUtils.closeQuietly(is);
-                // Restore default.
-                runtime.setTargetHeapUtilization(defaultUtilization);
+                try {
+                    if (false) {
+                        Log.v(TAG, "Preloading " + line + "...");
+                    }
+                    Class.forName(line);
+                    count++;
+                } catch (ClassNotFoundException e) {
+                    Log.w(TAG, "Class not found for preloading: " + line);
+                } catch (UnsatisfiedLinkError e) {
+                    Log.w(TAG, "Problem preloading " + line + ": " + e);
+                } catch (Throwable t) {
+                    Log.e(TAG, "Error preloading " + line + ".", t);
+                    if (t instanceof Error) {
+                        throw (Error) t;
+                    }
+                    if (t instanceof RuntimeException) {
+                        throw (RuntimeException) t;
+                    }
+                    throw new RuntimeException(t);
+                }
+            }
 
-                // Fill in dex caches with classes, fields, and methods brought in by preloading.
-                runtime.preloadDexCaches();
+            Log.i(TAG, "...preloaded " + count + " classes in "
+                    + (SystemClock.uptimeMillis()-startTime) + "ms.");
+        } catch (IOException e) {
+            Log.e(TAG, "Error reading " + PRELOADED_CLASSES + ".", e);
+        } finally {
+            IoUtils.closeQuietly(is);
+            // Restore default.
+            runtime.setTargetHeapUtilization(defaultUtilization);
 
-                // Bring back root. We'll need it later.
-                setEffectiveUser(ROOT_UID);
-                setEffectiveGroup(ROOT_GID);
+            // Fill in dex caches with classes, fields, and methods brought in by preloading.
+            runtime.preloadDexCaches();
+
+            // Bring back root. We'll need it later.
+            try {
+                Os.setreuid(ROOT_UID, ROOT_UID);
+                Os.setregid(ROOT_GID, ROOT_GID);
+            } catch (ErrnoException ex) {
+                throw new RuntimeException("Failed to restore root", ex);
             }
         }
     }
@@ -694,119 +690,42 @@
     private static void runSelectLoop(String abiList) throws MethodAndArgsCaller {
         ArrayList<FileDescriptor> fds = new ArrayList<FileDescriptor>();
         ArrayList<ZygoteConnection> peers = new ArrayList<ZygoteConnection>();
-        FileDescriptor[] fdArray = new FileDescriptor[4];
 
         fds.add(sServerSocket.getFileDescriptor());
         peers.add(null);
 
         while (true) {
-            int index;
-
-            try {
-                fdArray = fds.toArray(fdArray);
-                index = selectReadable(fdArray);
-            } catch (IOException ex) {
-                throw new RuntimeException("Error in select()", ex);
+            StructPollfd[] pollFds = new StructPollfd[fds.size()];
+            for (int i = 0; i < pollFds.length; ++i) {
+                pollFds[i] = new StructPollfd();
+                pollFds[i].fd = fds.get(i);
+                pollFds[i].events = (short) POLLIN;
             }
-
-            if (index < 0) {
-                throw new RuntimeException("Error in select()");
-            } else if (index == 0) {
-                ZygoteConnection newPeer = acceptCommandPeer(abiList);
-                peers.add(newPeer);
-                fds.add(newPeer.getFileDesciptor());
-            } else {
-                boolean done;
-                done = peers.get(index).runOnce();
-
-                if (done) {
-                    peers.remove(index);
-                    fds.remove(index);
+            try {
+                Os.poll(pollFds, -1);
+            } catch (ErrnoException ex) {
+                throw new RuntimeException("poll failed", ex);
+            }
+            for (int i = pollFds.length - 1; i >= 0; --i) {
+                if ((pollFds[i].revents & POLLIN) == 0) {
+                    continue;
+                }
+                if (i == 0) {
+                    ZygoteConnection newPeer = acceptCommandPeer(abiList);
+                    peers.add(newPeer);
+                    fds.add(newPeer.getFileDesciptor());
+                } else {
+                    boolean done = peers.get(i).runOnce();
+                    if (done) {
+                        peers.remove(i);
+                        fds.remove(i);
+                    }
                 }
             }
         }
     }
 
     /**
-     * The Linux syscall "setreuid()"
-     * @param ruid real uid
-     * @param euid effective uid
-     * @return 0 on success, non-zero errno on fail
-     */
-    static native int setreuid(int ruid, int euid);
-
-    /**
-     * The Linux syscall "setregid()"
-     * @param rgid real gid
-     * @param egid effective gid
-     * @return 0 on success, non-zero errno on fail
-     */
-    static native int setregid(int rgid, int egid);
-
-    /**
-     * Invokes the linux syscall "setpgid"
-     *
-     * @param pid pid to change
-     * @param pgid new process group of pid
-     * @return 0 on success or non-zero errno on fail
-     */
-    static native int setpgid(int pid, int pgid);
-
-    /**
-     * Invokes the linux syscall "getpgid"
-     *
-     * @param pid pid to query
-     * @return pgid of pid in question
-     * @throws IOException on error
-     */
-    static native int getpgid(int pid) throws IOException;
-
-    /**
-     * Invokes the syscall dup2() to copy the specified descriptors into
-     * stdin, stdout, and stderr. The existing stdio descriptors will be
-     * closed and errors during close will be ignored. The specified
-     * descriptors will also remain open at their original descriptor numbers,
-     * so the caller may want to close the original descriptors.
-     *
-     * @param in new stdin
-     * @param out new stdout
-     * @param err new stderr
-     * @throws IOException
-     */
-    static native void reopenStdio(FileDescriptor in,
-            FileDescriptor out, FileDescriptor err) throws IOException;
-
-    /**
-     * Toggles the close-on-exec flag for the specified file descriptor.
-     *
-     * @param fd non-null; file descriptor
-     * @param flag desired close-on-exec flag state
-     * @throws IOException
-     */
-    static native void setCloseOnExec(FileDescriptor fd, boolean flag)
-            throws IOException;
-
-    /**
-     * Invokes select() on the provider array of file descriptors (selecting
-     * for readability only). Array elements of null are ignored.
-     *
-     * @param fds non-null; array of readable file descriptors
-     * @return index of descriptor that is now readable or -1 for empty array.
-     * @throws IOException if an error occurs
-     */
-    static native int selectReadable(FileDescriptor[] fds) throws IOException;
-
-    /**
-     * Creates a file descriptor from an int fd.
-     *
-     * @param fd integer OS file descriptor
-     * @return non-null; FileDescriptor instance
-     * @throws IOException if fd is invalid
-     */
-    static native FileDescriptor createFileDescriptor(int fd)
-            throws IOException;
-
-    /**
      * Class not instantiable.
      */
     private ZygoteInit() {
diff --git a/core/java/com/android/internal/widget/LockPatternUtils.java b/core/java/com/android/internal/widget/LockPatternUtils.java
index d6885da..3326e42 100644
--- a/core/java/com/android/internal/widget/LockPatternUtils.java
+++ b/core/java/com/android/internal/widget/LockPatternUtils.java
@@ -48,6 +48,9 @@
 
 import com.android.internal.R;
 import com.google.android.collect.Lists;
+import java.io.ByteArrayOutputStream;
+import java.nio.charset.StandardCharsets;
+import libcore.util.HexEncoding;
 
 import java.security.MessageDigest;
 import java.security.NoSuchAlgorithmException;
@@ -359,7 +362,7 @@
      */
     public boolean checkPasswordHistory(String password) {
         String passwordHashString = new String(
-                passwordToHash(password, getCurrentOrCallingUserId()));
+                passwordToHash(password, getCurrentOrCallingUserId()), StandardCharsets.UTF_8);
         String passwordHistory = getString(PASSWORD_HISTORY_KEY);
         if (passwordHistory == null) {
             return false;
@@ -860,7 +863,7 @@
                     passwordHistory = "";
                 } else {
                     byte[] hash = passwordToHash(password, userHandle);
-                    passwordHistory = new String(hash) + "," + passwordHistory;
+                    passwordHistory = new String(hash, StandardCharsets.UTF_8) + "," + passwordHistory;
                     // Cut it to contain passwordHistoryLength hashes
                     // and passwordHistoryLength -1 commas.
                     passwordHistory = passwordHistory.substring(0, Math.min(hash.length
@@ -1040,34 +1043,30 @@
      * Generate a hash for the given password. To avoid brute force attacks, we use a salted hash.
      * Not the most secure, but it is at least a second level of protection. First level is that
      * the file is in a location only readable by the system process.
+     *
      * @param password the gesture pattern.
+     *
      * @return the hash of the pattern in a byte array.
      */
     public byte[] passwordToHash(String password, int userId) {
         if (password == null) {
             return null;
         }
-        String algo = null;
-        byte[] hashed = null;
+
         try {
             byte[] saltedPassword = (password + getSalt(userId)).getBytes();
-            byte[] sha1 = MessageDigest.getInstance(algo = "SHA-1").digest(saltedPassword);
-            byte[] md5 = MessageDigest.getInstance(algo = "MD5").digest(saltedPassword);
-            hashed = (toHex(sha1) + toHex(md5)).getBytes();
-        } catch (NoSuchAlgorithmException e) {
-            Log.w(TAG, "Failed to encode string because of missing algorithm: " + algo);
-        }
-        return hashed;
-    }
+            byte[] sha1 = MessageDigest.getInstance("SHA-1").digest(saltedPassword);
+            byte[] md5 = MessageDigest.getInstance("MD5").digest(saltedPassword);
 
-    private static String toHex(byte[] ary) {
-        final String hex = "0123456789ABCDEF";
-        String ret = "";
-        for (int i = 0; i < ary.length; i++) {
-            ret += hex.charAt((ary[i] >> 4) & 0xf);
-            ret += hex.charAt(ary[i] & 0xf);
+            byte[] combined = new byte[sha1.length + md5.length];
+            System.arraycopy(sha1, 0, combined, 0, sha1.length);
+            System.arraycopy(md5, 0, combined, sha1.length, md5.length);
+
+            final char[] hexEncoded = HexEncoding.encode(combined);
+            return new String(hexEncoded).getBytes(StandardCharsets.UTF_8);
+        } catch (NoSuchAlgorithmException e) {
+            throw new AssertionError("Missing digest algorithm: ", e);
         }
-        return ret;
     }
 
     /**
diff --git a/core/jni/Android.mk b/core/jni/Android.mk
index 245e0d2..d070c97 100644
--- a/core/jni/Android.mk
+++ b/core/jni/Android.mk
@@ -11,250 +11,244 @@
 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_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
@@ -262,7 +256,14 @@
 
 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 8bb3173..fb0d5d5 100644
--- a/core/jni/AndroidRuntime.cpp
+++ b/core/jni/AndroidRuntime.cpp
@@ -162,7 +162,6 @@
 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);
@@ -191,12 +190,6 @@
 
 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().
  */
@@ -354,6 +347,15 @@
     return 0;
 }
 
+static bool hasFile(const char* file) {
+    struct stat s;
+    int res = stat(file, &s);
+    if (res == 0) {
+        return S_ISREG(s.st_mode);
+    }
+    return false;
+}
+
 /*
  * Read the persistent locale.
  */
@@ -523,8 +525,6 @@
     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];
@@ -534,8 +534,6 @@
     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];
@@ -564,8 +562,6 @@
     char langOption[sizeof("-Duser.language=") + 3];
     char regionOption[sizeof("-Duser.region=") + 3];
     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;
@@ -584,9 +580,6 @@
         /* 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");
     }
@@ -602,30 +595,6 @@
 
     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);
@@ -652,14 +621,6 @@
     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=");
@@ -675,53 +636,6 @@
     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");
@@ -730,12 +644,6 @@
                        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) {
@@ -744,52 +652,57 @@
         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 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));
 
-    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");
-        }
+    // 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-zip=/system/framework/framework.jar");
-        addOption("-Ximage-compiler-option");
-        addOption("--image-classes=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");
-
+        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;
+    }
+    addOption("-Ximage-compiler-option");
+    addOption("--image-classes=/system/etc/preloaded-classes");
+
+    // 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");
+    } 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, "");
     parseExtraOpts(extraOptsBuf, NULL);
@@ -806,67 +719,65 @@
     /*
      * 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:");
+    // 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:");
+    // 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:");
+    // 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:");
+    // 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:");
+    // 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:");
+    // 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:");
+    // 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:");
+    // 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);
-        }
+    // 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;
@@ -1214,13 +1125,6 @@
     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),
@@ -1313,7 +1217,6 @@
     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 @@
 #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 70cf9a8..fbc1b35 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 <Caches.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_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 @@
 
 ///////////////////////////////////////////////////////////////////////////////
 
-#include <android_runtime/AndroidRuntime.h>
-
 static JNINativeMethod gBitmapMethods[] = {
     {   "nativeCreate",             "([IIIIIIZ)Landroid/graphics/Bitmap;",
         (void*)Bitmap_creator },
@@ -914,10 +911,8 @@
     {   "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 e0abc24..0a95b44 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 @@
 
 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;
@@ -185,8 +179,8 @@
 
         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;
         }
 
@@ -579,52 +573,40 @@
     {   "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");
+    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 = env->FindClass("android/graphics/Bitmap");
-    SkASSERT(bitmap_class);
-    gBitmap_nativeBitmapFieldID = getFieldIDCheck(env, bitmap_class, "mNativeBitmap", "J");
-    gBitmap_ninePatchInsetsFieldID = getFieldIDCheck(env, bitmap_class, "mNinePatchInsets",
+    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 @@
 
 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 91efc8c..3537bcb 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 {
@@ -273,8 +267,6 @@
 
 ///////////////////////////////////////////////////////////////////////////////
 
-#include <android_runtime/AndroidRuntime.h>
-
 static JNINativeMethod gBitmapRegionDecoderMethods[] = {
     {   "nativeDecodeRegion",
         "(JIIIILandroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;",
@@ -307,10 +299,8 @@
     },
 };
 
-#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 @@
 };
 
 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 @@
     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 @@
     { "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 b64ab0d..1a3fa14 100644
--- a/core/jni/android/graphics/CreateJavaOutputStreamAdaptor.cpp
+++ b/core/jni/android/graphics/CreateJavaOutputStreamAdaptor.cpp
@@ -24,7 +24,6 @@
     }
 
     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 @@
 
 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 @@
     {"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 @@
 
 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 e2b31cb..0ce6e49 100644
--- a/core/jni/android/graphics/GraphicsJNI.h
+++ b/core/jni/android/graphics/GraphicsJNI.h
@@ -1,8 +1,6 @@
-#ifndef GraphicsJNI_DEFINED
-#define GraphicsJNI_DEFINED
+#ifndef _ANDROID_GRAPHICS_GRAPHICS_JNI_H_
+#define _ANDROID_GRAPHICS_GRAPHICS_JNI_H_
 
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wunused-parameter"
 #include "SkBitmap.h"
 #include "SkDevice.h"
 #include "SkPixelRef.h"
@@ -10,8 +8,6 @@
 #include "SkPoint.h"
 #include "SkRect.h"
 #include "SkImageDecoder.h"
-#pragma GCC diagnostic pop
-
 #include <jni.h>
 
 class SkBitmapRegionDecoder;
@@ -19,7 +15,7 @@
 
 namespace android {
 class Paint;
-class TypefaceImpl;
+struct TypefaceImpl;
 }
 
 class GraphicsJNI {
@@ -205,7 +201,6 @@
 
 private:
     JavaVM* fVM;
-    bool fAllocateInJavaHeap;
     jbyteArray fStorageObj;
     int fAllocCount;
 };
@@ -293,4 +288,4 @@
 #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 @@
     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 @@
 
 }  // 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 @@
 
 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 @@
     { "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 cbd20e9..43c1dc9 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"
@@ -353,11 +353,10 @@
 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 @@
 
 } // 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 @@
 
 }  // 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 @@
 
 }  // 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 @@
 
 //////////////////////////////////////////////////////////////////////////////////////////////
 
-#include <android_runtime/AndroidRuntime.h>
-
 static JNINativeMethod gMethods[] = {
     {   "width",    "()I",  (void*)movie_width  },
     {   "height",   "()I",  (void*)movie_height  },
@@ -157,22 +151,14 @@
                             (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 cf23771..c7c5131 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 @@
 
 /////////////////////////////////////////////////////////////////////////////////////////
 
-#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 @@
 };
 
 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..4c589b7 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 @@
     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 @@
         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,13 +195,13 @@
     }
     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;
@@ -307,15 +300,15 @@
                 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 @@
     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 4bb31fc..8b5a730 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"
@@ -1018,35 +1018,26 @@
     {"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_class = FindClassOrDie(env, "android/graphics/Paint$FontMetrics");
+    gFontMetrics_class = MakeGlobalRefOrDie(env, 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"));
+    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 = env->FindClass("android/graphics/Paint$FontMetricsInt");
-    SkASSERT(gFontMetricsInt_class);
-    gFontMetricsInt_class = (jclass)env->NewGlobalRef(gFontMetricsInt_class);
+    gFontMetricsInt_class = FindClassOrDie(env, "android/graphics/Paint$FontMetricsInt");
+    gFontMetricsInt_class = MakeGlobalRefOrDie(env, 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"));
+    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");
 
-    int result = AndroidRuntime::registerNativeMethods(env, "android/graphics/Paint", methods,
-        sizeof(methods) / sizeof(methods[0]));
-    return result;
+    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 @@
 
 }  // 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 9d3e74b..ad46053 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 @@
 };
 
 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 @@
     { "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 @@
 };
 
 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 @@
 };
 
 }; // 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 @@
 };
 
 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 @@
     static void finalizer(JNIEnv* env, jobject clazz, jlong objHandle) {
         delete reinterpret_cast<NativeRasterizer *>(objHandle);
     }
- 
 };
 
 static JNINativeMethod gRasterizerMethods[] = {
@@ -67,9 +66,8 @@
 };
 
 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 @@
 
 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 @@
 
 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 @@
 
 } // 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 @@
     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 @@
     { "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;
+    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));
 
-    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;
+    return 0;
 }
diff --git a/core/jni/android/graphics/SurfaceTexture.cpp b/core/jni/android/graphics/SurfaceTexture.cpp
index eea16f1..f06bd21 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 @@
 
 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 @@
 
 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 d129f621..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 @@
 
 }
 
-#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 @@
 
 }; // 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 @@
     {"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 @@
     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 @@
 
 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 @@
             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 @@
 };
 
 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 5f60c9e..a1196af 100644
--- a/core/jni/android/graphics/pdf/PdfEditor.cpp
+++ b/core/jni/android/graphics/pdf/PdfEditor.cpp
@@ -20,7 +20,7 @@
 #include "fpdfedit.h"
 #include "fpdfsave.h"
 
-#include <android_runtime/AndroidRuntime.h>
+#include <core_jni_helpers.h>
 #include <vector>
 #include <utils/Log.h>
 #include <unistd.h>
@@ -72,8 +72,8 @@
 
     if (!document) {
         const long error = FPDF_GetLastError();
-        jniThrowException(env, "java/io/IOException",
-                "cannot create document. Error:" + error);
+        jniThrowExceptionFmt(env, "java/io/IOException",
+                "cannot create document. Error: %ld", error);
         destroyLibraryIfNeeded();
         return -1;
     }
@@ -124,7 +124,7 @@
 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;
     }
@@ -138,8 +138,8 @@
     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();
     }
 }
@@ -153,7 +153,7 @@
 };
 
 int register_android_graphics_pdf_PdfEditor(JNIEnv* env) {
-    return android::AndroidRuntime::registerNativeMethods(
+    return android::RegisterMethodsOrDie(
             env, "android/graphics/pdf/PdfEditor", gPdfEditor_Methods,
             NELEM(gPdfEditor_Methods));
 };
diff --git a/core/jni/android/graphics/pdf/PdfRenderer.cpp b/core/jni/android/graphics/pdf/PdfRenderer.cpp
index 303ddea..bb729ea 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"
-#include "fsdk_rendercontext.h"
 
-#include <android_runtime/AndroidRuntime.h>
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wdelete-non-virtual-dtor"
+#include "fsdk_rendercontext.h"
+#pragma GCC diagnostic pop
+
+#include "core_jni_helpers.h"
 #include <vector>
 #include <utils/Log.h>
 #include <unistd.h>
@@ -82,8 +86,8 @@
 
     if (!document) {
         const long error = FPDF_GetLastError();
-        jniThrowException(env, "java/io/IOException",
-                "cannot create document. Error:" + error);
+        jniThrowExceptionFmt(env, "java/io/IOException",
+                "cannot create document. Error: %ld", error);
         destroyLibraryIfNeeded();
         return -1;
     }
@@ -228,7 +232,6 @@
         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);
@@ -270,13 +273,13 @@
 };
 
 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 @@
 
 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 @@
 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 @@
 /* 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 @@
     jint limit;
     jint elementSizeShift;
     jlong pointer;
-    jint offset;
-    void *data;
 
     position = _env->GetIntField(buffer, positionID);
     limit = _env->GetIntField(buffer, limitID);
@@ -900,10 +896,8 @@
         } 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 @@
         } 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 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 @@
 
 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 @@
     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 @@
         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 @@
         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 @@
 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 @@
 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 @@
 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 @@
 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 @@
 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 @@
 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 @@
 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 @@
 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 @@
 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 @@
 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 @@
 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 @@
 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 @@
 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 @@
 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 @@
 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 @@
 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 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);
+    jclass clazz = FindClassOrDie(env, 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");
+    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 AndroidRuntime::registerNativeMethods(
-        env, kNativeActivityPathName,
-        g_methods, NELEM(g_methods));
+    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 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 @@
 
 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 @@
 {
     //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");
+    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 AndroidRuntime::registerNativeMethods(env, "android/app/backup/BackupDataInput",
-            g_methods, NELEM(g_methods));
+    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 @@
 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 @@
 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 @@
 
 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");
+    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 AndroidRuntime::registerNativeMethods(env, "android/app/backup/BackupHelperDispatcher",
-            g_methods, NELEM(g_methods));
+    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 @@
 
 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 @@
             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 @@
             (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");
+    jclass clazz = FindClassOrDie(env, "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");
+    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 AndroidRuntime::registerNativeMethods(env, "android/content/res/ObbScanner", gMethods,
-            NELEM(gMethods));
+    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 @@
             (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 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 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 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 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 @@
             (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 @@
             (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 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 @@
     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 @@
 };
 
 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 @@
     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 @@
     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 @@
 };
 
 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 @@
 };
 
 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 f8bab24..6f433c5 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>
 
@@ -206,7 +206,7 @@
 
     // 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);
 
@@ -216,7 +216,7 @@
         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;
@@ -402,7 +402,7 @@
                 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
@@ -438,7 +438,7 @@
 }
 
 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();
@@ -474,10 +474,12 @@
     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) {
@@ -740,7 +742,8 @@
     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) {
@@ -988,26 +991,14 @@
     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
@@ -1027,32 +1018,18 @@
         { "android/graphics/Rect", "bottom", "I", &fields.rect_bottom },
     };
 
-    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");
 
     // 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 @@
 
 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 @@
 
 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 7b33bc2..90d1c42 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>
@@ -798,112 +798,102 @@
 
 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 arrayListClass = FindClassOrDie(env, "java/util/ArrayList");
+    gArrayListClass = MakeGlobalRefOrDie(env, arrayListClass);
+    gArrayListMethods.add = GetMethodIDOrDie(env, 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 uuidClass = FindClassOrDie(env, "java/util/UUID");
+    gUUIDClass = MakeGlobalRefOrDie(env, uuidClass);
+    gUUIDMethods.toString = GetMethodIDOrDie(env, uuidClass, "toString", "()Ljava/lang/String;");
 
-    jclass lClass = env->FindClass(kSoundTriggerClassPathName);
-    gSoundTriggerClass = (jclass) env->NewGlobalRef(lClass);
+    jclass lClass = FindClassOrDie(env, kSoundTriggerClassPathName);
+    gSoundTriggerClass = MakeGlobalRefOrDie(env, 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 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 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 = 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 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 = 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 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 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 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 = 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 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 = 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 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 audioFormatClass = FindClassOrDie(env, kAudioFormatClassPathName);
+    gAudioFormatClass = MakeGlobalRefOrDie(env, audioFormatClass);
+    gAudioFormatCstor = GetMethodIDOrDie(env, audioFormatClass, "<init>", "(III)V");
 
-    jclass soundModelEventClass = env->FindClass(kSoundModelEventClassPathName);
-    gSoundModelEventClass = (jclass) env->NewGlobalRef(soundModelEventClass);
-    gSoundModelEventCstor = env->GetMethodID(soundModelEventClass, "<init>",
-                                              "(II[B)V");
+    jclass soundModelEventClass = FindClassOrDie(env, kSoundModelEventClassPathName);
+    gSoundModelEventClass = MakeGlobalRefOrDie(env, soundModelEventClass);
+    gSoundModelEventCstor = GetMethodIDOrDie(env, soundModelEventClass, "<init>", "(II[B)V");
 
 
-    int status = AndroidRuntime::registerNativeMethods(env,
-                kSoundTriggerClassPathName, gMethods, NELEM(gMethods));
-
-    if (status == 0) {
-        status = AndroidRuntime::registerNativeMethods(env,
-                kModuleClassPathName, gModuleMethods, NELEM(gModuleMethods));
-    }
-
-
-    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 @@
 
 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 @@
 
 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 @@
         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 @@
         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 @@
 
     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 @@
                              "Tag (%d) did not have a type", tag);
         return;
     }
-    size_t tagSize = Helpers::getTypeSize(tagType);
 
     status_t res;
 
@@ -597,7 +589,7 @@
 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 @@
     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 @@
 
         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 @@
                 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 @@
                              "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 31c7b9f..bb8de28 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,16 +36,7 @@
 #include <img_utils/Input.h>
 #include <img_utils/StripSource.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 <string.h>
-
-#include "android_runtime/AndroidRuntime.h"
+#include "core_jni_helpers.h"
 #include "android_runtime/android_hardware_camera2_CameraMetadata.h"
 
 #include <jni.h>
@@ -427,7 +427,6 @@
 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;
 
@@ -759,7 +758,8 @@
             }
         }
         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;
         }
     }
@@ -803,29 +803,20 @@
 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);
+    gDngCreatorClassInfo.mNativeContext = GetFieldIDOrDie(env,
+            clazz, ANDROID_DNGCREATOR_CTX_JNI_ID, "J");
 
-    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 outputStreamClazz = FindClassOrDie(env, "java/io/OutputStream");
+    gOutputStreamClassInfo.mWriteMethod = GetMethodIDOrDie(env,
+            outputStreamClazz, "write", "([BII)V");
 
-    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 inputStreamClazz = FindClassOrDie(env, "java/io/InputStream");
+    gInputStreamClassInfo.mReadMethod = GetMethodIDOrDie(env, inputStreamClazz, "read", "([BII)I");
+    gInputStreamClassInfo.mSkipMethod = GetMethodIDOrDie(env, inputStreamClazz, "skip", "(J)J");
 
-    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");
+    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,
@@ -853,7 +844,6 @@
 
     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;
 
@@ -1278,7 +1268,7 @@
             }
 
             BAIL_IF_INVALID(writer->addEntry(TAG_CAMERACALIBRATION2, entry2.count,
-                    calibrationTransform1, TIFF_IFD_0),  env, TAG_CAMERACALIBRATION2, writer);
+                    calibrationTransform2, TIFF_IFD_0),  env, TAG_CAMERACALIBRATION2, writer);
         }
     }
 
@@ -1401,8 +1391,9 @@
 
         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) {
@@ -1637,7 +1628,7 @@
 
     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);
@@ -1797,8 +1788,9 @@
         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);
@@ -1905,12 +1897,12 @@
     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;
     }
@@ -1984,7 +1976,6 @@
 };
 
 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 8440a0e..f75ab17 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"
 
@@ -312,8 +312,8 @@
         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);
@@ -604,7 +604,7 @@
         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;
@@ -719,7 +719,7 @@
 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 @@
 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 @@
     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 e38f3d4..2c36d3d 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>
@@ -605,59 +605,28 @@
 
 
     // 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 f099289..1ef70ea 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>
 
@@ -255,7 +255,9 @@
     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));
@@ -268,7 +270,8 @@
     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());
@@ -1059,7 +1062,7 @@
     return jStatus;
 }
 
-static int
+static jint
 android_media_AudioSystem_releaseAudioPatch(JNIEnv *env, jobject clazz,
                                                jobject jPatch)
 {
@@ -1081,7 +1084,7 @@
     status_t status = AudioSystem::releaseAudioPatch(handle);
     ALOGV("AudioSystem::releaseAudioPatch() returned %d", status);
     jint jStatus = nativeToJavaStatus(status);
-    return status;
+    return jStatus;
 }
 
 static jint
@@ -1161,7 +1164,7 @@
             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);
@@ -1185,7 +1188,7 @@
             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);
@@ -1210,7 +1213,7 @@
             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);
@@ -1354,99 +1357,94 @@
 
 int register_android_media_AudioSystem(JNIEnv *env)
 {
+    jclass arrayListClass = FindClassOrDie(env, "java/util/ArrayList");
+    gArrayListClass = MakeGlobalRefOrDie(env, arrayListClass);
+    gArrayListMethods.add = GetMethodIDOrDie(env, arrayListClass, "add", "(Ljava/lang/Object;)Z");
 
-    jclass arrayListClass = env->FindClass("java/util/ArrayList");
-    gArrayListClass = (jclass) env->NewGlobalRef(arrayListClass);
-    gArrayListMethods.add = env->GetMethodID(arrayListClass, "add", "(Ljava/lang/Object;)Z");
+    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 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 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;");
+    gAudioPortFields.mActiveConfig = GetFieldIDOrDie(env, 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",
+    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");
+    gAudioPortConfigFields.mConfigMask = GetFieldIDOrDie(env, 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 audioDevicePortConfigClass = FindClassOrDie(env, "android/media/AudioDevicePortConfig");
+    gAudioDevicePortConfigClass = MakeGlobalRefOrDie(env, audioDevicePortConfigClass);
+    gAudioDevicePortConfigCstor = GetMethodIDOrDie(env, 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 audioMixPortConfigClass = FindClassOrDie(env, "android/media/AudioMixPortConfig");
+    gAudioMixPortConfigClass = MakeGlobalRefOrDie(env, audioMixPortConfigClass);
+    gAudioMixPortConfigCstor = GetMethodIDOrDie(env, 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 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 = 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 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 = env->FindClass("android/media/AudioGain");
-    gAudioGainClass = (jclass) env->NewGlobalRef(audioGainClass);
-    gAudioGainCstor = env->GetMethodID(audioGainClass, "<init>", "(IIIIIIIII)V");
+    jclass audioGainClass = FindClassOrDie(env, "android/media/AudioGain");
+    gAudioGainClass = MakeGlobalRefOrDie(env, audioGainClass);
+    gAudioGainCstor = GetMethodIDOrDie(env, audioGainClass, "<init>", "(IIIIIIIII)V");
 
-    jclass audioGainConfigClass = env->FindClass("android/media/AudioGainConfig");
-    gAudioGainConfigClass = (jclass) env->NewGlobalRef(audioGainConfigClass);
-    gAudioGainConfigCstor = env->GetMethodID(audioGainConfigClass, "<init>",
+    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");
 
 
     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 @@
     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;
-    }
+    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 AndroidRuntime::registerNativeMethods(env, kClassPathName, gMethods, NELEM(gMethods));
+    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 @@
 
 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 @@
 
 int register_android_media_RemoteDisplay(JNIEnv* env)
 {
-    int err = AndroidRuntime::registerNativeMethods(env, "android/media/RemoteDisplay",
-            gMethods, NELEM(gMethods));
+    int err = RegisterMethodsOrDie(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");
+    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 @@
 
 
 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 a408a96..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;
@@ -492,7 +495,6 @@
         void *buffer, size_t len)
 {
     ssize_t ret;
-    ssize_t bytesread = 0;
     struct msghdr msg;
     struct iovec iv;
     unsigned char *buf = (unsigned char *)buffer;
@@ -722,7 +724,7 @@
     }
 
     err = socket_write_all(env, object, fd, &b, 1);
-
+    UNUSED(err);
     // A return of -1 above means an exception is pending
 }
 
@@ -758,7 +760,7 @@
 
     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);
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 @@
 
 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");
+    jclass dhcpResultsClass = FindClassOrDie(env, "android/net/DhcpResults");
 
-    return AndroidRuntime::registerNativeMethods(env,
-            NETUTILS_PKG_NAME, gNetworkUtilMethods, NELEM(gNetworkUtilMethods));
+    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 @@
 };
 
 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 @@
 
 ///////////////////////////////////////////////////////////////////////////////
 
-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..c634cb91 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 @@
 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 @@
     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 @@
     // 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 @@
     // 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 7b3528b..141138d 100644
--- a/core/jni/android_os_Debug.cpp
+++ b/core/jni/android_os_Debug.cpp
@@ -68,6 +68,9 @@
     HEAP_DALVIK_LINEARALLOC,
     HEAP_DALVIK_ACCOUNTING,
     HEAP_DALVIK_CODE_CACHE,
+    HEAP_DALVIK_ZYGOTE,
+    HEAP_DALVIK_NON_MOVING,
+    HEAP_DALVIK_INDIRECT_REFERENCE_TABLE,
 
     _NUM_HEAP,
     _NUM_EXCLUSIVE_HEAP = HEAP_OTHER_MEMTRACK+1,
@@ -222,13 +225,12 @@
     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;
@@ -272,14 +274,21 @@
                     if (strstr(name, "/dev/ashmem/dalvik-LinearAlloc") == name) {
                         subHeap = HEAP_DALVIK_LINEARALLOC;
                     } else if ((strstr(name, "/dev/ashmem/dalvik-alloc space") == name) ||
-                               (strstr(name, "/dev/ashmem/dalvik-main space") == name) ||
-                               (strstr(name, "/dev/ashmem/dalvik-non moving space") == name)) {
+                               (strstr(name, "/dev/ashmem/dalvik-main space") == name)) {
                         // This is the regular Dalvik heap.
                         whichHeap = HEAP_DALVIK;
                         subHeap = HEAP_DALVIK_NORMAL;
                     } else if (strstr(name, "/dev/ashmem/dalvik-large object space") == name) {
                         whichHeap = HEAP_DALVIK;
                         subHeap = HEAP_DALVIK_LARGE;
+                    } else if (strstr(name, "/dev/ashmem/dalvik-non moving space") == name) {
+                        whichHeap = HEAP_DALVIK;
+                        subHeap = HEAP_DALVIK_NON_MOVING;
+                    } else if (strstr(name, "/dev/ashmem/dalvik-zygote space") == name) {
+                        whichHeap = HEAP_DALVIK;
+                        subHeap = HEAP_DALVIK_ZYGOTE;
+                    } else if (strstr(name, "/dev/ashmem/dalvik-indirect ref") == name) {
+                        subHeap = HEAP_DALVIK_INDIRECT_REFERENCE_TABLE;
                     } else if (strstr(name, "/dev/ashmem/dalvik-jit-code-cache") == name) {
                         subHeap = HEAP_DALVIK_CODE_CACHE;
                     } else {
@@ -346,9 +355,9 @@
             }
 
             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) {
@@ -360,7 +369,7 @@
             } 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) {
@@ -484,7 +493,6 @@
     char line[1024];
     jlong pss = 0;
     jlong uss = 0;
-    unsigned temp;
 
     char tmp[128];
     FILE *fp;
@@ -897,7 +905,8 @@
     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 @@
 
 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 15d62a2..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 {
@@ -157,26 +159,15 @@
     { "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;
-    FIND_CLASS(clazz, "android/os/MessageQueue");
+    jclass clazz = FindClassOrDie(env, "android/os/MessageQueue");
 
-    GET_FIELD_ID(gMessageQueueClassInfo.mPtr, clazz,
-            "mPtr", "J");
-    
-    return 0;
+    gMessageQueueClassInfo.mPtr = GetFieldIDOrDie(env, clazz, "mPtr", "J");
+
+    return res;
 }
 
 } // namespace android
diff --git a/core/jni/android_os_Parcel.cpp b/core/jni/android_os_Parcel.cpp
index 44863cc..16f7d12 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 @@
         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 @@
         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 @@
         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 @@
         // 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_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 @@
             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) {
@@ -743,20 +749,14 @@
 
 int register_android_os_Parcel(JNIEnv* env)
 {
-    jclass clazz;
+    jclass clazz = FindClassOrDie(env, kParcelPathName);
 
-    clazz = env->FindClass(kParcelPathName);
-    LOG_FATAL_IF(clazz == NULL, "Unable to find class android.os.Parcel");
+    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");
 
-    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");
-
-    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 c282549..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>
@@ -469,8 +469,7 @@
 
     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_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_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 @@
 };
 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 @@
 
 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 @@
         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 @@
 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 @@
 
 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..c8aa22f7 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 @@
             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 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 @@
 // 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 @@
 };
 
 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_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 @@
 };
 
 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 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 @@
 
 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..0c2ebf41 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 @@
 
 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 4859ee6..e5cdee0 100644
--- a/core/jni/android_util_AssetManager.cpp
+++ b/core/jni/android_util_AssetManager.cpp
@@ -17,37 +17,38 @@
 
 #define LOG_TAG "asset"
 
-#define DEBUG_STYLES(x) //x
-#define THROW_ON_BAD_ID 0
-
 #include <android_runtime/android_util_AssetManager.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/ResourceTypes.h>
-
-#include <private/android_filesystem_config.h> // for AID_SYSTEM
-
+#include <inttypes.h>
+#include <linux/capability.h>
 #include <stdio.h>
 #include <sys/types.h>
 #include <sys/wait.h>
 
-#include <linux/capability.h>
+#include <private/android_filesystem_config.h> // for AID_SYSTEM
+
+#include "JNIHelp.h"
+#include "ScopedStringChars.h"
+#include "ScopedUtfChars.h"
+#include "android_runtime/AndroidRuntime.h"
+#include "android_util_Binder.h"
+#include "androidfw/Asset.h"
+#include "androidfw/AssetManager.h"
+#include "androidfw/ResourceTypes.h"
+#include "core_jni_helpers.h"
+#include "jni.h"
+#include "utils/Log.h"
+#include "utils/misc.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
@@ -650,23 +651,29 @@
         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;
@@ -803,21 +810,21 @@
     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;
-    }
-#endif
-    uint32_t ref = ident;
-    if (resolve) {
-        block = res.resolveReference(&value, block, &ref, &typeSpecFlags, &config);
-#if THROW_ON_BAD_ID
+    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 (kThrowOnBadId) {
+            if (block == BAD_INDEX) {
+                jniThrowException(env, "java/lang/IllegalStateException", "Bad resource!");
+                return 0;
+            }
+        }
     }
     if (block >= 0) {
         return copyValue(env, outValue, &res, value, ref, block, typeSpecFlags, &config);
@@ -863,12 +870,12 @@
     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);
@@ -926,8 +933,11 @@
     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;
 }
@@ -978,12 +988,12 @@
     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;
 }
@@ -994,6 +1004,7 @@
 {
     ResTable::Theme* theme = reinterpret_cast<ResTable::Theme*>(themeHandle);
     const ResTable& res(theme->getResTable());
+    (void)res;
 
     // XXX Need to use params.
     theme->dumpToLog();
@@ -1021,8 +1032,10 @@
         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();
@@ -1089,7 +1102,9 @@
     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
@@ -1104,8 +1119,9 @@
             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);
+            }
         }
 
         // Skip through the default style values until the end or the next possible match.
@@ -1118,8 +1134,9 @@
                 block = defStyleEnt->stringBlock;
                 typeSetFlags = defStyleTypeSetFlags;
                 value = defStyleEnt->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);
+                }
             }
             defStyleEnt++;
         }
@@ -1130,38 +1147,45 @@
             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;
             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;
@@ -1215,8 +1239,11 @@
         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();
@@ -1313,7 +1340,9 @@
     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
@@ -1334,8 +1363,9 @@
             xmlParser->getAttributeValue(ix, &value);
             ix++;
             curXmlAttr = xmlParser->getAttributeNameResID(ix);
-            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);
+            }
         }
 
         // Skip through the style values until the end or the next possible match.
@@ -1348,8 +1378,9 @@
                 block = styleEnt->stringBlock;
                 typeSetFlags = styleTypeSetFlags;
                 value = styleEnt->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);
+                }
             }
             styleEnt++;
         }
@@ -1364,8 +1395,9 @@
                 block = defStyleEnt->stringBlock;
                 typeSetFlags = defStyleTypeSetFlags;
                 value = defStyleEnt->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);
+                }
             }
             defStyleEnt++;
         }
@@ -1376,38 +1408,44 @@
             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;
             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;
@@ -1536,12 +1574,12 @@
             //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;
         }
 
@@ -1649,12 +1687,12 @@
             //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;
         }
 
@@ -1761,12 +1799,12 @@
             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
@@ -1809,12 +1847,12 @@
 
         // 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);
@@ -1822,7 +1860,8 @@
                 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
@@ -1872,12 +1911,12 @@
 
         // 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;
@@ -1909,7 +1948,6 @@
         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;
@@ -2001,7 +2039,7 @@
         (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 },
@@ -2084,69 +2122,43 @@
     { "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 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 = 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 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 = 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 assetManager = FindClassOrDie(env, "android/content/res/AssetManager");
+    gAssetManagerOffsets.mObject = GetFieldIDOrDie(env, assetManager, "mObject", "J");
 
-    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 stringClass = FindClassOrDie(env, "java/lang/String");
+    g_stringClass = MakeGlobalRefOrDie(env, stringClass);
 
-    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)");
+    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 AndroidRuntime::registerNativeMethods(env,
-            "android/content/res/AssetManager", gAssetManagerMethods, NELEM(gAssetManagerMethods));
+    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 a78c386..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 debug_offsets_t
-{
-    // Class state.
-    jclass mClass;
-
-} gDebugOffsets;
-
-// ----------------------------------------------------------------------------
-
 static struct error_offsets_t
 {
     jclass mClass;
@@ -215,7 +206,6 @@
         sleep(60);
         ALOGE("Forcefully exiting");
         exit(1);
-        *((int *) 1) = 1;
     }
 
 bail:
@@ -836,21 +826,13 @@
 
 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 @@
 
 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 @@
     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 @@
 }
 
 // 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,
@@ -1095,24 +1075,28 @@
     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;
@@ -1237,39 +1221,24 @@
 
 static int int_register_android_os_BinderProxy(JNIEnv* env)
 {
-    jclass clazz;
+    jclass clazz = FindClassOrDie(env, "java/lang/Error");
+    gErrorOffsets.mClass = MakeGlobalRefOrDie(env, 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 = 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");
 
-    clazz = env->FindClass(kBinderProxyPathName);
-    LOG_FATAL_IF(clazz == NULL, "Unable to find class android.os.BinderProxy");
+    gBinderProxyOffsets.mObject = GetFieldIDOrDie(env, clazz, "mObject", "J");
+    gBinderProxyOffsets.mSelf = GetFieldIDOrDie(env, clazz, "mSelf",
+                                                "Ljava/lang/ref/WeakReference;");
+    gBinderProxyOffsets.mOrgue = GetFieldIDOrDie(env, clazz, "mOrgue", "J");
 
-    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);
+    clazz = FindClassOrDie(env, "java/lang/Class");
+    gClassOffsets.mGetName = GetMethodIDOrDie(env, clazz, "getName", "()Ljava/lang/String;");
 
-    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(
+    return RegisterMethodsOrDie(
         env, kBinderProxyPathName,
         gBinderProxyMethods, NELEM(gBinderProxyMethods));
 }
@@ -1287,28 +1256,20 @@
     if (int_register_android_os_BinderProxy(env) < 0)
         return -1;
 
-    jclass clazz;
+    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 = 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 = FindClassOrDie(env, "android/os/ParcelFileDescriptor");
+    gParcelFileDescriptorOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
+    gParcelFileDescriptorOffsets.mConstructor = GetMethodIDOrDie(env, clazz, "<init>",
+                                                                 "(Ljava/io/FileDescriptor;)V");
 
-    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.");
+    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 @@
 
 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 b906cfd..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>
@@ -138,24 +138,12 @@
 
 int register_android_os_FileObserver(JNIEnv* env)
 {
-    jclass clazz;
+    jclass clazz = FindClassOrDie(env, "android/os/FileObserver$ObserverThread");
 
-    clazz = env->FindClass("android/os/FileObserver$ObserverThread");
+    method_onEvent = GetMethodIDOrDie(env, clazz, "onEvent", "(IILjava/lang/String;)V");
 
-    if (clazz == NULL)
-	{
-        ALOGE("Can't find android/os/FileObserver$ObserverThread");
-        return -1;
-    }
-
-    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;
-    }
-
-    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_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 @@
 
 int register_android_util_Log(JNIEnv* env)
 {
-    jclass clazz = env->FindClass("android/util/Log");
+    jclass clazz = FindClassOrDie(env, "android/util/Log");
 
-    if (clazz == NULL) {
-        ALOGE("Can't find android/util/Log");
-        return -1;
-    }
+    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"));
 
-    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"));
-
-    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 2b0960f..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 @@
     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 @@
     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 @@
 {
     ALOGV("%s pid=%d grp=%" PRId32, __func__, pid, grp);
     DIR *d;
-    FILE *fp;
     char proc_path[255];
     struct dirent *de;
 
@@ -191,26 +192,27 @@
     }
     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
@@ -385,7 +387,8 @@
     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);
     }
 
@@ -719,7 +722,7 @@
         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 {
@@ -729,7 +732,9 @@
         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;
         }
@@ -829,7 +834,9 @@
     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;
     }
@@ -840,7 +847,9 @@
     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;
@@ -1045,11 +1054,7 @@
     {"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 @@
 
 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 @@
     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 @@
 
 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 @@
     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 @@
             (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));
-
-#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_DisplayEventReceiver(JNIEnv* env) {
-    int res = jniRegisterNativeMethods(env, "android/view/DisplayEventReceiver",
-            gMethods, NELEM(gMethods));
-    LOG_FATAL_IF(res < 0, "Unable to register native methods.");
+    int res = RegisterMethodsOrDie(env, "android/view/DisplayEventReceiver", gMethods,
+                                   NELEM(gMethods));
 
-    FIND_CLASS(gDisplayEventReceiverClassInfo.clazz, "android/view/DisplayEventReceiver");
+    jclass clazz = FindClassOrDie(env, "android/view/DisplayEventReceiver");
+    gDisplayEventReceiverClassInfo.clazz = MakeGlobalRefOrDie(env, clazz);
 
-    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 2e2b23f..bd125a5 100644
--- a/core/jni/android_view_GLES20Canvas.cpp
+++ b/core/jni/android_view_GLES20Canvas.cpp
@@ -46,10 +46,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
@@ -61,21 +67,7 @@
 // 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
@@ -84,7 +76,9 @@
 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;
 }
 
@@ -833,24 +827,30 @@
 
 #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
 }
 
 // ----------------------------------------------------------------------------
@@ -859,10 +859,10 @@
 
 static void
 android_app_ActivityThread_dumpGraphics(JNIEnv* env, jobject clazz, jobject javaFileDescriptor) {
-#ifdef USE_OPENGL_RENDERER
-    int fd = jniGetFDFromFileDescriptor(env, javaFileDescriptor);
-    android::uirenderer::RenderNode::outputLogBuffer(fd);
-#endif // USE_OPENGL_RENDERER
+    if (kUseOpenGLRenderer) {
+        int fd = jniGetFDFromFileDescriptor(env, javaFileDescriptor);
+        android::uirenderer::RenderNode::outputLogBuffer(fd);
+    }
 }
 
 // ----------------------------------------------------------------------------
@@ -971,32 +971,17 @@
                                                (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 @@
 // ----------------------------------------------------------------------------
 
 // 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 @@
     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 @@
 // 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 @@
 };
 
 int register_android_view_GraphicBuffer(JNIEnv* env) {
-    jclass clazz;
-    FIND_CLASS(clazz, "android/view/GraphicBuffer");
-    GET_FIELD_ID(gGraphicBufferClassInfo.mNativeObject, clazz, "mNativeObject", "J");
+    jclass clazz = FindClassOrDie(env, "android/view/GraphicBuffer");
+    gGraphicBufferClassInfo.mNativeObject = GetFieldIDOrDie(env, 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");
+    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");
 
-    FIND_CLASS(clazz, "android/graphics/Canvas");
-    GET_FIELD_ID(gCanvasClassInfo.mSurfaceFormat, clazz, "mSurfaceFormat", "I");
-    GET_METHOD_ID(gCanvasClassInfo.setNativeBitmap, clazz, "setNativeBitmap", "(J)V");
+    clazz = FindClassOrDie(env, "android/graphics/Canvas");
+    gCanvasClassInfo.mSurfaceFormat = GetFieldIDOrDie(env, clazz, "mSurfaceFormat", "I");
+    gCanvasClassInfo.setNativeBitmap = GetMethodIDOrDie(env, clazz, "setNativeBitmap", "(J)V");
 
-    return AndroidRuntime::registerNativeMethods(env, kClassPathName, gMethods, NELEM(gMethods));
+    return RegisterMethodsOrDie(env, kClassPathName, gMethods, NELEM(gMethods));
 }
 
 };
diff --git a/core/jni/android_view_HardwareLayer.cpp b/core/jni/android_view_HardwareLayer.cpp
index aa674de..648d1e3 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>
@@ -117,7 +117,7 @@
 };
 
 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 @@
             (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));
 
-    FIND_CLASS(gInputChannelClassInfo.clazz, "android/view/InputChannel");
+    jclass clazz = FindClassOrDie(env, "android/view/InputChannel");
+    gInputChannelClassInfo.clazz = MakeGlobalRefOrDie(env, clazz);
 
-    GET_FIELD_ID(gInputChannelClassInfo.mPtr, gInputChannelClassInfo.clazz,
-            "mPtr", "J");
-    
-    GET_METHOD_ID(gInputChannelClassInfo.ctor, gInputChannelClassInfo.clazz,
-            "<init>", "()V");
+    gInputChannelClassInfo.mPtr = GetFieldIDOrDie(env, gInputChannelClassInfo.clazz, "mPtr", "J");
 
-    return 0;
+    gInputChannelClassInfo.ctor = GetMethodIDOrDie(env, gInputChannelClassInfo.clazz, "<init>",
+                                                   "()V");
+
+    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 @@
 }
 
 
-#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 @@
         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 @@
 }
 
 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 @@
 
 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 @@
                 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 @@
                 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 @@
 
 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 @@
                     }
 
                     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 @@
             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 @@
             }
 
             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 @@
             (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 @@
         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 @@
 }
 
 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::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 @@
 
 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 @@
 }
 
 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 @@
             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 @@
             (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));
 
-    FIND_CLASS(gInputEventSenderClassInfo.clazz, "android/view/InputEventSender");
+    jclass clazz = FindClassOrDie(env, "android/view/InputEventSender");
+    gInputEventSenderClassInfo.clazz = MakeGlobalRefOrDie(env, clazz);
 
-    GET_METHOD_ID(gInputEventSenderClassInfo.dispatchInputEventFinished,
-            gInputEventSenderClassInfo.clazz,
-            "dispatchInputEventFinished", "(IZ)V");
-    return 0;
+    gInputEventSenderClassInfo.dispatchInputEventFinished = GetMethodIDOrDie(
+            env, gInputEventSenderClassInfo.clazz, "dispatchInputEventFinished", "(IZ)V");
+
+    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 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 @@
         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 @@
 
     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 @@
             (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));
+    gKeyEventClassInfo.clazz = FindClassOrDie(env, "android/view/KeyEvent");
+    gKeyEventClassInfo.clazz = MakeGlobalRefOrDie(env, gKeyEventClassInfo.clazz);
 
-    jclass clazz;
-    FIND_CLASS(clazz, "android/view/KeyCharacterMap$FallbackAction");
+    jclass clazz = FindClassOrDie(env, "android/view/KeyCharacterMap$FallbackAction");
 
-    GET_FIELD_ID(gFallbackActionClassInfo.keyCode, clazz,
-            "keyCode", "I");
+    gFallbackActionClassInfo.keyCode = GetFieldIDOrDie(env, clazz, "keyCode", "I");
+    gFallbackActionClassInfo.metaState = GetFieldIDOrDie(env, clazz, "metaState", "I");
 
-    GET_FIELD_ID(gFallbackActionClassInfo.metaState, 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 @@
         (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;");
+    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 AndroidRuntime::registerNativeMethods(
-        env, "android/view/KeyEvent", g_methods, NELEM(g_methods));
+    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 @@
         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 @@
             (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");
+    jclass clazz = FindClassOrDie(env, "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");
+    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");
 
-    FIND_CLASS(clazz, "android/view/MotionEvent$PointerProperties");
+    clazz = FindClassOrDie(env, "android/view/MotionEvent$PointerProperties");
 
-    GET_FIELD_ID(gPointerPropertiesClassInfo.id, clazz,
-            "id", "I");
-    GET_FIELD_ID(gPointerPropertiesClassInfo.toolType, clazz,
-            "toolType", "I");
+    gPointerPropertiesClassInfo.id = GetFieldIDOrDie(env, clazz, "id", "I");
+    gPointerPropertiesClassInfo.toolType = GetFieldIDOrDie(env, clazz, "toolType", "I");
 
-    return 0;
+    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 @@
 
 // --- 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 050037e..d1e693b 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 @@
 #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 84b7913..90b311a 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;
@@ -148,11 +150,6 @@
     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);
@@ -202,22 +199,16 @@
 #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) {
-    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 9bb8195..3fe50a5 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>
@@ -319,7 +319,7 @@
     // 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());
     }
@@ -349,7 +349,7 @@
         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);
 }
 
 // ----------------------------------------------------------------------------
@@ -379,26 +379,26 @@
 
 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");
+    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 = env->FindClass("android/graphics/Canvas");
-    gCanvasClassInfo.mSurfaceFormat = env->GetFieldID(clazz, "mSurfaceFormat", "I");
-    gCanvasClassInfo.setNativeBitmap = env->GetMethodID(clazz, "setNativeBitmap", "(J)V");
+    clazz = FindClassOrDie(env, "android/graphics/Canvas");
+    gCanvasClassInfo.mSurfaceFormat = GetFieldIDOrDie(env, clazz, "mSurfaceFormat", "I");
+    gCanvasClassInfo.setNativeBitmap = GetMethodIDOrDie(env, 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");
+    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 @@
     status_t res;
     if (allLayers) {
         minLayer = 0;
-        maxLayer = -1UL;
+        maxLayer = -1;
     }
 
     res = screenshot->update(displayToken, sourceCrop, width, height,
@@ -647,41 +647,44 @@
 
 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 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 = 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 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 = env->FindClass("android/view/FrameStats");
-    jfieldID undefined_time_nano_field =  env->GetStaticFieldID(frameStatsClazz, "UNDEFINED_TIME_NANO", "J");
+    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 @@
             (void*) android_view_TextureView_unlockCanvasAndPost },
 };
 
-#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_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");
+    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");
 
-    FIND_CLASS(clazz, "android/graphics/Canvas");
-    GET_FIELD_ID(gCanvasClassInfo.mSurfaceFormat, clazz, "mSurfaceFormat", "I");
-    GET_METHOD_ID(gCanvasClassInfo.setNativeBitmap, clazz, "setNativeBitmap", "(J)V");
+    clazz = FindClassOrDie(env, "android/graphics/Canvas");
+    gCanvasClassInfo.mSurfaceFormat = GetFieldIDOrDie(env, clazz, "mSurfaceFormat", "I");
+    gCanvasClassInfo.setNativeBitmap = GetMethodIDOrDie(env, clazz, "setNativeBitmap", "(J)V");
 
-    FIND_CLASS(clazz, "android/view/TextureView");
-    GET_FIELD_ID(gTextureViewClassInfo.nativeWindow, clazz, "mNativeWindow", "J");
+    clazz = FindClassOrDie(env, "android/view/TextureView");
+    gTextureViewClassInfo.nativeWindow = GetFieldIDOrDie(env, 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 6219956..499ff16 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 @@
 };
 
 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 @@
             (void*)android_view_VelocityTracker_nativeGetEstimator },
 };
 
-#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_view_VelocityTracker(JNIEnv* env) {
-    int res = jniRegisterNativeMethods(env, "android/view/VelocityTracker",
-            gVelocityTrackerMethods, NELEM(gVelocityTrackerMethods));
-    LOG_FATAL_IF(res < 0, "Unable to register native methods.");
+    int res = RegisterMethodsOrDie(env, "android/view/VelocityTracker", gVelocityTrackerMethods,
+                                   NELEM(gVelocityTrackerMethods));
 
-    jclass clazz;
-    FIND_CLASS(clazz, "android/view/VelocityTracker$Estimator");
+    jclass clazz = FindClassOrDie(env, "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 @@
         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 @@
     }
 
     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 @@
 
 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 @@
         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 @@
         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 @@
     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 @@
 };
 
 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");
+    gStringClass = FindClassOrDie(env, "java/lang/String");
+    gStringClass = MakeGlobalRefOrDie(env, gStringClass);
 
-    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");
+    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 69d9387..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>
@@ -44,7 +44,7 @@
 #include <selinux/android.h>
 #include <processgroup/processgroup.h>
 
-#include "android_runtime/AndroidRuntime.h"
+#include "core_jni_helpers.h"
 #include "JNIHelp.h"
 #include "ScopedLocalRef.h"
 #include "ScopedPrimitiveArray.h"
@@ -104,7 +104,7 @@
     // 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);
     }
   }
@@ -189,7 +189,8 @@
 
     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);
     }
   }
@@ -235,7 +236,7 @@
   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);
   }
 }
@@ -612,15 +613,11 @@
 };
 
 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 10c6e2ce..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->ExceptionCheck()) {
-        return;
-    }
-
-    do {
-        err = dup2(fd, STDIN_FILENO);
-    } while (err < 0 && errno == EINTR);
-
-    fd = jniGetFDFromFileDescriptor(env, out);
-
-    if  (env->ExceptionCheck()) {
-        return;
-    }
-
-    do {
-        err = dup2(fd, STDOUT_FILENO);
-    } while (err < 0 && errno == EINTR);
-
-    fd = jniGetFDFromFileDescriptor(env, errfd);
-
-    if  (env->ExceptionCheck()) {
-        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->ExceptionCheck()) {
-        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->ExceptionCheck()) {
-        return -1;
-    }
-
-    FD_ZERO(&fdset);
-
-    int nfds = 0;
-    for (jsize i = 0; i < length; i++) {
-        jobject fdObj = env->GetObjectArrayElement(fds, i);
-        if  (env->ExceptionCheck()) {
-            return -1;
-        }
-        if (fdObj == NULL) {
-            continue;
-        }
-        int fd = jniGetFDFromFileDescriptor(env, fdObj);
-        if  (env->ExceptionCheck()) {
-            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->ExceptionCheck()) {
-            return -1;
-        }
-        if (fdObj == NULL) {
-            continue;
-        }
-        int fd = jniGetFDFromFileDescriptor(env, fdObj);
-        if  (env->ExceptionCheck()) {
-            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 @@
 };
 
 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 @@
 };
 
 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
diff --git a/core/tests/coretests/src/android/os/SELinuxTest.java b/core/tests/coretests/src/android/os/SELinuxTest.java
deleted file mode 100644
index 9b63a6b..0000000
--- a/core/tests/coretests/src/android/os/SELinuxTest.java
+++ /dev/null
@@ -1,45 +0,0 @@
-package android.os;
-
-import android.os.Process;
-import android.os.SELinux;
-import android.test.AndroidTestCase;
-import static junit.framework.Assert.assertEquals;
-
-public class SELinuxTest extends AndroidTestCase {
-
-    public void testgetFileCon() {
-        if(SELinux.isSELinuxEnabled() == false)
-            return;
-
-        String ctx = SELinux.getFileContext("/system/bin/toolbox");
-        assertEquals(ctx, "u:object_r:system_file:s0");
-    }
-
-    public void testgetCon() {
-        if(SELinux.isSELinuxEnabled() == false)
-            return;
-
-        String mycon = SELinux.getContext();
-        assertEquals(mycon, "u:r:untrusted_app:s0:c33");
-    }
-
-    public void testgetPidCon() {
-        if(SELinux.isSELinuxEnabled() == false)
-            return;
-
-        String mycon = SELinux.getPidContext(Process.myPid());
-        assertEquals(mycon, "u:r:untrusted_app:s0:c33");
-    }
-
-    public void testcheckSELinuxAccess() {
-        if(SELinux.isSELinuxEnabled() == false)
-            return;
-
-        String mycon = SELinux.getContext();
-        boolean ret;
-        ret = SELinux.checkSELinuxAccess(mycon, mycon, "process", "fork");
-        assertEquals(ret,"true");
-        ret = SELinux.checkSELinuxAccess(mycon, mycon, "memprotect", "mmap_zero");
-        assertEquals(ret,"true");
-    }
-}
diff --git a/core/tests/coretests/src/android/text/TextUtilsTest.java b/core/tests/coretests/src/android/text/TextUtilsTest.java
index d494c5d..5a6ef30 100644
--- a/core/tests/coretests/src/android/text/TextUtilsTest.java
+++ b/core/tests/coretests/src/android/text/TextUtilsTest.java
@@ -353,6 +353,7 @@
         assertNull("null CharSequence should generate null from parcel", text);
         p = Parcel.obtain();
         TextUtils.writeToParcel("test", p, 0);
+        p.setDataPosition(0);
         text = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(p);
         assertEquals("conversion to/from parcel failed", "test", text);
     }
diff --git a/core/tests/hosttests/test-apps/MultiDexLegacyTestApp/src/com/android/multidexlegacytestapp/Test.java b/core/tests/hosttests/test-apps/MultiDexLegacyTestApp/src/com/android/multidexlegacytestapp/Test.java
index bbdd3e5..41b8956 100644
--- a/core/tests/hosttests/test-apps/MultiDexLegacyTestApp/src/com/android/multidexlegacytestapp/Test.java
+++ b/core/tests/hosttests/test-apps/MultiDexLegacyTestApp/src/com/android/multidexlegacytestapp/Test.java
@@ -31,7 +31,7 @@
         assertEquals(3366, getActivity().getValue());
     }
 
-    public void testAnnotation() {
+    public void testAnnotation() throws Exception {
         assertEquals(ReferencedByAnnotation.B,
                 ((AnnotationWithEnum) TestApplication.annotation).value());
         assertEquals(ReferencedByAnnotation.B,
@@ -43,10 +43,25 @@
                 ((AnnotationWithClass) TestApplication.annotation3).value());
         // Just to verify that it doesn't crash
         ReferencedByClassInAnnotation.A.get();
+
+        // Tests about bug https://code.google.com/p/android/issues/detail?id=78144
+        // Dalvik may throw IllegalAccessError when a class is in a different dex than an enum
+        // used in its annotations.
+        String annotationPackage = "com.android.multidexlegacytestapp.annotation.";
+        Class<?> clazz = Class.forName(annotationPackage + "Annotated");
+        // Just to verify that it doesn't crash
+        clazz.getAnnotations();
+        clazz = Class.forName(annotationPackage + "Annotated2");
+        // Just to verify that it doesn't crash
+        clazz.getAnnotations();
+        clazz = Class.forName(annotationPackage + "Annotated3");
+        // Just to verify that it doesn't crash
+        clazz.getAnnotations();
     }
 
     public void testInterface() {
         assertEquals(InterfaceWithEnum.class,
                 TestApplication.interfaceClass);
     }
+
 }
diff --git a/core/java/android/webkit/MustOverrideException.java b/core/tests/hosttests/test-apps/MultiDexLegacyTestApp/src/com/android/multidexlegacytestapp/annotation/Annotated.java
similarity index 62%
copy from core/java/android/webkit/MustOverrideException.java
copy to core/tests/hosttests/test-apps/MultiDexLegacyTestApp/src/com/android/multidexlegacytestapp/annotation/Annotated.java
index 0643bf0..fb7787b 100644
--- a/core/java/android/webkit/MustOverrideException.java
+++ b/core/tests/hosttests/test-apps/MultiDexLegacyTestApp/src/com/android/multidexlegacytestapp/annotation/Annotated.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2012 The Android Open Source Project
+ * 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.
@@ -14,12 +14,13 @@
  * limitations under the License.
  */
 
-package android.webkit;
+package com.android.multidexlegacytestapp.annotation;
 
-// TODO: Remove MustOverrideException and make all methods throwing it abstract instead;
-// needs API file update.
-class MustOverrideException extends RuntimeException {
-    MustOverrideException() {
-        super("abstract function called: must be overriden!");
+@TestAnnotation(AnnotationValue.V1)
+public class Annotated {
+
+    public void m() {
+
     }
-}
\ No newline at end of file
+
+}
diff --git a/core/java/android/webkit/MustOverrideException.java b/core/tests/hosttests/test-apps/MultiDexLegacyTestApp/src/com/android/multidexlegacytestapp/annotation/Annotated2.java
similarity index 62%
copy from core/java/android/webkit/MustOverrideException.java
copy to core/tests/hosttests/test-apps/MultiDexLegacyTestApp/src/com/android/multidexlegacytestapp/annotation/Annotated2.java
index 0643bf0..7e2dea7 100644
--- a/core/java/android/webkit/MustOverrideException.java
+++ b/core/tests/hosttests/test-apps/MultiDexLegacyTestApp/src/com/android/multidexlegacytestapp/annotation/Annotated2.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2012 The Android Open Source Project
+ * 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.
@@ -14,12 +14,12 @@
  * limitations under the License.
  */
 
-package android.webkit;
+package com.android.multidexlegacytestapp.annotation;
 
-// TODO: Remove MustOverrideException and make all methods throwing it abstract instead;
-// needs API file update.
-class MustOverrideException extends RuntimeException {
-    MustOverrideException() {
-        super("abstract function called: must be overriden!");
+@TestAnnotation2(AnnotationValue.V1)
+public class Annotated2 {
+    public void m() {
+
     }
-}
\ No newline at end of file
+
+}
diff --git a/core/java/android/webkit/MustOverrideException.java b/core/tests/hosttests/test-apps/MultiDexLegacyTestApp/src/com/android/multidexlegacytestapp/annotation/Annotated3.java
similarity index 62%
rename from core/java/android/webkit/MustOverrideException.java
rename to core/tests/hosttests/test-apps/MultiDexLegacyTestApp/src/com/android/multidexlegacytestapp/annotation/Annotated3.java
index 0643bf0..8a01c5b 100644
--- a/core/java/android/webkit/MustOverrideException.java
+++ b/core/tests/hosttests/test-apps/MultiDexLegacyTestApp/src/com/android/multidexlegacytestapp/annotation/Annotated3.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2012 The Android Open Source Project
+ * 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.
@@ -14,12 +14,14 @@
  * limitations under the License.
  */
 
-package android.webkit;
+package com.android.multidexlegacytestapp.annotation;
 
-// TODO: Remove MustOverrideException and make all methods throwing it abstract instead;
-// needs API file update.
-class MustOverrideException extends RuntimeException {
-    MustOverrideException() {
-        super("abstract function called: must be overriden!");
+import com.android.multidexlegacytestapp.annotation.TestAnnotation3.Value;
+
+@TestAnnotation3(Value.V1)
+public class Annotated3 {
+    public void m() {
+
     }
-}
\ No newline at end of file
+
+}
diff --git a/core/java/android/webkit/MustOverrideException.java b/core/tests/hosttests/test-apps/MultiDexLegacyTestApp/src/com/android/multidexlegacytestapp/annotation/AnnotationValue.java
similarity index 61%
copy from core/java/android/webkit/MustOverrideException.java
copy to core/tests/hosttests/test-apps/MultiDexLegacyTestApp/src/com/android/multidexlegacytestapp/annotation/AnnotationValue.java
index 0643bf0..1322d73 100644
--- a/core/java/android/webkit/MustOverrideException.java
+++ b/core/tests/hosttests/test-apps/MultiDexLegacyTestApp/src/com/android/multidexlegacytestapp/annotation/AnnotationValue.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2012 The Android Open Source Project
+ * 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.
@@ -14,12 +14,10 @@
  * limitations under the License.
  */
 
-package android.webkit;
+package com.android.multidexlegacytestapp.annotation;
 
-// TODO: Remove MustOverrideException and make all methods throwing it abstract instead;
-// needs API file update.
-class MustOverrideException extends RuntimeException {
-    MustOverrideException() {
-        super("abstract function called: must be overriden!");
-    }
-}
\ No newline at end of file
+public enum AnnotationValue {
+  V1,
+  V2;
+
+}
diff --git a/core/java/android/webkit/MustOverrideException.java b/core/tests/hosttests/test-apps/MultiDexLegacyTestApp/src/com/android/multidexlegacytestapp/annotation/TestAnnotation.java
similarity index 61%
copy from core/java/android/webkit/MustOverrideException.java
copy to core/tests/hosttests/test-apps/MultiDexLegacyTestApp/src/com/android/multidexlegacytestapp/annotation/TestAnnotation.java
index 0643bf0..68684b6 100644
--- a/core/java/android/webkit/MustOverrideException.java
+++ b/core/tests/hosttests/test-apps/MultiDexLegacyTestApp/src/com/android/multidexlegacytestapp/annotation/TestAnnotation.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2012 The Android Open Source Project
+ * 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.
@@ -14,12 +14,12 @@
  * limitations under the License.
  */
 
-package android.webkit;
+package com.android.multidexlegacytestapp.annotation;
 
-// TODO: Remove MustOverrideException and make all methods throwing it abstract instead;
-// needs API file update.
-class MustOverrideException extends RuntimeException {
-    MustOverrideException() {
-        super("abstract function called: must be overriden!");
-    }
-}
\ No newline at end of file
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+@Retention(RetentionPolicy.RUNTIME)
+public @interface TestAnnotation {
+  AnnotationValue value();
+}
diff --git a/core/java/android/webkit/MustOverrideException.java b/core/tests/hosttests/test-apps/MultiDexLegacyTestApp/src/com/android/multidexlegacytestapp/annotation/TestAnnotation2.java
similarity index 61%
copy from core/java/android/webkit/MustOverrideException.java
copy to core/tests/hosttests/test-apps/MultiDexLegacyTestApp/src/com/android/multidexlegacytestapp/annotation/TestAnnotation2.java
index 0643bf0..327d49c 100644
--- a/core/java/android/webkit/MustOverrideException.java
+++ b/core/tests/hosttests/test-apps/MultiDexLegacyTestApp/src/com/android/multidexlegacytestapp/annotation/TestAnnotation2.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2012 The Android Open Source Project
+ * 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.
@@ -14,12 +14,12 @@
  * limitations under the License.
  */
 
-package android.webkit;
+package com.android.multidexlegacytestapp.annotation;
 
-// TODO: Remove MustOverrideException and make all methods throwing it abstract instead;
-// needs API file update.
-class MustOverrideException extends RuntimeException {
-    MustOverrideException() {
-        super("abstract function called: must be overriden!");
-    }
-}
\ No newline at end of file
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+@Retention(RetentionPolicy.RUNTIME)
+public @interface TestAnnotation2 {
+  AnnotationValue value();
+}
diff --git a/core/java/android/webkit/MustOverrideException.java b/core/tests/hosttests/test-apps/MultiDexLegacyTestApp/src/com/android/multidexlegacytestapp/annotation/TestAnnotation3.java
similarity index 61%
copy from core/java/android/webkit/MustOverrideException.java
copy to core/tests/hosttests/test-apps/MultiDexLegacyTestApp/src/com/android/multidexlegacytestapp/annotation/TestAnnotation3.java
index 0643bf0..b1bf75e 100644
--- a/core/java/android/webkit/MustOverrideException.java
+++ b/core/tests/hosttests/test-apps/MultiDexLegacyTestApp/src/com/android/multidexlegacytestapp/annotation/TestAnnotation3.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2012 The Android Open Source Project
+ * 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.
@@ -14,12 +14,18 @@
  * limitations under the License.
  */
 
-package android.webkit;
+package com.android.multidexlegacytestapp.annotation;
 
-// TODO: Remove MustOverrideException and make all methods throwing it abstract instead;
-// needs API file update.
-class MustOverrideException extends RuntimeException {
-    MustOverrideException() {
-        super("abstract function called: must be overriden!");
-    }
-}
\ No newline at end of file
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+@Retention(RetentionPolicy.RUNTIME)
+public @interface TestAnnotation3 {
+    public enum Value {
+        V1,
+        V2;
+
+      }
+
+  Value value();
+}
diff --git a/core/tests/overlaytests/OverlayTest/src/com/android/overlaytest/OverlayBaseTest.java b/core/tests/overlaytests/OverlayTest/src/com/android/overlaytest/OverlayBaseTest.java
index 42de9ea..e57c55c 100644
--- a/core/tests/overlaytests/OverlayTest/src/com/android/overlaytest/OverlayBaseTest.java
+++ b/core/tests/overlaytests/OverlayTest/src/com/android/overlaytest/OverlayBaseTest.java
@@ -225,8 +225,12 @@
             reader = new BufferedReader(new InputStreamReader(input));
             actual = reader.readLine();
         } finally {
-            reader.close();
-            input.close();
+            if (reader != null) {
+                reader.close();
+            }
+            if (input != null) {
+                input.close();
+            }
         }
 
         final String no = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, " +
diff --git a/core/tests/overlaytests/testrunner.py b/core/tests/overlaytests/testrunner.py
index 4f94373..3703f4a 100755
--- a/core/tests/overlaytests/testrunner.py
+++ b/core/tests/overlaytests/testrunner.py
@@ -421,8 +421,8 @@
         _create_disable_overlays_task(),
         MkdirTask('/system/vendor'),
         MkdirTask('/vendor/overlay'),
-        PushTask('/data/app/com.android.overlaytest.overlay.apk', '/vendor/overlay/framework_a.apk'),
-        PushTask('/data/app/com.android.overlaytest.first_app_overlay.apk', '/vendor/overlay/app_a.apk'),
+        PushTask('/data/app/com.android.overlaytest.overlay/com.android.overlaytest.overlay.apk', '/vendor/overlay/framework_a.apk'),
+        PushTask('/data/app/com.android.overlaytest.first_app_overlay/com.android.overlaytest.first_app_overlay.apk', '/vendor/overlay/app_a.apk'),
     ]
     return CompoundTask(TASK_ENABLE_SINGLE_OVERLAY, tasks)
 
@@ -432,9 +432,9 @@
         MkdirTask('/system/vendor'),
         MkdirTask('/vendor/overlay'),
 
-        PushTask('/data/app/com.android.overlaytest.overlay.apk', '/vendor/overlay/framework_b.apk'),
-        PushTask('/data/app/com.android.overlaytest.first_app_overlay.apk', '/vendor/overlay/app_a.apk'),
-        PushTask('/data/app/com.android.overlaytest.second_app_overlay.apk', '/vendor/overlay/app_b.apk'),
+        PushTask('/data/app/com.android.overlaytest.overlay/com.android.overlaytest.overlay.apk', '/vendor/overlay/framework_b.apk'),
+        PushTask('/data/app/com.android.overlaytest.first_app_overlay/com.android.overlaytest.first_app_overlay.apk', '/vendor/overlay/app_a.apk'),
+        PushTask('/data/app/com.android.overlaytest.second_app_overlay/com.android.overlaytest.second_app_overlay.apk', '/vendor/overlay/app_b.apk'),
     ]
     return CompoundTask(TASK_ENABLE_MULTIPLE_OVERLAYS, tasks)
 
@@ -584,7 +584,7 @@
     # remount filesystem, install test project
     tasks.append(RootTask())
     tasks.append(RemountTask())
-    tasks.append(PushTask('/system/app/OverlayTest.apk', '/system/app/OverlayTest.apk'))
+    tasks.append(PushTask('/system/app/OverlayTest/OverlayTest.apk', '/system/app/OverlayTest.apk'))
 
     # test idmap
     if opts.test_idmap:
@@ -609,9 +609,9 @@
         tasks.append(GrepIdmapTest(idmap, 'bool/config_annoy_dianne', 1))
 
         # overlays.list
-        overlays_list_path = '/data/resource-cache/overlays.list'
+        overlays_list_path = idmaps + '/overlays.list'
         expected_content = '''\
-/vendor/overlay/framework_b.apk /data/resource-cache/vendor@overlay@framework_b.apk@idmap
+/vendor/overlay/framework_b.apk /data/local/tmp/idmaps/vendor@overlay@framework_b.apk@idmap
 '''
         tasks.append(FileExistsTest(overlays_list_path))
         tasks.append(Md5Test(overlays_list_path, expected_content))
diff --git a/data/keyboards/Vendor_046d_Product_b501.kl b/data/keyboards/Vendor_046d_Product_b501.kl
new file mode 100644
index 0000000..496ddc3
--- /dev/null
+++ b/data/keyboards/Vendor_046d_Product_b501.kl
@@ -0,0 +1,65 @@
+# 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.
+
+# Logitech Bluetooth wireless gamepad (RedHawk)
+
+key 304 BUTTON_A
+key 305 BUTTON_B
+key 307 BUTTON_X
+key 308 BUTTON_Y
+key 310 BUTTON_L1
+key 311 BUTTON_R1
+key 312 BUTTON_L2
+key 313 BUTTON_R2
+
+key 314 BUTTON_SELECT
+key 315 BUTTON_START
+key 316 BUTTON_MODE
+key 317 BUTTON_THUMBL
+key 318 BUTTON_THUMBR
+
+key 103 DPAD_UP
+key 105 DPAD_LEFT
+key 106 DPAD_RIGHT
+key 108 DPAD_DOWN
+key 353 DPAD_CENTER
+
+key 113 VOLUME_MUTE
+key 114 VOLUME_DOWN
+key 115 VOLUME_UP
+key 152 POWER
+key 163 MEDIA_NEXT
+key 164 MEDIA_PLAY_PAUSE
+key 165 MEDIA_PREVIOUS
+
+key 158 BACK
+key 172 HOME
+
+key 217 SEARCH
+key 580 APP_SWITCH
+key 582 ASSIST
+
+axis 0x00 X
+axis 0x01 Y
+axis 0x02 Z
+axis 0x05 RZ
+axis 0x09 RTRIGGER
+axis 0x0a LTRIGGER
+axis 0x10 HAT_X
+axis 0x11 HAT_Y
+
+led 0x00 CONTROLLER_1
+led 0x01 CONTROLLER_2
+led 0x02 CONTROLLER_3
+led 0x03 CONTROLLER_4
diff --git a/data/keyboards/Vendor_1532_Product_0900.kl b/data/keyboards/Vendor_1532_Product_0900.kl
new file mode 100644
index 0000000..c2fc1b4
--- /dev/null
+++ b/data/keyboards/Vendor_1532_Product_0900.kl
@@ -0,0 +1,42 @@
+# 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.
+
+# Razer Serval
+
+key 304 BUTTON_A
+key 305 BUTTON_B
+key 307 BUTTON_X
+key 308 BUTTON_Y
+key 310 BUTTON_L1
+key 311 BUTTON_R1
+key 316 BUTTON_MODE
+key 317 BUTTON_THUMBL
+key 318 BUTTON_THUMBR
+
+key 158 BACK
+key 172 HOME
+
+axis 0x00 X
+axis 0x01 Y
+axis 0x02 Z
+axis 0x05 RZ
+axis 0x09 RTRIGGER
+axis 0x0a LTRIGGER
+axis 0x10 HAT_X
+axis 0x11 HAT_Y
+
+led 0x00 CONTROLLER_1
+led 0x01 CONTROLLER_2
+led 0x02 CONTROLLER_3
+led 0x03 CONTROLLER_4
diff --git a/docs/html/guide/topics/resources/string-resource.jd b/docs/html/guide/topics/resources/string-resource.jd
index e2326ec..cbfa82e 100644
--- a/docs/html/guide/topics/resources/string-resource.jd
+++ b/docs/html/guide/topics/resources/string-resource.jd
@@ -237,7 +237,8 @@
 <p>The selection of which string to use is made solely based on grammatical <i>necessity</i>.
 In English, a string for <code>zero</code> will be ignored even if the quantity is 0, because 0
 isn't grammatically different from 2, or any other number except 1 ("zero books", "one book",
-"two books", and so on).
+"two books", and so on). Conversely, in Korean <i>only</i> the <code>other</code> string will
+ever be used.
 
 <p>Don't be misled either by the fact that, say, <code>two</code> sounds like it could only apply to
 the quantity 2: a language may require that 2, 12, 102 (and so on) are all treated like one
@@ -343,7 +344,14 @@
 &lt;?xml version="1.0" encoding="utf-8"?>
 &lt;resources>
     &lt;plurals name="numberOfSongsAvailable">
-        &lt;item quantity="one">One song found.&lt;/item>
+        &lt;!--
+             As a developer, you should always supply "one" and "other"
+             strings. Your translators will know which strings are actually
+             needed for their language. Always include %d in "one" because
+             translators will need to use %d for languages where "one"
+             doesn't mean 1 (as explained above).
+          -->
+        &lt;item quantity="one">%d song found.&lt;/item>
         &lt;item quantity="other">%d songs found.&lt;/item>
     &lt;/plurals>
 &lt;/resources>
@@ -353,7 +361,7 @@
 &lt;?xml version="1.0" encoding="utf-8"?>
 &lt;resources>
     &lt;plurals name="numberOfSongsAvailable">
-        &lt;item quantity="one">Znaleziono jedn&#x0105; piosenk&#x0119;.&lt;/item>
+        &lt;item quantity="one">Znaleziono %d piosenk&#x0119;.&lt;/item>
         &lt;item quantity="few">Znaleziono %d piosenki.&lt;/item>
         &lt;item quantity="other">Znaleziono %d piosenek.&lt;/item>
     &lt;/plurals>
@@ -597,4 +605,4 @@
 // and bold the entire sequence.
 CharSequence text = bold(italic(res.getString(R.string.hello)),
     color(Color.RED, res.getString(R.string.world)));
-</pre>
\ No newline at end of file
+</pre>
diff --git a/docs/html/training/articles/perf-jni.jd b/docs/html/training/articles/perf-jni.jd
index 1a40f62..5a9fa1e 100644
--- a/docs/html/training/articles/perf-jni.jd
+++ b/docs/html/training/articles/perf-jni.jd
@@ -635,20 +635,31 @@
 <a name="faq_FindClass" id="faq_FindClass"></a>
 <h2>FAQ: Why didn't <code>FindClass</code> find my class?</h2>
 
+<p>(Most of this advice applies equally well to failures to find methods
+with <code>GetMethodID</code> or <code>GetStaticMethodID</code>, or fields
+with <code>GetFieldID</code> or <code>GetStaticFieldID</code>.)</p>
+
 <p>Make sure that the class name string has the correct format.  JNI class
 names start with the package name and are separated with slashes,
 such as <code>java/lang/String</code>.  If you're looking up an array class,
 you need to start with the appropriate number of square brackets and
 must also wrap the class with 'L' and ';', so a one-dimensional array of
-<code>String</code> would be <code>[Ljava/lang/String;</code>.</p>
+<code>String</code> would be <code>[Ljava/lang/String;</code>.
+If you're looking up an inner class, use '$' rather than '.'. In general,
+using <code>javap</code> on the .class file is a good way to find out the
+internal name of your class.</p>
+
+<p>If you're using ProGuard, make sure that
+<a href="{@docRoot}tools/help/proguard.html#configuring">ProGuard didn't
+strip out your class</a>. This can happen if your class/method/field is only
+used from JNI.
 
 <p>If the class name looks right, you could be running into a class loader
 issue.  <code>FindClass</code> wants to start the class search in the
 class loader associated with your code.  It examines the call stack,
 which will look something like:
 <pre>    Foo.myfunc(Native Method)
-    Foo.main(Foo.java:10)
-    dalvik.system.NativeStart.main(Native Method)</pre>
+    Foo.main(Foo.java:10)</pre>
 
 <p>The topmost method is <code>Foo.myfunc</code>.  <code>FindClass</code>
 finds the <code>ClassLoader</code> object associated with the <code>Foo</code>
@@ -656,12 +667,9 @@
 
 <p>This usually does what you want.  You can get into trouble if you
 create a thread yourself (perhaps by calling <code>pthread_create</code>
-and then attaching it with <code>AttachCurrentThread</code>).
-Now the stack trace looks like this:</p>
-<pre>    dalvik.system.NativeStart.run(Native Method)</pre>
-
-<p>The topmost method is <code>NativeStart.run</code>, which isn't part of
-your application.  If you call <code>FindClass</code> from this thread, the
+and then attaching it with <code>AttachCurrentThread</code>). Now there
+are no stack frames from your application.
+If you call <code>FindClass</code> from this thread, the
 JavaVM will start in the "system" class loader instead of the one associated
 with your application, so attempts to find app-specific classes will fail.</p>
 
diff --git a/include/androidfw/AssetManager.h b/include/androidfw/AssetManager.h
index 99b3195..0cfd2b1 100644
--- a/include/androidfw/AssetManager.h
+++ b/include/androidfw/AssetManager.h
@@ -236,9 +236,11 @@
 private:
     struct asset_path
     {
+        asset_path() : path(""), type(kFileTypeRegular), idmap(""), isSystemOverlay(false) {}
         String8 path;
         FileType type;
         String8 idmap;
+        bool isSystemOverlay;
     };
 
     Asset* openInPathLocked(const char* fileName, AccessMode mode,
diff --git a/keystore/java/android/security/AndroidKeyPairGenerator.java b/keystore/java/android/security/AndroidKeyPairGenerator.java
index 458a46c..a0ffb5f 100644
--- a/keystore/java/android/security/AndroidKeyPairGenerator.java
+++ b/keystore/java/android/security/AndroidKeyPairGenerator.java
@@ -17,7 +17,6 @@
 package android.security;
 
 import com.android.org.bouncycastle.x509.X509V3CertificateGenerator;
-
 import com.android.org.conscrypt.NativeCrypto;
 import com.android.org.conscrypt.OpenSSLEngine;
 
@@ -34,7 +33,6 @@
 import java.security.cert.CertificateEncodingException;
 import java.security.cert.X509Certificate;
 import java.security.spec.AlgorithmParameterSpec;
-import java.security.spec.DSAParameterSpec;
 import java.security.spec.InvalidKeySpecException;
 import java.security.spec.RSAKeyGenParameterSpec;
 import java.security.spec.X509EncodedKeySpec;
@@ -156,8 +154,6 @@
     private static String getDefaultSignatureAlgorithmForKeyType(String keyType) {
         if ("RSA".equalsIgnoreCase(keyType)) {
             return "sha256WithRSA";
-        } else if ("DSA".equalsIgnoreCase(keyType)) {
-            return "sha1WithDSA";
         } else if ("EC".equalsIgnoreCase(keyType)) {
             return "sha256WithECDSA";
         } else {
@@ -173,13 +169,6 @@
                     return new byte[][] { rsaSpec.getPublicExponent().toByteArray() };
                 }
                 break;
-            case NativeCrypto.EVP_PKEY_DSA:
-                if (spec instanceof DSAParameterSpec) {
-                    DSAParameterSpec dsaSpec = (DSAParameterSpec) spec;
-                    return new byte[][] { dsaSpec.getG().toByteArray(),
-                            dsaSpec.getP().toByteArray(), dsaSpec.getQ().toByteArray() };
-                }
-                break;
         }
         return null;
     }
diff --git a/keystore/java/android/security/KeyChain.java b/keystore/java/android/security/KeyChain.java
index 131e689..607817a 100644
--- a/keystore/java/android/security/KeyChain.java
+++ b/keystore/java/android/security/KeyChain.java
@@ -379,7 +379,7 @@
      */
     public static boolean isKeyAlgorithmSupported(String algorithm) {
         final String algUpper = algorithm.toUpperCase(Locale.US);
-        return "DSA".equals(algUpper) || "EC".equals(algUpper) || "RSA".equals(algUpper);
+        return "EC".equals(algUpper) || "RSA".equals(algUpper);
     }
 
     /**
diff --git a/keystore/java/android/security/KeyPairGeneratorSpec.java b/keystore/java/android/security/KeyPairGeneratorSpec.java
index 4a823cc..6b67f43 100644
--- a/keystore/java/android/security/KeyPairGeneratorSpec.java
+++ b/keystore/java/android/security/KeyPairGeneratorSpec.java
@@ -26,7 +26,6 @@
 import java.security.PrivateKey;
 import java.security.cert.Certificate;
 import java.security.spec.AlgorithmParameterSpec;
-import java.security.spec.DSAParameterSpec;
 import java.security.spec.RSAKeyGenParameterSpec;
 import java.util.Date;
 
@@ -59,11 +58,6 @@
      * These must be kept in sync with system/security/keystore/defaults.h
      */
 
-    /* DSA */
-    private static final int DSA_DEFAULT_KEY_SIZE = 1024;
-    private static final int DSA_MIN_KEY_SIZE = 512;
-    private static final int DSA_MAX_KEY_SIZE = 8192;
-
     /* EC */
     private static final int EC_DEFAULT_KEY_SIZE = 256;
     private static final int EC_MIN_KEY_SIZE = 192;
@@ -165,9 +159,7 @@
     }
 
     private static int getDefaultKeySizeForType(int keyType) {
-        if (keyType == NativeCrypto.EVP_PKEY_DSA) {
-            return DSA_DEFAULT_KEY_SIZE;
-        } else if (keyType == NativeCrypto.EVP_PKEY_EC) {
+        if (keyType == NativeCrypto.EVP_PKEY_EC) {
             return EC_DEFAULT_KEY_SIZE;
         } else if (keyType == NativeCrypto.EVP_PKEY_RSA) {
             return RSA_DEFAULT_KEY_SIZE;
@@ -176,12 +168,7 @@
     }
 
     private static void checkValidKeySize(int keyType, int keySize) {
-        if (keyType == NativeCrypto.EVP_PKEY_DSA) {
-            if (keySize < DSA_MIN_KEY_SIZE || keySize > DSA_MAX_KEY_SIZE) {
-                throw new IllegalArgumentException("DSA keys must be >= " + DSA_MIN_KEY_SIZE
-                        + " and <= " + DSA_MAX_KEY_SIZE);
-            }
-        } else if (keyType == NativeCrypto.EVP_PKEY_EC) {
+        if (keyType == NativeCrypto.EVP_PKEY_EC) {
             if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
                 throw new IllegalArgumentException("EC keys must be >= " + EC_MIN_KEY_SIZE
                         + " and <= " + EC_MAX_KEY_SIZE);
@@ -198,11 +185,7 @@
 
     private static void checkCorrectParametersSpec(int keyType, int keySize,
             AlgorithmParameterSpec spec) {
-        if (keyType == NativeCrypto.EVP_PKEY_DSA && spec != null) {
-            if (!(spec instanceof DSAParameterSpec)) {
-                throw new IllegalArgumentException("DSA keys must have DSAParameterSpec specified");
-            }
-        } else if (keyType == NativeCrypto.EVP_PKEY_RSA && spec != null) {
+        if (keyType == NativeCrypto.EVP_PKEY_RSA && spec != null) {
             if (spec instanceof RSAKeyGenParameterSpec) {
                 RSAKeyGenParameterSpec rsaSpec = (RSAKeyGenParameterSpec) spec;
                 if (keySize != -1 && keySize != rsaSpec.getKeysize()) {
diff --git a/keystore/java/android/security/KeyStore.java b/keystore/java/android/security/KeyStore.java
index 0db8c77..1dbdbfb 100644
--- a/keystore/java/android/security/KeyStore.java
+++ b/keystore/java/android/security/KeyStore.java
@@ -71,8 +71,6 @@
     static int getKeyTypeForAlgorithm(String keyType) throws IllegalArgumentException {
         if ("RSA".equalsIgnoreCase(keyType)) {
             return NativeCrypto.EVP_PKEY_RSA;
-        } else if ("DSA".equalsIgnoreCase(keyType)) {
-            return NativeCrypto.EVP_PKEY_DSA;
         } else if ("EC".equalsIgnoreCase(keyType)) {
             return NativeCrypto.EVP_PKEY_EC;
         } else {
diff --git a/libs/androidfw/AssetManager.cpp b/libs/androidfw/AssetManager.cpp
index e5c5b10..25cd363 100644
--- a/libs/androidfw/AssetManager.cpp
+++ b/libs/androidfw/AssetManager.cpp
@@ -302,6 +302,10 @@
     mAssetPaths.add(oap);
     *cookie = static_cast<int32_t>(mAssetPaths.size());
 
+    if (mResources != NULL) {
+        appendPathToResTable(oap);
+    }
+
     return true;
  }
 
@@ -607,6 +611,11 @@
 }
 
 bool AssetManager::appendPathToResTable(const asset_path& ap) const {
+    // skip those ap's that correspond to system overlays
+    if (ap.isSystemOverlay) {
+        return true;
+    }
+
     Asset* ass = NULL;
     ResTable* sharedRes = NULL;
     bool shared = true;
@@ -792,6 +801,7 @@
         oap.path = String8(buf, space - buf);
         oap.type = kFileTypeRegular;
         oap.idmap = String8(space + 1, newline - space - 1);
+        oap.isSystemOverlay = true;
 
         Asset* oass = const_cast<AssetManager*>(this)->
             openNonAssetInPathLocked("resources.arsc",
diff --git a/libs/androidfw/ResourceTypes.cpp b/libs/androidfw/ResourceTypes.cpp
index 679a75f..d66c4a5 100644
--- a/libs/androidfw/ResourceTypes.cpp
+++ b/libs/androidfw/ResourceTypes.cpp
@@ -47,18 +47,10 @@
 #ifdef HAVE_WINSOCK
 #undef  nhtol
 #undef  htonl
-
-#ifdef HAVE_LITTLE_ENDIAN
 #define ntohl(x)    ( ((x) << 24) | (((x) >> 24) & 255) | (((x) << 8) & 0xff0000) | (((x) >> 8) & 0xff00) )
 #define htonl(x)    ntohl(x)
 #define ntohs(x)    ( (((x) << 8) & 0xff00) | (((x) >> 8) & 255) )
 #define htons(x)    ntohs(x)
-#else
-#define ntohl(x)    (x)
-#define htonl(x)    (x)
-#define ntohs(x)    (x)
-#define htons(x)    (x)
-#endif
 #endif
 
 #define IDMAP_MAGIC             0x504D4449
@@ -6245,14 +6237,14 @@
             }
 
             if (typeMap.entryOffset + typeMap.entryMap.size() < entryIndex) {
-                // Resize to accomodate this entry and the 0's in between.
-                if (typeMap.entryMap.resize((entryIndex - typeMap.entryOffset) + 1) < 0) {
+                // pad with 0xffffffff's (indicating non-existing entries) before adding this entry
+                size_t index = typeMap.entryMap.size();
+                size_t numItems = entryIndex - (typeMap.entryOffset + index);
+                if (typeMap.entryMap.insertAt(0xffffffff, index, numItems) < 0) {
                     return NO_MEMORY;
                 }
-                typeMap.entryMap.editTop() = Res_GETENTRY(overlayResID);
-            } else {
-                typeMap.entryMap.add(Res_GETENTRY(overlayResID));
             }
+            typeMap.entryMap.add(Res_GETENTRY(overlayResID));
         }
 
         if (!typeMap.entryMap.isEmpty()) {
diff --git a/libs/common_time/Android.mk b/libs/common_time/Android.mk
index 75eb528..1fec504 100644
--- a/libs/common_time/Android.mk
+++ b/libs/common_time/Android.mk
@@ -33,4 +33,6 @@
 LOCAL_MODULE_TAGS := optional
 LOCAL_MODULE := common_time
 
+LOCAL_CFLAGS += -Wall -Werror -Wunused -Wunreachable-code
+
 include $(BUILD_EXECUTABLE)
diff --git a/libs/common_time/clock_recovery.cpp b/libs/common_time/clock_recovery.cpp
index 3a7c70c..392caa0 100644
--- a/libs/common_time/clock_recovery.cpp
+++ b/libs/common_time/clock_recovery.cpp
@@ -22,6 +22,7 @@
 #define __STDC_LIMIT_MACROS
 #define LOG_TAG "common_time"
 #include <utils/Log.h>
+#include <inttypes.h>
 #include <stdint.h>
 
 #include <common_time/local_clock.h>
@@ -280,7 +281,7 @@
     // system.
     setTargetCorrection_l(tgt_correction);
 
-    LOG_TS("clock_loop %lld %f %f %f %d\n", raw_delta, delta_f, CO, CObias, tgt_correction);
+    LOG_TS("clock_loop %" PRId64 " %f %f %f %d\n", raw_delta, delta_f, CO, CObias, tgt_correction);
 
 #ifdef TIME_SERVICE_DEBUG
     diag_thread_->pushDisciplineEvent(
@@ -335,7 +336,6 @@
     // 300mSec.
     if (tgt_correction_ != tgt) {
         int64_t now = local_clock_->getLocalTime();
-        status_t res;
 
         tgt_correction_ = tgt;
 
diff --git a/libs/common_time/clock_recovery.h b/libs/common_time/clock_recovery.h
index b6c87ff..278a75e 100644
--- a/libs/common_time/clock_recovery.h
+++ b/libs/common_time/clock_recovery.h
@@ -111,7 +111,6 @@
     bool    last_error_est_valid_;
     int32_t last_error_est_usec_;
     float last_delta_f_;
-    int32_t integrated_error_;
     int32_t tgt_correction_;
     int32_t cur_correction_;
     LinearTransform time_to_cur_slew_;
diff --git a/libs/common_time/common_clock.cpp b/libs/common_time/common_clock.cpp
index c9eb388..ee326e1 100644
--- a/libs/common_time/common_clock.cpp
+++ b/libs/common_time/common_clock.cpp
@@ -19,6 +19,7 @@
 #define LOG_TAG "common_time"
 #include <utils/Log.h>
 
+#include <inttypes.h>
 #include <stdint.h>
 
 #include <utils/Errors.h>
@@ -50,7 +51,7 @@
 
     LinearTransform::reduce(&numer, &denom);
     if ((numer > UINT32_MAX) || (denom > UINT32_MAX)) {
-        ALOGE("Overflow in CommonClock::init while trying to reduce %lld/%lld",
+        ALOGE("Overflow in CommonClock::init while trying to reduce %" PRIu64 "/%" PRIu64,
              kCommonFreq, local_freq);
         return false;
     }
diff --git a/libs/common_time/common_clock_service.cpp b/libs/common_time/common_clock_service.cpp
index 9ca6f35..592ab1d 100644
--- a/libs/common_time/common_clock_service.cpp
+++ b/libs/common_time/common_clock_service.cpp
@@ -99,14 +99,14 @@
         Mutex::Autolock lock(mCallbackLock);
         // check whether this is a duplicate
         for (size_t i = 0; i < mListeners.size(); i++) {
-            if (mListeners[i]->asBinder() == listener->asBinder())
+            if (IInterface::asBinder(mListeners[i]) == IInterface::asBinder(listener))
                 return ALREADY_EXISTS;
         }
     }
 
     mListeners.add(listener);
     mTimeServer.reevaluateAutoDisableState(0 != mListeners.size());
-    return listener->asBinder()->linkToDeath(this);
+    return IInterface::asBinder(listener)->linkToDeath(this);
 }
 
 status_t CommonClockService::unregisterListener(
@@ -117,8 +117,8 @@
     {   // scoping for autolock pattern
         Mutex::Autolock lock(mCallbackLock);
         for (size_t i = 0; i < mListeners.size(); i++) {
-            if (mListeners[i]->asBinder() == listener->asBinder()) {
-                mListeners[i]->asBinder()->unlinkToDeath(this);
+            if (IInterface::asBinder(mListeners[i]) == IInterface::asBinder(listener)) {
+                IInterface::asBinder(mListeners[i])->unlinkToDeath(this);
                 mListeners.removeAt(i);
                 ret_val = OK;
                 break;
@@ -136,7 +136,7 @@
     {   // scoping for autolock pattern
         Mutex::Autolock lock(mCallbackLock);
         for (size_t i = 0; i < mListeners.size(); i++) {
-            if (mListeners[i]->asBinder() == who) {
+            if (IInterface::asBinder(mListeners[i]) == who) {
                 mListeners.removeAt(i);
                 break;
             }
diff --git a/libs/common_time/common_time_server.cpp b/libs/common_time/common_time_server.cpp
index 3e11987..01372e0 100644
--- a/libs/common_time/common_time_server.cpp
+++ b/libs/common_time/common_time_server.cpp
@@ -25,6 +25,7 @@
 #include <arpa/inet.h>
 #include <assert.h>
 #include <fcntl.h>
+#include <inttypes.h>
 #include <linux/if_ether.h>
 #include <net/if.h>
 #include <net/if_arp.h>
@@ -969,13 +970,14 @@
         // if the RTT of the packet is significantly larger than the panic
         // threshold, we should simply discard it.  Its better to do nothing
         // than to take cues from a packet like that.
-        int rttCommon = mCommonClock.localDurationToCommonDuration(rtt);
+        int64_t rttCommon = mCommonClock.localDurationToCommonDuration(rtt);
         if (rttCommon > (static_cast<int64_t>(mPanicThresholdUsec) * 
                          kRTTDiscardPanicThreshMultiplier)) {
-            ALOGV("Dropping sync response with RTT of %lld uSec", rttCommon);
+            ALOGV("Dropping sync response with RTT of %" PRId64 " uSec", rttCommon);
             mClient_ExpiredSyncRespsRXedFromCurMaster++;
             if (shouldPanicNotGettingGoodData())
                 return becomeInitial("RX panic, no good data");
+            return true;
         } else {
             result = mClockRecovery.pushDisciplineEvent(avgLocal, avgCommon, rttCommon);
             mClient_LastGoodSyncRX = clientRxLocalTime;
diff --git a/libs/common_time/common_time_server_api.cpp b/libs/common_time/common_time_server_api.cpp
index e157071..e0f35a9 100644
--- a/libs/common_time/common_time_server_api.cpp
+++ b/libs/common_time/common_time_server_api.cpp
@@ -27,6 +27,8 @@
 
 #include "common_time_server.h"
 
+#include <inttypes.h>
+
 namespace android {
 
 //
@@ -286,7 +288,7 @@
 #define checked_percentage(a, b) ((0 == b) ? 0.0f : ((100.0f * a) / b))
 
 status_t CommonTimeServer::dumpClockInterface(int fd,
-                                              const Vector<String16>& args,
+                                              const Vector<String16>& /* args */,
                                               size_t activeClients) {
     AutoMutex _lock(&mLock);
     const size_t SIZE = 256;
@@ -308,15 +310,15 @@
         synced     = (OK == mCommonClock.localToCommon(localTime, &commonTime));
         sockaddrToString(mMasterEP, mMasterEPValid, maStr, sizeof(maStr));
 
-        dump_printf("Common Clock Service Status\nLocal time     : %lld\n",
+        dump_printf("Common Clock Service Status\nLocal time     : %" PRId64 "\n",
                     localTime);
 
         if (synced)
-            dump_printf("Common time    : %lld\n", commonTime);
+            dump_printf("Common time    : %" PRId64 "\n", commonTime);
         else
             dump_printf("Common time    : %s\n", "not synced");
 
-        dump_printf("Timeline ID    : %016llx\n", mTimelineID);
+        dump_printf("Timeline ID    : %016" PRIu64 "\n", mTimelineID);
         dump_printf("State          : %s\n", stateToString(mState));
         dump_printf("Master Addr    : %s\n", maStr);
 
@@ -349,10 +351,10 @@
             int64_t localDelta, usecDelta;
             localDelta = localTime - mClient_LastGoodSyncRX;
             usecDelta  = mCommonClock.localDurationToCommonDuration(localDelta);
-            dump_printf("Last Good RX   : %lld uSec ago\n", usecDelta);
+            dump_printf("Last Good RX   : %" PRId64 " uSec ago\n", usecDelta);
         }
 
-        dump_printf("Active Clients : %u\n", activeClients);
+        dump_printf("Active Clients : %zu\n", activeClients);
         mClient_PacketRTTLog.dumpLog(fd, mCommonClock);
         mStateChangeLog.dumpLog(fd);
         mElectionLog.dumpLog(fd);
@@ -363,7 +365,7 @@
 }
 
 status_t CommonTimeServer::dumpConfigInterface(int fd,
-                                               const Vector<String16>& args) {
+                                               const Vector<String16>& /* args */) {
     AutoMutex _lock(&mLock);
     const size_t SIZE = 256;
     char buffer[SIZE];
@@ -383,7 +385,7 @@
                     "Bound Interface           : %s\n",
                     mBindIfaceValid ? mBindIface.string() : "<unbound>");
         dump_printf("Master Election Endpoint  : %s\n", meStr);
-        dump_printf("Master Election Group ID  : %016llx\n", mSyncGroupID);
+        dump_printf("Master Election Group ID  : %016" PRIu64 "\n", mSyncGroupID);
         dump_printf("Master Announce Interval  : %d mSec\n",
                     mMasterAnnounceIntervalMs);
         dump_printf("Client Sync Interval      : %d mSec\n",
@@ -419,12 +421,12 @@
         if (rxTimes[i]) {
             int64_t delta = rxTimes[i] - txTimes[i];
             int64_t deltaUsec = cclk.localDurationToCommonDuration(delta);
-            dump_printf("pkt[%2d] : localTX %12lld localRX %12lld "
+            dump_printf("pkt[%2d] : localTX %12" PRId64 " localRX %12" PRId64 " "
                         "(%.3f msec RTT)\n",
                         ndx, txTimes[i], rxTimes[i],
                         static_cast<float>(deltaUsec) / 1000.0);
         } else {
-            dump_printf("pkt[%2d] : localTX %12lld localRX never\n",
+            dump_printf("pkt[%2d] : localTX %12" PRId64 " localRX never\n",
                         ndx, txTimes[i]);
         }
         i = (i + 1) % RTT_LOG_SIZE;
diff --git a/libs/common_time/main.cpp b/libs/common_time/main.cpp
index 49eb30a..ac52c85 100644
--- a/libs/common_time/main.cpp
+++ b/libs/common_time/main.cpp
@@ -27,7 +27,7 @@
 
 #include "common_time_server.h"
 
-int main(int argc, char *argv[]) {
+int main() {
     using namespace android;
 
     sp<CommonTimeServer> service = new CommonTimeServer();
diff --git a/libs/hwui/AmbientShadow.cpp b/libs/hwui/AmbientShadow.cpp
index 2d1cf78..f11437b0 100644
--- a/libs/hwui/AmbientShadow.cpp
+++ b/libs/hwui/AmbientShadow.cpp
@@ -128,7 +128,7 @@
 }
 
 inline bool needsExtraForEdge(float firstAlpha, float secondAlpha) {
-    return abs(firstAlpha - secondAlpha) > ALPHA_THRESHOLD;
+    return fabsf(firstAlpha - secondAlpha) > ALPHA_THRESHOLD;
 }
 
 /**
diff --git a/libs/hwui/Android.mk b/libs/hwui/Android.mk
index a09355b..3e590a9 100644
--- a/libs/hwui/Android.mk
+++ b/libs/hwui/Android.mk
@@ -115,7 +115,6 @@
 
     LOCAL_CFLAGS += -Wall -Werror -Wunused -Wunreachable-code
 
-    include external/stlport/libstlport.mk
     include $(BUILD_SHARED_LIBRARY)
 
     include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/libs/hwui/DisplayList.h b/libs/hwui/DisplayList.h
index 657632d..9eb8ae3 100644
--- a/libs/hwui/DisplayList.h
+++ b/libs/hwui/DisplayList.h
@@ -82,7 +82,7 @@
     LinearAllocator * const mAllocator;
 
     SkPath* allocPathForFrame() {
-        mTempPaths.push_back();
+        mTempPaths.push_back(SkPath());
         return &mTempPaths.back();
     }
 
diff --git a/libs/hwui/OpenGLRenderer.cpp b/libs/hwui/OpenGLRenderer.cpp
index 40a58f2..fdfcbe7 100755
--- a/libs/hwui/OpenGLRenderer.cpp
+++ b/libs/hwui/OpenGLRenderer.cpp
@@ -1607,13 +1607,7 @@
             setScissorFromClip();
         }
 
-        if (clearLayer) {
-            setStencilFromClip();
-        } else {
-            // While clearing layer, force disable stencil buffer, since
-            // it's invalid to stencil-clip *during* the layer clear
-            mCaches.stencil.disable();
-        }
+        setStencilFromClip();
     }
 
     mDescription.reset();
diff --git a/libs/hwui/PathTessellator.cpp b/libs/hwui/PathTessellator.cpp
index d842ed5..b3f779f 100644
--- a/libs/hwui/PathTessellator.cpp
+++ b/libs/hwui/PathTessellator.cpp
@@ -289,14 +289,14 @@
             }
 
             beginTheta += dTheta;
-            Vector2 beginRadialOffset = {cos(beginTheta), sin(beginTheta)};
+            Vector2 beginRadialOffset = {cosf(beginTheta), sinf(beginTheta)};
             paintInfo.scaleOffsetForStrokeWidth(beginRadialOffset);
             Vertex::set(&buffer[capOffset],
                     vertices[0].x + beginRadialOffset.x,
                     vertices[0].y + beginRadialOffset.y);
 
             endTheta += dTheta;
-            Vector2 endRadialOffset = {cos(endTheta), sin(endTheta)};
+            Vector2 endRadialOffset = {cosf(endTheta), sinf(endTheta)};
             paintInfo.scaleOffsetForStrokeWidth(endRadialOffset);
             Vertex::set(&buffer[allocSize - 1 - capOffset],
                     vertices[lastIndex].x + endRadialOffset.x,
@@ -467,7 +467,7 @@
         for (int i = 0; i < extra; i++) {
             theta += dTheta;
 
-            Vector2 radialOffset = {cos(theta), sin(theta)};
+            Vector2 radialOffset = {cosf(theta), sinf(theta)};
 
             // scale to compensate for pinching at sharp angles, see totalOffsetFromNormals()
             radialOffset *= radialScale;
diff --git a/libs/hwui/TextDropShadowCache.cpp b/libs/hwui/TextDropShadowCache.cpp
index 4eec462..96c09e6 100644
--- a/libs/hwui/TextDropShadowCache.cpp
+++ b/libs/hwui/TextDropShadowCache.cpp
@@ -40,7 +40,8 @@
     hash = JenkinsHashMix(hash, android::hash_type(italicStyle));
     hash = JenkinsHashMix(hash, android::hash_type(scaleX));
     if (text) {
-        hash = JenkinsHashMixShorts(hash, text, charCount);
+        hash = JenkinsHashMixShorts(
+            hash, reinterpret_cast<const uint16_t*>(text), charCount);
     }
     if (positions) {
         for (uint32_t i = 0; i < charCount * 2; i++) {
diff --git a/libs/hwui/renderthread/CanvasContext.cpp b/libs/hwui/renderthread/CanvasContext.cpp
index b50a433..92a30e5 100644
--- a/libs/hwui/renderthread/CanvasContext.cpp
+++ b/libs/hwui/renderthread/CanvasContext.cpp
@@ -59,6 +59,7 @@
 
 void CanvasContext::destroy() {
     stopDrawing();
+    setSurface(NULL);
     freePrefetechedLayers();
     destroyHardwareResources();
     mAnimationContext->destroy();
@@ -66,7 +67,6 @@
         delete mCanvas;
         mCanvas = 0;
     }
-    setSurface(NULL);
 }
 
 void CanvasContext::setSurface(ANativeWindow* window) {
diff --git a/libs/storage/IMountService.cpp b/libs/storage/IMountService.cpp
index 7ac7737..c643ed0 100644
--- a/libs/storage/IMountService.cpp
+++ b/libs/storage/IMountService.cpp
@@ -64,7 +64,7 @@
     {
         Parcel data, reply;
         data.writeInterfaceToken(IMountService::getInterfaceDescriptor());
-        data.writeStrongBinder(listener->asBinder());
+        data.writeStrongBinder(IInterface::asBinder(listener));
         if (remote()->transact(TRANSACTION_registerListener, data, &reply) != NO_ERROR) {
             ALOGD("registerListener could not contact remote\n");
             return;
@@ -80,7 +80,7 @@
     {
         Parcel data, reply;
         data.writeInterfaceToken(IMountService::getInterfaceDescriptor());
-        data.writeStrongBinder(listener->asBinder());
+        data.writeStrongBinder(IInterface::asBinder(listener));
         if (remote()->transact(TRANSACTION_unregisterListener, data, &reply) != NO_ERROR) {
             ALOGD("unregisterListener could not contact remote\n");
             return;
@@ -413,7 +413,7 @@
     {
         Parcel data, reply;
         data.writeInterfaceToken(IMountService::getInterfaceDescriptor());
-        data.writeStrongBinder(observer->asBinder());
+        data.writeStrongBinder(IInterface::asBinder(observer));
         if (remote()->transact(TRANSACTION_shutdown, data, &reply) != NO_ERROR) {
             ALOGD("shutdown could not contact remote\n");
             return;
@@ -450,7 +450,7 @@
         data.writeString16(rawPath);
         data.writeString16(canonicalPath);
         data.writeString16(key);
-        data.writeStrongBinder(token->asBinder());
+        data.writeStrongBinder(IInterface::asBinder(token));
         data.writeInt32(nonce);
         if (remote()->transact(TRANSACTION_mountObb, data, &reply) != NO_ERROR) {
             ALOGD("mountObb could not contact remote\n");
@@ -470,7 +470,7 @@
         data.writeInterfaceToken(IMountService::getInterfaceDescriptor());
         data.writeString16(filename);
         data.writeInt32(force ? 1 : 0);
-        data.writeStrongBinder(token->asBinder());
+        data.writeStrongBinder(IInterface::asBinder(token));
         data.writeInt32(nonce);
         if (remote()->transact(TRANSACTION_unmountObb, data, &reply) != NO_ERROR) {
             ALOGD("unmountObb could not contact remote\n");
diff --git a/location/java/android/location/LocationRequest.java b/location/java/android/location/LocationRequest.java
index 39fe4ea..65e7ced 100644
--- a/location/java/android/location/LocationRequest.java
+++ b/location/java/android/location/LocationRequest.java
@@ -212,6 +212,7 @@
                 switch (criteria.getPowerRequirement()) {
                     case Criteria.POWER_HIGH:
                         quality = POWER_HIGH;
+                        break;
                     default:
                         quality = POWER_LOW;
                 }
diff --git a/media/java/android/media/MediaCodecInfo.java b/media/java/android/media/MediaCodecInfo.java
index 01f8193..4513643 100644
--- a/media/java/android/media/MediaCodecInfo.java
+++ b/media/java/android/media/MediaCodecInfo.java
@@ -648,7 +648,7 @@
                 maxChannels = 48;
             } else if (mime.equalsIgnoreCase(MediaFormat.MIMETYPE_AUDIO_VORBIS)) {
                 bitRates = Range.create(32000, 500000);
-                sampleRates = new int[] { 8000, 12000, 16000, 24000, 48000, 192000 };
+                sampleRateRange = Range.create(8000, 192000);
                 maxChannels = 255;
             } else if (mime.equalsIgnoreCase(MediaFormat.MIMETYPE_AUDIO_OPUS)) {
                 bitRates = Range.create(6000, 510000);
@@ -973,7 +973,7 @@
         }
 
         private boolean supports(
-                Integer width, Integer height, Double rate) {
+                Integer width, Integer height, Number rate) {
             boolean ok = true;
 
             if (ok && width != null) {
@@ -985,7 +985,7 @@
                         && (height % mHeightAlignment == 0);
             }
             if (ok && rate != null) {
-                ok = mFrameRateRange.contains(Utils.intRangeFor(rate));
+                ok = mFrameRateRange.contains(Utils.intRangeFor(rate.doubleValue()));
             }
             if (ok && height != null && width != null) {
                 ok = Math.min(height, width) <= mSmallerDimensionUpperLimit;
@@ -998,7 +998,7 @@
                                 new Rational(widthInBlocks, heightInBlocks))
                         && mAspectRatioRange.contains(new Rational(width, height));
                 if (ok && rate != null) {
-                    double blocksPerSec = blockCount * rate;
+                    double blocksPerSec = blockCount * rate.doubleValue();
                     ok = mBlocksPerSecondRange.contains(
                             Utils.longRangeFor(blocksPerSec));
                 }
@@ -1013,7 +1013,7 @@
             final Map<String, Object> map = format.getMap();
             Integer width = (Integer)map.get(MediaFormat.KEY_WIDTH);
             Integer height = (Integer)map.get(MediaFormat.KEY_HEIGHT);
-            Double rate = (Double)map.get(MediaFormat.KEY_FRAME_RATE);
+            Number rate = (Number)map.get(MediaFormat.KEY_FRAME_RATE);
 
             // we ignore color-format for now as it is not reliably reported by codec
 
diff --git a/media/jni/android_media_MediaExtractor.cpp b/media/jni/android_media_MediaExtractor.cpp
index 52e9910..c0795b6 100644
--- a/media/jni/android_media_MediaExtractor.cpp
+++ b/media/jni/android_media_MediaExtractor.cpp
@@ -93,7 +93,7 @@
         env->GetByteArrayRegion(byteArrayObj, 0, size, (jbyte*) buffer);
         env->DeleteLocalRef(byteArrayObj);
         if (env->ExceptionCheck()) {
-            ALOGW("Exception occurred while reading %zu at %lld", size, offset);
+            ALOGW("Exception occurred while reading %zu at %lld", size, (long long)offset);
             LOGW_EX(env);
             env->ExceptionClear();
             return -1;
diff --git a/media/jni/android_media_MediaExtractor.h b/media/jni/android_media_MediaExtractor.h
index e5a0c16e..9f62506 100644
--- a/media/jni/android_media_MediaExtractor.h
+++ b/media/jni/android_media_MediaExtractor.h
@@ -30,7 +30,7 @@
 namespace android {
 
 struct IMediaHTTPService;
-struct MetaData;
+class MetaData;
 struct NuMediaExtractor;
 
 struct JMediaExtractor : public RefBase {
diff --git a/media/jni/android_media_MediaHTTPConnection.cpp b/media/jni/android_media_MediaHTTPConnection.cpp
index 0e7d83e..7226ef5 100644
--- a/media/jni/android_media_MediaHTTPConnection.cpp
+++ b/media/jni/android_media_MediaHTTPConnection.cpp
@@ -128,7 +128,7 @@
         JNIEnv *env, jobject thiz) {
     sp<JMediaHTTPConnection> conn = getObject(env, thiz);
 
-    return javaObjectForIBinder(env, conn->getIMemory()->asBinder());
+    return javaObjectForIBinder(env, IInterface::asBinder(conn->getIMemory()));
 }
 
 static jint android_media_MediaHTTPConnection_native_readAt(
diff --git a/media/jni/android_media_MediaHTTPConnection.h b/media/jni/android_media_MediaHTTPConnection.h
index 62ff678..f87f1eb 100644
--- a/media/jni/android_media_MediaHTTPConnection.h
+++ b/media/jni/android_media_MediaHTTPConnection.h
@@ -24,8 +24,8 @@
 
 namespace android {
 
-struct IMemory;
-struct MemoryDealer;
+class IMemory;
+class MemoryDealer;
 
 struct JMediaHTTPConnection : public RefBase {
     enum {
diff --git a/media/jni/android_media_MediaMetadataRetriever.cpp b/media/jni/android_media_MediaMetadataRetriever.cpp
index dae6d3b..fc7931e 100644
--- a/media/jni/android_media_MediaMetadataRetriever.cpp
+++ b/media/jni/android_media_MediaMetadataRetriever.cpp
@@ -228,7 +228,7 @@
 
 static jobject android_media_MediaMetadataRetriever_getFrameAtTime(JNIEnv *env, jobject thiz, jlong timeUs, jint option)
 {
-    ALOGV("getFrameAtTime: %lld us option: %d", timeUs, option);
+    ALOGV("getFrameAtTime: %lld us option: %d", (long long)timeUs, option);
     MediaMetadataRetriever* retriever = getRetriever(env, thiz);
     if (retriever == 0) {
         jniThrowException(env, "java/lang/IllegalStateException", "No retriever available");
diff --git a/media/jni/android_media_MediaMuxer.cpp b/media/jni/android_media_MediaMuxer.cpp
index f234a1b..ecb2ac8 100644
--- a/media/jni/android_media_MediaMuxer.cpp
+++ b/media/jni/android_media_MediaMuxer.cpp
@@ -107,7 +107,7 @@
 
     if (dstSize < (offset + size)) {
         ALOGE("writeSampleData saw wrong dstSize %lld, size  %d, offset %d",
-              dstSize, size, offset);
+              (long long)dstSize, size, offset);
         if (byteArray != NULL) {
             env->ReleaseByteArrayElements(byteArray, (jbyte *)dst, 0);
         }
diff --git a/media/jni/android_media_MediaPlayer.cpp b/media/jni/android_media_MediaPlayer.cpp
index 73a924d..820de5b 100644
--- a/media/jni/android_media_MediaPlayer.cpp
+++ b/media/jni/android_media_MediaPlayer.cpp
@@ -895,8 +895,6 @@
     {"setNextMediaPlayer",  "(Landroid/media/MediaPlayer;)V",   (void *)android_media_MediaPlayer_setNextMediaPlayer},
 };
 
-static const char* const kClassPathName = "android/media/MediaPlayer";
-
 // This function only registers the native methods
 static int register_android_media_MediaPlayer(JNIEnv *env)
 {
diff --git a/media/jni/android_media_MediaRecorder.cpp b/media/jni/android_media_MediaRecorder.cpp
index 5646740..914b8a6 100644
--- a/media/jni/android_media_MediaRecorder.cpp
+++ b/media/jni/android_media_MediaRecorder.cpp
@@ -305,7 +305,7 @@
 android_media_MediaRecorder_setMaxFileSize(
         JNIEnv *env, jobject thiz, jlong max_filesize_bytes)
 {
-    ALOGV("setMaxFileSize(%lld)", max_filesize_bytes);
+    ALOGV("setMaxFileSize(%lld)", (long long)max_filesize_bytes);
     sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
 
     char params[64];
@@ -461,11 +461,13 @@
     sp<JNIMediaRecorderListener> listener = new JNIMediaRecorderListener(env, thiz, weak_this);
     mr->setListener(listener);
 
-   // Convert client name jstring to String16
-    const char16_t *rawClientName = env->GetStringChars(packageName, NULL);
+    // Convert client name jstring to String16
+    const char16_t *rawClientName = reinterpret_cast<const char16_t*>(
+        env->GetStringChars(packageName, NULL));
     jsize rawClientNameLen = env->GetStringLength(packageName);
     String16 clientName(rawClientName, rawClientNameLen);
-    env->ReleaseStringChars(packageName, rawClientName);
+    env->ReleaseStringChars(packageName,
+                            reinterpret_cast<const jchar*>(rawClientName));
 
     // pass client package name for permissions tracking
     mr->setClientName(clientName);
@@ -507,8 +509,6 @@
     {"native_finalize",      "()V",                             (void *)android_media_MediaRecorder_native_finalize},
 };
 
-static const char* const kClassPathName = "android/media/MediaRecorder";
-
 // This function only registers the native methods, and is called from
 // JNI_OnLoad in android_media_MediaPlayer.cpp
 int register_android_media_MediaRecorder(JNIEnv *env)
diff --git a/media/jni/android_mtp_MtpDatabase.cpp b/media/jni/android_mtp_MtpDatabase.cpp
index 1a0675e..f381488 100644
--- a/media/jni/android_mtp_MtpDatabase.cpp
+++ b/media/jni/android_mtp_MtpDatabase.cpp
@@ -814,7 +814,7 @@
     info.mAssociationType = MTP_ASSOCIATION_TYPE_UNDEFINED;
 
     jchar* str = env->GetCharArrayElements(mStringBuffer, 0);
-    MtpString temp(str);
+    MtpString temp(reinterpret_cast<char16_t*>(str));
     info.mName = strdup((const char *)temp);
     env->ReleaseCharArrayElements(mStringBuffer, str, 0);
 
@@ -883,7 +883,8 @@
     }
 
     jchar* str = env->GetCharArrayElements(mStringBuffer, 0);
-    outFilePath.setTo(str, strlen16(str));
+    outFilePath.setTo(reinterpret_cast<char16_t*>(str),
+                      strlen16(reinterpret_cast<char16_t*>(str)));
     env->ReleaseCharArrayElements(mStringBuffer, str, 0);
 
     jlong* longValues = env->GetLongArrayElements(mLongBuffer, 0);
@@ -1173,8 +1174,6 @@
                                         (void *)android_mtp_MtpPropertyGroup_format_date_time},
 };
 
-static const char* const kClassPathName = "android/mtp/MtpDatabase";
-
 int register_android_mtp_MtpDatabase(JNIEnv *env)
 {
     jclass clazz;
diff --git a/media/jni/android_mtp_MtpDevice.cpp b/media/jni/android_mtp_MtpDevice.cpp
index fb15770..2dbd7dc 100644
--- a/media/jni/android_mtp_MtpDevice.cpp
+++ b/media/jni/android_mtp_MtpDevice.cpp
@@ -417,8 +417,6 @@
                                         (void *)android_mtp_MtpDevice_import_file},
 };
 
-static const char* const kClassPathName = "android/mtp/MtpDevice";
-
 int register_android_mtp_MtpDevice(JNIEnv *env)
 {
     jclass clazz;
diff --git a/media/jni/android_mtp_MtpServer.cpp b/media/jni/android_mtp_MtpServer.cpp
index 2f90dfe..2ce2a90 100644
--- a/media/jni/android_mtp_MtpServer.cpp
+++ b/media/jni/android_mtp_MtpServer.cpp
@@ -193,8 +193,6 @@
     {"native_remove_storage",       "(I)V", (void *)android_mtp_MtpServer_remove_storage},
 };
 
-static const char* const kClassPathName = "android/mtp/MtpServer";
-
 int register_android_mtp_MtpServer(JNIEnv *env)
 {
     jclass clazz;
diff --git a/media/mca/filterfw/Android.mk b/media/mca/filterfw/Android.mk
index a5b4b27..334f4e2 100644
--- a/media/mca/filterfw/Android.mk
+++ b/media/mca/filterfw/Android.mk
@@ -43,11 +43,4 @@
                           libjnigraphics \
                           libmedia
 
-# Don't prelink this library.  For more efficient code, you may want
-# to add this library to the prelink map and set this to true. However,
-# it's difficult to do this for applications that are not supplied as
-# part of a system image.
-LOCAL_PRELINK_MODULE := false
-
-include external/stlport/libstlport.mk
 include $(BUILD_SHARED_LIBRARY)
diff --git a/media/mca/filterfw/jni/Android.mk b/media/mca/filterfw/jni/Android.mk
index 67337e0..cba4e7e 100644
--- a/media/mca/filterfw/jni/Android.mk
+++ b/media/mca/filterfw/jni/Android.mk
@@ -41,13 +41,6 @@
     $(JNI_H_INCLUDE) \
     $(LOCAL_PATH)/..
 
-# Don't prelink this library.  For more efficient code, you may want
-# to add this library to the prelink map and set this to true. However,
-# it's difficult to do this for applications that are not supplied as
-# part of a system image.
-LOCAL_PRELINK_MODULE := false
-
-LOCAL_CFLAGS += -Wall -Werror -Wunused -Wunreachable-code
+LOCAL_CFLAGS += -Wall -Werror -Wunused -Wunreachable-code -Wno-unused-parameter
 
 include $(BUILD_STATIC_LIBRARY)
-
diff --git a/media/mca/filterfw/jni/jni_util.h b/media/mca/filterfw/jni/jni_util.h
index 68ff653..11c0871 100644
--- a/media/mca/filterfw/jni/jni_util.h
+++ b/media/mca/filterfw/jni/jni_util.h
@@ -16,7 +16,7 @@
 
 #include <jni.h>
 
-#include <hash_map>
+#include <unordered_map>
 #include <string>
 
 #include "base/utilities.h"
@@ -188,8 +188,8 @@
         id_field_name_(id_fld_name),
         next_id_(0) { }
 
-    typedef std::hash_map<int, T*>    CObjMap;
-    typedef std::hash_map<int, bool>  FlagMap;
+    typedef std::unordered_map<int, T*>    CObjMap;
+    typedef std::unordered_map<int, bool>  FlagMap;
     static ObjectPool* instance_;
     std::string jclass_name_;
     std::string id_field_name_;
diff --git a/media/mca/filterfw/native/core/shader_program.cpp b/media/mca/filterfw/native/core/shader_program.cpp
index 002327b..1e573fb 100644
--- a/media/mca/filterfw/native/core/shader_program.cpp
+++ b/media/mca/filterfw/native/core/shader_program.cpp
@@ -30,9 +30,6 @@
 namespace android {
 namespace filterfw {
 
-// VBO attachment keys
-static const int kDefaultVboKey = 1;
-
 static const char* s_default_vertex_shader_source_ =
   "attribute vec4 a_position;\n"
   "attribute vec2 a_texcoord;\n"
@@ -55,10 +52,6 @@
   *yt = w0 * b[1] + w1 * b[3] + w2 * b[5] + w3 * b[7];
 }
 
-static inline float AdjustRatio(float current, float next) {
-  return (current + next) / 2.0;
-}
-
 // VertexAttrib implementation /////////////////////////////////////////////////
 ShaderProgram::VertexAttrib::VertexAttrib()
   : is_const(true),
@@ -322,7 +315,7 @@
       size_t next_pos = 0;
       size_t line_number = 1;
       while ( (next_pos = src.find_first_of('\n', cur_pos)) != std::string::npos) {
-        ALOGE("%03d : %s", line_number, src.substr(cur_pos, next_pos-cur_pos).c_str());
+        ALOGE("%03zd : %s", line_number, src.substr(cur_pos, next_pos-cur_pos).c_str());
         cur_pos = next_pos + 1;
         line_number++;
       }
@@ -442,7 +435,7 @@
     if (tex_var >= 0) {
       glUniform1i(tex_var, i);
     } else {
-      ALOGE("ShaderProgram: Shader does not seem to support %d number of "
+      ALOGE("ShaderProgram: Shader does not seem to support %zd number of "
            "inputs! Missing uniform 'tex_sampler_%d'!", textures.size(), i);
       return false;
     }
diff --git a/media/mca/filterfw/native/libfilterfw.mk b/media/mca/filterfw/native/libfilterfw.mk
index 4e88e6f..69227ce 100644
--- a/media/mca/filterfw/native/libfilterfw.mk
+++ b/media/mca/filterfw/native/libfilterfw.mk
@@ -18,9 +18,6 @@
 
 # Uncomment the requirements below, once we need them:
 
-# STLport
-include external/stlport/libstlport.mk
-
 # Neven FaceDetect SDK
 #LOCAL_C_INCLUDES += external/neven/FaceRecEm/common/src/b_FDSDK \
 #	external/neven/FaceRecEm/common/src \
diff --git a/media/mca/filterpacks/Android.mk b/media/mca/filterpacks/Android.mk
index d030749..0ff7658 100644
--- a/media/mca/filterpacks/Android.mk
+++ b/media/mca/filterpacks/Android.mk
@@ -30,8 +30,6 @@
 
 LOCAL_CFLAGS += -Wall -Werror -Wunused -Wunreachable-code
 
-include external/stlport/libstlport.mk
-
 include $(BUILD_STATIC_LIBRARY)
 
 ##
@@ -50,8 +48,6 @@
 
 LOCAL_SHARED_LIBRARIES := liblog libutils libfilterfw
 
-LOCAL_PRELINK_MODULE := false
-
 LOCAL_CFLAGS += -Wall -Werror -Wunused -Wunreachable-code
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/media/tests/audiotests/Android.mk b/media/tests/audiotests/Android.mk
index 69f0bb5..794e7f22 100644
--- a/media/tests/audiotests/Android.mk
+++ b/media/tests/audiotests/Android.mk
@@ -1,21 +1,23 @@
-ifeq ($(TARGET_ARCH),arm)
 
 LOCAL_PATH:= $(call my-dir)
 
 include $(CLEAR_VARS)
 
 LOCAL_MODULE:= shared_mem_test
+
 LOCAL_SRC_FILES := \
-		   shared_mem_test.cpp
+    shared_mem_test.cpp
+
 LOCAL_SHARED_LIBRARIES :=  \
-		libc \
-        libcutils \
-        libutils \
-        libbinder \
-        libhardware_legacy \
-		libmedia
+    libc \
+    libcutils \
+    libutils \
+    libbinder \
+    libhardware_legacy \
+    libmedia
+
 LOCAL_MODULE_TAGS := tests
 
-include $(BUILD_EXECUTABLE)
+LOCAL_CFLAGS += -Wall -Werror -Wunused -Wunreachable-code
 
-endif
+include $(BUILD_EXECUTABLE)
diff --git a/media/tests/audiotests/shared_mem_test.cpp b/media/tests/audiotests/shared_mem_test.cpp
index 992c900..2f57499 100644
--- a/media/tests/audiotests/shared_mem_test.cpp
+++ b/media/tests/audiotests/shared_mem_test.cpp
@@ -133,12 +133,8 @@
 ************************************************************/
 void AudioTrackTest::Generate(short *buffer, long bufferSz, long amplitude, unsigned long &phi, long dPhi)
 {
-    long pi13 = 25736;   // 2^13*pi
     // fill buffer
     for(int i0=0; i0<bufferSz; i0++) {
-        long sample;
-        long l0, l1;
-
         buffer[i0] = ComputeSine( amplitude, phi);
         phi += dPhi;
     }
@@ -210,7 +206,7 @@
 *    global main
 *
 ************************************************************/
-int main(int argc, char *argv[]) {
+int main() {
 
     return android::main();
 }
diff --git a/media/tests/omxjpegdecoder/Android.mk b/media/tests/omxjpegdecoder/Android.mk
index b0bc5d4..70fdd05 100644
--- a/media/tests/omxjpegdecoder/Android.mk
+++ b/media/tests/omxjpegdecoder/Android.mk
@@ -17,9 +17,9 @@
 include $(CLEAR_VARS)
 
 LOCAL_SRC_FILES := \
-        omx_jpeg_decoder.cpp \
-        jpeg_decoder_bench.cpp \
-        StreamSource.cpp
+    omx_jpeg_decoder.cpp \
+    jpeg_decoder_bench.cpp \
+    StreamSource.cpp
 
 LOCAL_SHARED_LIBRARIES := \
     libcutils \
@@ -42,4 +42,6 @@
 
 LOCAL_MODULE_TAGS := optional
 
+LOCAL_CFLAGS += -Wall -Werror -Wunused -Wunreachable-code
+
 include $(BUILD_EXECUTABLE)
diff --git a/media/tests/omxjpegdecoder/StreamSource.h b/media/tests/omxjpegdecoder/StreamSource.h
index 9807385..6e4adfb 100644
--- a/media/tests/omxjpegdecoder/StreamSource.h
+++ b/media/tests/omxjpegdecoder/StreamSource.h
@@ -20,7 +20,11 @@
 
 #include <stdio.h>
 
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wunused-parameter"
 #include <SkStream.h>
+#pragma GCC diagnostic pop
+
 #include <media/stagefright/DataSource.h>
 #include <media/stagefright/MediaErrors.h>
 #include <utils/threads.h>
diff --git a/media/tests/omxjpegdecoder/jpeg_decoder_bench.cpp b/media/tests/omxjpegdecoder/jpeg_decoder_bench.cpp
index de6294d..83474d7 100644
--- a/media/tests/omxjpegdecoder/jpeg_decoder_bench.cpp
+++ b/media/tests/omxjpegdecoder/jpeg_decoder_bench.cpp
@@ -20,9 +20,13 @@
 
 #include <binder/ProcessState.h>
 
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wunused-parameter"
 #include "SkBitmap.h"
 #include "SkImageDecoder.h"
 #include "SkStream.h"
+#pragma GCC diagnostic pop
+
 #include "omx_jpeg_decoder.h"
 
 class SkJPEGImageDecoder : public SkImageDecoder {
@@ -101,6 +105,11 @@
 }
 
 int main(int argc, char** argv) {
+    if (argc < 2) {
+        printf("Need a parameter!\n");
+        return 1;
+    }
+
     android::ProcessState::self()->startThreadPool();
 
     printf("Decoding jpeg with libjpeg...\n");
diff --git a/media/tests/omxjpegdecoder/omx_jpeg_decoder.cpp b/media/tests/omxjpegdecoder/omx_jpeg_decoder.cpp
index 229bfdb..c54490e 100644
--- a/media/tests/omxjpegdecoder/omx_jpeg_decoder.cpp
+++ b/media/tests/omxjpegdecoder/omx_jpeg_decoder.cpp
@@ -30,35 +30,18 @@
 #include <media/stagefright/MetaData.h>
 #include <media/stagefright/OMXClient.h>
 #include <media/stagefright/OMXCodec.h>
+
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wunused-parameter"
 #include <SkImage.h>
 #include <SkMallocPixelRef.h>
+#pragma GCC diagnostic pop
 
 #include "omx_jpeg_decoder.h"
 #include "StreamSource.h"
 
 using namespace android;
 
-static void getJpegOutput(MediaBuffer* buffer, const char* filename) {
-    int size = buffer->range_length();
-    int offset = buffer->range_offset();
-    FILE *pFile = fopen(filename, "w+");
-
-    if (pFile == NULL) {
-        printf("Error: cannot open %s.\n", filename);
-    } else {
-        char* data = (char*) buffer->data();
-        data += offset;
-        while (size > 0) {
-            int numChars = fwrite(data, sizeof(char), 1024, pFile);
-            int numBytes = numChars * sizeof(char);
-            size -= numBytes;
-            data += numBytes;
-        }
-        fclose(pFile);
-    }
-    return;
-}
-
 extern int storeBitmapToFile(SkBitmap* bitmap, const char* filename) {
     bitmap->lockPixels();
     uint8_t* data = (uint8_t *)bitmap->getPixels();
@@ -140,7 +123,7 @@
 }
 
 bool OmxJpegImageDecoder::decodeSource(sp<MediaSource> decoder,
-        const sp<MediaSource>& source, SkBitmap* bm) {
+        const sp<MediaSource>& /* source */, SkBitmap* bm) {
     status_t rt = decoder->start();
     if (rt != OK) {
         ALOGE("Cannot start OMX Decoder!");
@@ -169,7 +152,7 @@
     return true;
 }
 
-void OmxJpegImageDecoder::configBitmapSize(SkBitmap* bm, SkColorType pref,
+void OmxJpegImageDecoder::configBitmapSize(SkBitmap* bm, SkColorType /* pref */,
         int width, int height) {
     // Set the color space to ARGB_8888 for now (ignoring pref)
     // because of limitation in hardware support.
diff --git a/media/tests/omxjpegdecoder/omx_jpeg_decoder.h b/media/tests/omxjpegdecoder/omx_jpeg_decoder.h
index e487245..284410c 100644
--- a/media/tests/omxjpegdecoder/omx_jpeg_decoder.h
+++ b/media/tests/omxjpegdecoder/omx_jpeg_decoder.h
@@ -25,8 +25,12 @@
 #include <media/stagefright/MediaSource.h>
 #include <media/stagefright/OMXClient.h>
 #include <media/stagefright/OMXCodec.h>
+
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wunused-parameter"
 #include <SkImageDecoder.h>
 #include <SkStream.h>
+#pragma GCC diagnostic pop
 
 using namespace android;
 
diff --git a/media/tests/players/Android.mk b/media/tests/players/Android.mk
index adf0d30..7ab6458 100644
--- a/media/tests/players/Android.mk
+++ b/media/tests/players/Android.mk
@@ -26,5 +26,6 @@
 LOCAL_MODULE:= invoke_mock_media_player
 LOCAL_MODULE_TAGS := tests eng
 
+LOCAL_CFLAGS += -Wall -Werror -Wunused -Wunreachable-code
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/media/tests/players/invoke_mock_media_player.cpp b/media/tests/players/invoke_mock_media_player.cpp
index d1fed7bb..0d0c7ad 100644
--- a/media/tests/players/invoke_mock_media_player.cpp
+++ b/media/tests/players/invoke_mock_media_player.cpp
@@ -58,7 +58,7 @@
     virtual bool        hardwareOutput() {return true;}
 
     virtual status_t    setDataSource(
-            const sp<IMediaHTTPService> &httpService,
+            const sp<IMediaHTTPService>& /* httpService */,
             const char *url,
             const KeyedVector<String8, String8> *) {
         ALOGV("setDataSource %s", url);
@@ -69,24 +69,28 @@
         return OK;
     }
 
-    virtual status_t    setDataSource(int fd, int64_t offset, int64_t length) {return OK;}
+    virtual status_t    setDataSource(int /* fd */, int64_t /* offset */, int64_t /* length */) {
+        return OK;
+    }
     virtual status_t    setVideoSurfaceTexture(
-                                const sp<IGraphicBufferProducer>& bufferProducer) {return OK;}
-    virtual status_t    prepare() {return OK;}
-    virtual status_t    prepareAsync() {return OK;}
-    virtual status_t    start() {return OK;}
-    virtual status_t    stop() {return OK;}
-    virtual status_t    pause() {return OK;}
-    virtual bool        isPlaying() {return true;}
-    virtual status_t    seekTo(int msec) {return OK;}
-    virtual status_t    getCurrentPosition(int *msec) {return OK;}
-    virtual status_t    getDuration(int *msec) {return OK;}
+                                const sp<IGraphicBufferProducer>& /* bufferProducer */) {
+        return OK;
+    }
+    virtual status_t    prepare() { return OK; }
+    virtual status_t    prepareAsync() { return OK; }
+    virtual status_t    start() { return OK; }
+    virtual status_t    stop() { return OK; }
+    virtual status_t    pause() { return OK; }
+    virtual bool        isPlaying() { return true; }
+    virtual status_t    seekTo(int /* msec */) { return OK; }
+    virtual status_t    getCurrentPosition(int* /* msec */) { return OK; }
+    virtual status_t    getDuration(int* /* msec */) { return OK; }
     virtual status_t    reset() {return OK;}
-    virtual status_t    setLooping(int loop) {return OK;}
+    virtual status_t    setLooping(int /* loop */) { return OK; }
     virtual player_type playerType() {return TEST_PLAYER;}
     virtual status_t    invoke(const Parcel& request, Parcel *reply);
-    virtual status_t    setParameter(int key, const Parcel &request) {return OK;}
-    virtual status_t    getParameter(int key, Parcel *reply) {return OK;}
+    virtual status_t    setParameter(int /* key */, const Parcel& /* request */) { return OK; }
+    virtual status_t    getParameter(int /* key */, Parcel* /* reply */) { return OK; }
 
 
   private:
diff --git a/packages/DefaultContainerService/jni/Android.mk b/packages/DefaultContainerService/jni/Android.mk
index ef4f699..7808ae1 100644
--- a/packages/DefaultContainerService/jni/Android.mk
+++ b/packages/DefaultContainerService/jni/Android.mk
@@ -18,8 +18,6 @@
 
 include $(CLEAR_VARS)
 
-
-
 LOCAL_SRC_FILES := \
     com_android_defcontainer_MeasurementUtils.cpp
 
@@ -37,4 +35,6 @@
 LOCAL_MODULE := libdefcontainer_jni
 LOCAL_MODULE_TAGS := optional
 
+LOCAL_CFLAGS += -Wall -Werror -Wunused -Wunreachable-code
+
 include $(BUILD_SHARED_LIBRARY)
diff --git a/packages/DefaultContainerService/jni/com_android_defcontainer_MeasurementUtils.cpp b/packages/DefaultContainerService/jni/com_android_defcontainer_MeasurementUtils.cpp
index 7390bb7..6be4849 100644
--- a/packages/DefaultContainerService/jni/com_android_defcontainer_MeasurementUtils.cpp
+++ b/packages/DefaultContainerService/jni/com_android_defcontainer_MeasurementUtils.cpp
@@ -29,7 +29,7 @@
 
 namespace android {
 
-static jlong native_measureDirectory(JNIEnv* env, jobject clazz, jstring directory) {
+static jlong native_measureDirectory(JNIEnv* env, jobject /* clazz */, jstring directory) {
     jlong ret = 0L;
 
     const char* path = env->GetStringUTFChars(directory, NULL);
@@ -65,7 +65,7 @@
 
 } // namespace android
 
-int JNI_OnLoad(JavaVM *jvm, void* reserved) {
+int JNI_OnLoad(JavaVM *jvm, void* /* reserved */) {
     JNIEnv *env;
 
     if (jvm->GetEnv((void**)&env, JNI_VERSION_1_6)) {
diff --git a/packages/PrintSpooler/jni/Android.mk b/packages/PrintSpooler/jni/Android.mk
index fe7d06b..9fd4c84 100644
--- a/packages/PrintSpooler/jni/Android.mk
+++ b/packages/PrintSpooler/jni/Android.mk
@@ -16,4 +16,6 @@
 LOCAL_MODULE := libprintspooler_jni
 LOCAL_MODULE_TAGS := optional
 
+LOCAL_CFLAGS += -Wall -Werror -Wunused -Wunreachable-code
+
 include $(BUILD_SHARED_LIBRARY)
diff --git a/packages/PrintSpooler/jni/com_android_printspooler_util_BitmapSerializeUtils.cpp b/packages/PrintSpooler/jni/com_android_printspooler_util_BitmapSerializeUtils.cpp
index 57281c8..b5d9138 100644
--- a/packages/PrintSpooler/jni/com_android_printspooler_util_BitmapSerializeUtils.cpp
+++ b/packages/PrintSpooler/jni/com_android_printspooler_util_BitmapSerializeUtils.cpp
@@ -79,7 +79,7 @@
     throwException(env, className, message);
 }
 
-static void readBitmapPixels(JNIEnv* env, jclass clazz, jobject jbitmap, jint fd) {
+static void readBitmapPixels(JNIEnv* env, jclass /* clazz */, jobject jbitmap, jint fd) {
     // Read the info.
     AndroidBitmapInfo readInfo;
     bool read = readAllBytes(fd, (void*) &readInfo, sizeof(AndroidBitmapInfo));
@@ -127,7 +127,7 @@
     }
 }
 
-static void writeBitmapPixels(JNIEnv* env, jclass clazz, jobject jbitmap, jint fd) {
+static void writeBitmapPixels(JNIEnv* env, jclass /* clazz */, jobject jbitmap, jint fd) {
     // Get the info.
     AndroidBitmapInfo info;
     int result = AndroidBitmap_getInfo(env, jbitmap, &info);
diff --git a/packages/services/PacProcessor/jni/Android.mk b/packages/services/PacProcessor/jni/Android.mk
index f16c90b..254cbc2 100644
--- a/packages/services/PacProcessor/jni/Android.mk
+++ b/packages/services/PacProcessor/jni/Android.mk
@@ -36,6 +36,6 @@
 LOCAL_MODULE := libjni_pacprocessor
 LOCAL_MODULE_TAGS := optional
 
-include external/stlport/libstlport.mk
+LOCAL_CFLAGS += -Wall -Werror -Wunused -Wunreachable-code
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/packages/services/PacProcessor/jni/com_android_pacprocessor_PacNative.cpp b/packages/services/PacProcessor/jni/com_android_pacprocessor_PacNative.cpp
index c5aa13b..2727338 100644
--- a/packages/services/PacProcessor/jni/com_android_pacprocessor_PacNative.cpp
+++ b/packages/services/PacProcessor/jni/com_android_pacprocessor_PacNative.cpp
@@ -48,7 +48,8 @@
 
 String16 jstringToString16(JNIEnv* env, jstring jstr) {
     const jchar* str = env->GetStringCritical(jstr, 0);
-    String16 str16(str, env->GetStringLength(jstr));
+    String16 str16(reinterpret_cast<const char16_t*>(str),
+                   env->GetStringLength(jstr));
     env->ReleaseStringCritical(jstr, str);
     return str16;
 }
@@ -57,10 +58,10 @@
     const char16_t* str = string.string();
     size_t len = string.size();
 
-    return env->NewString(str, len);
+    return env->NewString(reinterpret_cast<const jchar*>(str), len);
 }
 
-static jboolean com_android_pacprocessor_PacNative_createV8ParserNativeLocked(JNIEnv* env, 
+static jboolean com_android_pacprocessor_PacNative_createV8ParserNativeLocked(JNIEnv* /* env */,
         jobject) {
     if (proxyResolver == NULL) {
         logger = new ProxyErrorLogger();
@@ -72,7 +73,7 @@
     return JNI_TRUE;
 }
 
-static jboolean com_android_pacprocessor_PacNative_destroyV8ParserNativeLocked(JNIEnv* env, 
+static jboolean com_android_pacprocessor_PacNative_destroyV8ParserNativeLocked(JNIEnv* /* env */,
         jobject) {
     if (proxyResolver != NULL) {
         delete logger;
diff --git a/packages/services/PacProcessor/jni/jni_init.cpp b/packages/services/PacProcessor/jni/jni_init.cpp
index bda33fb..de844c8 100644
--- a/packages/services/PacProcessor/jni/jni_init.cpp
+++ b/packages/services/PacProcessor/jni/jni_init.cpp
@@ -25,7 +25,7 @@
 
 using namespace android;
 
-extern "C" jint JNI_OnLoad(JavaVM* vm, void* reserved) {
+extern "C" jint JNI_OnLoad(JavaVM* vm, void* /* reserved */) {
     JNIEnv *env;
     if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
         ALOGE("ERROR: GetEnv failed");
diff --git a/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java b/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java
index 2699d13b..1502829 100644
--- a/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java
+++ b/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java
@@ -4389,7 +4389,7 @@
                 result &= ~ACTION_PASS_TO_USER;
                 if (down) {
                     boolean panic = mImmersiveModeConfirmation.onPowerKeyDown(interactive,
-                            event.getDownTime(), isImmersiveMode(mLastSystemUiFlags));
+                            SystemClock.elapsedRealtime(), isImmersiveMode(mLastSystemUiFlags));
                     if (panic) {
                         mHandler.post(mRequestTransientNav);
                     }
@@ -5797,6 +5797,7 @@
         if (denyTransientStatus || denyTransientNav) {
             // clear the clearable flags instead
             clearClearableFlagsLw();
+            vis &= ~View.SYSTEM_UI_CLEARABLE_FLAGS;
         }
 
         vis = mStatusBarController.updateVisibilityLw(transientStatusBarAllowed, oldVis, vis);
diff --git a/preloaded-classes b/preloaded-classes
index 7686431..dee84f0 100644
--- a/preloaded-classes
+++ b/preloaded-classes
@@ -2631,7 +2631,6 @@
 javax.microedition.khronos.opengles.GL11ExtensionPack
 javax.net.DefaultSocketFactory
 javax.net.SocketFactory
-javax.net.ssl.DefaultHostnameVerifier
 javax.net.ssl.DistinguishedNameParser
 javax.net.ssl.HostnameVerifier
 javax.net.ssl.HttpsURLConnection
diff --git a/rs/java/android/renderscript/RenderScript.java b/rs/java/android/renderscript/RenderScript.java
index 2ee4ff2..114042d 100644
--- a/rs/java/android/renderscript/RenderScript.java
+++ b/rs/java/android/renderscript/RenderScript.java
@@ -1146,6 +1146,13 @@
             mApplicationContext = ctx.getApplicationContext();
         }
         mRWLock = new ReentrantReadWriteLock();
+        try {
+            registerNativeAllocation.invoke(sRuntime, 4 * 1024 * 1024); // 4MB for GC sake
+        } catch (Exception e) {
+            Log.e(RenderScript.LOG_TAG, "Couldn't invoke registerNativeAllocation:" + e);
+            throw new RSRuntimeException("Couldn't invoke registerNativeAllocation:" + e);
+        }
+
     }
 
     /**
diff --git a/rs/java/android/renderscript/ScriptIntrinsicResize.java b/rs/java/android/renderscript/ScriptIntrinsicResize.java
index d6764cc..cee4c33 100644
--- a/rs/java/android/renderscript/ScriptIntrinsicResize.java
+++ b/rs/java/android/renderscript/ScriptIntrinsicResize.java
@@ -29,6 +29,8 @@
     /**
      * Supported elements types are {@link Element#U8}, {@link
      * Element#U8_2}, {@link Element#U8_3}, {@link Element#U8_4}
+     * {@link Element#F32}, {@link Element#F32_2}, {@link
+     * Element#F32_3}, {@link Element#F32_4}
      *
      * @param rs The RenderScript context
      *
@@ -52,7 +54,11 @@
         if (!e.isCompatible(Element.U8(mRS)) &&
             !e.isCompatible(Element.U8_2(mRS)) &&
             !e.isCompatible(Element.U8_3(mRS)) &&
-            !e.isCompatible(Element.U8_4(mRS))) {
+            !e.isCompatible(Element.U8_4(mRS)) &&
+            !e.isCompatible(Element.F32(mRS)) &&
+            !e.isCompatible(Element.F32_2(mRS)) &&
+            !e.isCompatible(Element.F32_3(mRS)) &&
+            !e.isCompatible(Element.F32_4(mRS))) {
             throw new RSIllegalArgumentException("Unsuported element type.");
         }
 
diff --git a/rs/jni/Android.mk b/rs/jni/Android.mk
index f2c2e98..f1f0bfc 100644
--- a/rs/jni/Android.mk
+++ b/rs/jni/Android.mk
@@ -5,27 +5,28 @@
     android_renderscript_RenderScript.cpp
 
 LOCAL_SHARED_LIBRARIES := \
-        libandroid_runtime \
-        libandroidfw \
-        libnativehelper \
-        libRS \
-        libcutils \
-        liblog \
-        libskia \
-        libutils \
-        libui \
-        libgui
+    libandroid_runtime \
+    libandroidfw \
+    libnativehelper \
+    libRS \
+    libcutils \
+    liblog \
+    libskia \
+    libutils \
+    libui \
+    libgui
 
 LOCAL_STATIC_LIBRARIES :=
 
 rs_generated_include_dir := $(call intermediates-dir-for,SHARED_LIBRARIES,libRS,,)
 
 LOCAL_C_INCLUDES += \
-	$(JNI_H_INCLUDE) \
-	frameworks/rs \
-	$(rs_generated_include_dir)
+    $(JNI_H_INCLUDE) \
+    frameworks/rs \
+    $(rs_generated_include_dir)
 
 LOCAL_CFLAGS += -Wno-unused-parameter -std=c++11
+LOCAL_CFLAGS += -Wall -Werror -Wunused -Wunreachable-code
 
 LOCAL_ADDITIONAL_DEPENDENCIES := $(addprefix $(rs_generated_include_dir)/,rsgApiFuncDecl.h)
 LOCAL_MODULE:= librs_jni
diff --git a/rs/jni/android_renderscript_RenderScript.cpp b/rs/jni/android_renderscript_RenderScript.cpp
index 2d94131..68a0b83 100644
--- a/rs/jni/android_renderscript_RenderScript.cpp
+++ b/rs/jni/android_renderscript_RenderScript.cpp
@@ -22,6 +22,7 @@
 #include <unistd.h>
 #include <math.h>
 #include <utils/misc.h>
+#include <inttypes.h>
 
 #include <SkBitmap.h>
 
@@ -43,10 +44,13 @@
 #include <android_runtime/android_graphics_SurfaceTexture.h>
 
 //#define LOG_API ALOGE
-#define LOG_API(...)
+static constexpr bool kLogApi = false;
 
 using namespace android;
 
+template <typename... T>
+void UNUSED(T... t) {}
+
 #define PER_ARRAY_TYPE(flag, fnc, readonly, ...) {                                      \
     jint len = 0;                                                                       \
     void *ptr = nullptr;                                                                \
@@ -106,6 +110,7 @@
     default:                                                                            \
         break;                                                                          \
     }                                                                                   \
+    UNUSED(len, ptr, typeBytes, relFlag);                                               \
 }
 
 
@@ -168,7 +173,6 @@
 
 static jfieldID gContextId = 0;
 static jfieldID gNativeBitmapID = 0;
-static jfieldID gTypeNativeCache = 0;
 
 static void _nInit(JNIEnv *_env, jclass _this)
 {
@@ -183,14 +187,18 @@
 static void
 nContextFinish(JNIEnv *_env, jobject _this, jlong con)
 {
-    LOG_API("nContextFinish, con(%p)", (RsContext)con);
+    if (kLogApi) {
+        ALOGD("nContextFinish, con(%p)", (RsContext)con);
+    }
     rsContextFinish((RsContext)con);
 }
 
 static void
 nAssignName(JNIEnv *_env, jobject _this, jlong con, jlong obj, jbyteArray str)
 {
-    LOG_API("nAssignName, con(%p), obj(%p)", (RsContext)con, (void *)obj);
+    if (kLogApi) {
+        ALOGD("nAssignName, con(%p), obj(%p)", (RsContext)con, (void *)obj);
+    }
     jint len = _env->GetArrayLength(str);
     jbyte * cptr = (jbyte *) _env->GetPrimitiveArrayCritical(str, 0);
     rsAssignName((RsContext)con, (void *)obj, (const char *)cptr, len);
@@ -200,7 +208,9 @@
 static jstring
 nGetName(JNIEnv *_env, jobject _this, jlong con, jlong obj)
 {
-    LOG_API("nGetName, con(%p), obj(%p)", (RsContext)con, (void *)obj);
+    if (kLogApi) {
+        ALOGD("nGetName, con(%p), obj(%p)", (RsContext)con, (void *)obj);
+    }
     const char *name = nullptr;
     rsaGetName((RsContext)con, (void *)obj, &name);
     if(name == nullptr || strlen(name) == 0) {
@@ -212,7 +222,9 @@
 static void
 nObjDestroy(JNIEnv *_env, jobject _this, jlong con, jlong obj)
 {
-    LOG_API("nObjDestroy, con(%p) obj(%p)", (RsContext)con, (void *)obj);
+    if (kLogApi) {
+        ALOGD("nObjDestroy, con(%p) obj(%p)", (RsContext)con, (void *)obj);
+    }
     rsObjDestroy((RsContext)con, (void *)obj);
 }
 
@@ -221,29 +233,37 @@
 static jlong
 nDeviceCreate(JNIEnv *_env, jobject _this)
 {
-    LOG_API("nDeviceCreate");
+    if (kLogApi) {
+        ALOGD("nDeviceCreate");
+    }
     return (jlong)(uintptr_t)rsDeviceCreate();
 }
 
 static void
 nDeviceDestroy(JNIEnv *_env, jobject _this, jlong dev)
 {
-    LOG_API("nDeviceDestroy");
+    if (kLogApi) {
+        ALOGD("nDeviceDestroy");
+    }
     return rsDeviceDestroy((RsDevice)dev);
 }
 
 static void
 nDeviceSetConfig(JNIEnv *_env, jobject _this, jlong dev, jint p, jint value)
 {
-    LOG_API("nDeviceSetConfig  dev(%p), param(%i), value(%i)", (void *)dev, p, value);
+    if (kLogApi) {
+        ALOGD("nDeviceSetConfig  dev(%p), param(%i), value(%i)", (void *)dev, p, value);
+    }
     return rsDeviceSetConfig((RsDevice)dev, (RsDeviceParam)p, value);
 }
 
 static jlong
-nContextCreate(JNIEnv *_env, jobject _this, jlong dev, jint ver, jint sdkVer, jint ct)
+nContextCreate(JNIEnv *_env, jobject _this, jlong dev, jint flags, jint sdkVer, jint contextType)
 {
-    LOG_API("nContextCreate");
-    return (jlong)(uintptr_t)rsContextCreate((RsDevice)dev, ver, sdkVer, (RsContextType)ct, 0);
+    if (kLogApi) {
+        ALOGD("nContextCreate");
+    }
+    return (jlong)(uintptr_t)rsContextCreate((RsDevice)dev, 0, sdkVer, (RsContextType)contextType, flags);
 }
 
 static jlong
@@ -266,14 +286,18 @@
     sc.samplesPref = samplesPref;
     sc.samplesQ = samplesQ;
 
-    LOG_API("nContextCreateGL");
+    if (kLogApi) {
+        ALOGD("nContextCreateGL");
+    }
     return (jlong)(uintptr_t)rsContextCreateGL((RsDevice)dev, ver, sdkVer, sc, dpi);
 }
 
 static void
 nContextSetPriority(JNIEnv *_env, jobject _this, jlong con, jint p)
 {
-    LOG_API("ContextSetPriority, con(%p), priority(%i)", (RsContext)con, p);
+    if (kLogApi) {
+        ALOGD("ContextSetPriority, con(%p), priority(%i)", (RsContext)con, p);
+    }
     rsContextSetPriority((RsContext)con, p);
 }
 
@@ -282,7 +306,10 @@
 static void
 nContextSetSurface(JNIEnv *_env, jobject _this, jlong con, jint width, jint height, jobject wnd)
 {
-    LOG_API("nContextSetSurface, con(%p), width(%i), height(%i), surface(%p)", (RsContext)con, width, height, (Surface *)wnd);
+    if (kLogApi) {
+        ALOGD("nContextSetSurface, con(%p), width(%i), height(%i), surface(%p)", (RsContext)con,
+              width, height, (Surface *)wnd);
+    }
 
     ANativeWindow * window = nullptr;
     if (wnd == nullptr) {
@@ -297,28 +324,36 @@
 static void
 nContextDestroy(JNIEnv *_env, jobject _this, jlong con)
 {
-    LOG_API("nContextDestroy, con(%p)", (RsContext)con);
+    if (kLogApi) {
+        ALOGD("nContextDestroy, con(%p)", (RsContext)con);
+    }
     rsContextDestroy((RsContext)con);
 }
 
 static void
 nContextDump(JNIEnv *_env, jobject _this, jlong con, jint bits)
 {
-    LOG_API("nContextDump, con(%p)  bits(%i)", (RsContext)con, bits);
+    if (kLogApi) {
+        ALOGD("nContextDump, con(%p)  bits(%i)", (RsContext)con, bits);
+    }
     rsContextDump((RsContext)con, bits);
 }
 
 static void
 nContextPause(JNIEnv *_env, jobject _this, jlong con)
 {
-    LOG_API("nContextPause, con(%p)", (RsContext)con);
+    if (kLogApi) {
+        ALOGD("nContextPause, con(%p)", (RsContext)con);
+    }
     rsContextPause((RsContext)con);
 }
 
 static void
 nContextResume(JNIEnv *_env, jobject _this, jlong con)
 {
-    LOG_API("nContextResume, con(%p)", (RsContext)con);
+    if (kLogApi) {
+        ALOGD("nContextResume, con(%p)", (RsContext)con);
+    }
     rsContextResume((RsContext)con);
 }
 
@@ -326,7 +361,9 @@
 static jstring
 nContextGetErrorMessage(JNIEnv *_env, jobject _this, jlong con)
 {
-    LOG_API("nContextGetErrorMessage, con(%p)", (RsContext)con);
+    if (kLogApi) {
+        ALOGD("nContextGetErrorMessage, con(%p)", (RsContext)con);
+    }
     char buf[1024];
 
     size_t receiveLen;
@@ -336,7 +373,7 @@
                                  &receiveLen, sizeof(receiveLen),
                                  &subID, sizeof(subID));
     if (!id && receiveLen) {
-        ALOGV("message receive buffer too small.  %i", receiveLen);
+        ALOGV("message receive buffer too small.  %zu", receiveLen);
     }
     return _env->NewStringUTF(buf);
 }
@@ -345,7 +382,9 @@
 nContextGetUserMessage(JNIEnv *_env, jobject _this, jlong con, jintArray data)
 {
     jint len = _env->GetArrayLength(data);
-    LOG_API("nContextGetMessage, con(%p), len(%i)", (RsContext)con, len);
+    if (kLogApi) {
+        ALOGD("nContextGetMessage, con(%p), len(%i)", (RsContext)con, len);
+    }
     jint *ptr = _env->GetIntArrayElements(data, nullptr);
     size_t receiveLen;
     uint32_t subID;
@@ -354,7 +393,7 @@
                                  &receiveLen, sizeof(receiveLen),
                                  &subID, sizeof(subID));
     if (!id && receiveLen) {
-        ALOGV("message receive buffer too small.  %i", receiveLen);
+        ALOGV("message receive buffer too small.  %zu", receiveLen);
     }
     _env->ReleaseIntArrayElements(data, ptr, 0);
     return (jint)id;
@@ -363,7 +402,9 @@
 static jint
 nContextPeekMessage(JNIEnv *_env, jobject _this, jlong con, jintArray auxData)
 {
-    LOG_API("nContextPeekMessage, con(%p)", (RsContext)con);
+    if (kLogApi) {
+        ALOGD("nContextPeekMessage, con(%p)", (RsContext)con);
+    }
     jint *auxDataPtr = _env->GetIntArrayElements(auxData, nullptr);
     size_t receiveLen;
     uint32_t subID;
@@ -377,13 +418,17 @@
 
 static void nContextInitToClient(JNIEnv *_env, jobject _this, jlong con)
 {
-    LOG_API("nContextInitToClient, con(%p)", (RsContext)con);
+    if (kLogApi) {
+        ALOGD("nContextInitToClient, con(%p)", (RsContext)con);
+    }
     rsContextInitToClient((RsContext)con);
 }
 
 static void nContextDeinitToClient(JNIEnv *_env, jobject _this, jlong con)
 {
-    LOG_API("nContextDeinitToClient, con(%p)", (RsContext)con);
+    if (kLogApi) {
+        ALOGD("nContextDeinitToClient, con(%p)", (RsContext)con);
+    }
     rsContextDeinitToClient((RsContext)con);
 }
 
@@ -396,7 +441,9 @@
         len = _env->GetArrayLength(data);
         ptr = _env->GetIntArrayElements(data, nullptr);
     }
-    LOG_API("nContextSendMessage, con(%p), id(%i), len(%i)", (RsContext)con, id, len);
+    if (kLogApi) {
+        ALOGD("nContextSendMessage, con(%p), id(%i), len(%i)", (RsContext)con, id, len);
+    }
     rsContextSendMessage((RsContext)con, id, (const uint8_t *)ptr, len * sizeof(int));
     if (data) {
         _env->ReleaseIntArrayElements(data, ptr, JNI_ABORT);
@@ -406,10 +453,15 @@
 
 
 static jlong
-nElementCreate(JNIEnv *_env, jobject _this, jlong con, jlong type, jint kind, jboolean norm, jint size)
+nElementCreate(JNIEnv *_env, jobject _this, jlong con, jlong type, jint kind, jboolean norm,
+               jint size)
 {
-    LOG_API("nElementCreate, con(%p), type(%i), kind(%i), norm(%i), size(%i)", (RsContext)con, type, kind, norm, size);
-    return (jlong)(uintptr_t)rsElementCreate((RsContext)con, (RsDataType)type, (RsDataKind)kind, norm, size);
+    if (kLogApi) {
+        ALOGD("nElementCreate, con(%p), type(%" PRId64 "), kind(%i), norm(%i), size(%i)", (RsContext)con,
+              type, kind, norm, size);
+    }
+    return (jlong)(uintptr_t)rsElementCreate((RsContext)con, (RsDataType)type, (RsDataKind)kind,
+                                             norm, size);
 }
 
 static jlong
@@ -417,7 +469,9 @@
                 jlongArray _ids, jobjectArray _names, jintArray _arraySizes)
 {
     int fieldCount = _env->GetArrayLength(_ids);
-    LOG_API("nElementCreate2, con(%p)", (RsContext)con);
+    if (kLogApi) {
+        ALOGD("nElementCreate2, con(%p)", (RsContext)con);
+    }
 
     jlong *jIds = _env->GetLongArrayElements(_ids, nullptr);
     jint *jArraySizes = _env->GetIntArrayElements(_arraySizes, nullptr);
@@ -452,7 +506,9 @@
 nElementGetNativeData(JNIEnv *_env, jobject _this, jlong con, jlong id, jintArray _elementData)
 {
     int dataSize = _env->GetArrayLength(_elementData);
-    LOG_API("nElementGetNativeData, con(%p)", (RsContext)con);
+    if (kLogApi) {
+        ALOGD("nElementGetNativeData, con(%p)", (RsContext)con);
+    }
 
     // we will pack mType; mKind; mNormalized; mVectorSize; NumSubElements
     assert(dataSize == 5);
@@ -474,13 +530,16 @@
                        jintArray _arraySizes)
 {
     uint32_t dataSize = _env->GetArrayLength(_IDs);
-    LOG_API("nElementGetSubElements, con(%p)", (RsContext)con);
+    if (kLogApi) {
+        ALOGD("nElementGetSubElements, con(%p)", (RsContext)con);
+    }
 
     uintptr_t *ids = (uintptr_t*)malloc(dataSize * sizeof(uintptr_t));
     const char **names = (const char **)malloc(dataSize * sizeof(const char *));
     uint32_t *arraySizes = (uint32_t *)malloc(dataSize * sizeof(uint32_t));
 
-    rsaElementGetSubElements((RsContext)con, (RsElement)id, ids, names, arraySizes, (uint32_t)dataSize);
+    rsaElementGetSubElements((RsContext)con, (RsElement)id, ids, names, arraySizes,
+                             (uint32_t)dataSize);
 
     for(uint32_t i = 0; i < dataSize; i++) {
         const jlong id = (jlong)(uintptr_t)ids[i];
@@ -501,10 +560,13 @@
 nTypeCreate(JNIEnv *_env, jobject _this, jlong con, jlong eid,
             jint dimx, jint dimy, jint dimz, jboolean mips, jboolean faces, jint yuv)
 {
-    LOG_API("nTypeCreate, con(%p) eid(%p), x(%i), y(%i), z(%i), mips(%i), faces(%i), yuv(%i)",
-            (RsContext)con, eid, dimx, dimy, dimz, mips, faces, yuv);
+    if (kLogApi) {
+        ALOGD("nTypeCreate, con(%p) eid(%p), x(%i), y(%i), z(%i), mips(%i), faces(%i), yuv(%i)",
+              (RsContext)con, (void*)eid, dimx, dimy, dimz, mips, faces, yuv);
+    }
 
-    return (jlong)(uintptr_t)rsTypeCreate((RsContext)con, (RsElement)eid, dimx, dimy, dimz, mips, faces, yuv);
+    return (jlong)(uintptr_t)rsTypeCreate((RsContext)con, (RsElement)eid, dimx, dimy, dimz, mips,
+                                          faces, yuv);
 }
 
 static void
@@ -515,7 +577,9 @@
     int elementCount = _env->GetArrayLength(_typeData);
 
     assert(elementCount == 6);
-    LOG_API("nTypeGetNativeData, con(%p)", (RsContext)con);
+    if (kLogApi) {
+        ALOGD("nTypeGetNativeData, con(%p)", (RsContext)con);
+    }
 
     uintptr_t typeData[6];
     rsaTypeGetNativeData((RsContext)con, (RsType)id, typeData, 6);
@@ -529,25 +593,37 @@
 // -----------------------------------
 
 static jlong
-nAllocationCreateTyped(JNIEnv *_env, jobject _this, jlong con, jlong type, jint mips, jint usage, jlong pointer)
+nAllocationCreateTyped(JNIEnv *_env, jobject _this, jlong con, jlong type, jint mips, jint usage,
+                       jlong pointer)
 {
-    LOG_API("nAllocationCreateTyped, con(%p), type(%p), mip(%i), usage(%i), ptr(%p)", (RsContext)con, (RsElement)type, mips, usage, (void *)pointer);
-    return (jlong)(uintptr_t) rsAllocationCreateTyped((RsContext)con, (RsType)type, (RsAllocationMipmapControl)mips, (uint32_t)usage, (uintptr_t)pointer);
+    if (kLogApi) {
+        ALOGD("nAllocationCreateTyped, con(%p), type(%p), mip(%i), usage(%i), ptr(%p)",
+              (RsContext)con, (RsElement)type, mips, usage, (void *)pointer);
+    }
+    return (jlong)(uintptr_t) rsAllocationCreateTyped((RsContext)con, (RsType)type,
+                                                      (RsAllocationMipmapControl)mips,
+                                                      (uint32_t)usage, (uintptr_t)pointer);
 }
 
 static void
 nAllocationSyncAll(JNIEnv *_env, jobject _this, jlong con, jlong a, jint bits)
 {
-    LOG_API("nAllocationSyncAll, con(%p), a(%p), bits(0x%08x)", (RsContext)con, (RsAllocation)a, bits);
+    if (kLogApi) {
+        ALOGD("nAllocationSyncAll, con(%p), a(%p), bits(0x%08x)", (RsContext)con, (RsAllocation)a,
+              bits);
+    }
     rsAllocationSyncAll((RsContext)con, (RsAllocation)a, (RsAllocationUsageType)bits);
 }
 
 static jobject
 nAllocationGetSurface(JNIEnv *_env, jobject _this, jlong con, jlong a)
 {
-    LOG_API("nAllocationGetSurface, con(%p), a(%p)", (RsContext)con, (RsAllocation)a);
+    if (kLogApi) {
+        ALOGD("nAllocationGetSurface, con(%p), a(%p)", (RsContext)con, (RsAllocation)a);
+    }
 
-    IGraphicBufferProducer *v = (IGraphicBufferProducer *)rsAllocationGetSurface((RsContext)con, (RsAllocation)a);
+    IGraphicBufferProducer *v = (IGraphicBufferProducer *)rsAllocationGetSurface((RsContext)con,
+                                                                                 (RsAllocation)a);
     sp<IGraphicBufferProducer> bp = v;
     v->decStrong(nullptr);
 
@@ -558,28 +634,35 @@
 static void
 nAllocationSetSurface(JNIEnv *_env, jobject _this, jlong con, jlong alloc, jobject sur)
 {
-    LOG_API("nAllocationSetSurface, con(%p), alloc(%p), surface(%p)",
-            (RsContext)con, (RsAllocation)alloc, (Surface *)sur);
+    if (kLogApi) {
+        ALOGD("nAllocationSetSurface, con(%p), alloc(%p), surface(%p)", (RsContext)con,
+              (RsAllocation)alloc, (Surface *)sur);
+    }
 
     sp<Surface> s;
     if (sur != 0) {
         s = android_view_Surface_getSurface(_env, sur);
     }
 
-    rsAllocationSetSurface((RsContext)con, (RsAllocation)alloc, static_cast<ANativeWindow *>(s.get()));
+    rsAllocationSetSurface((RsContext)con, (RsAllocation)alloc,
+                           static_cast<ANativeWindow *>(s.get()));
 }
 
 static void
 nAllocationIoSend(JNIEnv *_env, jobject _this, jlong con, jlong alloc)
 {
-    LOG_API("nAllocationIoSend, con(%p), alloc(%p)", (RsContext)con, alloc);
+    if (kLogApi) {
+        ALOGD("nAllocationIoSend, con(%p), alloc(%p)", (RsContext)con, (RsAllocation)alloc);
+    }
     rsAllocationIoSend((RsContext)con, (RsAllocation)alloc);
 }
 
 static void
 nAllocationIoReceive(JNIEnv *_env, jobject _this, jlong con, jlong alloc)
 {
-    LOG_API("nAllocationIoReceive, con(%p), alloc(%p)", (RsContext)con, alloc);
+    if (kLogApi) {
+        ALOGD("nAllocationIoReceive, con(%p), alloc(%p)", (RsContext)con, (RsAllocation)alloc);
+    }
     rsAllocationIoReceive((RsContext)con, (RsAllocation)alloc);
 }
 
@@ -587,12 +670,15 @@
 static void
 nAllocationGenerateMipmaps(JNIEnv *_env, jobject _this, jlong con, jlong alloc)
 {
-    LOG_API("nAllocationGenerateMipmaps, con(%p), a(%p)", (RsContext)con, (RsAllocation)alloc);
+    if (kLogApi) {
+        ALOGD("nAllocationGenerateMipmaps, con(%p), a(%p)", (RsContext)con, (RsAllocation)alloc);
+    }
     rsAllocationGenerateMipmaps((RsContext)con, (RsAllocation)alloc);
 }
 
 static jlong
-nAllocationCreateFromBitmap(JNIEnv *_env, jobject _this, jlong con, jlong type, jint mip, jobject jbitmap, jint usage)
+nAllocationCreateFromBitmap(JNIEnv *_env, jobject _this, jlong con, jlong type, jint mip,
+                            jobject jbitmap, jint usage)
 {
     SkBitmap const * nativeBitmap =
             (SkBitmap const *)_env->GetLongField(jbitmap, gNativeBitmapID);
@@ -608,7 +694,8 @@
 }
 
 static jlong
-nAllocationCreateBitmapBackedAllocation(JNIEnv *_env, jobject _this, jlong con, jlong type, jint mip, jobject jbitmap, jint usage)
+nAllocationCreateBitmapBackedAllocation(JNIEnv *_env, jobject _this, jlong con, jlong type,
+                                        jint mip, jobject jbitmap, jint usage)
 {
     SkBitmap const * nativeBitmap =
             (SkBitmap const *)_env->GetLongField(jbitmap, gNativeBitmapID);
@@ -624,7 +711,8 @@
 }
 
 static jlong
-nAllocationCubeCreateFromBitmap(JNIEnv *_env, jobject _this, jlong con, jlong type, jint mip, jobject jbitmap, jint usage)
+nAllocationCubeCreateFromBitmap(JNIEnv *_env, jobject _this, jlong con, jlong type, jint mip,
+                                jobject jbitmap, jint usage)
 {
     SkBitmap const * nativeBitmap =
             (SkBitmap const *)_env->GetLongField(jbitmap, gNativeBitmapID);
@@ -670,31 +758,33 @@
     bitmap.notifyPixelsChanged();
 }
 
-static void ReleaseBitmapCallback(void *bmp)
-{
-    SkBitmap const * nativeBitmap = (SkBitmap const *)bmp;
-    nativeBitmap->unlockPixels();
-}
-
-
 // Copies from the Java object data into the Allocation pointed to by _alloc.
 static void
 nAllocationData1D(JNIEnv *_env, jobject _this, jlong con, jlong _alloc, jint offset, jint lod,
                   jint count, jobject data, jint sizeBytes, jint dataType)
 {
     RsAllocation *alloc = (RsAllocation *)_alloc;
-    LOG_API("nAllocation1DData, con(%p), adapter(%p), offset(%i), count(%i), sizeBytes(%i), dataType(%i)",
-            (RsContext)con, (RsAllocation)alloc, offset, count, sizeBytes, dataType);
-    PER_ARRAY_TYPE(nullptr, rsAllocation1DData, true, (RsContext)con, alloc, offset, lod, count, ptr, sizeBytes);
+    if (kLogApi) {
+        ALOGD("nAllocation1DData, con(%p), adapter(%p), offset(%i), count(%i), sizeBytes(%i), "
+              "dataType(%i)", (RsContext)con, (RsAllocation)alloc, offset, count, sizeBytes,
+              dataType);
+    }
+    PER_ARRAY_TYPE(nullptr, rsAllocation1DData, true, (RsContext)con, alloc, offset, lod, count,
+                   ptr, sizeBytes);
 }
 
 // Copies from the Java array data into the Allocation pointed to by alloc.
 static void
 //    native void rsnAllocationElementData1D(long con, long id, int xoff, int compIdx, byte[] d, int sizeBytes);
-nAllocationElementData1D(JNIEnv *_env, jobject _this, jlong con, jlong alloc, jint offset, jint lod, jint compIdx, jbyteArray data, jint sizeBytes)
+nAllocationElementData1D(JNIEnv *_env, jobject _this, jlong con, jlong alloc, jint offset, jint lod,
+                         jint compIdx, jbyteArray data, jint sizeBytes)
 {
     jint len = _env->GetArrayLength(data);
-    LOG_API("nAllocationElementData1D, con(%p), alloc(%p), offset(%i), comp(%i), len(%i), sizeBytes(%i)", (RsContext)con, (RsAllocation)alloc, offset, compIdx, len, sizeBytes);
+    if (kLogApi) {
+        ALOGD("nAllocationElementData1D, con(%p), alloc(%p), offset(%i), comp(%i), len(%i), "
+              "sizeBytes(%i)", (RsContext)con, (RsAllocation)alloc, offset, compIdx, len,
+              sizeBytes);
+    }
     jbyte *ptr = _env->GetByteArrayElements(data, nullptr);
     rsAllocation1DElementData((RsContext)con, (RsAllocation)alloc, offset, lod, ptr, sizeBytes, compIdx);
     _env->ReleaseByteArrayElements(data, ptr, JNI_ABORT);
@@ -707,8 +797,10 @@
 {
     RsAllocation *alloc = (RsAllocation *)_alloc;
     RsAllocationCubemapFace face = (RsAllocationCubemapFace)_face;
-    LOG_API("nAllocation2DData, con(%p), adapter(%p), xoff(%i), yoff(%i), w(%i), h(%i), len(%i) type(%i)",
-            (RsContext)con, alloc, xoff, yoff, w, h, sizeBytes, dataType);
+    if (kLogApi) {
+        ALOGD("nAllocation2DData, con(%p), adapter(%p), xoff(%i), yoff(%i), w(%i), h(%i), len(%i) "
+              "type(%i)", (RsContext)con, alloc, xoff, yoff, w, h, sizeBytes, dataType);
+    }
     PER_ARRAY_TYPE(nullptr, rsAllocation2DData, true, (RsContext)con, alloc, xoff, yoff, lod, face, w, h, ptr, sizeBytes, 0);
 }
 
@@ -722,11 +814,13 @@
                         jlong srcAlloc, jint srcXoff, jint srcYoff,
                         jint srcMip, jint srcFace)
 {
-    LOG_API("nAllocation2DData_s, con(%p), dstAlloc(%p), dstXoff(%i), dstYoff(%i),"
-            " dstMip(%i), dstFace(%i), width(%i), height(%i),"
-            " srcAlloc(%p), srcXoff(%i), srcYoff(%i), srcMip(%i), srcFace(%i)",
-            (RsContext)con, (RsAllocation)dstAlloc, dstXoff, dstYoff, dstMip, dstFace,
-            width, height, (RsAllocation)srcAlloc, srcXoff, srcYoff, srcMip, srcFace);
+    if (kLogApi) {
+        ALOGD("nAllocation2DData_s, con(%p), dstAlloc(%p), dstXoff(%i), dstYoff(%i),"
+              " dstMip(%i), dstFace(%i), width(%i), height(%i),"
+              " srcAlloc(%p), srcXoff(%i), srcYoff(%i), srcMip(%i), srcFace(%i)",
+              (RsContext)con, (RsAllocation)dstAlloc, dstXoff, dstYoff, dstMip, dstFace,
+              width, height, (RsAllocation)srcAlloc, srcXoff, srcYoff, srcMip, srcFace);
+    }
 
     rsAllocationCopy2DRange((RsContext)con,
                             (RsAllocation)dstAlloc,
@@ -744,8 +838,11 @@
                     jint w, jint h, jint d, jobject data, int sizeBytes, int dataType)
 {
     RsAllocation *alloc = (RsAllocation *)_alloc;
-    LOG_API("nAllocation3DData, con(%p), alloc(%p), xoff(%i), yoff(%i), zoff(%i), lod(%i), w(%i), h(%i), d(%i), sizeBytes(%i)",
-            (RsContext)con, (RsAllocation)alloc, xoff, yoff, zoff, lod, w, h, d, sizeBytes);
+    if (kLogApi) {
+        ALOGD("nAllocation3DData, con(%p), alloc(%p), xoff(%i), yoff(%i), zoff(%i), lod(%i), w(%i),"
+              " h(%i), d(%i), sizeBytes(%i)", (RsContext)con, (RsAllocation)alloc, xoff, yoff, zoff,
+              lod, w, h, d, sizeBytes);
+    }
     PER_ARRAY_TYPE(nullptr, rsAllocation3DData, true, (RsContext)con, alloc, xoff, yoff, zoff, lod, w, h, d, ptr, sizeBytes, 0);
 }
 
@@ -759,11 +856,13 @@
                         jlong srcAlloc, jint srcXoff, jint srcYoff, jint srcZoff,
                         jint srcMip)
 {
-    LOG_API("nAllocationData3D_alloc, con(%p), dstAlloc(%p), dstXoff(%i), dstYoff(%i),"
-            " dstMip(%i), width(%i), height(%i),"
-            " srcAlloc(%p), srcXoff(%i), srcYoff(%i), srcMip(%i)",
-            (RsContext)con, (RsAllocation)dstAlloc, dstXoff, dstYoff, dstMip,
-            width, height, (RsAllocation)srcAlloc, srcXoff, srcYoff, srcMip);
+    if (kLogApi) {
+        ALOGD("nAllocationData3D_alloc, con(%p), dstAlloc(%p), dstXoff(%i), dstYoff(%i),"
+              " dstMip(%i), width(%i), height(%i),"
+              " srcAlloc(%p), srcXoff(%i), srcYoff(%i), srcMip(%i)",
+              (RsContext)con, (RsAllocation)dstAlloc, dstXoff, dstYoff, dstMip,
+              width, height, (RsAllocation)srcAlloc, srcXoff, srcYoff, srcMip);
+    }
 
     rsAllocationCopy3DRange((RsContext)con,
                             (RsAllocation)dstAlloc,
@@ -779,7 +878,9 @@
 nAllocationRead(JNIEnv *_env, jobject _this, jlong con, jlong _alloc, jobject data, int dataType)
 {
     RsAllocation *alloc = (RsAllocation *)_alloc;
-    LOG_API("nAllocationRead, con(%p), alloc(%p)", (RsContext)con, (RsAllocation)alloc);
+    if (kLogApi) {
+        ALOGD("nAllocationRead, con(%p), alloc(%p)", (RsContext)con, (RsAllocation)alloc);
+    }
     PER_ARRAY_TYPE(0, rsAllocationRead, false, (RsContext)con, alloc, ptr, len * typeBytes);
 }
 
@@ -789,8 +890,10 @@
                   jint count, jobject data, int sizeBytes, int dataType)
 {
     RsAllocation *alloc = (RsAllocation *)_alloc;
-    LOG_API("nAllocation1DRead, con(%p), adapter(%p), offset(%i), count(%i), sizeBytes(%i), dataType(%i)",
-            (RsContext)con, alloc, offset, count, sizeBytes, dataType);
+    if (kLogApi) {
+        ALOGD("nAllocation1DRead, con(%p), adapter(%p), offset(%i), count(%i), sizeBytes(%i), "
+              "dataType(%i)", (RsContext)con, alloc, offset, count, sizeBytes, dataType);
+    }
     PER_ARRAY_TYPE(0, rsAllocation1DRead, false, (RsContext)con, alloc, offset, lod, count, ptr, sizeBytes);
 }
 
@@ -801,22 +904,30 @@
 {
     RsAllocation *alloc = (RsAllocation *)_alloc;
     RsAllocationCubemapFace face = (RsAllocationCubemapFace)_face;
-    LOG_API("nAllocation2DRead, con(%p), adapter(%p), xoff(%i), yoff(%i), w(%i), h(%i), len(%i) type(%i)",
-            (RsContext)con, alloc, xoff, yoff, w, h, sizeBytes, dataType);
-    PER_ARRAY_TYPE(0, rsAllocation2DRead, false, (RsContext)con, alloc, xoff, yoff, lod, face, w, h, ptr, sizeBytes, 0);
+    if (kLogApi) {
+        ALOGD("nAllocation2DRead, con(%p), adapter(%p), xoff(%i), yoff(%i), w(%i), h(%i), len(%i) "
+              "type(%i)", (RsContext)con, alloc, xoff, yoff, w, h, sizeBytes, dataType);
+    }
+    PER_ARRAY_TYPE(0, rsAllocation2DRead, false, (RsContext)con, alloc, xoff, yoff, lod, face, w, h,
+                   ptr, sizeBytes, 0);
 }
 
 static jlong
 nAllocationGetType(JNIEnv *_env, jobject _this, jlong con, jlong a)
 {
-    LOG_API("nAllocationGetType, con(%p), a(%p)", (RsContext)con, (RsAllocation)a);
+    if (kLogApi) {
+        ALOGD("nAllocationGetType, con(%p), a(%p)", (RsContext)con, (RsAllocation)a);
+    }
     return (jlong)(uintptr_t) rsaAllocationGetType((RsContext)con, (RsAllocation)a);
 }
 
 static void
 nAllocationResize1D(JNIEnv *_env, jobject _this, jlong con, jlong alloc, jint dimX)
 {
-    LOG_API("nAllocationResize1D, con(%p), alloc(%p), sizeX(%i)", (RsContext)con, (RsAllocation)alloc, dimX);
+    if (kLogApi) {
+        ALOGD("nAllocationResize1D, con(%p), alloc(%p), sizeX(%i)", (RsContext)con,
+              (RsAllocation)alloc, dimX);
+    }
     rsAllocationResize1D((RsContext)con, (RsAllocation)alloc, dimX);
 }
 
@@ -947,21 +1058,29 @@
 static void
 nScriptBindAllocation(JNIEnv *_env, jobject _this, jlong con, jlong script, jlong alloc, jint slot)
 {
-    LOG_API("nScriptBindAllocation, con(%p), script(%p), alloc(%p), slot(%i)", (RsContext)con, (RsScript)script, (RsAllocation)alloc, slot);
+    if (kLogApi) {
+        ALOGD("nScriptBindAllocation, con(%p), script(%p), alloc(%p), slot(%i)", (RsContext)con,
+              (RsScript)script, (RsAllocation)alloc, slot);
+    }
     rsScriptBindAllocation((RsContext)con, (RsScript)script, (RsAllocation)alloc, slot);
 }
 
 static void
 nScriptSetVarI(JNIEnv *_env, jobject _this, jlong con, jlong script, jint slot, jint val)
 {
-    LOG_API("nScriptSetVarI, con(%p), s(%p), slot(%i), val(%i)", (RsContext)con, (void *)script, slot, val);
+    if (kLogApi) {
+        ALOGD("nScriptSetVarI, con(%p), s(%p), slot(%i), val(%i)", (RsContext)con, (void *)script,
+              slot, val);
+    }
     rsScriptSetVarI((RsContext)con, (RsScript)script, slot, val);
 }
 
 static jint
 nScriptGetVarI(JNIEnv *_env, jobject _this, jlong con, jlong script, jint slot)
 {
-    LOG_API("nScriptGetVarI, con(%p), s(%p), slot(%i)", (RsContext)con, (void *)script, slot);
+    if (kLogApi) {
+        ALOGD("nScriptGetVarI, con(%p), s(%p), slot(%i)", (RsContext)con, (void *)script, slot);
+    }
     int value = 0;
     rsScriptGetVarV((RsContext)con, (RsScript)script, slot, &value, sizeof(value));
     return value;
@@ -970,21 +1089,29 @@
 static void
 nScriptSetVarObj(JNIEnv *_env, jobject _this, jlong con, jlong script, jint slot, jlong val)
 {
-    LOG_API("nScriptSetVarObj, con(%p), s(%p), slot(%i), val(%i)", (RsContext)con, (void *)script, slot, val);
+    if (kLogApi) {
+        ALOGD("nScriptSetVarObj, con(%p), s(%p), slot(%i), val(%" PRId64 ")", (RsContext)con, (void *)script,
+              slot, val);
+    }
     rsScriptSetVarObj((RsContext)con, (RsScript)script, slot, (RsObjectBase)val);
 }
 
 static void
 nScriptSetVarJ(JNIEnv *_env, jobject _this, jlong con, jlong script, jint slot, jlong val)
 {
-    LOG_API("nScriptSetVarJ, con(%p), s(%p), slot(%i), val(%lli)", (RsContext)con, (void *)script, slot, val);
+    if (kLogApi) {
+        ALOGD("nScriptSetVarJ, con(%p), s(%p), slot(%i), val(%" PRId64 ")", (RsContext)con, (void *)script,
+              slot, val);
+    }
     rsScriptSetVarJ((RsContext)con, (RsScript)script, slot, val);
 }
 
 static jlong
 nScriptGetVarJ(JNIEnv *_env, jobject _this, jlong con, jlong script, jint slot)
 {
-    LOG_API("nScriptGetVarJ, con(%p), s(%p), slot(%i)", (RsContext)con, (void *)script, slot);
+    if (kLogApi) {
+        ALOGD("nScriptGetVarJ, con(%p), s(%p), slot(%i)", (RsContext)con, (void *)script, slot);
+    }
     jlong value = 0;
     rsScriptGetVarV((RsContext)con, (RsScript)script, slot, &value, sizeof(value));
     return value;
@@ -993,14 +1120,19 @@
 static void
 nScriptSetVarF(JNIEnv *_env, jobject _this, jlong con, jlong script, jint slot, float val)
 {
-    LOG_API("nScriptSetVarF, con(%p), s(%p), slot(%i), val(%f)", (RsContext)con, (void *)script, slot, val);
+    if (kLogApi) {
+        ALOGD("nScriptSetVarF, con(%p), s(%p), slot(%i), val(%f)", (RsContext)con, (void *)script,
+              slot, val);
+    }
     rsScriptSetVarF((RsContext)con, (RsScript)script, slot, val);
 }
 
 static jfloat
 nScriptGetVarF(JNIEnv *_env, jobject _this, jlong con, jlong script, jint slot)
 {
-    LOG_API("nScriptGetVarF, con(%p), s(%p), slot(%i)", (RsContext)con, (void *)script, slot);
+    if (kLogApi) {
+        ALOGD("nScriptGetVarF, con(%p), s(%p), slot(%i)", (RsContext)con, (void *)script, slot);
+    }
     jfloat value = 0;
     rsScriptGetVarV((RsContext)con, (RsScript)script, slot, &value, sizeof(value));
     return value;
@@ -1009,14 +1141,19 @@
 static void
 nScriptSetVarD(JNIEnv *_env, jobject _this, jlong con, jlong script, jint slot, double val)
 {
-    LOG_API("nScriptSetVarD, con(%p), s(%p), slot(%i), val(%lf)", (RsContext)con, (void *)script, slot, val);
+    if (kLogApi) {
+        ALOGD("nScriptSetVarD, con(%p), s(%p), slot(%i), val(%lf)", (RsContext)con, (void *)script,
+              slot, val);
+    }
     rsScriptSetVarD((RsContext)con, (RsScript)script, slot, val);
 }
 
 static jdouble
 nScriptGetVarD(JNIEnv *_env, jobject _this, jlong con, jlong script, jint slot)
 {
-    LOG_API("nScriptGetVarD, con(%p), s(%p), slot(%i)", (RsContext)con, (void *)script, slot);
+    if (kLogApi) {
+        ALOGD("nScriptGetVarD, con(%p), s(%p), slot(%i)", (RsContext)con, (void *)script, slot);
+    }
     jdouble value = 0;
     rsScriptGetVarV((RsContext)con, (RsScript)script, slot, &value, sizeof(value));
     return value;
@@ -1025,7 +1162,9 @@
 static void
 nScriptSetVarV(JNIEnv *_env, jobject _this, jlong con, jlong script, jint slot, jbyteArray data)
 {
-    LOG_API("nScriptSetVarV, con(%p), s(%p), slot(%i)", (RsContext)con, (void *)script, slot);
+    if (kLogApi) {
+        ALOGD("nScriptSetVarV, con(%p), s(%p), slot(%i)", (RsContext)con, (void *)script, slot);
+    }
     jint len = _env->GetArrayLength(data);
     jbyte *ptr = _env->GetByteArrayElements(data, nullptr);
     rsScriptSetVarV((RsContext)con, (RsScript)script, slot, ptr, len);
@@ -1035,7 +1174,9 @@
 static void
 nScriptGetVarV(JNIEnv *_env, jobject _this, jlong con, jlong script, jint slot, jbyteArray data)
 {
-    LOG_API("nScriptSetVarV, con(%p), s(%p), slot(%i)", (RsContext)con, (void *)script, slot);
+    if (kLogApi) {
+        ALOGD("nScriptSetVarV, con(%p), s(%p), slot(%i)", (RsContext)con, (void *)script, slot);
+    }
     jint len = _env->GetArrayLength(data);
     jbyte *ptr = _env->GetByteArrayElements(data, nullptr);
     rsScriptGetVarV((RsContext)con, (RsScript)script, slot, ptr, len);
@@ -1043,9 +1184,12 @@
 }
 
 static void
-nScriptSetVarVE(JNIEnv *_env, jobject _this, jlong con, jlong script, jint slot, jbyteArray data, jlong elem, jintArray dims)
+nScriptSetVarVE(JNIEnv *_env, jobject _this, jlong con, jlong script, jint slot, jbyteArray data,
+                jlong elem, jintArray dims)
 {
-    LOG_API("nScriptSetVarVE, con(%p), s(%p), slot(%i)", (RsContext)con, (void *)script, slot);
+    if (kLogApi) {
+        ALOGD("nScriptSetVarVE, con(%p), s(%p), slot(%i)", (RsContext)con, (void *)script, slot);
+    }
     jint len = _env->GetArrayLength(data);
     jbyte *ptr = _env->GetByteArrayElements(data, nullptr);
     jint dimsLen = _env->GetArrayLength(dims) * sizeof(int);
@@ -1060,7 +1204,9 @@
 static void
 nScriptSetTimeZone(JNIEnv *_env, jobject _this, jlong con, jlong script, jbyteArray timeZone)
 {
-    LOG_API("nScriptCSetTimeZone, con(%p), s(%p)", (RsContext)con, (void *)script);
+    if (kLogApi) {
+        ALOGD("nScriptCSetTimeZone, con(%p), s(%p)", (RsContext)con, (void *)script);
+    }
 
     jint length = _env->GetArrayLength(timeZone);
     jbyte* timeZone_ptr;
@@ -1076,14 +1222,18 @@
 static void
 nScriptInvoke(JNIEnv *_env, jobject _this, jlong con, jlong obj, jint slot)
 {
-    LOG_API("nScriptInvoke, con(%p), script(%p)", (RsContext)con, (void *)obj);
+    if (kLogApi) {
+        ALOGD("nScriptInvoke, con(%p), script(%p)", (RsContext)con, (void *)obj);
+    }
     rsScriptInvoke((RsContext)con, (RsScript)obj, slot);
 }
 
 static void
 nScriptInvokeV(JNIEnv *_env, jobject _this, jlong con, jlong script, jint slot, jbyteArray data)
 {
-    LOG_API("nScriptInvokeV, con(%p), s(%p), slot(%i)", (RsContext)con, (void *)script, slot);
+    if (kLogApi) {
+        ALOGD("nScriptInvokeV, con(%p), s(%p), slot(%i)", (RsContext)con, (void *)script, slot);
+    }
     jint len = _env->GetArrayLength(data);
     jbyte *ptr = _env->GetByteArrayElements(data, nullptr);
     rsScriptInvokeV((RsContext)con, (RsScript)script, slot, ptr, len);
@@ -1095,8 +1245,9 @@
                jlongArray ains, jlong aout, jbyteArray params,
                jintArray limits)
 {
-    LOG_API("nScriptForEach, con(%p), s(%p), slot(%i)", (RsContext)con,
-            (void *)script, slot);
+    if (kLogApi) {
+        ALOGD("nScriptForEach, con(%p), s(%p), slot(%i)", (RsContext)con, (void *)script, slot);
+    }
 
     jint   in_len = 0;
     jlong *in_ptr = nullptr;
@@ -1140,6 +1291,7 @@
         limit_ptr = _env->GetIntArrayElements(limits, nullptr);
 
         assert(limit_len == 6);
+        UNUSED(limit_len);  // As the assert might not be compiled.
 
         sc.xStart     = limit_ptr[0];
         sc.xEnd       = limit_ptr[1];
@@ -1176,7 +1328,9 @@
                jstring resName, jstring cacheDir,
                jbyteArray scriptRef, jint length)
 {
-    LOG_API("nScriptCCreate, con(%p)", (RsContext)con);
+    if (kLogApi) {
+        ALOGD("nScriptCCreate, con(%p)", (RsContext)con);
+    }
 
     AutoJavaStringToUTF8 resNameUTF(_env, resName);
     AutoJavaStringToUTF8 cacheDirUTF(_env, cacheDir);
@@ -1223,21 +1377,30 @@
 static jlong
 nScriptIntrinsicCreate(JNIEnv *_env, jobject _this, jlong con, jint id, jlong eid)
 {
-    LOG_API("nScriptIntrinsicCreate, con(%p) id(%i) element(%p)", (RsContext)con, id, (void *)eid);
+    if (kLogApi) {
+        ALOGD("nScriptIntrinsicCreate, con(%p) id(%i) element(%p)", (RsContext)con, id,
+              (void *)eid);
+    }
     return (jlong)(uintptr_t)rsScriptIntrinsicCreate((RsContext)con, id, (RsElement)eid);
 }
 
 static jlong
 nScriptKernelIDCreate(JNIEnv *_env, jobject _this, jlong con, jlong sid, jint slot, jint sig)
 {
-    LOG_API("nScriptKernelIDCreate, con(%p) script(%p), slot(%i), sig(%i)", (RsContext)con, (void *)sid, slot, sig);
+    if (kLogApi) {
+        ALOGD("nScriptKernelIDCreate, con(%p) script(%p), slot(%i), sig(%i)", (RsContext)con,
+              (void *)sid, slot, sig);
+    }
     return (jlong)(uintptr_t)rsScriptKernelIDCreate((RsContext)con, (RsScript)sid, slot, sig);
 }
 
 static jlong
 nScriptFieldIDCreate(JNIEnv *_env, jobject _this, jlong con, jlong sid, jint slot)
 {
-    LOG_API("nScriptFieldIDCreate, con(%p) script(%p), slot(%i)", (RsContext)con, (void *)sid, slot);
+    if (kLogApi) {
+        ALOGD("nScriptFieldIDCreate, con(%p) script(%p), slot(%i)", (RsContext)con, (void *)sid,
+              slot);
+    }
     return (jlong)(uintptr_t)rsScriptFieldIDCreate((RsContext)con, (RsScript)sid, slot);
 }
 
@@ -1245,7 +1408,9 @@
 nScriptGroupCreate(JNIEnv *_env, jobject _this, jlong con, jlongArray _kernels, jlongArray _src,
     jlongArray _dstk, jlongArray _dstf, jlongArray _types)
 {
-    LOG_API("nScriptGroupCreate, con(%p)", (RsContext)con);
+    if (kLogApi) {
+        ALOGD("nScriptGroupCreate, con(%p)", (RsContext)con);
+    }
 
     jint kernelsLen = _env->GetArrayLength(_kernels);
     jlong *jKernelsPtr = _env->GetLongArrayElements(_kernels, nullptr);
@@ -1305,23 +1470,29 @@
 static void
 nScriptGroupSetInput(JNIEnv *_env, jobject _this, jlong con, jlong gid, jlong kid, jlong alloc)
 {
-    LOG_API("nScriptGroupSetInput, con(%p) group(%p), kernelId(%p), alloc(%p)", (RsContext)con,
-        (void *)gid, (void *)kid, (void *)alloc);
+    if (kLogApi) {
+        ALOGD("nScriptGroupSetInput, con(%p) group(%p), kernelId(%p), alloc(%p)", (RsContext)con,
+              (void *)gid, (void *)kid, (void *)alloc);
+    }
     rsScriptGroupSetInput((RsContext)con, (RsScriptGroup)gid, (RsScriptKernelID)kid, (RsAllocation)alloc);
 }
 
 static void
 nScriptGroupSetOutput(JNIEnv *_env, jobject _this, jlong con, jlong gid, jlong kid, jlong alloc)
 {
-    LOG_API("nScriptGroupSetOutput, con(%p) group(%p), kernelId(%p), alloc(%p)", (RsContext)con,
-        (void *)gid, (void *)kid, (void *)alloc);
+    if (kLogApi) {
+        ALOGD("nScriptGroupSetOutput, con(%p) group(%p), kernelId(%p), alloc(%p)", (RsContext)con,
+              (void *)gid, (void *)kid, (void *)alloc);
+    }
     rsScriptGroupSetOutput((RsContext)con, (RsScriptGroup)gid, (RsScriptKernelID)kid, (RsAllocation)alloc);
 }
 
 static void
 nScriptGroupExecute(JNIEnv *_env, jobject _this, jlong con, jlong gid)
 {
-    LOG_API("nScriptGroupSetOutput, con(%p) group(%p)", (RsContext)con, (void *)gid);
+    if (kLogApi) {
+        ALOGD("nScriptGroupSetOutput, con(%p) group(%p)", (RsContext)con, (void *)gid);
+    }
     rsScriptGroupExecute((RsContext)con, (RsScriptGroup)gid);
 }
 
@@ -1334,7 +1505,9 @@
                     jint srcFunc, jint destFunc,
                     jint depthFunc)
 {
-    LOG_API("nProgramStoreCreate, con(%p)", (RsContext)con);
+    if (kLogApi) {
+        ALOGD("nProgramStoreCreate, con(%p)", (RsContext)con);
+    }
     return (jlong)(uintptr_t)rsProgramStoreCreate((RsContext)con, colorMaskR, colorMaskG, colorMaskB, colorMaskA,
                                       depthMask, ditherEnable, (RsBlendSrcFunc)srcFunc,
                                       (RsBlendDstFunc)destFunc, (RsDepthFunc)depthFunc);
@@ -1345,21 +1518,30 @@
 static void
 nProgramBindConstants(JNIEnv *_env, jobject _this, jlong con, jlong vpv, jint slot, jlong a)
 {
-    LOG_API("nProgramBindConstants, con(%p), vpf(%p), sloat(%i), a(%p)", (RsContext)con, (RsProgramVertex)vpv, slot, (RsAllocation)a);
+    if (kLogApi) {
+        ALOGD("nProgramBindConstants, con(%p), vpf(%p), sloat(%i), a(%p)", (RsContext)con,
+              (RsProgramVertex)vpv, slot, (RsAllocation)a);
+    }
     rsProgramBindConstants((RsContext)con, (RsProgram)vpv, slot, (RsAllocation)a);
 }
 
 static void
 nProgramBindTexture(JNIEnv *_env, jobject _this, jlong con, jlong vpf, jint slot, jlong a)
 {
-    LOG_API("nProgramBindTexture, con(%p), vpf(%p), slot(%i), a(%p)", (RsContext)con, (RsProgramFragment)vpf, slot, (RsAllocation)a);
+    if (kLogApi) {
+        ALOGD("nProgramBindTexture, con(%p), vpf(%p), slot(%i), a(%p)", (RsContext)con,
+              (RsProgramFragment)vpf, slot, (RsAllocation)a);
+    }
     rsProgramBindTexture((RsContext)con, (RsProgramFragment)vpf, slot, (RsAllocation)a);
 }
 
 static void
 nProgramBindSampler(JNIEnv *_env, jobject _this, jlong con, jlong vpf, jint slot, jlong a)
 {
-    LOG_API("nProgramBindSampler, con(%p), vpf(%p), slot(%i), a(%p)", (RsContext)con, (RsProgramFragment)vpf, slot, (RsSampler)a);
+    if (kLogApi) {
+        ALOGD("nProgramBindSampler, con(%p), vpf(%p), slot(%i), a(%p)", (RsContext)con,
+              (RsProgramFragment)vpf, slot, (RsSampler)a);
+    }
     rsProgramBindSampler((RsContext)con, (RsProgramFragment)vpf, slot, (RsSampler)a);
 }
 
@@ -1378,7 +1560,9 @@
     const char ** nameArray = names.c_str();
     size_t* sizeArray = names.c_str_len();
 
-    LOG_API("nProgramFragmentCreate, con(%p), paramLen(%i)", (RsContext)con, paramLen);
+    if (kLogApi) {
+        ALOGD("nProgramFragmentCreate, con(%p), paramLen(%i)", (RsContext)con, paramLen);
+    }
 
     uintptr_t * paramPtr = (uintptr_t*) malloc(sizeof(uintptr_t) * paramLen);
     for(int i = 0; i < paramLen; ++i) {
@@ -1404,7 +1588,9 @@
     jlong *jParamPtr = _env->GetLongArrayElements(params, nullptr);
     jint paramLen = _env->GetArrayLength(params);
 
-    LOG_API("nProgramVertexCreate, con(%p), paramLen(%i)", (RsContext)con, paramLen);
+    if (kLogApi) {
+        ALOGD("nProgramVertexCreate, con(%p), paramLen(%i)", (RsContext)con, paramLen);
+    }
 
     int texCount = _env->GetArrayLength(texNames);
     AutoJavaStringArrayToUTF8 names(_env, texNames, texCount);
@@ -1430,7 +1616,10 @@
 static jlong
 nProgramRasterCreate(JNIEnv *_env, jobject _this, jlong con, jboolean pointSprite, jint cull)
 {
-    LOG_API("nProgramRasterCreate, con(%p), pointSprite(%i), cull(%i)", (RsContext)con, pointSprite, cull);
+    if (kLogApi) {
+        ALOGD("nProgramRasterCreate, con(%p), pointSprite(%i), cull(%i)", (RsContext)con,
+              pointSprite, cull);
+    }
     return (jlong)(uintptr_t)rsProgramRasterCreate((RsContext)con, pointSprite, (RsCullMode)cull);
 }
 
@@ -1440,35 +1629,46 @@
 static void
 nContextBindRootScript(JNIEnv *_env, jobject _this, jlong con, jlong script)
 {
-    LOG_API("nContextBindRootScript, con(%p), script(%p)", (RsContext)con, (RsScript)script);
+    if (kLogApi) {
+        ALOGD("nContextBindRootScript, con(%p), script(%p)", (RsContext)con, (RsScript)script);
+    }
     rsContextBindRootScript((RsContext)con, (RsScript)script);
 }
 
 static void
 nContextBindProgramStore(JNIEnv *_env, jobject _this, jlong con, jlong pfs)
 {
-    LOG_API("nContextBindProgramStore, con(%p), pfs(%p)", (RsContext)con, (RsProgramStore)pfs);
+    if (kLogApi) {
+        ALOGD("nContextBindProgramStore, con(%p), pfs(%p)", (RsContext)con, (RsProgramStore)pfs);
+    }
     rsContextBindProgramStore((RsContext)con, (RsProgramStore)pfs);
 }
 
 static void
 nContextBindProgramFragment(JNIEnv *_env, jobject _this, jlong con, jlong pf)
 {
-    LOG_API("nContextBindProgramFragment, con(%p), pf(%p)", (RsContext)con, (RsProgramFragment)pf);
+    if (kLogApi) {
+        ALOGD("nContextBindProgramFragment, con(%p), pf(%p)", (RsContext)con,
+              (RsProgramFragment)pf);
+    }
     rsContextBindProgramFragment((RsContext)con, (RsProgramFragment)pf);
 }
 
 static void
 nContextBindProgramVertex(JNIEnv *_env, jobject _this, jlong con, jlong pf)
 {
-    LOG_API("nContextBindProgramVertex, con(%p), pf(%p)", (RsContext)con, (RsProgramVertex)pf);
+    if (kLogApi) {
+        ALOGD("nContextBindProgramVertex, con(%p), pf(%p)", (RsContext)con, (RsProgramVertex)pf);
+    }
     rsContextBindProgramVertex((RsContext)con, (RsProgramVertex)pf);
 }
 
 static void
 nContextBindProgramRaster(JNIEnv *_env, jobject _this, jlong con, jlong pf)
 {
-    LOG_API("nContextBindProgramRaster, con(%p), pf(%p)", (RsContext)con, (RsProgramRaster)pf);
+    if (kLogApi) {
+        ALOGD("nContextBindProgramRaster, con(%p), pf(%p)", (RsContext)con, (RsProgramRaster)pf);
+    }
     rsContextBindProgramRaster((RsContext)con, (RsProgramRaster)pf);
 }
 
@@ -1479,7 +1679,9 @@
 nSamplerCreate(JNIEnv *_env, jobject _this, jlong con, jint magFilter, jint minFilter,
                jint wrapS, jint wrapT, jint wrapR, jfloat aniso)
 {
-    LOG_API("nSamplerCreate, con(%p)", (RsContext)con);
+    if (kLogApi) {
+        ALOGD("nSamplerCreate, con(%p)", (RsContext)con);
+    }
     return (jlong)(uintptr_t)rsSamplerCreate((RsContext)con,
                                  (RsSamplerValue)magFilter,
                                  (RsSamplerValue)minFilter,
@@ -1493,7 +1695,9 @@
 
 static jlong
 nPathCreate(JNIEnv *_env, jobject _this, jlong con, jint prim, jboolean isStatic, jlong _vtx, jlong _loop, jfloat q) {
-    LOG_API("nPathCreate, con(%p)", (RsContext)con);
+    if (kLogApi) {
+        ALOGD("nPathCreate, con(%p)", (RsContext)con);
+    }
 
     jlong id = (jlong)(uintptr_t)rsPathCreate((RsContext)con, (RsPathPrimitive)prim, isStatic,
                                    (RsAllocation)_vtx,
@@ -1504,7 +1708,9 @@
 static jlong
 nMeshCreate(JNIEnv *_env, jobject _this, jlong con, jlongArray _vtx, jlongArray _idx, jintArray _prim)
 {
-    LOG_API("nMeshCreate, con(%p)", (RsContext)con);
+    if (kLogApi) {
+        ALOGD("nMeshCreate, con(%p)", (RsContext)con);
+    }
 
     jint vtxLen = _env->GetArrayLength(_vtx);
     jlong *jVtxPtr = _env->GetLongArrayElements(_vtx, nullptr);
@@ -1539,7 +1745,9 @@
 static jint
 nMeshGetVertexBufferCount(JNIEnv *_env, jobject _this, jlong con, jlong mesh)
 {
-    LOG_API("nMeshGetVertexBufferCount, con(%p), Mesh(%p)", (RsContext)con, (RsMesh)mesh);
+    if (kLogApi) {
+        ALOGD("nMeshGetVertexBufferCount, con(%p), Mesh(%p)", (RsContext)con, (RsMesh)mesh);
+    }
     jint vtxCount = 0;
     rsaMeshGetVertexBufferCount((RsContext)con, (RsMesh)mesh, &vtxCount);
     return vtxCount;
@@ -1548,7 +1756,9 @@
 static jint
 nMeshGetIndexCount(JNIEnv *_env, jobject _this, jlong con, jlong mesh)
 {
-    LOG_API("nMeshGetIndexCount, con(%p), Mesh(%p)", (RsContext)con, (RsMesh)mesh);
+    if (kLogApi) {
+        ALOGD("nMeshGetIndexCount, con(%p), Mesh(%p)", (RsContext)con, (RsMesh)mesh);
+    }
     jint idxCount = 0;
     rsaMeshGetIndexCount((RsContext)con, (RsMesh)mesh, &idxCount);
     return idxCount;
@@ -1557,7 +1767,9 @@
 static void
 nMeshGetVertices(JNIEnv *_env, jobject _this, jlong con, jlong mesh, jlongArray _ids, jint numVtxIDs)
 {
-    LOG_API("nMeshGetVertices, con(%p), Mesh(%p)", (RsContext)con, (RsMesh)mesh);
+    if (kLogApi) {
+        ALOGD("nMeshGetVertices, con(%p), Mesh(%p)", (RsContext)con, (RsMesh)mesh);
+    }
 
     RsAllocation *allocs = (RsAllocation*)malloc((uint32_t)numVtxIDs * sizeof(RsAllocation));
     rsaMeshGetVertices((RsContext)con, (RsMesh)mesh, allocs, (uint32_t)numVtxIDs);
@@ -1573,7 +1785,9 @@
 static void
 nMeshGetIndices(JNIEnv *_env, jobject _this, jlong con, jlong mesh, jlongArray _idxIds, jintArray _primitives, jint numIndices)
 {
-    LOG_API("nMeshGetVertices, con(%p), Mesh(%p)", (RsContext)con, (RsMesh)mesh);
+    if (kLogApi) {
+        ALOGD("nMeshGetVertices, con(%p), Mesh(%p)", (RsContext)con, (RsMesh)mesh);
+    }
 
     RsAllocation *allocs = (RsAllocation*)malloc((uint32_t)numIndices * sizeof(RsAllocation));
     uint32_t *prims= (uint32_t*)malloc((uint32_t)numIndices * sizeof(uint32_t));
diff --git a/services/core/java/com/android/server/AlarmManagerService.java b/services/core/java/com/android/server/AlarmManagerService.java
index 8b524dd..0c555c5 100644
--- a/services/core/java/com/android/server/AlarmManagerService.java
+++ b/services/core/java/com/android/server/AlarmManagerService.java
@@ -1587,7 +1587,7 @@
         if (mLastAlarmDeliveryTime <= 0) {
             return false;
         }
-        if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime > nowELAPSED) {
+        if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
             // This is just a little paranoia, if somehow we have pending non-wakeup alarms
             // and the next delivery time is in the past, then just deliver them all.  This
             // avoids bugs where we get stuck in a loop trying to poll for alarms.
diff --git a/services/core/java/com/android/server/LocationManagerService.java b/services/core/java/com/android/server/LocationManagerService.java
index 28a6917..9eb1a18 100644
--- a/services/core/java/com/android/server/LocationManagerService.java
+++ b/services/core/java/com/android/server/LocationManagerService.java
@@ -1450,14 +1450,13 @@
         if (receiver == null) {
             receiver = new Receiver(listener, null, pid, uid, packageName, workSource,
                     hideFromAppOps);
-            mReceivers.put(binder, receiver);
-
             try {
                 receiver.getListener().asBinder().linkToDeath(receiver, 0);
             } catch (RemoteException e) {
                 Slog.e(TAG, "linkToDeath failed:", e);
                 return null;
             }
+            mReceivers.put(binder, receiver);
         }
         return receiver;
     }
diff --git a/services/core/java/com/android/server/MountService.java b/services/core/java/com/android/server/MountService.java
index 24d81a0..59570bf 100644
--- a/services/core/java/com/android/server/MountService.java
+++ b/services/core/java/com/android/server/MountService.java
@@ -76,9 +76,8 @@
 import com.android.server.pm.UserManagerService;
 import com.google.android.collect.Lists;
 import com.google.android.collect.Maps;
+import libcore.util.HexEncoding;
 
-import org.apache.commons.codec.binary.Hex;
-import org.apache.commons.codec.DecoderException;
 import org.xmlpull.v1.XmlPullParserException;
 
 import java.io.File;
@@ -2156,25 +2155,21 @@
         }
     }
 
-    private String toHex(String password) {
+    private static String toHex(String password) {
         if (password == null) {
-            return new String();
+            return "";
         }
         byte[] bytes = password.getBytes(StandardCharsets.UTF_8);
-        return new String(Hex.encodeHex(bytes));
+        return new String(HexEncoding.encode(bytes));
     }
 
-    private String fromHex(String hexPassword) {
+    private static String fromHex(String hexPassword) throws IllegalArgumentException {
         if (hexPassword == null) {
             return null;
         }
 
-        try {
-            byte[] bytes = Hex.decodeHex(hexPassword.toCharArray());
-            return new String(bytes, StandardCharsets.UTF_8);
-        } catch (DecoderException e) {
-            return null;
-        }
+        final byte[] bytes = HexEncoding.decode(hexPassword.toCharArray(), false);
+        return new String(bytes, StandardCharsets.UTF_8);
     }
 
     @Override
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index 8dfb321..e3f7fb3 100755
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -81,6 +81,7 @@
 import com.android.server.Watchdog;
 import com.android.server.am.ActivityStack.ActivityState;
 import com.android.server.firewall.IntentFirewall;
+import com.android.server.pm.Installer;
 import com.android.server.pm.UserManagerService;
 import com.android.server.wm.AppTransition;
 import com.android.server.wm.WindowManagerService;
@@ -370,6 +371,8 @@
     /** All system services */
     SystemServiceManager mSystemServiceManager;
 
+    private Installer mInstaller;
+
     /** Run all ActivityStacks through this */
     ActivityStackSupervisor mStackSupervisor;
 
@@ -1833,7 +1836,9 @@
                 break;
             }
             case REQUEST_ALL_PSS_MSG: {
-                requestPssAllProcsLocked(SystemClock.uptimeMillis(), true, false);
+                synchronized (ActivityManagerService.this) {
+                    requestPssAllProcsLocked(SystemClock.uptimeMillis(), true, false);
+                }
                 break;
             }
             case START_PROFILES_MSG: {
@@ -2358,6 +2363,10 @@
         mSystemServiceManager = mgr;
     }
 
+    public void setInstaller(Installer installer) {
+        mInstaller = installer;
+    }
+
     private void start() {
         Process.removeAllProcessGroups();
         mProcessCpuThread.start();
@@ -3032,12 +3041,12 @@
         if (app == null) {
             checkTime(startTime, "startProcess: creating new process record");
             app = newProcessRecordLocked(info, processName, isolated, isolatedUid);
-            app.crashHandler = crashHandler;
             if (app == null) {
                 Slog.w(TAG, "Failed making new process record for "
                         + processName + "/" + info.uid + " isolated=" + isolated);
                 return null;
             }
+            app.crashHandler = crashHandler;
             mProcessNames.put(processName, app.uid, app);
             if (isolated) {
                 mIsolatedProcesses.put(app.uid, app);
@@ -4865,9 +4874,11 @@
             stats.noteProcessDiedLocked(app.info.uid, pid);
         }
 
-        Process.killProcessQuiet(pid);
-        Process.killProcessGroup(app.info.uid, pid);
-        app.killed = true;
+        if (!app.killed) {
+            Process.killProcessQuiet(pid);
+            Process.killProcessGroup(app.info.uid, pid);
+            app.killed = true;
+        }
 
         // Clean up already done if the process has been re-started.
         if (app.pid == pid && app.thread != null &&
@@ -6091,6 +6102,7 @@
         app.hasShownUi = false;
         app.debugging = false;
         app.cached = false;
+        app.killedByAm = false;
 
         mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
 
@@ -6326,6 +6338,18 @@
             mCallFinishBooting = false;
         }
 
+        ArraySet<String> completedIsas = new ArraySet<String>();
+        for (String abi : Build.SUPPORTED_ABIS) {
+            Process.establishZygoteConnectionForAbi(abi);
+            final String instructionSet = VMRuntime.getInstructionSet(abi);
+            if (!completedIsas.contains(instructionSet)) {
+                if (mInstaller.markBootComplete(VMRuntime.getInstructionSet(abi)) != 0) {
+                    Slog.e(TAG, "Unable to mark boot complete for abi: " + abi);
+                }
+                completedIsas.add(instructionSet);
+            }
+        }
+
         // Register receivers to handle package update events
         mPackageMonitor.register(mContext, Looper.getMainLooper(), UserHandle.ALL, false);
 
@@ -9372,9 +9396,9 @@
                             "Attempt to launch content provider before system ready");
                 }
 
-                // Make sure that the user who owns this provider is started.  If not,
+                // Make sure that the user who owns this provider is running.  If not,
                 // we don't want to allow it to run.
-                if (mStartedUsers.get(userId) == null) {
+                if (!isUserRunningLocked(userId, false)) {
                     Slog.w(TAG, "Unable to launch app "
                             + cpi.applicationInfo.packageName + "/"
                             + cpi.applicationInfo.uid + " for provider "
@@ -9464,11 +9488,13 @@
                             if (DEBUG_PROVIDER) {
                                 Slog.d(TAG, "Installing in existing process " + proc);
                             }
-                            checkTime(startTime, "getContentProviderImpl: scheduling install");
-                            proc.pubProviders.put(cpi.name, cpr);
-                            try {
-                                proc.thread.scheduleInstallProvider(cpi);
-                            } catch (RemoteException e) {
+                            if (!proc.pubProviders.containsKey(cpi.name)) {
+                                checkTime(startTime, "getContentProviderImpl: scheduling install");
+                                proc.pubProviders.put(cpi.name, cpr);
+                                try {
+                                    proc.thread.scheduleInstallProvider(cpi);
+                                } catch (RemoteException e) {
+                                }
                             }
                         } else {
                             checkTime(startTime, "getContentProviderImpl: before start process");
@@ -10032,10 +10058,9 @@
             } finally {
                 // Ensure that whatever happens, we clean up the identity state
                 sCallerIdentity.remove();
+                // Ensure we're done with the provider.
+                removeContentProviderExternalUnchecked(name, null, userId);
             }
-
-            // We've got the fd now, so we're done with the provider.
-            removeContentProviderExternalUnchecked(name, null, userId);
         } else {
             Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
         }
@@ -15440,10 +15465,10 @@
         userId = handleIncomingUser(callingPid, callingUid, userId,
                 true, ALLOW_NON_FULL, "broadcast", callerPackage);
 
-        // Make sure that the user who is receiving this broadcast is started.
+        // Make sure that the user who is receiving this broadcast is running.
         // If not, we will just skip it.
 
-        if (userId != UserHandle.USER_ALL && mStartedUsers.get(userId) == null) {
+        if (userId != UserHandle.USER_ALL && !isUserRunningLocked(userId, false)) {
             if (callingUid != Process.SYSTEM_UID || (intent.getFlags()
                     & Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) {
                 Slog.w(TAG, "Skipping broadcast of " + intent
diff --git a/services/core/java/com/android/server/am/ActivityStack.java b/services/core/java/com/android/server/am/ActivityStack.java
index e1b8278..c03dbc2 100644
--- a/services/core/java/com/android/server/am/ActivityStack.java
+++ b/services/core/java/com/android/server/am/ActivityStack.java
@@ -1595,6 +1595,7 @@
         mStackSupervisor.mGoingToSleepActivities.remove(next);
         next.sleeping = false;
         mStackSupervisor.mWaitingVisibleActivities.remove(next);
+        next.waitingVisible = false;
 
         if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next);
 
@@ -1819,6 +1820,9 @@
                     // Do over!
                     mStackSupervisor.scheduleResumeTopActivities();
                 }
+                if (next == mLastScreenshotActivity) {
+                    invalidateLastScreenshot();
+                }
                 if (mStackSupervisor.reportResumedActivityLocked(next)) {
                     mNoAnimActivities.clear();
                     if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
@@ -2266,7 +2270,7 @@
                     // In this case, we want to finish this activity
                     // and everything above it, so be sneaky and pretend
                     // like these are all in the reply chain.
-                    end = numActivities - 1;
+                    end = activities.size() - 1;
                 } else if (replyChainEnd < 0) {
                     end = i;
                 } else {
@@ -2804,6 +2808,7 @@
         mStackSupervisor.mStoppingActivities.remove(r);
         mStackSupervisor.mGoingToSleepActivities.remove(r);
         mStackSupervisor.mWaitingVisibleActivities.remove(r);
+        r.waitingVisible = false;
         if (mResumedActivity == r) {
             mResumedActivity = null;
         }
@@ -3004,6 +3009,7 @@
         // down to the max limit while they are still waiting to finish.
         mStackSupervisor.mFinishingActivities.remove(r);
         mStackSupervisor.mWaitingVisibleActivities.remove(r);
+        r.waitingVisible = false;
 
         // Remove any pending results.
         if (r.finishing && r.pendingResults != null) {
diff --git a/services/core/java/com/android/server/am/ActivityStackSupervisor.java b/services/core/java/com/android/server/am/ActivityStackSupervisor.java
index 03dd3c0..6f5866a 100644
--- a/services/core/java/com/android/server/am/ActivityStackSupervisor.java
+++ b/services/core/java/com/android/server/am/ActivityStackSupervisor.java
@@ -1315,7 +1315,6 @@
                 }
             }
         }
-        ActivityStack resultStack = resultRecord == null ? null : resultRecord.task.stack;
 
         final int launchFlags = intent.getFlags();
 
@@ -1392,6 +1391,8 @@
             }
         }
 
+        final ActivityStack resultStack = resultRecord == null ? null : resultRecord.task.stack;
+
         if (err != ActivityManager.START_SUCCESS) {
             if (resultRecord != null) {
                 resultStack.sendActivityResultLocked(-1,
diff --git a/services/core/java/com/android/server/am/BroadcastQueue.java b/services/core/java/com/android/server/am/BroadcastQueue.java
index e01b983..9b7d0b2 100644
--- a/services/core/java/com/android/server/am/BroadcastQueue.java
+++ b/services/core/java/com/android/server/am/BroadcastQueue.java
@@ -296,7 +296,7 @@
     public void skipCurrentReceiverLocked(ProcessRecord app) {
         boolean reschedule = false;
         BroadcastRecord r = app.curReceiver;
-        if (r != null) {
+        if (r != null && r.queue == this) {
             // The current broadcast is waiting for this app's receiver
             // to be finished.  Looks like that's not going to happen, so
             // let the broadcast continue.
@@ -352,7 +352,7 @@
         }
         r.receiver = null;
         r.intent.setComponent(null);
-        if (r.curApp != null) {
+        if (r.curApp != null && r.curApp.curReceiver == r) {
             r.curApp.curReceiver = null;
         }
         if (r.curFilter != null) {
diff --git a/services/core/java/com/android/server/am/ProcessStatsService.java b/services/core/java/com/android/server/am/ProcessStatsService.java
index bffb541..c5f63f1 100644
--- a/services/core/java/com/android/server/am/ProcessStatsService.java
+++ b/services/core/java/com/android/server/am/ProcessStatsService.java
@@ -445,14 +445,14 @@
         mAm.mContext.enforceCallingOrSelfPermission(
                 android.Manifest.permission.PACKAGE_USAGE_STATS, null);
         Parcel current = Parcel.obtain();
+        synchronized (mAm) {
+            long now = SystemClock.uptimeMillis();
+            mProcessStats.mTimePeriodEndRealtime = SystemClock.elapsedRealtime();
+            mProcessStats.mTimePeriodEndUptime = now;
+            mProcessStats.writeToParcel(current, now, 0);
+        }
         mWriteLock.lock();
         try {
-            synchronized (mAm) {
-                long now = SystemClock.uptimeMillis();
-                mProcessStats.mTimePeriodEndRealtime = SystemClock.elapsedRealtime();
-                mProcessStats.mTimePeriodEndUptime = now;
-                mProcessStats.writeToParcel(current, now, 0);
-            }
             if (historic != null) {
                 ArrayList<String> files = getCommittedFiles(0, false, true);
                 if (files != null) {
@@ -476,18 +476,18 @@
     public ParcelFileDescriptor getStatsOverTime(long minTime) {
         mAm.mContext.enforceCallingOrSelfPermission(
                 android.Manifest.permission.PACKAGE_USAGE_STATS, null);
+        Parcel current = Parcel.obtain();
+        long curTime;
+        synchronized (mAm) {
+            long now = SystemClock.uptimeMillis();
+            mProcessStats.mTimePeriodEndRealtime = SystemClock.elapsedRealtime();
+            mProcessStats.mTimePeriodEndUptime = now;
+            mProcessStats.writeToParcel(current, now, 0);
+            curTime = mProcessStats.mTimePeriodEndRealtime
+                    - mProcessStats.mTimePeriodStartRealtime;
+        }
         mWriteLock.lock();
         try {
-            Parcel current = Parcel.obtain();
-            long curTime;
-            synchronized (mAm) {
-                long now = SystemClock.uptimeMillis();
-                mProcessStats.mTimePeriodEndRealtime = SystemClock.elapsedRealtime();
-                mProcessStats.mTimePeriodEndUptime = now;
-                mProcessStats.writeToParcel(current, now, 0);
-                curTime = mProcessStats.mTimePeriodEndRealtime
-                        - mProcessStats.mTimePeriodStartRealtime;
-            }
             if (curTime < minTime) {
                 // Need to add in older stats to reach desired time.
                 ArrayList<String> files = getCommittedFiles(0, false, true);
diff --git a/services/core/java/com/android/server/pm/Installer.java b/services/core/java/com/android/server/pm/Installer.java
index ca11862..31c604f 100644
--- a/services/core/java/com/android/server/pm/Installer.java
+++ b/services/core/java/com/android/server/pm/Installer.java
@@ -216,6 +216,18 @@
         return mInstaller.execute(builder.toString());
     }
 
+    public int markBootComplete(String instructionSet) {
+        if (!isValidInstructionSet(instructionSet)) {
+            Slog.e(TAG, "Invalid instruction set: " + instructionSet);
+            return -1;
+        }
+
+        StringBuilder builder = new StringBuilder("markbootcomplete");
+        builder.append(' ');
+        builder.append(instructionSet);
+        return mInstaller.execute(builder.toString());
+    }
+
     public boolean ping() {
         if (mInstaller.execute("ping") < 0) {
             return false;
diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java
index b79e157..2564962 100644
--- a/services/core/java/com/android/server/pm/PackageManagerService.java
+++ b/services/core/java/com/android/server/pm/PackageManagerService.java
@@ -4225,6 +4225,14 @@
         boolean updatedPkgBetter = false;
         // First check if this is a system package that may involve an update
         if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
+            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
+            // it needs to drop FLAG_PRIVILEGED.
+            if (locationIsPrivileged(scanFile)) {
+                updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
+            } else {
+                updatedPkg.pkgFlags &= ~ApplicationInfo.FLAG_PRIVILEGED;
+            }
+
             if (ps != null && !ps.codePath.equals(scanFile)) {
                 // The path has changed from what was last scanned...  check the
                 // version of the new path against what we have stored to determine
@@ -4242,12 +4250,8 @@
                                 + " to " + scanFile);
                         updatedPkg.codePath = scanFile;
                         updatedPkg.codePathString = scanFile.toString();
-                        // This is the point at which we know that the system-disk APK
-                        // for this package has moved during a reboot (e.g. due to an OTA),
-                        // so we need to reevaluate it for privilege policy.
-                        if (locationIsPrivileged(scanFile)) {
-                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
-                        }
+                        updatedPkg.resourcePath = scanFile;
+                        updatedPkg.resourcePathString = scanFile.toString();
                     }
                     updatedPkg.pkg = pkg;
                     throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
@@ -7103,7 +7107,9 @@
                         // If the original was granted this permission, we take
                         // that grant decision as read and propagate it to the
                         // update.
-                        allowed = true;
+                        if (sysPs.isPrivileged()) {
+                            allowed = true;
+                        }
                     } else {
                         // The system apk may have been updated with an older
                         // version of the one on the data partition, but which
diff --git a/services/core/java/com/android/server/pm/SELinuxMMAC.java b/services/core/java/com/android/server/pm/SELinuxMMAC.java
index 98f2997..95ed7bc 100644
--- a/services/core/java/com/android/server/pm/SELinuxMMAC.java
+++ b/services/core/java/com/android/server/pm/SELinuxMMAC.java
@@ -35,13 +35,22 @@
 import java.security.MessageDigest;
 import java.security.NoSuchAlgorithmException;
 
+import java.util.ArrayList;
+import java.util.Collections;
 import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
 
 import org.xmlpull.v1.XmlPullParser;
 import org.xmlpull.v1.XmlPullParserException;
 
 /**
- * Centralized access to SELinux MMAC (middleware MAC) implementation.
+ * Centralized access to SELinux MMAC (middleware MAC) implementation. This
+ * class is responsible for loading the appropriate mac_permissions.xml file
+ * as well as providing an interface for assigning seinfo values to apks.
+ *
  * {@hide}
  */
 public final class SELinuxMMAC {
@@ -51,11 +60,9 @@
     private static final boolean DEBUG_POLICY = false;
     private static final boolean DEBUG_POLICY_INSTALL = DEBUG_POLICY || false;
 
-    // Signature seinfo values read from policy.
-    private static HashMap<Signature, Policy> sSigSeinfo = new HashMap<Signature, Policy>();
-
-    // Default seinfo read from policy.
-    private static String sDefaultSeinfo = null;
+    // All policy stanzas read from mac_permissions.xml. This is also the lock
+    // to synchronize access during policy load and access attempts.
+    private static final List<Policy> sPolicies = new ArrayList<Policy>();
 
     // Data policy override version file.
     private static final String DATA_VERSION_FILE =
@@ -94,293 +101,289 @@
     private static final String SEAPP_HASH_FILE =
             Environment.getDataDirectory().toString() + "/system/seapp_hash";
 
-
-    // Signature policy stanzas
-    static class Policy {
-        private String seinfo;
-        private final HashMap<String, String> pkgMap;
-
-        Policy() {
-            seinfo = null;
-            pkgMap = new HashMap<String, String>();
-        }
-
-        void putSeinfo(String seinfoValue) {
-            seinfo = seinfoValue;
-        }
-
-        void putPkg(String pkg, String seinfoValue) {
-            pkgMap.put(pkg, seinfoValue);
-        }
-
-        // Valid policy stanza means there exists a global
-        // seinfo value or at least one package policy.
-        boolean isValid() {
-            return (seinfo != null) || (!pkgMap.isEmpty());
-        }
-
-        String checkPolicy(String pkgName) {
-            // Check for package name seinfo value first.
-            String seinfoValue = pkgMap.get(pkgName);
-            if (seinfoValue != null) {
-                return seinfoValue;
-            }
-
-            // Return the global seinfo value.
-            return seinfo;
-        }
-    }
-
-    private static void flushInstallPolicy() {
-        sSigSeinfo.clear();
-        sDefaultSeinfo = null;
-    }
-
+    /**
+     * Load the mac_permissions.xml file containing all seinfo assignments used to
+     * label apps. The loaded mac_permissions.xml file is determined by the
+     * MAC_PERMISSIONS class variable which is set at class load time which itself
+     * is based on the USE_OVERRIDE_POLICY class variable. For further guidance on
+     * the proper structure of a mac_permissions.xml file consult the source code
+     * located at external/sepolicy/mac_permissions.xml.
+     *
+     * @return boolean indicating if policy was correctly loaded. A value of false
+     *         typically indicates a structural problem with the xml or incorrectly
+     *         constructed policy stanzas. A value of true means that all stanzas
+     *         were loaded successfully; no partial loading is possible.
+     */
     public static boolean readInstallPolicy() {
-        return readInstallPolicy(MAC_PERMISSIONS);
-    }
+        // Temp structure to hold the rules while we parse the xml file. We add
+        // all the rules once we know there's no problems.
+        List<Policy> policies = new ArrayList<>();
 
-    public static boolean readInstallPolicy(String macPermsPath) {
-        if (macPermsPath == null) {
-            throw new NullPointerException("mac_permissions.xml file path is null");
-        }
+        // A separate structure to hold the default stanza. We need to add this to
+        // the end of the policies list structure.
+        Policy defaultPolicy = null;
 
-        // Temp structures to hold the rules while we parse the xml file.
-        // We add all the rules together once we know there's no structural problems.
-        HashMap<Signature, Policy> sigSeinfo = new HashMap<Signature, Policy>();
-        String defaultSeinfo = null;
+        // Track sets of known policy certs so we can enforce rules across stanzas.
+        Set<Set<Signature>> knownCerts = new HashSet<>();
 
         FileReader policyFile = null;
+        XmlPullParser parser = Xml.newPullParser();
         try {
-            policyFile = new FileReader(macPermsPath);
-            Slog.d(TAG, "Using policy file " + macPermsPath);
+            policyFile = new FileReader(MAC_PERMISSIONS);
+            Slog.d(TAG, "Using policy file " + MAC_PERMISSIONS);
 
-            XmlPullParser parser = Xml.newPullParser();
             parser.setInput(policyFile);
+            parser.nextTag();
+            parser.require(XmlPullParser.START_TAG, null, "policy");
 
-            XmlUtils.beginDocument(parser, "policy");
-            while (true) {
-                XmlUtils.nextElement(parser);
-                if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
-                    break;
+            while (parser.next() != XmlPullParser.END_TAG) {
+                if (parser.getEventType() != XmlPullParser.START_TAG) {
+                    continue;
                 }
 
                 String tagName = parser.getName();
                 if ("signer".equals(tagName)) {
-                    String cert = parser.getAttributeValue(null, "signature");
-                    if (cert == null) {
-                        Slog.w(TAG, "<signer> without signature at "
-                               + parser.getPositionDescription());
-                        XmlUtils.skipCurrentTag(parser);
-                        continue;
+                    Policy signerPolicy = readSignerOrThrow(parser);
+                    // Return of a Policy instance ensures certain invariants have
+                    // passed, however, we still want to do some cross policy checking.
+                    // Thus, check that we haven't seen the certs in another stanza.
+                    Set<Signature> certs = signerPolicy.getSignatures();
+                    if (knownCerts.contains(certs)) {
+                        String msg = "Separate stanzas have identical certs";
+                        throw new IllegalStateException(msg);
                     }
-                    Signature signature;
-                    try {
-                        signature = new Signature(cert);
-                    } catch (IllegalArgumentException e) {
-                        Slog.w(TAG, "<signer> with bad signature at "
-                               + parser.getPositionDescription(), e);
-                        XmlUtils.skipCurrentTag(parser);
-                        continue;
-                    }
-                    Policy policy = readPolicyTags(parser);
-                    if (policy.isValid()) {
-                        sigSeinfo.put(signature, policy);
-                    }
+                    knownCerts.add(certs);
+                    policies.add(signerPolicy);
                 } else if ("default".equals(tagName)) {
-                    // Value is null if default tag is absent or seinfo tag is malformed.
-                    defaultSeinfo = readSeinfoTag(parser);
-                    if (DEBUG_POLICY_INSTALL)
-                        Slog.i(TAG, "<default> tag assigned seinfo=" + defaultSeinfo);
-
+                    Policy defPolicy = readDefaultOrThrow(parser);
+                    // Return of a Policy instance ensures certain invariants have
+                    // passed, however, we still want to do some cross policy checking.
+                    // Thus, check that we haven't already seen a default stanza.
+                    if (defaultPolicy != null) {
+                        String msg = "Multiple default stanzas identified";
+                        throw new IllegalStateException(msg);
+                    }
+                    defaultPolicy = defPolicy;
                 } else {
-                    XmlUtils.skipCurrentTag(parser);
+                    skip(parser);
                 }
             }
-        } catch (XmlPullParserException xpe) {
-            Slog.w(TAG, "Got exception parsing " + macPermsPath, xpe);
+        } catch (IllegalStateException | IllegalArgumentException |
+                XmlPullParserException ex) {
+            StringBuilder sb = new StringBuilder("Exception @");
+            sb.append(parser.getPositionDescription());
+            sb.append(" while parsing ");
+            sb.append(MAC_PERMISSIONS);
+            sb.append(":");
+            sb.append(ex);
+            Slog.w(TAG, sb.toString());
             return false;
         } catch (IOException ioe) {
-            Slog.w(TAG, "Got exception parsing " + macPermsPath, ioe);
+            Slog.w(TAG, "Exception parsing " + MAC_PERMISSIONS, ioe);
             return false;
         } finally {
             IoUtils.closeQuietly(policyFile);
         }
 
-        flushInstallPolicy();
-        sSigSeinfo = sigSeinfo;
-        sDefaultSeinfo = defaultSeinfo;
+        // Add the default policy to the end if there is one. This will ensure that
+        // the default stanza is consulted last when performing policy lookups.
+        if (defaultPolicy != null) {
+            policies.add(defaultPolicy);
+        }
+
+        synchronized (sPolicies) {
+            sPolicies.clear();
+            sPolicies.addAll(policies);
+        }
 
         return true;
     }
 
-    private static Policy readPolicyTags(XmlPullParser parser) throws
-            IOException, XmlPullParserException {
+    /**
+     * Loop over a signer tag looking for seinfo, package and cert tags. A {@link Policy}
+     * instance will be created and returned in the process. During the pass all other
+     * tag elements will be skipped.
+     *
+     * @param parser an XmlPullParser object representing a signer element.
+     * @return the constructed {@link Policy} instance
+     * @throws IOException
+     * @throws XmlPullParserException
+     * @throws IllegalArgumentException if any of the validation checks fail while
+     *         parsing tag values.
+     * @throws IllegalStateException if any of the invariants fail when constructing
+     *         the {@link Policy} instance.
+     */
+    private static Policy readSignerOrThrow(XmlPullParser parser) throws IOException,
+            XmlPullParserException {
 
-        int type;
-        int outerDepth = parser.getDepth();
-        Policy policy = new Policy();
-        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
-               && (type != XmlPullParser.END_TAG
-                   || parser.getDepth() > outerDepth)) {
-            if (type == XmlPullParser.END_TAG
-                || type == XmlPullParser.TEXT) {
+        parser.require(XmlPullParser.START_TAG, null, "signer");
+        Policy.PolicyBuilder pb = new Policy.PolicyBuilder();
+
+        // Check for a cert attached to the signer tag. We allow a signature
+        // to appear as an attribute as well as those attached to cert tags.
+        String cert = parser.getAttributeValue(null, "signature");
+        if (cert != null) {
+            pb.addSignature(cert);
+        }
+
+        while (parser.next() != XmlPullParser.END_TAG) {
+            if (parser.getEventType() != XmlPullParser.START_TAG) {
                 continue;
             }
 
             String tagName = parser.getName();
             if ("seinfo".equals(tagName)) {
-                String seinfo = parseSeinfo(parser);
-                if (seinfo != null) {
-                    policy.putSeinfo(seinfo);
-                }
-                XmlUtils.skipCurrentTag(parser);
+                String seinfo = parser.getAttributeValue(null, "value");
+                pb.setGlobalSeinfoOrThrow(seinfo);
+                readSeinfo(parser);
             } else if ("package".equals(tagName)) {
-                String pkg = parser.getAttributeValue(null, "name");
-                if (!validatePackageName(pkg)) {
-                    Slog.w(TAG, "<package> without valid name at "
-                           + parser.getPositionDescription());
-                    XmlUtils.skipCurrentTag(parser);
-                    continue;
-                }
-
-                String seinfo = readSeinfoTag(parser);
-                if (seinfo != null) {
-                    policy.putPkg(pkg, seinfo);
-                }
+                readPackageOrThrow(parser, pb);
+            } else if ("cert".equals(tagName)) {
+                String sig = parser.getAttributeValue(null, "signature");
+                pb.addSignature(sig);
+                readCert(parser);
             } else {
-                XmlUtils.skipCurrentTag(parser);
+                skip(parser);
             }
         }
-        return policy;
+
+        return pb.build();
     }
 
-    private static String readSeinfoTag(XmlPullParser parser) throws
-            IOException, XmlPullParserException {
+    /**
+     * Loop over a default element looking for seinfo child tags. A {@link Policy}
+     * instance will be created and returned in the process. All other tags encountered
+     * will be skipped.
+     *
+     * @param parser an XmlPullParser object representing a default element.
+     * @return the constructed {@link Policy} instance
+     * @throws IOException
+     * @throws XmlPullParserException
+     * @throws IllegalArgumentException if any of the validation checks fail while
+     *         parsing tag values.
+     * @throws IllegalStateException if any of the invariants fail when constructing
+     *         the {@link Policy} instance.
+     */
+    private static Policy readDefaultOrThrow(XmlPullParser parser) throws IOException,
+            XmlPullParserException {
 
-        int type;
-        int outerDepth = parser.getDepth();
-        String seinfo = null;
-        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
-               && (type != XmlPullParser.END_TAG
-                   || parser.getDepth() > outerDepth)) {
-            if (type == XmlPullParser.END_TAG
-                || type == XmlPullParser.TEXT) {
+        parser.require(XmlPullParser.START_TAG, null, "default");
+        Policy.PolicyBuilder pb = new Policy.PolicyBuilder();
+        pb.setAsDefaultPolicy();
+
+        while (parser.next() != XmlPullParser.END_TAG) {
+            if (parser.getEventType() != XmlPullParser.START_TAG) {
                 continue;
             }
 
             String tagName = parser.getName();
             if ("seinfo".equals(tagName)) {
-                seinfo = parseSeinfo(parser);
+                String seinfo = parser.getAttributeValue(null, "value");
+                pb.setGlobalSeinfoOrThrow(seinfo);
+                readSeinfo(parser);
+            } else {
+                skip(parser);
             }
-            XmlUtils.skipCurrentTag(parser);
         }
-        return seinfo;
-    }
 
-    private static String parseSeinfo(XmlPullParser parser) {
-
-        String seinfoValue = parser.getAttributeValue(null, "value");
-        if (!validateValue(seinfoValue)) {
-            Slog.w(TAG, "<seinfo> without valid value at "
-                   + parser.getPositionDescription());
-            seinfoValue = null;
-        }
-        return seinfoValue;
+        return pb.build();
     }
 
     /**
-     * General validation routine for package names.
-     * Returns a boolean indicating if the passed string
-     * is a valid android package name.
+     * Loop over a package element looking for seinfo child tags. If found return the
+     * value attribute of the seinfo tag, otherwise return null. All other tags encountered
+     * will be skipped.
+     *
+     * @param parser an XmlPullParser object representing a package element.
+     * @param pb a Policy.PolicyBuilder instance to build
+     * @throws IOException
+     * @throws XmlPullParserException
+     * @throws IllegalArgumentException if any of the validation checks fail while
+     *         parsing tag values.
+     * @throws IllegalStateException if there is a duplicate seinfo tag for the current
+     *         package tag.
      */
-    private static boolean validatePackageName(String name) {
-        if (name == null)
-            return false;
+    private static void readPackageOrThrow(XmlPullParser parser, Policy.PolicyBuilder pb) throws
+            IOException, XmlPullParserException {
+        parser.require(XmlPullParser.START_TAG, null, "package");
+        String pkgName = parser.getAttributeValue(null, "name");
 
-        final int N = name.length();
-        boolean hasSep = false;
-        boolean front = true;
-        for (int i=0; i<N; i++) {
-            final char c = name.charAt(i);
-            if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
-                front = false;
+        while (parser.next() != XmlPullParser.END_TAG) {
+            if (parser.getEventType() != XmlPullParser.START_TAG) {
                 continue;
             }
-            if (!front) {
-                if ((c >= '0' && c <= '9') || c == '_') {
-                    continue;
-                }
+
+            String tagName = parser.getName();
+            if ("seinfo".equals(tagName)) {
+                String seinfo = parser.getAttributeValue(null, "value");
+                pb.addInnerPackageMapOrThrow(pkgName, seinfo);
+                readSeinfo(parser);
+            } else {
+                skip(parser);
             }
-            if (c == '.') {
-                hasSep = true;
-                front = true;
-                continue;
-            }
-            return false;
         }
-        return hasSep;
+    }
+
+    private static void readCert(XmlPullParser parser) throws IOException,
+            XmlPullParserException {
+        parser.require(XmlPullParser.START_TAG, null, "cert");
+        parser.nextTag();
+    }
+
+    private static void readSeinfo(XmlPullParser parser) throws IOException,
+            XmlPullParserException {
+        parser.require(XmlPullParser.START_TAG, null, "seinfo");
+        parser.nextTag();
+    }
+
+    private static void skip(XmlPullParser p) throws IOException, XmlPullParserException {
+        if (p.getEventType() != XmlPullParser.START_TAG) {
+            throw new IllegalStateException();
+        }
+        int depth = 1;
+        while (depth != 0) {
+            switch (p.next()) {
+            case XmlPullParser.END_TAG:
+                depth--;
+                break;
+            case XmlPullParser.START_TAG:
+                depth++;
+                break;
+            }
+        }
     }
 
     /**
-     * General validation routine for tag values.
-     * Returns a boolean indicating if the passed string
-     * contains only letters or underscores.
-     */
-    private static boolean validateValue(String name) {
-        if (name == null)
-            return false;
-
-        final int N = name.length();
-        if (N == 0)
-            return false;
-
-        for (int i = 0; i < N; i++) {
-            final char c = name.charAt(i);
-            if ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && (c != '_')) {
-                return false;
-            }
-        }
-        return true;
-    }
-
-    /**
-     * Labels a package based on an seinfo tag from install policy.
-     * The label is attached to the ApplicationInfo instance of the package.
+     * Applies a security label to a package based on an seinfo tag taken from a matched
+     * policy. All signature based policy stanzas are consulted first and, if no match
+     * is found, the default policy stanza is then consulted. The security label is
+     * attached to the ApplicationInfo instance of the package in the event that a matching
+     * policy was found.
+     *
      * @param pkg object representing the package to be labeled.
-     * @return boolean which determines whether a non null seinfo label
-     *         was assigned to the package. A null value simply meaning that
-     *         no policy matched.
+     * @return boolean which determines whether a non null seinfo label was assigned
+     *         to the package. A null value simply represents that no policy matched.
      */
     public static boolean assignSeinfoValue(PackageParser.Package pkg) {
-
-        // We just want one of the signatures to match.
-        for (Signature s : pkg.mSignatures) {
-            if (s == null)
-                continue;
-
-            Policy policy = sSigSeinfo.get(s);
-            if (policy != null) {
-                String seinfo = policy.checkPolicy(pkg.packageName);
+        synchronized (sPolicies) {
+            for (Policy policy : sPolicies) {
+                String seinfo = policy.getMatchedSeinfo(pkg);
                 if (seinfo != null) {
                     pkg.applicationInfo.seinfo = seinfo;
-                    if (DEBUG_POLICY_INSTALL)
-                        Slog.i(TAG, "package (" + pkg.packageName +
-                               ") labeled with seinfo=" + seinfo);
-
+                    if (DEBUG_POLICY_INSTALL) {
+                        Slog.i(TAG, "package (" + pkg.packageName + ") labeled with " +
+                               "seinfo=" + seinfo);
+                    }
                     return true;
                 }
             }
         }
 
-        // If we have a default seinfo value then great, otherwise
-        // we set a null object and that is what we started with.
-        pkg.applicationInfo.seinfo = sDefaultSeinfo;
-        if (DEBUG_POLICY_INSTALL)
-            Slog.i(TAG, "package (" + pkg.packageName + ") labeled with seinfo="
-                   + (sDefaultSeinfo == null ? "null" : sDefaultSeinfo));
-
-        return (sDefaultSeinfo != null);
+        if (DEBUG_POLICY_INSTALL) {
+            Slog.i(TAG, "package (" + pkg.packageName + ") doesn't match any policy; " +
+                   "seinfo will remain null");
+        }
+        return false;
     }
 
     /**
@@ -485,3 +488,312 @@
         return false;
     }
 }
+
+/**
+ * Holds valid policy representations of individual stanzas from a mac_permissions.xml
+ * file. Each instance can further be used to assign seinfo values to apks using the
+ * {@link Policy#getMatchedSeinfo} method. To create an instance of this use the
+ * {@link PolicyBuilder} pattern class, where each instance is validated against a set
+ * of invariants before being built and returned. Each instance can be guaranteed to
+ * hold one valid policy stanza as outlined in the external/sepolicy/mac_permissions.xml
+ * file.
+ * </p>
+ * The following is an example of how to use {@link Policy.PolicyBuilder} to create a
+ * signer based Policy instance.
+ * </p>
+ * <pre>
+ * {@code
+ * Policy policy = new Policy.PolicyBuilder()
+ *         .addSignature("308204a8...")
+ *         .addSignature("483538c8...")
+ *         .setGlobalSeinfoOrThrow("paltform")
+ *         .addInnerPackageMapOrThrow("com.foo.", "bar")
+ *         .addInnerPackageMapOrThrow("com.foo.other", "bar")
+ *         .build();
+ * }
+ * </pre>
+ * <p>
+ * An example of how to use {@link Policy.PolicyBuilder} to create a default based Policy
+ * instance.
+ * </p>
+ * <pre>
+ * {@code
+ * Policy policy = new Policy.PolicyBuilder()
+ *         .setAsDefaultPolicy()
+ *         .setGlobalSeinfoOrThrow("defualt")
+ *         .build();
+ * }
+ * </pre>
+ */
+final class Policy {
+
+    private final String mSeinfo;
+    private final boolean mDefaultStanza;
+    private final Set<Signature> mCerts;
+    private final Map<String, String> mPkgMap;
+
+    // Use the PolicyBuilder pattern to instantiate
+    private Policy(PolicyBuilder builder) {
+        mSeinfo = builder.mSeinfo;
+        mDefaultStanza = builder.mDefaultStanza;
+        mCerts = Collections.unmodifiableSet(builder.mCerts);
+        mPkgMap = Collections.unmodifiableMap(builder.mPkgMap);
+    }
+
+    /**
+     * Return all the certs stored with this policy stanza.
+     *
+     * @return A set of Signature objects representing all the certs stored
+     *         with the policy.
+     */
+    public Set<Signature> getSignatures() {
+        return mCerts;
+    }
+
+    /**
+     * <p>
+     * Determine the seinfo value to assign to an apk. The appropriate seinfo value
+     * is determined using the following steps:
+     * </p>
+     * <ul>
+     *   <li> If this Policy instance is defined as a default stanza:
+     *       <ul><li>Return the global seinfo value</li></ul>
+     *   </li>
+     *   <li> If this Policy instance is defined as a signer stanza:
+     *     <ul>
+     *       <li> All certs used to sign the apk and all certs stored with this policy
+     *         instance are tested for set equality. If this fails then null is returned.
+     *       </li>
+     *       <li> If all certs match then an appropriate inner package stanza is
+     *         searched based on package name alone. If matched, the stored seinfo
+     *         value for that mapping is returned.
+     *       </li>
+     *       <li> If all certs matched and no inner package stanza matches then return
+     *         the global seinfo value. The returned value can be null in this case.
+     *       </li>
+     *     </ul>
+     *   </li>
+     * </ul>
+     * <p>
+     * In all cases, a return value of null should be interpreted as the apk failing
+     * to match this Policy instance; i.e. failing this policy stanza.
+     * </p>
+     * @param pkg the apk to check given as a PackageParser.Package object
+     * @return A string representing the seinfo matched during policy lookup.
+     *         A value of null can also be returned if no match occured.
+     */
+    public String getMatchedSeinfo(PackageParser.Package pkg) {
+        if (!mDefaultStanza) {
+            // Check for exact signature matches across all certs.
+            Signature[] certs = mCerts.toArray(new Signature[0]);
+            if (!Signature.areExactMatch(certs, pkg.mSignatures)) {
+                return null;
+            }
+
+            // Check for inner package name matches given that the
+            // signature checks already passed.
+            String seinfoValue = mPkgMap.get(pkg.packageName);
+            if (seinfoValue != null) {
+                return seinfoValue;
+            }
+        }
+
+        // Return the global seinfo value (even if it's null).
+        return mSeinfo;
+    }
+
+    /**
+     * A nested builder class to create {@link Policy} instances. A {@link Policy}
+     * class instance represents one valid policy stanza found in a mac_permissions.xml
+     * file. A valid policy stanza is defined to be either a signer or default stanza
+     * which obeys the rules outlined in external/sepolicy/mac_permissions.xml. The
+     * {@link #build} method ensures a set of invariants are upheld enforcing the correct
+     * stanza structure before returning a valid Policy object.
+     */
+    public static final class PolicyBuilder {
+
+        private String mSeinfo;
+        private boolean mDefaultStanza;
+        private final Set<Signature> mCerts;
+        private final Map<String, String> mPkgMap;
+
+        public PolicyBuilder() {
+            mCerts = new HashSet<Signature>(2);
+            mPkgMap = new HashMap<String, String>(2);
+        }
+
+        /**
+         * Sets this stanza as a defualt stanza. All policy stanzas are assumed to
+         * be signer stanzas unless this method is explicitly called. Default stanzas
+         * are treated differently with respect to allowable child tags, ordering and
+         * when and how policy decisions are enforced.
+         *
+         * @return The reference to this PolicyBuilder.
+         */
+        public PolicyBuilder setAsDefaultPolicy() {
+            mDefaultStanza = true;
+            return this;
+        }
+
+        /**
+         * Adds a signature to the set of certs used for validation checks. The purpose
+         * being that all contained certs will need to be matched against all certs
+         * contained with an apk.
+         *
+         * @param cert the signature to add given as a String.
+         * @return The reference to this PolicyBuilder.
+         * @throws IllegalArgumentException if the cert value fails validation;
+         *         null or is an invalid hex-encoded ASCII string.
+         */
+        public PolicyBuilder addSignature(String cert) {
+            if (cert == null) {
+                String err = "Invalid signature value " + cert;
+                throw new IllegalArgumentException(err);
+            }
+
+            mCerts.add(new Signature(cert));
+            return this;
+        }
+
+        /**
+         * Set the global seinfo tag for this policy stanza. The global seinfo tag
+         * represents the seinfo element that is used in one of two ways depending on
+         * its context. When attached to a signer tag the global seinfo represents an
+         * assignment when there isn't a further inner package refinement in policy.
+         * When used with a default tag, it represents the only allowable assignment
+         * value.
+         *
+         * @param seinfo the seinfo value given as a String.
+         * @return The reference to this PolicyBuilder.
+         * @throws IllegalArgumentException if the seinfo value fails validation;
+         *         null, zero length or contains non-valid characters [^a-zA-Z_\._0-9].
+         * @throws IllegalStateException if an seinfo value has already been found
+         */
+        public PolicyBuilder setGlobalSeinfoOrThrow(String seinfo) {
+            if (!validateValue(seinfo)) {
+                String err = "Invalid seinfo value " + seinfo;
+                throw new IllegalArgumentException(err);
+            }
+
+            if (mSeinfo != null && !mSeinfo.equals(seinfo)) {
+                String err = "Duplicate seinfo tag found";
+                throw new IllegalStateException(err);
+            }
+
+            mSeinfo = seinfo;
+            return this;
+        }
+
+        /**
+         * Create a package name to seinfo value mapping. Each mapping represents
+         * the seinfo value that will be assigned to the described package name.
+         * These localized mappings allow the global seinfo to be overriden. This
+         * mapping provides no value when used in conjunction with a default stanza;
+         * enforced through the {@link #build} method.
+         *
+         * @param pkgName the android package name given to the app
+         * @param seinfo the seinfo value that will be assigned to the passed pkgName
+         * @return The reference to this PolicyBuilder.
+         * @throws IllegalArgumentException if the seinfo value fails validation;
+         *         null, zero length or contains non-valid characters [^a-zA-Z_\.0-9].
+         *         Or, if the package name isn't a valid android package name.
+         * @throws IllegalStateException if trying to reset a package mapping with a
+         *         different seinfo value.
+         */
+        public PolicyBuilder addInnerPackageMapOrThrow(String pkgName, String seinfo) {
+            if (!validateValue(pkgName)) {
+                String err = "Invalid package name " + pkgName;
+                throw new IllegalArgumentException(err);
+            }
+            if (!validateValue(seinfo)) {
+                String err = "Invalid seinfo value " + seinfo;
+                throw new IllegalArgumentException(err);
+            }
+
+            String pkgValue = mPkgMap.get(pkgName);
+            if (pkgValue != null && !pkgValue.equals(seinfo)) {
+                String err = "Conflicting seinfo value found";
+                throw new IllegalStateException(err);
+            }
+
+            mPkgMap.put(pkgName, seinfo);
+            return this;
+        }
+
+        /**
+         * General validation routine for the attribute strings of an element. Checks
+         * if the string is non-null, positive length and only contains [a-zA-Z_\.0-9].
+         *
+         * @param name the string to validate.
+         * @return boolean indicating if the string was valid.
+         */
+        private boolean validateValue(String name) {
+            if (name == null)
+                return false;
+
+            // Want to match on [0-9a-zA-Z_.]
+            if (!name.matches("\\A[\\.\\w]+\\z")) {
+                return false;
+            }
+
+            return true;
+        }
+
+        /**
+         * <p>
+         * Create a {@link Policy} instance based on the current configuration. This
+         * method checks for certain policy invariants used to enforce certain guarantees
+         * about the expected structure of a policy stanza.
+         * Those invariants are:
+         * </p>
+         *    <ul>
+         *      <li> If a default stanza
+         *        <ul>
+         *          <li> an attached global seinfo tag must be present </li>
+         *          <li> no signatures and no package names can be present </li>
+         *        </ul>
+         *      </li>
+         *      <li> If a signer stanza
+         *        <ul>
+         *           <li> at least one cert must be found </li>
+         *           <li> either a global seinfo value is present OR at least one
+         *           inner package mapping must be present. </li>
+         *        </ul>
+         *      </li>
+         *    </ul>
+         *
+         * @return an instance of {@link Policy} with the options set from this builder
+         * @throws IllegalStateException if an invariant is violated.
+         */
+        public Policy build() {
+            Policy p = new Policy(this);
+
+            if (p.mDefaultStanza) {
+                if (p.mSeinfo == null) {
+                    String err = "Missing global seinfo tag with default stanza.";
+                    throw new IllegalStateException(err);
+                }
+                if (p.mCerts.size() != 0) {
+                    String err = "Certs not allowed with default stanza.";
+                    throw new IllegalStateException(err);
+                }
+                if (!p.mPkgMap.isEmpty()) {
+                    String err = "Inner package mappings not allowed with default stanza.";
+                    throw new IllegalStateException(err);
+                }
+            } else {
+                if (p.mCerts.size() == 0) {
+                    String err = "Missing certs with signer tag. Expecting at least one.";
+                    throw new IllegalStateException(err);
+                }
+                if ((p.mSeinfo == null) && (p.mPkgMap.isEmpty())) {
+                    String err = "Missing seinfo OR package tags with signer tag. At " +
+                            "least one must be present.";
+                    throw new IllegalStateException(err);
+                }
+            }
+
+            return p;
+        }
+    }
+}
diff --git a/services/core/java/com/android/server/updates/ConfigUpdateInstallReceiver.java b/services/core/java/com/android/server/updates/ConfigUpdateInstallReceiver.java
index 7f7aae3..1135dfe 100644
--- a/services/core/java/com/android/server/updates/ConfigUpdateInstallReceiver.java
+++ b/services/core/java/com/android/server/updates/ConfigUpdateInstallReceiver.java
@@ -47,7 +47,6 @@
 
     private static final String TAG = "ConfigUpdateInstallReceiver";
 
-    private static final String EXTRA_CONTENT_PATH = "CONTENT_PATH";
     private static final String EXTRA_REQUIRED_HASH = "REQUIRED_HASH";
     private static final String EXTRA_SIGNATURE = "SIGNATURE";
     private static final String EXTRA_VERSION_NUMBER = "VERSION";
diff --git a/services/core/java/com/android/server/wm/DisplayContent.java b/services/core/java/com/android/server/wm/DisplayContent.java
index 30589b1..c6c2666 100644
--- a/services/core/java/com/android/server/wm/DisplayContent.java
+++ b/services/core/java/com/android/server/wm/DisplayContent.java
@@ -241,6 +241,7 @@
                 mTouchExcludeRegion.op(mTmpRect, Region.Op.DIFFERENCE);
             }
         }
+        mTapDetector.setTouchExcludeRegion(mTouchExcludeRegion);
     }
 
     void switchUserStacks(int newUserId) {
diff --git a/services/core/java/com/android/server/wm/StackTapPointerEventListener.java b/services/core/java/com/android/server/wm/StackTapPointerEventListener.java
index 19d8ab3..1a85993 100644
--- a/services/core/java/com/android/server/wm/StackTapPointerEventListener.java
+++ b/services/core/java/com/android/server/wm/StackTapPointerEventListener.java
@@ -31,7 +31,7 @@
     private float mDownX;
     private float mDownY;
     private int mPointerId;
-    final private Region mTouchExcludeRegion;
+    final private Region mTouchExcludeRegion = new Region();
     private final WindowManagerService mService;
     private final DisplayContent mDisplayContent;
 
@@ -39,7 +39,6 @@
             DisplayContent displayContent) {
         mService = service;
         mDisplayContent = displayContent;
-        mTouchExcludeRegion = displayContent.mTouchExcludeRegion;
         DisplayInfo info = displayContent.getDisplayInfo();
         mMotionSlop = (int)(info.logicalDensityDpi * TAP_MOTION_SLOP_INCHES);
     }
@@ -57,8 +56,9 @@
                 if (mPointerId >= 0) {
                     int index = motionEvent.findPointerIndex(mPointerId);
                     if ((motionEvent.getEventTime() - motionEvent.getDownTime()) > TAP_TIMEOUT_MSEC
-                            || (motionEvent.getX(index) - mDownX) > mMotionSlop
-                            || (motionEvent.getY(index) - mDownY) > mMotionSlop) {
+                            || index < 0
+                            || Math.abs(motionEvent.getX(index) - mDownX) > mMotionSlop
+                            || Math.abs(motionEvent.getY(index) - mDownY) > mMotionSlop) {
                         mPointerId = -1;
                     }
                 }
@@ -71,12 +71,15 @@
                 if (mPointerId == motionEvent.getPointerId(index)) {
                     final int x = (int)motionEvent.getX(index);
                     final int y = (int)motionEvent.getY(index);
-                    if ((motionEvent.getEventTime() - motionEvent.getDownTime())
-                            < TAP_TIMEOUT_MSEC
-                            && (x - mDownX) < mMotionSlop && (y - mDownY) < mMotionSlop
-                            && !mTouchExcludeRegion.contains(x, y)) {
-                        mService.mH.obtainMessage(H.TAP_OUTSIDE_STACK, x, y,
-                                mDisplayContent).sendToTarget();
+                    synchronized(this) {
+                        if ((motionEvent.getEventTime() - motionEvent.getDownTime())
+                                < TAP_TIMEOUT_MSEC
+                                && Math.abs(x - mDownX) < mMotionSlop
+                                && Math.abs(y - mDownY) < mMotionSlop
+                                && !mTouchExcludeRegion.contains(x, y)) {
+                            mService.mH.obtainMessage(H.TAP_OUTSIDE_STACK, x, y,
+                                    mDisplayContent).sendToTarget();
+                        }
                     }
                     mPointerId = -1;
                 }
@@ -84,4 +87,10 @@
             }
         }
     }
+
+    void setTouchExcludeRegion(Region newRegion) {
+        synchronized (this) {
+           mTouchExcludeRegion.set(newRegion);
+        }
+    }
 }
diff --git a/services/core/java/com/android/server/wm/TaskStack.java b/services/core/java/com/android/server/wm/TaskStack.java
index 238c77e..802cf4b 100644
--- a/services/core/java/com/android/server/wm/TaskStack.java
+++ b/services/core/java/com/android/server/wm/TaskStack.java
@@ -191,7 +191,9 @@
         mTasks.add(stackNdx, task);
 
         task.mStack = this;
-        mDisplayContent.moveStack(this, true);
+        if (toTop) {
+            mDisplayContent.moveStack(this, true);
+        }
         EventLog.writeEvent(EventLogTags.WM_TASK_MOVED, task.taskId, toTop ? 1 : 0, stackNdx);
     }
 
diff --git a/services/core/java/com/android/server/wm/WindowManagerService.java b/services/core/java/com/android/server/wm/WindowManagerService.java
index 837672a..c80d0e1 100644
--- a/services/core/java/com/android/server/wm/WindowManagerService.java
+++ b/services/core/java/com/android/server/wm/WindowManagerService.java
@@ -4000,6 +4000,15 @@
             if (changed) {
                 mFocusedApp = newFocus;
                 mInputMonitor.setFocusedAppLw(newFocus);
+                setFocusedStackFrame();
+                if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG, ">>> OPEN TRANSACTION setFocusedApp");
+                SurfaceControl.openTransaction();
+                try {
+                    setFocusedStackLayer();
+                } finally {
+                    SurfaceControl.closeTransaction();
+                    if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG, ">>> CLOSE TRANSACTION setFocusedApp");
+                }
             }
 
             if (moveFocusNow && changed) {
@@ -4820,8 +4829,19 @@
         if (NW > 0) {
             mWindowsChanged = true;
         }
+        int targetDisplayId = -1;
+        Task targetTask = mTaskIdToTask.get(token.appWindowToken.groupId);
+        if (targetTask != null) {
+            DisplayContent targetDisplayContent = targetTask.getDisplayContent();
+            if (targetDisplayContent != null) {
+                targetDisplayId = targetDisplayContent.getDisplayId();
+            }
+        }
         for (int i = 0; i < NW; i++) {
             WindowState win = windows.get(i);
+            if (targetDisplayId != -1 && win.getDisplayId() != targetDisplayId) {
+                continue;
+            }
             if (DEBUG_WINDOW_MOVEMENT) Slog.v(TAG, "Tmp removing app window " + win);
             win.getWindowList().remove(win);
             int j = win.mChildWindows.size();
@@ -6081,9 +6101,13 @@
                     }
 
                     if (ws.mAppToken != null && ws.mAppToken.token == appToken &&
-                            ws.isDisplayedLw()) {
+                            ws.isDisplayedLw() && winAnim.mSurfaceShown) {
                         screenshotReady = true;
                     }
+
+                    if (ws.isFullscreen(dw, dh) && ws.isOpaqueDrawn()){
+                        break;
+                    }
                 }
 
                 if (appToken != null && appWin == null) {
@@ -7129,6 +7153,7 @@
             displayInfo.getAppMetrics(mDisplayMetrics);
             mDisplayManagerInternal.setDisplayInfoOverrideFromWindowManager(
                     displayContent.getDisplayId(), displayInfo);
+            displayContent.mBaseDisplayRect.set(0, 0, dw, dh);
         }
         if (false) {
             Slog.i(TAG, "Set app display size: " + appWidth + " x " + appHeight);
@@ -8771,7 +8796,8 @@
             if (!gone || !win.mHaveFrame || win.mLayoutNeeded
                     || ((win.isConfigChanged() || win.setInsetsChanged()) &&
                             ((win.mAttrs.privateFlags & PRIVATE_FLAG_KEYGUARD) != 0 ||
-                            win.mAppToken != null && win.mAppToken.layoutConfigChanges))
+                            (win.mHasSurface && win.mAppToken != null &&
+                            win.mAppToken.layoutConfigChanges)))
                     || win.mAttrs.type == TYPE_UNIVERSE_BACKGROUND) {
                 if (!win.mLayoutAttached) {
                     if (initial) {
diff --git a/services/core/java/com/android/server/wm/WindowState.java b/services/core/java/com/android/server/wm/WindowState.java
index b4a7f04..04dab3e 100644
--- a/services/core/java/com/android/server/wm/WindowState.java
+++ b/services/core/java/com/android/server/wm/WindowState.java
@@ -386,28 +386,26 @@
             mAttachedWindow = attachedWindow;
             if (WindowManagerService.DEBUG_ADD_REMOVE) Slog.v(TAG, "Adding " + this + " to " + mAttachedWindow);
 
-            int children_size = mAttachedWindow.mChildWindows.size();
-            if (children_size == 0) {
-                mAttachedWindow.mChildWindows.add(this);
+            final WindowList childWindows = mAttachedWindow.mChildWindows;
+            final int numChildWindows = childWindows.size();
+            if (numChildWindows == 0) {
+                childWindows.add(this);
             } else {
-                for (int i = 0; i < children_size; i++) {
-                    WindowState child = (WindowState)mAttachedWindow.mChildWindows.get(i);
-                    if (this.mSubLayer < child.mSubLayer) {
-                        mAttachedWindow.mChildWindows.add(i, this);
+                boolean added = false;
+                for (int i = 0; i < numChildWindows; i++) {
+                    final int childSubLayer = childWindows.get(i).mSubLayer;
+                    if (mSubLayer < childSubLayer
+                            || (mSubLayer == childSubLayer && childSubLayer < 0)) {
+                        // We insert the child window into the list ordered by the sub-layer. For
+                        // same sub-layers, the negative one should go below others; the positive
+                        // one should go above others.
+                        childWindows.add(i, this);
+                        added = true;
                         break;
-                    } else if (this.mSubLayer > child.mSubLayer) {
-                        continue;
-                    }
-
-                    if (this.mBaseLayer <= child.mBaseLayer) {
-                        mAttachedWindow.mChildWindows.add(i, this);
-                        break;
-                    } else {
-                        continue;
                     }
                 }
-                if (children_size == mAttachedWindow.mChildWindows.size()) {
-                    mAttachedWindow.mChildWindows.add(this);
+                if (!added) {
+                    childWindows.add(this);
                 }
             }
 
diff --git a/services/core/jni/Android.mk b/services/core/jni/Android.mk
index 7996f73..dc073ad 100644
--- a/services/core/jni/Android.mk
+++ b/services/core/jni/Android.mk
@@ -2,7 +2,7 @@
 # files
 LOCAL_REL_DIR := core/jni
 
-LOCAL_CFLAGS += -Wall -Werror
+LOCAL_CFLAGS += -Wall -Werror -Wno-unused-parameter
 
 LOCAL_SRC_FILES += \
     $(LOCAL_REL_DIR)/com_android_server_AlarmManagerService.cpp \
@@ -27,8 +27,6 @@
     $(LOCAL_REL_DIR)/com_android_server_PersistentDataBlockService.cpp \
     $(LOCAL_REL_DIR)/onload.cpp
 
-include external/stlport/libstlport.mk
-
 LOCAL_C_INCLUDES += \
     $(JNI_H_INCLUDE) \
     frameworks/base/services \
@@ -37,8 +35,8 @@
     frameworks/native/services \
     libcore/include \
     libcore/include/libsuspend \
-	$(call include-path-for, libhardware)/hardware \
-	$(call include-path-for, libhardware_legacy)/hardware_legacy \
+    $(call include-path-for, libhardware)/hardware \
+    $(call include-path-for, libhardware_legacy)/hardware_legacy \
 
 LOCAL_SHARED_LIBRARIES += \
     libandroid_runtime \
diff --git a/services/core/jni/com_android_server_AlarmManagerService.cpp b/services/core/jni/com_android_server_AlarmManagerService.cpp
index a58b00bce..3d981ab 100644
--- a/services/core/jni/com_android_server_AlarmManagerService.cpp
+++ b/services/core/jni/com_android_server_AlarmManagerService.cpp
@@ -290,7 +290,7 @@
 
     epollfd = epoll_create(N_ANDROID_TIMERFDS);
     if (epollfd < 0) {
-        ALOGV("epoll_create(%u) failed: %s", N_ANDROID_TIMERFDS,
+        ALOGV("epoll_create(%zu) failed: %s", N_ANDROID_TIMERFDS,
                 strerror(errno));
         return 0;
     }
diff --git a/services/core/jni/com_android_server_UsbDeviceManager.cpp b/services/core/jni/com_android_server_UsbDeviceManager.cpp
index 8d1a338..a1bff9d 100644
--- a/services/core/jni/com_android_server_UsbDeviceManager.cpp
+++ b/services/core/jni/com_android_server_UsbDeviceManager.cpp
@@ -41,20 +41,12 @@
     jmethodID mConstructor;
 } gParcelFileDescriptorOffsets;
 
-static void checkAndClearExceptionFromCallback(JNIEnv* env, const char* methodName) {
-    if (env->ExceptionCheck()) {
-        ALOGE("An exception was thrown by callback '%s'.", methodName);
-        LOGE_EX(env);
-        env->ExceptionClear();
-    }
-}
-
 static void set_accessory_string(JNIEnv *env, int fd, int cmd, jobjectArray strArray, int index)
 {
     char buffer[256];
 
     buffer[0] = 0;
-    int length = ioctl(fd, cmd, buffer);
+    ioctl(fd, cmd, buffer);
     if (buffer[0]) {
         jstring obj = env->NewStringUTF(buffer);
         env->SetObjectArrayElement(strArray, index, obj);
diff --git a/services/core/jni/com_android_server_hdmi_HdmiCecController.cpp b/services/core/jni/com_android_server_hdmi_HdmiCecController.cpp
index 5c557b6..4a08b2d 100644
--- a/services/core/jni/com_android_server_hdmi_HdmiCecController.cpp
+++ b/services/core/jni/com_android_server_hdmi_HdmiCecController.cpp
@@ -408,6 +408,7 @@
 int register_android_server_hdmi_HdmiCecController(JNIEnv* env) {
     int res = jniRegisterNativeMethods(env, CLASS_PATH, sMethods, NELEM(sMethods));
     LOG_FATAL_IF(res < 0, "Unable to register native methods.");
+    (void)res; // Don't scream about unused variable in the LOG_NDEBUG case
     return 0;
 }
 
diff --git a/services/core/jni/com_android_server_input_InputApplicationHandle.cpp b/services/core/jni/com_android_server_input_InputApplicationHandle.cpp
index f943d16..11388d8 100644
--- a/services/core/jni/com_android_server_input_InputApplicationHandle.cpp
+++ b/services/core/jni/com_android_server_input_InputApplicationHandle.cpp
@@ -137,6 +137,7 @@
 int register_android_server_InputApplicationHandle(JNIEnv* env) {
     int res = jniRegisterNativeMethods(env, "com/android/server/input/InputApplicationHandle",
             gInputApplicationHandleMethods, NELEM(gInputApplicationHandleMethods));
+    (void) res;  // Faked use when LOG_NDEBUG.
     LOG_FATAL_IF(res < 0, "Unable to register native methods.");
 
     jclass clazz;
diff --git a/services/core/jni/com_android_server_input_InputManagerService.cpp b/services/core/jni/com_android_server_input_InputManagerService.cpp
index 5d73af8..7c5980a 100644
--- a/services/core/jni/com_android_server_input_InputManagerService.cpp
+++ b/services/core/jni/com_android_server_input_InputManagerService.cpp
@@ -1416,6 +1416,7 @@
 int register_android_server_InputManager(JNIEnv* env) {
     int res = jniRegisterNativeMethods(env, "com/android/server/input/InputManagerService",
             gInputManagerMethods, NELEM(gInputManagerMethods));
+    (void) res;  // Faked use when LOG_NDEBUG.
     LOG_FATAL_IF(res < 0, "Unable to register native methods.");
 
     // Callbacks
diff --git a/services/core/jni/com_android_server_input_InputWindowHandle.cpp b/services/core/jni/com_android_server_input_InputWindowHandle.cpp
index 03bf7eb..5e15db5 100644
--- a/services/core/jni/com_android_server_input_InputWindowHandle.cpp
+++ b/services/core/jni/com_android_server_input_InputWindowHandle.cpp
@@ -230,6 +230,7 @@
 int register_android_server_InputWindowHandle(JNIEnv* env) {
     int res = jniRegisterNativeMethods(env, "com/android/server/input/InputWindowHandle",
             gInputWindowHandleMethods, NELEM(gInputWindowHandleMethods));
+    (void) res;  // Faked use when LOG_NDEBUG.
     LOG_FATAL_IF(res < 0, "Unable to register native methods.");
 
     jclass clazz;
diff --git a/services/core/jni/com_android_server_location_GpsLocationProvider.cpp b/services/core/jni/com_android_server_location_GpsLocationProvider.cpp
index d730b7e..b18b14d 100644
--- a/services/core/jni/com_android_server_location_GpsLocationProvider.cpp
+++ b/services/core/jni/com_android_server_location_GpsLocationProvider.cpp
@@ -214,7 +214,7 @@
 
     size_t status_size = agps_status->size;
     if (status_size == sizeof(AGpsStatus_v3)) {
-      ALOGV("AGpsStatus is V3: %d", status_size);
+      ALOGV("AGpsStatus is V3: %zd", status_size);
       switch (agps_status->addr.ss_family)
       {
       case AF_INET:
@@ -256,7 +256,7 @@
           break;
       }
     } else if (status_size >= sizeof(AGpsStatus_v2)) {
-      ALOGV("AGpsStatus is V2+: %d", status_size);
+      ALOGV("AGpsStatus is V2+: %zd", status_size);
       // for back-compatibility reasons we check in v2 that the data structure size is greater or
       // equal to the declared size in gps.h
       uint32_t ipaddr = agps_status->ipaddr;
@@ -266,12 +266,12 @@
           isSupported = true;
       }
     } else if (status_size >= sizeof(AGpsStatus_v1)) {
-        ALOGV("AGpsStatus is V1+: %d", status_size);
+        ALOGV("AGpsStatus is V1+: %zd", status_size);
         // because we have to check for >= with regards to v2, we also need to relax the check here
         // and only make sure that the size is at least what we expect
         isSupported = true;
     } else {
-        ALOGE("Invalid size of AGpsStatus found: %d.", status_size);
+        ALOGE("Invalid size of AGpsStatus found: %zd.", status_size);
     }
 
     if (isSupported) {
@@ -758,7 +758,7 @@
     } else if (interface_size == sizeof(AGpsInterface_v1)) {
         sAGpsInterface->data_conn_open(apnStr);
     } else {
-        ALOGE("Invalid size of AGpsInterface found: %d.", interface_size);
+        ALOGE("Invalid size of AGpsInterface found: %zd.", interface_size);
     }
 
     env->ReleaseStringUTFChars(apn, apnStr);
@@ -1260,7 +1260,7 @@
         env->DeleteLocalRef(gpsMeasurementsEventClass);
         env->DeleteLocalRef(gpsMeasurementsEvent);
     } else {
-        ALOGE("Invalid GpsData size found in gps_measurement_callback, size=%d", data->size);
+        ALOGE("Invalid GpsData size found in gps_measurement_callback, size=%zd", data->size);
     }
 }
 
@@ -1311,7 +1311,7 @@
     size_t dataLength = message->data_length;
     uint8_t* data = message->data;
     if (dataLength == 0 || data == NULL) {
-        ALOGE("Invalid Navigation Message found: data=%p, length=%d", data, dataLength);
+        ALOGE("Invalid Navigation Message found: data=%p, length=%zd", data, dataLength);
         return NULL;
     }
 
@@ -1370,7 +1370,7 @@
         env->DeleteLocalRef(navigationMessageEventClass);
         env->DeleteLocalRef(navigationMessageEvent);
     } else {
-        ALOGE("Invalid GpsNavigationMessage size found: %d", message->size);
+        ALOGE("Invalid GpsNavigationMessage size found: %zd", message->size);
     }
 }
 
diff --git a/services/core/jni/com_android_server_power_PowerManagerService.cpp b/services/core/jni/com_android_server_power_PowerManagerService.cpp
index db642dd..6dcdd9d 100644
--- a/services/core/jni/com_android_server_power_PowerManagerService.cpp
+++ b/services/core/jni/com_android_server_power_PowerManagerService.cpp
@@ -189,6 +189,7 @@
 int register_android_server_PowerManagerService(JNIEnv* env) {
     int res = jniRegisterNativeMethods(env, "com/android/server/power/PowerManagerService",
             gPowerManagerServiceMethods, NELEM(gPowerManagerServiceMethods));
+    (void) res;  // Faked use when LOG_NDEBUG.
     LOG_FATAL_IF(res < 0, "Unable to register native methods.");
 
     // Callbacks
diff --git a/services/core/jni/com_android_server_tv_TvInputHal.cpp b/services/core/jni/com_android_server_tv_TvInputHal.cpp
index d5abe0c..4914c62 100644
--- a/services/core/jni/com_android_server_tv_TvInputHal.cpp
+++ b/services/core/jni/com_android_server_tv_TvInputHal.cpp
@@ -634,6 +634,7 @@
     int res = jniRegisterNativeMethods(env, "com/android/server/tv/TvInputHal",
             gTvInputHalMethods, NELEM(gTvInputHalMethods));
     LOG_FATAL_IF(res < 0, "Unable to register native methods.");
+    (void)res; // Don't complain about unused variable in the LOG_NDEBUG case
 
     jclass clazz;
     FIND_CLASS(clazz, "com/android/server/tv/TvInputHal");
diff --git a/services/java/com/android/server/SystemServer.java b/services/java/com/android/server/SystemServer.java
index 92ad1ad..5573017 100644
--- a/services/java/com/android/server/SystemServer.java
+++ b/services/java/com/android/server/SystemServer.java
@@ -147,7 +147,6 @@
     private SystemServiceManager mSystemServiceManager;
 
     // TODO: remove all of these references by improving dependency resolution and boot phases
-    private Installer mInstaller;
     private PowerManagerService mPowerManagerService;
     private ActivityManagerService mActivityManagerService;
     private DisplayManagerService mDisplayManagerService;
@@ -309,12 +308,13 @@
         // Wait for installd to finish starting up so that it has a chance to
         // create critical directories such as /data/user with the appropriate
         // permissions.  We need this to complete before we initialize other services.
-        mInstaller = mSystemServiceManager.startService(Installer.class);
+        Installer installer = mSystemServiceManager.startService(Installer.class);
 
         // Activity manager runs the show.
         mActivityManagerService = mSystemServiceManager.startService(
                 ActivityManagerService.Lifecycle.class).getService();
         mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
+        mActivityManagerService.setInstaller(installer);
 
         // Power manager needs to be started early because other services need it.
         // Native daemons may be watching for it to be registered so it must be ready
@@ -345,7 +345,7 @@
 
         // Start the package manager.
         Slog.i(TAG, "Package Manager");
-        mPackageManagerService = PackageManagerService.main(mSystemContext, mInstaller,
+        mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
                 mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
         mFirstBoot = mPackageManagerService.isFirstBoot();
         mPackageManager = mSystemContext.getPackageManager();
@@ -407,6 +407,7 @@
         ConsumerIrService consumerIr = null;
         AudioService audioService = null;
         MmsServiceBroker mmsService = null;
+        EntropyMixer entropyMixer = null;
 
         boolean disableStorage = SystemProperties.getBoolean("config.disable_storage", false);
         boolean disableMedia = SystemProperties.getBoolean("config.disable_media", false);
@@ -430,7 +431,7 @@
             ServiceManager.addService("telephony.registry", telephonyRegistry);
 
             Slog.i(TAG, "Entropy Mixer");
-            ServiceManager.addService("entropy", new EntropyMixer(context));
+            entropyMixer = new EntropyMixer(context);
 
             mContentResolver = context.getContentResolver();
 
@@ -546,20 +547,6 @@
             reportWtf("making display ready", e);
         }
 
-        try {
-            mPackageManagerService.performBootDexOpt();
-        } catch (Throwable e) {
-            reportWtf("performing boot dexopt", e);
-        }
-
-        try {
-            ActivityManagerNative.getDefault().showBootMessage(
-                    context.getResources().getText(
-                            com.android.internal.R.string.android_upgrading_starting_apps),
-                    false);
-        } catch (RemoteException e) {
-        }
-
         if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
             if (!disableStorage &&
                 !"0".equals(SystemProperties.get("system_init.startmountservice"))) {
@@ -575,7 +562,23 @@
                     reportWtf("starting Mount Service", e);
                 }
             }
+        }
 
+        try {
+            mPackageManagerService.performBootDexOpt();
+        } catch (Throwable e) {
+            reportWtf("performing boot dexopt", e);
+        }
+
+        try {
+            ActivityManagerNative.getDefault().showBootMessage(
+                    context.getResources().getText(
+                            com.android.internal.R.string.android_upgrading_starting_apps),
+                    false);
+        } catch (RemoteException e) {
+        }
+
+        if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
             if (!disableNonCoreServices) {
                 try {
                     Slog.i(TAG,  "LockSettingsService");
diff --git a/telephony/java/android/telephony/PhoneStateListener.java b/telephony/java/android/telephony/PhoneStateListener.java
index 0dcd7c6..e2189f5 100644
--- a/telephony/java/android/telephony/PhoneStateListener.java
+++ b/telephony/java/android/telephony/PhoneStateListener.java
@@ -231,8 +231,7 @@
 
     /**
      * Create a PhoneStateListener for the Phone with the default subscription.
-     * This class requires Looper.myLooper() not return null. To supply your
-     * own non-null looper use PhoneStateListener(Looper looper) below.
+     * This class requires Looper.myLooper() not return null.
      */
     public PhoneStateListener() {
         this(SubscriptionManager.DEFAULT_SUB_ID, Looper.myLooper());
diff --git a/tests/CoreTests/android/core/InetAddrTest.java b/tests/CoreTests/android/core/InetAddrTest.java
deleted file mode 100644
index c7b89e1..0000000
--- a/tests/CoreTests/android/core/InetAddrTest.java
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * Copyright (C) 2008 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.
- */
-
-package android.core;
-
-import junit.framework.TestCase;
-
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.util.Random;
-
-import android.test.suitebuilder.annotation.Suppress;
-
-/**
- * Tests InetAddr class by checking methods to resolve domains to IP addresses
- * and by checking if the class returns correct addresses for local host address
- * and host name.
- */
-@Suppress
-public class InetAddrTest extends TestCase {
-    private static final String[] HOSTS = {
-            "localhost", "www.google.com", "www.slashdot.org", "www.wikipedia.org",
-            "www.paypal.com", "www.cnn.com", "www.yahoo.com", "www.amazon.com",
-            "www.ebay.com", "www.android.com"
-    };
-
-    public void testInetAddr() throws Exception {
-        byte[] raw;
-
-        InetAddress ia = InetAddress.getByName("localhost");
-
-        raw = ia.getAddress();
-
-        assertEquals(127, raw[0]);
-        assertEquals(0, raw[1]);
-        assertEquals(0, raw[2]);
-        assertEquals(1, raw[3]);
-
-        ia = InetAddress.getByName("127.0.0.1");
-
-        raw = ia.getAddress();
-
-        assertEquals(127, raw[0]);
-        assertEquals(0, raw[1]);
-        assertEquals(0, raw[2]);
-        assertEquals(1, raw[3]);
-
-        ia = InetAddress.getByName(null);
-
-        try {
-            InetAddress.getByName(".0.0.1");
-            fail("expected ex");
-        } catch (UnknownHostException ex) {
-            // expected
-        }
-
-        try {
-            InetAddress.getByName("thereisagoodchancethisdomaindoesnotexist.weirdtld");
-            fail("expected ex");
-        } catch (UnknownHostException ex) {
-            // expected
-        }
-
-        try {
-            InetAddress.getByName("127.0.0.");
-            fail("expected ex");
-        } catch (UnknownHostException ex) {
-            // expected
-        }
-
-        Random random = new Random();
-        int count = 0;
-        for (int i = 0; i < 100; i++) {
-            int index = random.nextInt(HOSTS.length);
-            try {
-                InetAddress.getByName(HOSTS[index]);
-                count++;
-                try {
-                    Thread.sleep(50);
-                } catch (InterruptedException ex) {
-                }
-            } catch (UnknownHostException ex) {
-            }
-        }
-        assertEquals("Not all host lookups succeeded", 100, count);
-    }
-}
diff --git a/tests/CoreTests/android/core/SSLSocketTest.java b/tests/CoreTests/android/core/SSLSocketTest.java
deleted file mode 100644
index 65062c2..0000000
--- a/tests/CoreTests/android/core/SSLSocketTest.java
+++ /dev/null
@@ -1,1094 +0,0 @@
-/*
- * Copyright (C) 2008 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.
- */
-
-package android.core;
-
-import junit.framework.TestCase;
-
-import com.android.org.conscrypt.FileClientSessionCache;
-import com.android.org.conscrypt.OpenSSLContextImpl;
-import com.android.org.conscrypt.SSLClientSessionCache;
-import org.apache.commons.codec.binary.Base64;
-
-import java.io.ByteArrayInputStream;
-import java.io.DataInputStream;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.PrintWriter;
-import java.net.InetSocketAddress;
-import java.net.Socket;
-import java.security.KeyStore;
-import java.security.KeyManagementException;
-import java.security.cert.X509Certificate;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Random;
-
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLServerSocket;
-import javax.net.ssl.SSLSession;
-import javax.net.ssl.SSLSocket;
-import javax.net.ssl.SSLSocketFactory;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.X509TrustManager;
-
-/**
- * SSL integration tests that hit real servers.
- */
-public class SSLSocketTest extends TestCase {
-
-    private static SSLSocketFactory clientFactory =
-            (SSLSocketFactory) SSLSocketFactory.getDefault();
-
-    /**
-     * Does a number of HTTPS requests on some host and consumes the response.
-     * We don't use the HttpsUrlConnection class, but do this on our own
-     * with the SSLSocket class. This gives us a chance to test the basic
-     * behavior of SSL.
-     *
-     * @param host      The host name the request is being sent to.
-     * @param port      The port the request is being sent to.
-     * @param path      The path being requested (e.g. "/index.html").
-     * @param outerLoop The number of times we reconnect and do the request.
-     * @param innerLoop The number of times we do the request for each
-     *                  connection (using HTTP keep-alive).
-     * @param delay     The delay after each request (in seconds).
-     * @throws IOException When a problem occurs.
-     */
-    private void fetch(SSLSocketFactory socketFactory, String host, int port,
-            boolean secure, String path, int outerLoop, int innerLoop,
-            int delay, int timeout) throws IOException {
-        InetSocketAddress address = new InetSocketAddress(host, port);
-
-        for (int i = 0; i < outerLoop; i++) {
-            // Connect to the remote host
-            Socket socket = secure ? socketFactory.createSocket()
-                    : new Socket();
-            if (timeout >= 0) {
-                socket.setKeepAlive(true);
-                socket.setSoTimeout(timeout * 1000);
-            }
-            socket.connect(address);
-
-            // Get the streams
-            OutputStream output = socket.getOutputStream();
-            PrintWriter writer = new PrintWriter(output);
-
-            try {
-                DataInputStream input = new DataInputStream(socket.getInputStream());
-                try {
-                    for (int j = 0; j < innerLoop; j++) {
-                        android.util.Log.d("SSLSocketTest",
-                                "GET https://" + host + path + " HTTP/1.1");
-
-                        // Send a request
-                        writer.println("GET https://" + host + path + " HTTP/1.1\r");
-                        writer.println("Host: " + host + "\r");
-                        writer.println("Connection: " +
-                                (j == innerLoop - 1 ? "Close" : "Keep-Alive")
-                                + "\r");
-                        writer.println("\r");
-                        writer.flush();
-
-                        int length = -1;
-                        boolean chunked = false;
-
-                        String line = input.readLine();
-
-                        if (line == null) {
-                            throw new IOException("No response from server");
-                            // android.util.Log.d("SSLSocketTest", "No response from server");
-                        }
-
-                        // Consume the headers, check content length and encoding type
-                        while (line != null && line.length() != 0) {
-//                    System.out.println(line);
-                            int dot = line.indexOf(':');
-                            if (dot != -1) {
-                                String key = line.substring(0, dot).trim();
-                                String value = line.substring(dot + 1).trim();
-
-                                if ("Content-Length".equalsIgnoreCase(key)) {
-                                    length = Integer.valueOf(value);
-                                } else if ("Transfer-Encoding".equalsIgnoreCase(key)) {
-                                    chunked = "Chunked".equalsIgnoreCase(value);
-                                }
-
-                            }
-                            line = input.readLine();
-                        }
-
-                        assertTrue("Need either content length or chunked encoding", length != -1
-                                || chunked);
-
-                        // Consume the content itself
-                        if (chunked) {
-                            length = Integer.parseInt(input.readLine(), 16);
-                            while (length != 0) {
-                                byte[] buffer = new byte[length];
-                                input.readFully(buffer);
-                                input.readLine();
-                                length = Integer.parseInt(input.readLine(), 16);
-                            }
-                            input.readLine();
-                        } else {
-                            byte[] buffer = new byte[length];
-                            input.readFully(buffer);
-                        }
-
-                        // Sleep for the given number of seconds
-                        try {
-                            Thread.sleep(delay * 1000);
-                        } catch (InterruptedException ex) {
-                            // Shut up!
-                        }
-                    }
-                } finally {
-                    input.close();
-                }
-            } finally {
-                writer.close();
-            }
-            // Close the connection
-            socket.close();
-        }
-    }
-
-    /**
-     * Invokes fetch() with the default socket factory.
-     */
-    private void fetch(String host, int port, boolean secure, String path,
-            int outerLoop, int innerLoop,
-            int delay, int timeout) throws IOException {
-        fetch(clientFactory, host, port, secure, path, outerLoop, innerLoop,
-                delay, timeout);
-    }
-
-    /**
-     * Does a single request for each of the hosts. Consumes the response.
-     *
-     * @throws IOException If a problem occurs.
-     */
-    public void testSimple() throws IOException {
-        fetch("www.fortify.net", 443, true, "/sslcheck.html", 1, 1, 0, 60);
-        fetch("mail.google.com", 443, true, "/mail/", 1, 1, 0, 60);
-        fetch("www.paypal.com", 443, true, "/", 1, 1, 0, 60);
-        fetch("www.yellownet.ch", 443, true, "/", 1, 1, 0, 60);
-    }
-
-    /**
-     * Does repeated requests for each of the hosts, with the connection being
-     * closed in between.
-     *
-     * @throws IOException If a problem occurs.
-     */
-    public void testRepeatedClose() throws IOException {
-        fetch("www.fortify.net", 443, true, "/sslcheck.html", 10, 1, 0, 60);
-        fetch("mail.google.com", 443, true, "/mail/", 10, 1, 0, 60);
-        fetch("www.paypal.com", 443, true, "/", 10, 1, 0, 60);
-        fetch("www.yellownet.ch", 443, true, "/", 10, 1, 0, 60);
-    }
-
-    /**
-     * Does repeated requests for each of the hosts, with the connection being
-     * kept alive in between.
-     *
-     * @throws IOException If a problem occurs.
-     */
-    public void testRepeatedKeepAlive() throws IOException {
-        fetch("www.fortify.net", 443, true, "/sslcheck.html", 1, 10, 0, 60);
-        fetch("mail.google.com", 443, true, "/mail/", 1, 10, 0, 60);
-
-        // These two don't accept keep-alive
-        // fetch("www.paypal.com", 443, "/", 1, 10);
-        // fetch("www.yellownet.ch", 443, "/", 1, 10);
-    }
-
-    /**
-     * Does repeated requests for each of the hosts, with the connection being
-     * closed in between. Waits a couple of seconds after each request, but
-     * stays within a reasonable timeout. Expectation is that the connection
-     * stays open.
-     *
-     * @throws IOException If a problem occurs.
-     */
-    public void testShortTimeout() throws IOException {
-        fetch("www.fortify.net", 443, true, "/sslcheck.html", 1, 10, 5, 60);
-        fetch("mail.google.com", 443, true, "/mail/", 1, 10, 5, 60);
-
-        // These two don't accept keep-alive
-        // fetch("www.paypal.com", 443, "/", 1, 10);
-        // fetch("www.yellownet.ch", 443, "/", 1, 10);
-    }
-
-    /**
-     * Does repeated requests for each of the hosts, with the connection being
-     * kept alive in between. Waits a longer time after each request.
-     * Expectation is that the host closes the connection.
-     */
-    public void testLongTimeout() {
-        // Seems to have a veeeery long timeout.
-        // fetch("www.fortify.net", 443, "/sslcheck.html", 1, 2, 60);
-
-        // Google has a 60s timeout, so 90s of waiting should trigger it.
-        try {
-            fetch("mail.google.com", 443, true, "/mail/", 1, 2, 90, 180);
-            fail("Oops - timeout expected.");
-        } catch (IOException ex) {
-            // Expected.
-        }
-
-        // These two don't accept keep-alive
-        // fetch("www.paypal.com", 443, "/", 1, 10);
-        // fetch("www.yellownet.ch", 443, "/", 1, 10);
-    }
-
-    /**
-     * Does repeated requests for each of the hosts, with the connection being
-     * closed in between. Waits a longer time after each request. Expectation is
-     * that the host closes the connection.
-     */
-    // These two need manual interaction to reproduce...
-    public void xxtestBrokenConnection() {
-        try {
-            fetch("www.fortify.net", 443, true, "/sslcheck.html", 1, 2, 60, 60);
-            fail("Oops - timeout expected.");
-        } catch (IOException ex) {
-            android.util.Log.d("SSLSocketTest", "Exception", ex);
-            // Expected.
-        }
-
-        // These two don't accept keep-alive
-        // fetch("www.paypal.com", 443, "/", 1, 10);
-        // fetch("www.yellownet.ch", 443, "/", 1, 10);
-    }
-
-    /**
-     * Does repeated requests for each of the hosts, with the connection being
-     * closed in between. Waits a longer time after each request. Expectation is
-     * that the host closes the connection.
-     */
-    // These two need manual interaction to reproduce...
-    public void xxtestBrokenConnection2() {
-        try {
-            fetch("www.heise.de", 80, false, "/index.html", 1, 2, 60, 60);
-            fail("Oops - timeout expected.");
-        } catch (IOException ex) {
-            android.util.Log.d("SSLSocketTest", "Exception", ex);
-            // Expected.
-        }
-
-        // These two don't accept keep-alive
-        // fetch("www.paypal.com", 443, "/", 1, 10);
-        // fetch("www.yellownet.ch", 443, "/", 1, 10);
-    }
-
-    /**
-     * Regression test for 865926: SSLContext.init() should
-     * use default values for null arguments.
-     */
-    public void testContextInitNullArgs() throws Exception {
-            SSLContext ctx = SSLContext.getInstance("TLS");
-            ctx.init(null, null, null);
-    }
-
-    /**
-     * Regression test for 963650: javax.net.ssl.KeyManager has no implemented
-     * (documented?) algorithms.
-     */
-    public void testDefaultAlgorithms() throws Exception {
-            SSLContext ctx = SSLContext.getInstance("TLS");
-            KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
-            KeyStore ks = KeyStore.getInstance("BKS");
-
-            assertEquals("X509", kmf.getAlgorithm());
-            assertEquals("X509", KeyManagerFactory.getDefaultAlgorithm());
-
-            assertEquals("BKS", ks.getType());
-            assertEquals("BKS", KeyStore.getDefaultType());
-    }
-
-    /**
-     * Regression test for problem where close() resulted in a hand if
-     * a different thread was sitting in a blocking read or write.
-     */
-    public void testMultithreadedClose() throws Exception {
-            InetSocketAddress address = new InetSocketAddress("www.fortify.net", 443);
-            final Socket socket = clientFactory.createSocket();
-            socket.connect(address);
-
-            Thread reader = new Thread() {
-                @Override
-                public void run() {
-                    try {
-                        byte[] buffer = new byte[512];
-                        InputStream stream = socket.getInputStream();
-                        socket.getInputStream().read(buffer);
-                    } catch (Exception ex) {
-                        android.util.Log.d("SSLSocketTest",
-                                "testMultithreadedClose() reader got " + ex.toString());
-                    }
-                }
-            };
-
-            Thread closer = new Thread() {
-                @Override
-                public void run() {
-                    try {
-                        Thread.sleep(5000);
-                        socket.close();
-                    } catch (Exception ex) {
-                        android.util.Log.d("SSLSocketTest",
-                                "testMultithreadedClose() closer got " + ex.toString());
-                    }
-                }
-            };
-
-            android.util.Log.d("SSLSocketTest", "testMultithreadedClose() starting reader...");
-            reader.start();
-            android.util.Log.d("SSLSocketTest", "testMultithreadedClose() starting closer...");
-            closer.start();
-
-            long t1 = System.currentTimeMillis();
-            android.util.Log.d("SSLSocketTest", "testMultithreadedClose() joining reader...");
-            reader.join(30000);
-            android.util.Log.d("SSLSocketTest", "testMultithreadedClose() joining closer...");
-            closer.join(30000);
-            long t2 = System.currentTimeMillis();
-
-            assertTrue("Concurrent close() hangs", t2 - t1 < 30000);
-    }
-
-    private int multithreadedFetchRuns;
-
-    private int multithreadedFetchWins;
-
-    private Random multithreadedFetchRandom = new Random();
-
-    /**
-     * Regression test for problem where multiple threads with multiple SSL
-     * connection would cause problems due to either missing native locking
-     * or the slowness of the SSL connections.
-     */
-    public void testMultithreadedFetch() {
-        Thread[] threads = new Thread[10];
-
-        for (int i = 0; i < threads.length; i++) {
-            threads[i] = new Thread() {
-                @Override
-                public void run() {
-                    for (int i = 0; i < 10; i++) {
-                        try {
-                            multithreadedFetchRuns++;
-                            switch (multithreadedFetchRandom.nextInt(4)) {
-                                case 0: {
-                                    fetch("www.fortify.net", 443,
-                                            true, "/sslcheck.html", 1, 1, 0, 60);
-                                    break;
-                                }
-
-                                case 1: {
-                                    fetch("mail.google.com", 443, true, "/mail/", 1, 1, 0, 60);
-                                    break;
-                                }
-
-                                case 2: {
-                                    fetch("www.paypal.com", 443, true, "/", 1, 1, 0, 60);
-                                    break;
-                                }
-
-                                case 3: {
-                                    fetch("www.yellownet.ch", 443, true, "/", 1, 1, 0, 60);
-                                    break;
-                                }
-                            }
-                            multithreadedFetchWins++;
-                        } catch (Exception ex) {
-                            android.util.Log.d("SSLSocketTest",
-                                    "testMultithreadedFetch() got Exception", ex);
-                        }
-                    }
-                }
-            };
-            threads[i].start();
-
-            android.util.Log.d("SSLSocketTest", "testMultithreadedFetch() started thread #" + i);
-        }
-
-        for (int i = 0; i < threads.length; i++) {
-            try {
-                threads[i].join();
-                android.util.Log.d("SSLSocketTest", "testMultithreadedFetch() joined thread #" + i);
-            } catch (InterruptedException ex) {
-                // Not interested.
-            }
-        }
-
-        assertTrue("At least 95% of multithreaded SSL connections must succeed",
-                multithreadedFetchWins >= (multithreadedFetchRuns * 95) / 100);
-    }
-
-    // -------------------------------------------------------------------------
-    // Regression test for #1204316: Missing client cert unit test. Passes on
-    // both Android and the RI. To use on the RI, install Apache Commons and
-    // replace the references to the base64-encoded keys by the JKS versions.
-    // -------------------------------------------------------------------------
-    
-    /** 
-     * Defines the keystore contents for the server, JKS version. Holds just a
-     * single self-generated key. The subject name is "Test Server".
-     */
-    private static final String SERVER_KEYS_JKS = 
-        "/u3+7QAAAAIAAAABAAAAAQAFbXlrZXkAAAEaWFfBeAAAArowggK2MA4GCisGAQQBKgIRAQEFAASC" +
-        "AqI2kp5XjnF8YZkhcF92YsJNQkvsmH7zqMM87j23zSoV4DwyE3XeC/gZWq1ToScIhoqZkzlbWcu4" +
-        "T/Zfc/DrfGk/rKbBL1uWKGZ8fMtlZk8KoAhxZk1JSyJvdkyKxqmzUbxk1OFMlN2VJNu97FPVH+du" +
-        "dvjTvmpdoM81INWBW/1fZJeQeDvn4mMbbe0IxgpiLnI9WSevlaDP/sm1X3iO9yEyzHLL+M5Erspo" +
-        "Cwa558fOu5DdsICMXhvDQxjWFKFhPHnKtGe+VvwkG9/bAaDgx3kfhk0w5zvdnkKb+8Ed9ylNRzdk" +
-        "ocAa/mxlMTOsTvDKXjjsBupNPIIj7OP4GNnZaxkJjSs98pEO67op1GX2qhy6FSOPNuq8k/65HzUc" +
-        "PYn6voEeh6vm02U/sjEnzRevQ2+2wXoAdp0EwtQ/DlMe+NvcwPGWKuMgX4A4L93DZGb04N2VmAU3" +
-        "YLOtZwTO0LbuWrcCM/q99G/7LcczkxIVrO2I/rh8RXVczlf9QzcrFObFv4ATuspWJ8xG7DhsMbnk" +
-        "rT94Pq6TogYeoz8o8ZMykesAqN6mt/9+ToIemmXv+e+KU1hI5oLwWMnUG6dXM6hIvrULY6o+QCPH" +
-        "172YQJMa+68HAeS+itBTAF4Clm/bLn6reHCGGU6vNdwU0lYldpiOj9cB3t+u2UuLo6tiFWjLf5Zs" +
-        "EQJETd4g/EK9nHxJn0GAKrWnTw7pEHQJ08elzUuy04C/jEEG+4QXU1InzS4o/kR0Sqz2WTGDoSoq" +
-        "ewuPRU5bzQs/b9daq3mXrnPtRBL6HfSDAdpTK76iHqLCGdqx3avHjVSBm4zFvEuYBCev+3iKOBmg" +
-        "yh7eQRTjz4UOWfy85omMBr7lK8PtfVBDzOXpasxS0uBgdUyBDX4tO6k9jZ8a1kmQRQAAAAEABVgu" +
-        "NTA5AAACSDCCAkQwggGtAgRIR8SKMA0GCSqGSIb3DQEBBAUAMGkxCzAJBgNVBAYTAlVTMRMwEQYD" +
-        "VQQIEwpDYWxpZm9ybmlhMQwwCgYDVQQHEwNNVFYxDzANBgNVBAoTBkdvb2dsZTEQMA4GA1UECxMH" +
-        "QW5kcm9pZDEUMBIGA1UEAxMLVGVzdCBTZXJ2ZXIwHhcNMDgwNjA1MTA0ODQyWhcNMDgwOTAzMTA0" +
-        "ODQyWjBpMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8w" +
-        "DQYDVQQKEwZHb29nbGUxEDAOBgNVBAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMIGf" +
-        "MA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwoC6chqCI84rj1PrXuJgbiit4EV909zR6N0jNlYfg" +
-        "itwB39bP39wH03rFm8T59b3mbSptnGmCIpLZn25KPPFsYD3JJ+wFlmiUdEP9H05flfwtFQJnw9uT" +
-        "3rRIdYVMPcQ3RoZzwAMliGr882I2thIDbA6xjGU/1nRIdvk0LtxH3QIDAQABMA0GCSqGSIb3DQEB" +
-        "BAUAA4GBAJn+6YgUlY18Ie+0+Vt8oEi81DNi/bfPrAUAh63fhhBikx/3R9dl3wh09Z6p7cIdNxjW" +
-        "n2ll+cRW9eqF7z75F0Omm0C7/KAEPjukVbszmzeU5VqzkpSt0j84YWi+TfcHRrfvhLbrlmGITVpY" +
-        "ol5pHLDyqGmDs53pgwipWqsn/nEXEBgj3EoqPeqHbDf7YaP8h/5BSt0=";
-
-    /** 
-     * Defines the keystore contents for the server, BKS version. Holds just a
-     * single self-generated key. The subject name is "Test Server".
-     */
-    private static final String SERVER_KEYS_BKS = 
-        "AAAAAQAAABQDkebzoP1XwqyWKRCJEpn/t8dqIQAABDkEAAVteWtleQAAARpYl20nAAAAAQAFWC41" +
-        "MDkAAAJNMIICSTCCAbKgAwIBAgIESEfU1jANBgkqhkiG9w0BAQUFADBpMQswCQYDVQQGEwJVUzET" +
-        "MBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8wDQYDVQQKEwZHb29nbGUxEDAOBgNV" +
-        "BAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMB4XDTA4MDYwNTExNTgxNFoXDTA4MDkw" +
-        "MzExNTgxNFowaTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01U" +
-        "VjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdBbmRyb2lkMRQwEgYDVQQDEwtUZXN0IFNlcnZl" +
-        "cjCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA0LIdKaIr9/vsTq8BZlA3R+NFWRaH4lGsTAQy" +
-        "DPMF9ZqEDOaL6DJuu0colSBBBQ85hQTPa9m9nyJoN3pEi1hgamqOvQIWcXBk+SOpUGRZZFXwniJV" +
-        "zDKU5nE9MYgn2B9AoiH3CSuMz6HRqgVaqtppIe1jhukMc/kHVJvlKRNy9XMCAwEAATANBgkqhkiG" +
-        "9w0BAQUFAAOBgQC7yBmJ9O/eWDGtSH9BH0R3dh2NdST3W9hNZ8hIa8U8klhNHbUCSSktZmZkvbPU" +
-        "hse5LI3dh6RyNDuqDrbYwcqzKbFJaq/jX9kCoeb3vgbQElMRX8D2ID1vRjxwlALFISrtaN4VpWzV" +
-        "yeoHPW4xldeZmoVtjn8zXNzQhLuBqX2MmAAAAqwAAAAUvkUScfw9yCSmALruURNmtBai7kQAAAZx" +
-        "4Jmijxs/l8EBaleaUru6EOPioWkUAEVWCxjM/TxbGHOi2VMsQWqRr/DZ3wsDmtQgw3QTrUK666sR" +
-        "MBnbqdnyCyvM1J2V1xxLXPUeRBmR2CXorYGF9Dye7NkgVdfA+9g9L/0Au6Ugn+2Cj5leoIgkgApN" +
-        "vuEcZegFlNOUPVEs3SlBgUF1BY6OBM0UBHTPwGGxFBBcetcuMRbUnu65vyDG0pslT59qpaR0TMVs" +
-        "P+tcheEzhyjbfM32/vwhnL9dBEgM8qMt0sqF6itNOQU/F4WGkK2Cm2v4CYEyKYw325fEhzTXosck" +
-        "MhbqmcyLab8EPceWF3dweoUT76+jEZx8lV2dapR+CmczQI43tV9btsd1xiBbBHAKvymm9Ep9bPzM" +
-        "J0MQi+OtURL9Lxke/70/MRueqbPeUlOaGvANTmXQD2OnW7PISwJ9lpeLfTG0LcqkoqkbtLKQLYHI" +
-        "rQfV5j0j+wmvmpMxzjN3uvNajLa4zQ8l0Eok9SFaRr2RL0gN8Q2JegfOL4pUiHPsh64WWya2NB7f" +
-        "V+1s65eA5ospXYsShRjo046QhGTmymwXXzdzuxu8IlnTEont6P4+J+GsWk6cldGbl20hctuUKzyx" +
-        "OptjEPOKejV60iDCYGmHbCWAzQ8h5MILV82IclzNViZmzAapeeCnexhpXhWTs+xDEYSKEiG/camt" +
-        "bhmZc3BcyVJrW23PktSfpBQ6D8ZxoMfF0L7V2GQMaUg+3r7ucrx82kpqotjv0xHghNIm95aBr1Qw" +
-        "1gaEjsC/0wGmmBDg1dTDH+F1p9TInzr3EFuYD0YiQ7YlAHq3cPuyGoLXJ5dXYuSBfhDXJSeddUkl" +
-        "k1ufZyOOcskeInQge7jzaRfmKg3U94r+spMEvb0AzDQVOKvjjo1ivxMSgFRZaDb/4qw=";
-    
-    /** 
-     * Defines the keystore contents for the client, JKS version. Holds just a
-     * single self-generated key. The subject name is "Test Client".
-     */
-    private static final String CLIENT_KEYS_JKS = 
-        "/u3+7QAAAAIAAAABAAAAAQAFbXlrZXkAAAEaWFhyMAAAArkwggK1MA4GCisGAQQBKgIRAQEFAASC" +
-        "AqGVSfXolBStZy4nnRNn4fAr+S7kfU2BS23wwW8uB2Ru3GvtLzlK9q08Gvq/LNqBafjyFTVL5FV5" +
-        "SED/8YomO5a98GpskSeRvytCiTBLJdgGhws5TOGekgIAcBROPGIyOtJPQ0HfOQs+BqgzGDHzHQhw" +
-        "u/8Tm6yQwiP+W/1I9B1QnaEztZA3mhTyMMJsmsFTYroGgAog885D5Cmzd8sYGfxec3R6I+xcmBAY" +
-        "eibR5kGpWwt1R+qMvRrtBqh5r6WSKhCBNax+SJVbtUNRiKyjKccdJg6fGqIWWeivwYTy0OhjA6b4" +
-        "NiZ/ZZs5pxFGWUj/Rlp0RYy8fCF6aw5/5s4Bf4MI6dPSqMG8Hf7sJR91GbcELyzPdM0h5lNavgit" +
-        "QPEzKeuDrGxhY1frJThBsNsS0gxeu+OgfJPEb/H4lpYX5IvuIGbWKcxoO9zq4/fimIZkdA8A+3eY" +
-        "mfDaowvy65NBVQPJSxaOyFhLHfeLqOeCsVENAea02vA7andZHTZehvcrqyKtm+z8ncHGRC2H9H8O" +
-        "jKwKHfxxrYY/jMAKLl00+PBb3kspO+BHI2EcQnQuMw/zr83OR9Meq4TJ0TMuNkApZELAeFckIBbS" +
-        "rBr8NNjAIfjuCTuKHhsTFWiHfk9ZIzigxXagfeDRiyVc6khOuF/bGorj23N2o7Rf3uLoU6PyXWi4" +
-        "uhctR1aL6NzxDoK2PbYCeA9hxbDv8emaVPIzlVwpPK3Ruvv9mkjcOhZ74J8bPK2fQmbplbOljcZi" +
-        "tZijOfzcO/11JrwhuJZRA6wanTqHoujgChV9EukVrmbWGGAcewFnAsSbFXIik7/+QznXaDIt5NgL" +
-        "H/Bcz4Z/fdV7Ae1eUaxKXdPbI//4J+8liVT/d8awjW2tldIaDlmGMR3aoc830+3mAAAAAQAFWC41" +
-        "MDkAAAJIMIICRDCCAa0CBEhHxLgwDQYJKoZIhvcNAQEEBQAwaTELMAkGA1UEBhMCVVMxEzARBgNV" +
-        "BAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01UVjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdB" +
-        "bmRyb2lkMRQwEgYDVQQDEwtUZXN0IENsaWVudDAeFw0wODA2MDUxMDQ5MjhaFw0wODA5MDMxMDQ5" +
-        "MjhaMGkxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMQwwCgYDVQQHEwNNVFYxDzAN" +
-        "BgNVBAoTBkdvb2dsZTEQMA4GA1UECxMHQW5kcm9pZDEUMBIGA1UEAxMLVGVzdCBDbGllbnQwgZ8w" +
-        "DQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAIK3Q+KiFbmCGg422TAo4gggdhMH6FJhiuz8DxRyeMKR" +
-        "UAfP4MK0wtc8N42waZ6OKvxpBFUy0BRfBsX0GD4Ku99yu9/tavSigTraeJtwV3WWRRjIqk7L3wX5" +
-        "cmgS2KSD43Y0rNUKrko26lnt9N4qiYRBSj+tcAN3Lx9+ptqk1LApAgMBAAEwDQYJKoZIhvcNAQEE" +
-        "BQADgYEANb7Q1GVSuy1RPJ0FmiXoMYCCtvlRLkmJphwxovK0cAQK12Vll+yAzBhHiQHy/RA11mng" +
-        "wYudC7u3P8X/tBT8GR1Yk7QW3KgFyPafp3lQBBCraSsfrjKj+dCLig1uBLUr4f68W8VFWZWWTHqp" +
-        "NMGpCX6qmjbkJQLVK/Yfo1ePaUexPSOX0G9m8+DoV3iyNw6at01NRw==";
-
-    /** 
-     * Defines the keystore contents for the client, BKS version. Holds just a
-     * single self-generated key. The subject name is "Test Client".
-     */
-    private static final String CLIENT_KEYS_BKS = 
-        "AAAAAQAAABT4Rka6fxbFps98Y5k2VilmbibNkQAABfQEAAVteWtleQAAARpYl+POAAAAAQAFWC41" +
-        "MDkAAAJNMIICSTCCAbKgAwIBAgIESEfU9TANBgkqhkiG9w0BAQUFADBpMQswCQYDVQQGEwJVUzET" +
-        "MBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8wDQYDVQQKEwZHb29nbGUxEDAOBgNV" +
-        "BAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgQ2xpZW50MB4XDTA4MDYwNTExNTg0NVoXDTA4MDkw" +
-        "MzExNTg0NVowaTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01U" +
-        "VjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdBbmRyb2lkMRQwEgYDVQQDEwtUZXN0IENsaWVu" +
-        "dDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEApUvmWsQDHPpbDKK13Yez2/q54tTOmRml/qva" +
-        "2K6dZjkjSTW0iRuk7ztaVEvdJpfVIDv1oBsCI51ttyLHROy1epjF+GoL74mJb7fkcd0VOoSOTjtD" +
-        "+3GgZkHPAm5YmUYxiJXqxKKJJqMCTIW46eJaA2nAep9QIwZ14/NFAs4ObV8CAwEAATANBgkqhkiG" +
-        "9w0BAQUFAAOBgQCJrCr3hZQFDlLIfsSKI1/w+BLvyf4fubOid0pBxfklR8KBNPTiqjSmu7pd/C/F" +
-        "1FR8CdZUDoPflZHCOU+fj5r5KUC1HyigY/tEUvlforBpfB0uCF+tXW4DbUfOWhfMtLV4nCOJOOZg" +
-        "awfZLJWBJouLKOp427vDftxTSB+Ks8YjlgAAAqwAAAAU+NH6TtrzjyDdCXm5B6Vo7xX5G4YAAAZx" +
-        "EAUkcZtmykn7YdaYxC1jRFJ+GEJpC8nZVg83QClVuCSIS8a5f8Hl44Bk4oepOZsPzhtz3RdVzDVi" +
-        "RFfoyZFsrk9F5bDTVJ6sQbb/1nfJkLhZFXokka0vND5AXMSoD5Bj1Fqem3cK7fSUyqKvFoRKC3XD" +
-        "FQvhqoam29F1rbl8FaYdPvhhZo8TfZQYUyUKwW+RbR44M5iHPx+ykieMe/C/4bcM3z8cwIbYI1aO" +
-        "gjQKS2MK9bs17xaDzeAh4sBKrskFGrDe+2dgvrSKdoakJhLTNTBSG6m+rzqMSCeQpafLKMSjTSSz" +
-        "+KoQ9bLyax8cbvViGGju0SlVhquloZmKOfHr8TukIoV64h3uCGFOVFtQjCYDOq6NbfRvMh14UVF5" +
-        "zgDIGczoD9dMoULWxBmniGSntoNgZM+QP6Id7DBasZGKfrHIAw3lHBqcvB5smemSu7F4itRoa3D8" +
-        "N7hhUEKAc+xA+8NKmXfiCBoHfPHTwDvt4IR7gWjeP3Xv5vitcKQ/MAfO5RwfzkYCXQ3FfjfzmsE1" +
-        "1IfLRDiBj+lhQSulhRVStKI88Che3M4JUNGKllrc0nt1pWa1vgzmUhhC4LSdm6trTHgyJnB6OcS9" +
-        "t2furYjK88j1AuB4921oxMxRm8c4Crq8Pyuf+n3YKi8Pl2BzBtw++0gj0ODlgwut8SrVj66/nvIB" +
-        "jN3kLVahR8nZrEFF6vTTmyXi761pzq9yOVqI57wJGx8o3Ygox1p+pWUPl1hQR7rrhUbgK/Q5wno9" +
-        "uJk07h3IZnNxE+/IKgeMTP/H4+jmyT4mhsexJ2BFHeiKF1KT/FMcJdSi+ZK5yoNVcYuY8aZbx0Ef" +
-        "lHorCXAmLFB0W6Cz4KPP01nD9YBB4olxiK1t7m0AU9zscdivNiuUaB5OIEr+JuZ6dNw=";    
-    /** 
-     * Defines the password for the keystore.
-     */
-    private static final String PASSWORD = "android";
-            
-    /** 
-     * Implements basically a dummy TrustManager. It stores the certificate
-     * chain it sees, so it can later be queried.
-     */
-    class TestTrustManager implements X509TrustManager {
-        
-        private X509Certificate[] chain;
-        
-        private String authType;
-        
-        public void checkClientTrusted(X509Certificate[] chain, String authType) {
-            this.chain = chain;
-            this.authType = authType;
-        }
-
-        public void checkServerTrusted(X509Certificate[] chain, String authType) {
-            this.chain = chain;
-            this.authType = authType;
-        }
-
-        public X509Certificate[] getAcceptedIssuers() {
-            return new X509Certificate[0];
-        }
-
-        public X509Certificate[] getChain() {
-            return chain;
-        }
-        
-        public String getAuthType() {
-            return authType;
-        }
-        
-    }
-    
-    /** 
-     * Implements a test SSL socket server. It wait for a connection on a given
-     * port, requests client authentication (if specified), and read 256 bytes
-     * from the socket. 
-     */
-    class TestServer implements Runnable {
-
-        public static final int CLIENT_AUTH_NONE = 0;
-
-        public static final int CLIENT_AUTH_WANTED = 1;
-
-        public static final int CLIENT_AUTH_NEEDED = 2;
-        
-        private TestTrustManager trustManager;
-
-        private Exception exception;
-
-        private int port;
-        
-        private int clientAuth;
-        
-        private boolean provideKeys;
-
-        public TestServer(int port, boolean provideKeys, int clientAuth) {
-            this.port = port;
-            this.clientAuth = clientAuth;
-            this.provideKeys = provideKeys;
-            
-            trustManager = new TestTrustManager(); 
-        }
-        
-        public void run() {
-            try {
-                KeyManager[] keyManagers = provideKeys
-                        ? getKeyManagers(SERVER_KEYS_BKS) : null;
-                TrustManager[] trustManagers = new TrustManager[] {
-                        trustManager };
-
-                SSLContext sslContext = SSLContext.getInstance("TLS");
-                sslContext.init(keyManagers, trustManagers, null);
-                
-                SSLServerSocket serverSocket
-                        = (SSLServerSocket) sslContext.getServerSocketFactory()
-                        .createServerSocket();
-                
-                if (clientAuth == CLIENT_AUTH_WANTED) {
-                    serverSocket.setWantClientAuth(true);
-                } else if (clientAuth == CLIENT_AUTH_NEEDED) {
-                    serverSocket.setNeedClientAuth(true);
-                } else {
-                    serverSocket.setWantClientAuth(false);
-                }
-                
-                serverSocket.bind(new InetSocketAddress(port));
-                
-                SSLSocket clientSocket = (SSLSocket) serverSocket.accept();
-
-                InputStream stream = clientSocket.getInputStream();
-
-                for (int i = 0; i < 256; i++) {
-                    int j = stream.read();
-                    if (i != j) {
-                        throw new RuntimeException("Error reading socket,"
-                                + " expected " + i + ", got " + j);
-                    }
-                }
-                
-                stream.close();
-                clientSocket.close();
-                serverSocket.close();
-                
-            } catch (Exception ex) {
-                exception = ex;
-            }
-        }
-
-        public Exception getException() {
-            return exception;
-        }
-        
-        public X509Certificate[] getChain() {
-            return trustManager.getChain();
-        }
-        
-    }
-
-    /** 
-     * Implements a test SSL socket client. It open a connection to localhost on
-     * a given port and writes 256 bytes to the socket. 
-     */
-    class TestClient implements Runnable {
-        
-        private TestTrustManager trustManager;
-
-        private Exception exception;
-        
-        private int port;
-        
-        private boolean provideKeys;
-        
-        public TestClient(int port, boolean provideKeys) {
-            this.port = port;
-            this.provideKeys = provideKeys;
-            
-            trustManager = new TestTrustManager(); 
-        }
-        
-        public void run() {
-            try {
-                KeyManager[] keyManagers = provideKeys
-                        ? getKeyManagers(CLIENT_KEYS_BKS) : null;
-                TrustManager[] trustManagers = new TrustManager[] {
-                        trustManager };
-
-                SSLContext sslContext = SSLContext.getInstance("TLS");
-                sslContext.init(keyManagers, trustManagers, null);
-                
-                SSLSocket socket = (SSLSocket) sslContext.getSocketFactory()
-                        .createSocket();
-
-                socket.connect(new InetSocketAddress(port));
-                socket.startHandshake();
-
-                OutputStream stream = socket.getOutputStream();
-                
-                for (int i = 0; i < 256; i++) {
-                    stream.write(i);
-                }
-                
-                stream.flush();
-                stream.close();
-                socket.close();
-                
-            } catch (Exception ex) {
-                exception = ex;
-            }
-        }
-
-        public Exception getException() {
-            return exception;
-        }
-
-        public X509Certificate[] getChain() {
-            return trustManager.getChain();
-        }
-        
-    }
-    
-    /**
-     * Loads a keystore from a base64-encoded String. Returns the KeyManager[]
-     * for the result.
-     */
-    private KeyManager[] getKeyManagers(String keys) throws Exception {
-        byte[] bytes = new Base64().decode(keys.getBytes());                    
-        InputStream inputStream = new ByteArrayInputStream(bytes);
-        
-        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
-        keyStore.load(inputStream, PASSWORD.toCharArray());
-        inputStream.close();
-        
-        String algorithm = KeyManagerFactory.getDefaultAlgorithm();
-        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm);
-        keyManagerFactory.init(keyStore, PASSWORD.toCharArray());
-        
-        return keyManagerFactory.getKeyManagers();
-    }
-
-    /**
-     * Implements the actual test case. Launches a server and a client, requires
-     * client authentication and checks the certificates afterwards (not in the
-     * usual sense, we just make sure that we got the expected certificates,
-     * because our self-signed test certificates are not valid.)
-     */
-    public void testClientAuth() {
-        try {
-            TestServer server = new TestServer(8088, true, TestServer.CLIENT_AUTH_WANTED);
-            TestClient client = new TestClient(8088, true);
-            
-            Thread serverThread = new Thread(server);
-            Thread clientThread = new Thread(client);
-            
-            serverThread.start();
-            clientThread.start();
-            
-            serverThread.join();
-            clientThread.join();
-            
-            // The server must have completed without an exception.
-            if (server.getException() != null) {
-                throw new RuntimeException(server.getException());
-            }
-
-            // The client must have completed without an exception.
-            if (client.getException() != null) {
-                throw new RuntimeException(client.getException());
-            }
-            
-            // Caution: The clientChain is the certificate chain from our
-            // client object. It contains the server certificates, of course!
-            X509Certificate[] clientChain = client.getChain();
-            assertTrue("Client cert chain must not be null", clientChain != null);
-            assertTrue("Client cert chain must not be empty", clientChain.length != 0);
-            assertEquals("CN=Test Server, OU=Android, O=Google, L=MTV, ST=California, C=US", clientChain[0].getSubjectDN().toString());
-            // Important part ------^
-            
-            // Caution: The serverChain is the certificate chain from our
-            // server object. It contains the client certificates, of course!
-            X509Certificate[] serverChain = server.getChain();
-            assertTrue("Server cert chain must not be null", serverChain != null);
-            assertTrue("Server cert chain must not be empty", serverChain.length != 0);
-            assertEquals("CN=Test Client, OU=Android, O=Google, L=MTV, ST=California, C=US", serverChain[0].getSubjectDN().toString());
-            // Important part ------^
-            
-        } catch (Exception ex) {
-            throw new RuntimeException(ex);
-        }
-    }
-
-    // -------------------------------------------------------------------------
-    private SSLSocket handshakeSocket;
-
-    private Exception handshakeException;
-
-    
-    public void testSSLHandshakeHangTimeout() {
-        
-        Thread thread = new Thread() {
-            @Override
-            public void run() {
-                try {
-                    SSLSocket socket = (SSLSocket)clientFactory.createSocket(
-                            "www.heise.de", 80);
-                    socket.setSoTimeout(5000);
-                    socket.startHandshake();
-                    socket.close();
-                } catch (Exception ex) {
-                    handshakeException = ex;
-                }
-            }
-        };
-        
-        thread.start();
-        
-        try {
-            thread.join(10000);
-        } catch (InterruptedException ex) {
-            // Ignore.
-        }
-        
-        if (handshakeException == null) {
-            fail("SSL handshake should have failed.");
-        }
-    }
-
-    public void testSSLHandshakeHangClose() {
-        
-        Thread thread = new Thread() {
-            @Override
-            public void run() {
-                try {
-                    handshakeSocket = (SSLSocket)clientFactory.createSocket(
-                            "www.heise.de", 80);
-                    handshakeSocket.startHandshake();
-                } catch (Exception ex) {
-                    handshakeException = ex;
-                }
-            }
-        };
-        
-        thread.start();
-
-        
-        try {
-            Thread.sleep(5000);
-            try {
-                handshakeSocket.close();
-            } catch (Exception ex) {
-                throw new RuntimeException(ex);
-            }
-
-            thread.join(5000);
-        } catch (InterruptedException ex) {
-            // Ignore.
-        }
-        
-        if (handshakeException == null) {
-            fail("SSL handshake should have failed.");
-        }
-    }
-
-    /**
-     * Tests our in-memory and persistent caching support.
-     */
-    public void testClientSessionCaching() throws IOException,
-            KeyManagementException {
-        OpenSSLContextImpl context = OpenSSLContextImpl.getPreferred();
-
-        // Cache size = 2.
-        FakeClientSessionCache fakeCache = new FakeClientSessionCache();
-        context.engineInit(null, null, null);
-        context.engineGetClientSessionContext().setPersistentCache(fakeCache);
-        SSLSocketFactory socketFactory = context.engineGetSocketFactory();
-        context.engineGetClientSessionContext().setSessionCacheSize(2);
-        makeRequests(socketFactory);
-        List<String> smallCacheOps = Arrays.asList(
-                "get www.fortify.net",
-                "put www.fortify.net",
-                "get www.paypal.com",
-                "put www.paypal.com",
-                "get www.yellownet.ch",
-                "put www.yellownet.ch",
-
-                // At this point, all in-memory cache requests should miss,
-                // but the sessions will still be in the persistent cache.
-                "get www.fortify.net",
-                "get www.paypal.com",
-                "get www.yellownet.ch"
-        );
-        assertEquals(smallCacheOps, fakeCache.ops);
-
-        // Cache size = 3.
-        fakeCache = new FakeClientSessionCache();
-        context.engineInit(null, null, null);
-        context.engineGetClientSessionContext().setPersistentCache(fakeCache);
-        socketFactory = context.engineGetSocketFactory();
-        context.engineGetClientSessionContext().setSessionCacheSize(3);
-        makeRequests(socketFactory);
-        List<String> bigCacheOps = Arrays.asList(
-                "get www.fortify.net",
-                "put www.fortify.net",
-                "get www.paypal.com",
-                "put www.paypal.com",
-                "get www.yellownet.ch",
-                "put www.yellownet.ch"
-
-                // At this point, all results should be in the in-memory
-                // cache, and the persistent cache shouldn't be hit anymore.
-        );
-        assertEquals(bigCacheOps, fakeCache.ops);
-
-        // Cache size = 4.
-        fakeCache = new FakeClientSessionCache();
-        context.engineInit(null, null, null);
-        context.engineGetClientSessionContext().setPersistentCache(fakeCache);
-        socketFactory = context.engineGetSocketFactory();
-        context.engineGetClientSessionContext().setSessionCacheSize(4);
-        makeRequests(socketFactory);
-        assertEquals(bigCacheOps, fakeCache.ops);
-    }
-
-    /**
-     * Executes sequence of requests twice using given socket factory.
-     */
-    private void makeRequests(SSLSocketFactory socketFactory)
-            throws IOException {
-        for (int i = 0; i < 2; i++) {
-            fetch(socketFactory, "www.fortify.net", 443, true, "/sslcheck.html",
-                    1, 1, 0, 60);
-            fetch(socketFactory, "www.paypal.com", 443, true, "/",
-                    1, 1, 0, 60);
-            fetch(socketFactory, "www.yellownet.ch", 443, true, "/",
-                    1, 1, 0, 60);
-        }
-    }
-
-    /**
-     * Fake in the sense that it doesn't actually persist anything.
-     */
-    static class FakeClientSessionCache implements SSLClientSessionCache {
-
-        List<String> ops = new ArrayList<String>();
-        Map<String, byte[]> sessions = new HashMap<String, byte[]>();
-
-        public byte[] getSessionData(String host, int port) {
-            ops.add("get " + host);
-            return sessions.get(host);
-        }
-
-        public void putSessionData(SSLSession session, byte[] sessionData) {
-            String host = session.getPeerHost();
-            System.err.println("length: " + sessionData.length);
-            ops.add("put " + host);
-            sessions.put(host, sessionData);
-        }
-    }
-
-    public void testFileBasedClientSessionCache() throws IOException,
-            KeyManagementException {
-        OpenSSLContextImpl context = OpenSSLContextImpl.getPreferred();
-        String tmpDir = System.getProperty("java.io.tmpdir");
-        if (tmpDir == null) {
-            fail("Please set 'java.io.tmpdir' system property.");
-        }
-        File cacheDir = new File(tmpDir
-                + "/" + SSLSocketTest.class.getName() + "/cache");
-        deleteDir(cacheDir);
-        SSLClientSessionCache fileCache
-                = FileClientSessionCache.usingDirectory(cacheDir);
-        try {
-            ClientSessionCacheProxy cacheProxy
-                    = new ClientSessionCacheProxy(fileCache);
-            context.engineInit(null, null, null);
-            context.engineGetClientSessionContext().setPersistentCache(cacheProxy);
-            SSLSocketFactory socketFactory = context.engineGetSocketFactory();
-            context.engineGetClientSessionContext().setSessionCacheSize(1);
-            makeRequests(socketFactory);
-            List<String> expected = Arrays.asList(
-                    "unsuccessful get www.fortify.net",
-                    "put www.fortify.net",
-                    "unsuccessful get www.paypal.com",
-                    "put www.paypal.com",
-                    "unsuccessful get www.yellownet.ch",
-                    "put www.yellownet.ch",
-
-                    // At this point, all in-memory cache requests should miss,
-                    // but the sessions will still be in the persistent cache.
-                    "successful get www.fortify.net",
-                    "successful get www.paypal.com",
-                    "successful get www.yellownet.ch"
-            );
-            assertEquals(expected, cacheProxy.ops);
-
-            // Try again now that file-based cache is populated.
-            fileCache = FileClientSessionCache.usingDirectory(cacheDir);
-            cacheProxy = new ClientSessionCacheProxy(fileCache);
-            context.engineInit(null, null, null);
-            context.engineGetClientSessionContext().setPersistentCache(cacheProxy);
-            socketFactory = context.engineGetSocketFactory();
-            context.engineGetClientSessionContext().setSessionCacheSize(1);
-            makeRequests(socketFactory);
-            expected = Arrays.asList(
-                    "successful get www.fortify.net",
-                    "successful get www.paypal.com",
-                    "successful get www.yellownet.ch",
-                    "successful get www.fortify.net",
-                    "successful get www.paypal.com",
-                    "successful get www.yellownet.ch"
-            );
-            assertEquals(expected, cacheProxy.ops);
-        } finally {
-            deleteDir(cacheDir);
-        }
-    }
-
-    private static void deleteDir(File directory) {
-        if (!directory.exists()) {
-            return;
-        }
-        for (File file : directory.listFiles()) {
-            file.delete();
-        }
-        directory.delete();
-    }
-
-    static class ClientSessionCacheProxy implements SSLClientSessionCache {
-
-        final SSLClientSessionCache delegate;
-        final List<String> ops = new ArrayList<String>();
-
-        ClientSessionCacheProxy(SSLClientSessionCache delegate) {
-            this.delegate = delegate;
-        }
-
-        public byte[] getSessionData(String host, int port) {
-            byte[] sessionData = delegate.getSessionData(host, port);
-            ops.add((sessionData == null ? "unsuccessful" : "successful")
-                    + " get " + host);
-            return sessionData;
-        }
-
-        public void putSessionData(SSLSession session, byte[] sessionData) {
-            delegate.putSessionData(session, sessionData);
-            ops.add("put " + session.getPeerHost());
-        }
-    }
-
-    public static void main(String[] args) throws KeyManagementException, IOException {
-        new SSLSocketTest().testFileBasedClientSessionCache();
-    }
-}
diff --git a/tests/CoreTests/android/core/SocketTest.java b/tests/CoreTests/android/core/SocketTest.java
deleted file mode 100644
index 9db6077..0000000
--- a/tests/CoreTests/android/core/SocketTest.java
+++ /dev/null
@@ -1,294 +0,0 @@
-/*
- * Copyright (C) 2008 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.
- */
-
-package android.core;
-
-import junit.framework.Assert;
-import junit.framework.TestCase;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.ServerSocket;
-import java.net.Socket;
-import java.net.SocketException;
-import java.net.SocketTimeoutException;
-import java.nio.channels.SocketChannel;
-import java.util.concurrent.Semaphore;
-
-import android.test.suitebuilder.annotation.LargeTest;
-import android.test.suitebuilder.annotation.SmallTest;
-import android.test.suitebuilder.annotation.Suppress;
-
-/**
- * Regression tests for various socket related problems. And a few general
- * socket tests.
- */
-public class SocketTest extends TestCase {
-
-    private static final String NON_EXISTING_ADDRESS = "123.123.123.123";
-
-    private static final String KNOW_GOOD_ADDRESS = "209.85.129.147";
-
-    private static final String PACKAGE_DROPPING_ADDRESS = "191.167.0.1";
-    
-    // Test for basic bind/connect/accept behavior.
-    @SmallTest
-    public void testSocketSimple() throws Exception {
-        ServerSocket ss;
-        Socket s, s1;
-        int port;
-
-        IOException lastEx = null;
-
-        ss = new ServerSocket();
-
-        for (port = 9900; port < 9999; port++) {
-            try {
-                ss.bind(new InetSocketAddress("127.0.0.1", port));
-                lastEx = null;
-                break;
-            } catch (IOException ex) {
-                lastEx = ex;
-            }
-        }
-
-        if (lastEx != null) {
-            throw lastEx;
-        }
-
-        s = new Socket("127.0.0.1", port);
-
-        s1 = ss.accept();
-
-        s.getOutputStream().write(0xa5);
-
-        assertEquals(0xa5, s1.getInputStream().read());
-
-        s1.getOutputStream().write(0x5a);
-        assertEquals(0x5a, s.getInputStream().read());
-    }
-    
-    // Regression test for #820068: Wildcard address
-    @SmallTest
-    public void testWildcardAddress() throws Exception {
-        Socket s2 = new Socket();
-        s2.bind(new InetSocketAddress((InetAddress) null, 12345));
-        byte[] addr = s2.getLocalAddress().getAddress();
-        for (int i = 0; i < 4; i++) {
-            assertEquals("Not the wildcard address", 0, addr[i]);
-        }
-    }
-    
-    // Regression test for #865753: server sockets not closing properly
-    @SmallTest
-    public void testServerSocketClose() throws Exception {
-        ServerSocket s3 = new ServerSocket(23456);
-        s3.close();
-        ServerSocket s4 = new ServerSocket(23456);
-        s4.close();
-    }
-    
-    // Regression test for #876985: SO_REUSEADDR not working properly
-    
-    private Exception serverError = null;
-    
-    @LargeTest
-    public void testSetReuseAddress() throws IOException {
-        InetSocketAddress addr = new InetSocketAddress(8383);
-
-        final ServerSocket serverSock = new ServerSocket();
-        serverSock.setReuseAddress(true);
-        serverSock.bind(addr);
-
-        final Semaphore semThreadEnd = new Semaphore(0);
-        new Thread() {
-            @Override
-            public void run() {
-                try {
-                    Socket sock = serverSock.accept();
-                    sock.getInputStream().read();
-                    sock.close();
-                } catch (IOException e) {
-                    serverError = e;
-                }
-                semThreadEnd.release();
-            }
-        }.start();
-
-        // Give the server a bit of time for startup
-        try {
-            Thread.sleep(2000);
-        } catch (InterruptedException ex) {
-            // Ignored.
-        }
-        
-        Socket client = new Socket("localhost", 8383);
-        client.getOutputStream().write(1);
-        // Just leave this connection open from the client side. It will be
-        // closed from the server side so the server stays in the TIME_WAIT
-        // state for a while. setReuseAddress() should be able to handle this.
-
-        try {
-            semThreadEnd.acquire();
-        } catch (InterruptedException e) {
-            // ignore
-        }
-        serverSock.close();
-
-        ServerSocket serverSock2 = new ServerSocket();
-        serverSock2.setReuseAddress(true);
-        serverSock2.bind(addr);
-        serverSock2.close();
-        
-        if (serverError != null) {
-            throw new RuntimeException("Server must complete without error", serverError);
-        }
-    }
-
-    // Regression for 916701, a wrong exception was thrown after timeout of
-    // a ServerSocket.
-    @LargeTest
-    public void testTimeoutException() throws IOException {
-        ServerSocket s = new ServerSocket(9800);
-        s.setSoTimeout(2000);
-        try {
-            s.accept();
-        } catch (SocketTimeoutException e) {
-            // this is ok.
-        }
-    }
-
-    // Regression for issue 1001980, openening a SocketChannel threw an Exception
-    @SmallTest
-    public void testNativeSocketChannelOpen() throws IOException {
-        SocketChannel.open();
-    }
-
-// Regression test for issue 1018016, connecting ignored a set timeout.
-//
-// Disabled because test behaves differently depending on networking
-// environment. It works fine in the emulator and one the device with
-// WLAN, but when 3G comes into play, the possible existence of a
-// proxy makes it fail.
-//
-//    @LargeTest
-//    public void testSocketSetSOTimeout() throws IOException {
-//        Socket sock = new Socket();
-//        int timeout = 5000;
-//        long start = System.currentTimeMillis();
-//        try {
-//            sock.connect(new InetSocketAddress(NON_EXISTING_ADDRESS, 80), timeout);
-//        } catch (SocketTimeoutException e) {
-//            // expected
-//            long delay = System.currentTimeMillis() - start;
-//            if (Math.abs(delay - timeout) > 1000) {
-//                fail("timeout was not accurate. expected: " + timeout
-//                        + " actual: " + delay + " miliseconds.");
-//            }
-//        } finally {
-//            try {
-//                sock.close();
-//            } catch (IOException ioe) {
-//                // ignore
-//            }
-//        }
-//    }
-    
-    /**
-     * Regression test for 1062928: Dotted IP addresses (e.g., 192.168.100.1)
-     * appear to be broken in the M5 SDK.
-     * 
-     * Tests that a connection given a ip-addressv4 such as 192.168.100.100 does
-     * not fail - sdk m5 seems only to accept dns names instead of ip numbers.
-     * ip 209.85.129.147 (one address of www.google.com) on port 80 (http) is
-     * used to test the connection.
-     */
-
-// Commenting out this test since it is flaky, even at the best of times.  See
-// #1191317 for Info.
-    @Suppress
-    public void disable_testConnectWithIP4IPAddr() {
-        // call a Google Web server
-        InetSocketAddress scktAddrss = new InetSocketAddress(KNOW_GOOD_ADDRESS,
-                80);
-        Socket clntSckt = new Socket();
-        try {
-            clntSckt.connect(scktAddrss, 5000);
-        } catch (Throwable e) {
-            fail("connection problem:" + e.getClass().getName() + ": "
-                    + e.getMessage());
-        } finally {
-            try {
-                clntSckt.close();
-            } catch (Exception e) {
-                // ignore
-            }
-        }
-    }
-
-    
-    // Regression test for #1058962: Socket.close() does not cause
-    // socket.connect() to return immediately.
-    private Socket client;
-    
-    private Exception error;
-    
-    private boolean connected;
-
-// This test isn't working now, but really should work.
-// TODO Enable this test again.
-
-    @Suppress
-    public void disable_testSocketConnectClose() {
-        try {
-            client = new Socket();
-            
-            new Thread() {
-                @Override
-                public void run() {
-                    try {
-                        client.connect(new InetSocketAddress(PACKAGE_DROPPING_ADDRESS, 1357));
-                    } catch (Exception ex) {
-                        error = ex;
-                    }
-                    
-                    connected = true;
-                }
-            }.start();
-            
-            Thread.sleep(1000);
-            
-            Assert.assertNull("Connect must not fail immediately. Maybe try different address.", error);
-            Assert.assertFalse("Connect must not succeed. Maybe try different address.", connected);
-            
-            client.close();
-            
-            Thread.sleep(1000);
-
-            if (error == null) {
-                fail("Socket connect still ongoing");
-            } else if (!(error instanceof SocketException)) {
-                fail("Socket connect interrupted with wrong error: " + error.toString());
-            }
-            
-        } catch (Exception ex) {
-            throw new RuntimeException(ex);
-        }
-            
-    }
-    
-}
diff --git a/tests/RenderScriptTests/Fountain_v11/Android.mk b/tests/RenderScriptTests/Fountain_v11/Android.mk
index fe7f9e7..ac2690c 100644
--- a/tests/RenderScriptTests/Fountain_v11/Android.mk
+++ b/tests/RenderScriptTests/Fountain_v11/Android.mk
@@ -14,8 +14,6 @@
 # limitations under the License.
 #
 
-ifneq ($(TARGET_SIMULATOR),true)
-
 LOCAL_PATH := $(call my-dir)
 include $(CLEAR_VARS)
 
@@ -28,5 +26,3 @@
 LOCAL_SDK_VERSION := 11
 
 include $(BUILD_PACKAGE)
-
-endif
diff --git a/tools/aapt/AaptXml.cpp b/tools/aapt/AaptXml.cpp
index 708e405..b04a55d 100644
--- a/tools/aapt/AaptXml.cpp
+++ b/tools/aapt/AaptXml.cpp
@@ -41,7 +41,7 @@
     }
 
     size_t len;
-    const uint16_t* str = tree.getAttributeStringValue(attrIndex, &len);
+    const char16_t* str = tree.getAttributeStringValue(attrIndex, &len);
     return str ? String8(str, len) : String8();
 }
 
@@ -103,7 +103,7 @@
     if (tree.getAttributeValue(idx, &value) != NO_ERROR) {
         if (value.dataType == Res_value::TYPE_STRING) {
             size_t len;
-            const uint16_t* str = tree.getAttributeStringValue(idx, &len);
+            const char16_t* str = tree.getAttributeStringValue(idx, &len);
             return str ? String8(str, len) : String8();
         }
         resTable.resolveReference(&value, 0);
diff --git a/tools/aapt/Android.mk b/tools/aapt/Android.mk
index 6d3b73d..ba1411e 100644
--- a/tools/aapt/Android.mk
+++ b/tools/aapt/Android.mk
@@ -167,7 +167,6 @@
 LOCAL_CFLAGS += $(aaptCFlags)
 LOCAL_CPPFLAGS += -Wno-non-virtual-dtor
 
-include external/stlport/libstlport.mk
 include $(BUILD_EXECUTABLE)
 
 endif # Not SDK_ONLY
diff --git a/tools/aapt/ResourceTable.cpp b/tools/aapt/ResourceTable.cpp
index 4cca57f..0ec1aeb 100644
--- a/tools/aapt/ResourceTable.cpp
+++ b/tools/aapt/ResourceTable.cpp
@@ -3009,7 +3009,7 @@
 
             // We need to write one type chunk for each configuration for
             // which we have entries in this type.
-            const size_t NC = t->getUniqueConfigs().size();
+            const size_t NC = t != NULL ? t->getUniqueConfigs().size() : 0;
             
             const size_t typeSize = sizeof(ResTable_type) + sizeof(uint32_t)*N;
             
diff --git a/tools/aapt/ZipEntry.cpp b/tools/aapt/ZipEntry.cpp
index f97f604..54a8e9c 100644
--- a/tools/aapt/ZipEntry.cpp
+++ b/tools/aapt/ZipEntry.cpp
@@ -338,7 +338,7 @@
  */
 void ZipEntry::setModWhen(time_t when)
 {
-#ifdef HAVE_LOCALTIME_R
+#if !defined(_WIN32)
     struct tm tmResult;
 #endif
     time_t even;
@@ -350,7 +350,7 @@
     even = (time_t)(((unsigned long)(when) + 1) & (~1));
 
     /* expand */
-#ifdef HAVE_LOCALTIME_R
+#if !defined(_WIN32)
     ptm = localtime_r(&even, &tmResult);
 #else
     ptm = localtime(&even);