Merge "Use long for pointers in EmojiFactory and PdfDocument"
diff --git a/api/current.txt b/api/current.txt
index 50337c0..a98fcfb 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -21794,7 +21794,7 @@
   }
 
   public class BaseObj {
-    method public synchronized void destroy();
+    method public void destroy();
     method public java.lang.String getName();
     method public void setName(java.lang.String);
   }
@@ -42720,11 +42720,11 @@
   }
 
   public class ConcurrentHashMap extends java.util.AbstractMap implements java.util.concurrent.ConcurrentMap java.io.Serializable {
-    ctor public ConcurrentHashMap(int, float, int);
-    ctor public ConcurrentHashMap(int, float);
-    ctor public ConcurrentHashMap(int);
     ctor public ConcurrentHashMap();
+    ctor public ConcurrentHashMap(int);
     ctor public ConcurrentHashMap(java.util.Map<? extends K, ? extends V>);
+    ctor public ConcurrentHashMap(int, float);
+    ctor public ConcurrentHashMap(int, float, int);
     method public boolean contains(java.lang.Object);
     method public java.util.Enumeration<V> elements();
     method public java.util.Set<java.util.Map.Entry<K, V>> entrySet();
@@ -44164,12 +44164,12 @@
   public final class Matcher implements java.util.regex.MatchResult {
     method public java.util.regex.Matcher appendReplacement(java.lang.StringBuffer, java.lang.String);
     method public java.lang.StringBuffer appendTail(java.lang.StringBuffer);
-    method public int end(int);
     method public int end();
+    method public int end(int);
     method public boolean find(int);
     method public boolean find();
-    method public java.lang.String group(int);
     method public java.lang.String group();
+    method public java.lang.String group(int);
     method public int groupCount();
     method public boolean hasAnchoringBounds();
     method public boolean hasTransparentBounds();
@@ -44186,8 +44186,8 @@
     method public boolean requireEnd();
     method public java.util.regex.Matcher reset();
     method public java.util.regex.Matcher reset(java.lang.CharSequence);
-    method public int start(int) throws java.lang.IllegalStateException;
     method public int start();
+    method public int start(int) throws java.lang.IllegalStateException;
     method public java.util.regex.MatchResult toMatchResult();
     method public java.util.regex.Matcher useAnchoringBounds(boolean);
     method public java.util.regex.Matcher usePattern(java.util.regex.Pattern);
@@ -50928,7 +50928,7 @@
     method public java.lang.String getString(java.lang.String) throws org.json.JSONException;
     method public boolean has(java.lang.String);
     method public boolean isNull(java.lang.String);
-    method public java.util.Iterator keys();
+    method public java.util.Iterator<java.lang.String> keys();
     method public int length();
     method public org.json.JSONArray names();
     method public static java.lang.String numberToString(java.lang.Number) throws org.json.JSONException;
diff --git a/core/java/android/content/res/AssetManager.java b/core/java/android/content/res/AssetManager.java
index 93ce633..780c4be 100644
--- a/core/java/android/content/res/AssetManager.java
+++ b/core/java/android/content/res/AssetManager.java
@@ -69,13 +69,13 @@
     private final long[] mOffsets = new long[2];
     
     // For communication with native code.
-    private int mObject;
+    private long mObject;
 
     private StringBlock mStringBlocks[] = null;
     
     private int mNumRefs = 1;
     private boolean mOpen = true;
-    private HashMap<Integer, RuntimeException> mRefStacks; 
+    private HashMap<Long, RuntimeException> mRefStacks;
  
     /**
      * Create a new AssetManager containing only the basic system assets.
@@ -224,7 +224,7 @@
         return retArray;
     }
     
-    /*package*/ final boolean getThemeValue(int theme, int ident,
+    /*package*/ final boolean getThemeValue(long theme, int ident,
             TypedValue outValue, boolean resolveRefs) {
         int block = loadThemeAttributeValue(theme, ident, outValue, resolveRefs);
         if (block >= 0) {
@@ -312,7 +312,7 @@
             if (!mOpen) {
                 throw new RuntimeException("Assetmanager has been closed");
             }
-            int asset = openAsset(fileName, accessMode);
+            long asset = openAsset(fileName, accessMode);
             if (asset != 0) {
                 AssetInputStream res = new AssetInputStream(asset);
                 incRefsLocked(res.hashCode());
@@ -404,7 +404,7 @@
             if (!mOpen) {
                 throw new RuntimeException("Assetmanager has been closed");
             }
-            int asset = openNonAssetNative(cookie, fileName, accessMode);
+            long asset = openNonAssetNative(cookie, fileName, accessMode);
             if (asset != 0) {
                 AssetInputStream res = new AssetInputStream(asset);
                 incRefsLocked(res.hashCode());
@@ -484,7 +484,7 @@
             if (!mOpen) {
                 throw new RuntimeException("Assetmanager has been closed");
             }
-            int xmlBlock = openXmlAssetNative(cookie, fileName);
+            long xmlBlock = openXmlAssetNative(cookie, fileName);
             if (xmlBlock != 0) {
                 XmlBlock res = new XmlBlock(this, xmlBlock);
                 incRefsLocked(res.hashCode());
@@ -500,18 +500,18 @@
         }
     }
 
-    /*package*/ final int createTheme() {
+    /*package*/ final long createTheme() {
         synchronized (this) {
             if (!mOpen) {
                 throw new RuntimeException("Assetmanager has been closed");
             }
-            int res = newTheme();
+            long res = newTheme();
             incRefsLocked(res);
             return res;
         }
     }
 
-    /*package*/ final void releaseTheme(int theme) {
+    /*package*/ final void releaseTheme(long theme) {
         synchronized (this) {
             deleteTheme(theme);
             decRefsLocked(theme);
@@ -537,7 +537,7 @@
     
     public final class AssetInputStream extends InputStream {
         public final int getAssetInt() {
-            return mAsset;
+            return (int) mAsset;
         }
         /**
          * @hide
@@ -545,7 +545,7 @@
         public final long getNativeAsset() {
             return mAsset;
         }
-        private AssetInputStream(int asset)
+        private AssetInputStream(long asset)
         {
             mAsset = asset;
             mLength = getAssetLength(asset);
@@ -597,7 +597,7 @@
             close();
         }
 
-        private int mAsset;
+        private long mAsset;
         private long mLength;
         private long mMarkPos;
     }
@@ -678,19 +678,19 @@
     /*package*/ native final String getResourceTypeName(int resid);
     /*package*/ native final String getResourceEntryName(int resid);
     
-    private native final int openAsset(String fileName, int accessMode);
+    private native final long openAsset(String fileName, int accessMode);
     private final native ParcelFileDescriptor openAssetFd(String fileName,
             long[] outOffsets) throws IOException;
-    private native final int openNonAssetNative(int cookie, String fileName,
+    private native final long openNonAssetNative(int cookie, String fileName,
             int accessMode);
     private native ParcelFileDescriptor openNonAssetFdNative(int cookie,
             String fileName, long[] outOffsets) throws IOException;
-    private native final void destroyAsset(int asset);
-    private native final int readAssetChar(int asset);
-    private native final int readAsset(int asset, byte[] b, int off, int len);
-    private native final long seekAsset(int asset, long offset, int whence);
-    private native final long getAssetLength(int asset);
-    private native final long getAssetRemainingLength(int asset);
+    private native final void destroyAsset(long asset);
+    private native final int readAssetChar(long asset);
+    private native final int readAsset(long asset, byte[] b, int off, int len);
+    private native final long seekAsset(long asset, long offset, int whence);
+    private native final long getAssetLength(long asset);
+    private native final long getAssetRemainingLength(long asset);
 
     /** Returns true if the resource was found, filling in mRetStringBlock and
      *  mRetData. */
@@ -707,15 +707,15 @@
     /*package*/ static final int STYLE_RESOURCE_ID = 3;
     /*package*/ static final int STYLE_CHANGING_CONFIGURATIONS = 4;
     /*package*/ static final int STYLE_DENSITY = 5;
-    /*package*/ native static final boolean applyStyle(int theme,
-            int defStyleAttr, int defStyleRes, int xmlParser,
+    /*package*/ native static final boolean applyStyle(long theme,
+            int defStyleAttr, int defStyleRes, long xmlParser,
             int[] inAttrs, int[] outValues, int[] outIndices);
     /*package*/ native final boolean retrieveAttributes(
-            int xmlParser, int[] inAttrs, int[] outValues, int[] outIndices);
+            long xmlParser, int[] inAttrs, int[] outValues, int[] outIndices);
     /*package*/ native final int getArraySize(int resource);
     /*package*/ native final int retrieveArray(int resource, int[] outValues);
     private native final int getStringBlockCount();
-    private native final int getNativeStringBlock(int block);
+    private native final long getNativeStringBlock(int block);
 
     /**
      * {@hide}
@@ -737,16 +737,16 @@
      */
     public native static final int getGlobalAssetManagerCount();
     
-    private native final int newTheme();
-    private native final void deleteTheme(int theme);
-    /*package*/ native static final void applyThemeStyle(int theme, int styleRes, boolean force);
-    /*package*/ native static final void copyTheme(int dest, int source);
-    /*package*/ native static final int loadThemeAttributeValue(int theme, int ident,
+    private native final long newTheme();
+    private native final void deleteTheme(long theme);
+    /*package*/ native static final void applyThemeStyle(long theme, int styleRes, boolean force);
+    /*package*/ native static final void copyTheme(long dest, long source);
+    /*package*/ native static final int loadThemeAttributeValue(long theme, int ident,
                                                                 TypedValue outValue,
                                                                 boolean resolve);
-    /*package*/ native static final void dumpTheme(int theme, int priority, String tag, String prefix);
+    /*package*/ native static final void dumpTheme(long theme, int priority, String tag, String prefix);
 
-    private native final int openXmlAssetNative(int cookie, String fileName);
+    private native final long openXmlAssetNative(int cookie, String fileName);
 
     private native final String[] getArrayStringResource(int arrayRes);
     private native final int[] getArrayStringInfo(int arrayRes);
@@ -755,19 +755,19 @@
     private native final void init();
     private native final void destroy();
 
-    private final void incRefsLocked(int id) {
+    private final void incRefsLocked(long id) {
         if (DEBUG_REFS) {
             if (mRefStacks == null) {
-                mRefStacks = new HashMap<Integer, RuntimeException>();
-                RuntimeException ex = new RuntimeException();
-                ex.fillInStackTrace();
-                mRefStacks.put(this.hashCode(), ex);
+                mRefStacks = new HashMap<Long, RuntimeException>();
             }
+            RuntimeException ex = new RuntimeException();
+            ex.fillInStackTrace();
+            mRefStacks.put(id, ex);
         }
         mNumRefs++;
     }
     
-    private final void decRefsLocked(int id) {
+    private final void decRefsLocked(long id) {
         if (DEBUG_REFS && mRefStacks != null) {
             mRefStacks.remove(id);
         }
diff --git a/core/java/android/content/res/Resources.java b/core/java/android/content/res/Resources.java
index cd5b5d2f..7fc364f 100644
--- a/core/java/android/content/res/Resources.java
+++ b/core/java/android/content/res/Resources.java
@@ -1460,7 +1460,7 @@
         }
 
         private final AssetManager mAssets;
-        private final int mTheme;
+        private final long mTheme;
     }
 
     /**
diff --git a/core/java/android/content/res/StringBlock.java b/core/java/android/content/res/StringBlock.java
index 78180b1..77b8a33 100644
--- a/core/java/android/content/res/StringBlock.java
+++ b/core/java/android/content/res/StringBlock.java
@@ -36,7 +36,7 @@
     private static final String TAG = "AssetManager";
     private static final boolean localLOGV = false;
 
-    private final int mNative;
+    private final long mNative;
     private final boolean mUseSparse;
     private final boolean mOwnsNative;
     private CharSequence[] mStrings;
@@ -474,7 +474,7 @@
      *  are doing!  The given native object must exist for the entire lifetime
      *  of this newly creating StringBlock.
      */
-    StringBlock(int obj, boolean useSparse) {
+    StringBlock(long obj, boolean useSparse) {
         mNative = obj;
         mUseSparse = useSparse;
         mOwnsNative = false;
@@ -482,11 +482,11 @@
                 + ": " + nativeGetSize(mNative));
     }
 
-    private static native int nativeCreate(byte[] data,
+    private static native long nativeCreate(byte[] data,
                                                  int offset,
                                                  int size);
-    private static native int nativeGetSize(int obj);
-    private static native String nativeGetString(int obj, int idx);
-    private static native int[] nativeGetStyle(int obj, int idx);
-    private static native void nativeDestroy(int obj);
+    private static native int nativeGetSize(long obj);
+    private static native String nativeGetString(long obj, int idx);
+    private static native int[] nativeGetStyle(long obj, int idx);
+    private static native void nativeDestroy(long obj);
 }
diff --git a/core/java/android/content/res/XmlBlock.java b/core/java/android/content/res/XmlBlock.java
index bea6529..3ad357f2 100644
--- a/core/java/android/content/res/XmlBlock.java
+++ b/core/java/android/content/res/XmlBlock.java
@@ -75,7 +75,7 @@
     }
 
     /*package*/ final class Parser implements XmlResourceParser {
-        Parser(int parseState, XmlBlock block) {
+        Parser(long parseState, XmlBlock block) {
             mParseState = parseState;
             mBlock = block;
             block.mOpenCount++;
@@ -458,7 +458,7 @@
             return mStrings.get(id);
         }
 
-        /*package*/ int mParseState;
+        /*package*/ long mParseState;
         private final XmlBlock mBlock;
         private boolean mStarted = false;
         private boolean mDecNextDepth = false;
@@ -476,41 +476,41 @@
      *  are doing!  The given native object must exist for the entire lifetime
      *  of this newly creating XmlBlock.
      */
-    XmlBlock(AssetManager assets, int xmlBlock) {
+    XmlBlock(AssetManager assets, long xmlBlock) {
         mAssets = assets;
         mNative = xmlBlock;
         mStrings = new StringBlock(nativeGetStringBlock(xmlBlock), false);
     }
 
     private final AssetManager mAssets;
-    private final int mNative;
+    private final long mNative;
     /*package*/ final StringBlock mStrings;
     private boolean mOpen = true;
     private int mOpenCount = 1;
 
-    private static final native int nativeCreate(byte[] data,
+    private static final native long nativeCreate(byte[] data,
                                                  int offset,
                                                  int size);
-    private static final native int nativeGetStringBlock(int obj);
+    private static final native long nativeGetStringBlock(long obj);
 
-    private static final native int nativeCreateParseState(int obj);
-    /*package*/ static final native int nativeNext(int state);
-    private static final native int nativeGetNamespace(int state);
-    /*package*/ static final native int nativeGetName(int state);
-    private static final native int nativeGetText(int state);
-    private static final native int nativeGetLineNumber(int state);
-    private static final native int nativeGetAttributeCount(int state);
-    private static final native int nativeGetAttributeNamespace(int state, int idx);
-    private static final native int nativeGetAttributeName(int state, int idx);
-    private static final native int nativeGetAttributeResource(int state, int idx);
-    private static final native int nativeGetAttributeDataType(int state, int idx);
-    private static final native int nativeGetAttributeData(int state, int idx);
-    private static final native int nativeGetAttributeStringValue(int state, int idx);
-    private static final native int nativeGetIdAttribute(int state);
-    private static final native int nativeGetClassAttribute(int state);
-    private static final native int nativeGetStyleAttribute(int state);
-    private static final native int nativeGetAttributeIndex(int state, String namespace, String name);
-    private static final native void nativeDestroyParseState(int state);
+    private static final native long nativeCreateParseState(long obj);
+    /*package*/ static final native int nativeNext(long state);
+    private static final native int nativeGetNamespace(long state);
+    /*package*/ static final native int nativeGetName(long state);
+    private static final native int nativeGetText(long state);
+    private static final native int nativeGetLineNumber(long state);
+    private static final native int nativeGetAttributeCount(long state);
+    private static final native int nativeGetAttributeNamespace(long state, int idx);
+    private static final native int nativeGetAttributeName(long state, int idx);
+    private static final native int nativeGetAttributeResource(long state, int idx);
+    private static final native int nativeGetAttributeDataType(long state, int idx);
+    private static final native int nativeGetAttributeData(long state, int idx);
+    private static final native int nativeGetAttributeStringValue(long state, int idx);
+    private static final native int nativeGetIdAttribute(long state);
+    private static final native int nativeGetClassAttribute(long state);
+    private static final native int nativeGetStyleAttribute(long state);
+    private static final native int nativeGetAttributeIndex(long state, String namespace, String name);
+    private static final native void nativeDestroyParseState(long state);
 
-    private static final native void nativeDestroy(int obj);
+    private static final native void nativeDestroy(long obj);
 }
diff --git a/core/java/android/os/CountDownTimer.java b/core/java/android/os/CountDownTimer.java
index 15e6405..58acbcf 100644
--- a/core/java/android/os/CountDownTimer.java
+++ b/core/java/android/os/CountDownTimer.java
@@ -16,8 +16,6 @@
 
 package android.os;
 
-import android.util.Log;
-
 /**
  * Schedule a countdown until a time in the future, with
  * regular notifications on intervals along the way.
@@ -56,6 +54,11 @@
     private final long mCountdownInterval;
 
     private long mStopTimeInFuture;
+    
+    /**
+    * boolean representing if the timer was cancelled
+    */
+    private boolean mCancelled = false;
 
     /**
      * @param millisInFuture The number of millis in the future from the call
@@ -72,7 +75,8 @@
     /**
      * Cancel the countdown.
      */
-    public final void cancel() {
+    public synchronized final void cancel() {
+        mCancelled = true;
         mHandler.removeMessages(MSG);
     }
 
@@ -80,6 +84,7 @@
      * Start the countdown.
      */
     public synchronized final CountDownTimer start() {
+        mCancelled = false;
         if (mMillisInFuture <= 0) {
             onFinish();
             return this;
@@ -112,6 +117,10 @@
         public void handleMessage(Message msg) {
 
             synchronized (CountDownTimer.this) {
+                if (mCancelled) {
+                    return;
+                }
+
                 final long millisLeft = mStopTimeInFuture - SystemClock.elapsedRealtime();
 
                 if (millisLeft <= 0) {
diff --git a/core/jni/android_database_SQLiteGlobal.cpp b/core/jni/android_database_SQLiteGlobal.cpp
index acc2276..89d64fa 100644
--- a/core/jni/android_database_SQLiteGlobal.cpp
+++ b/core/jni/android_database_SQLiteGlobal.cpp
@@ -39,7 +39,7 @@
     bool verboseLog = !!data;
     if (iErrCode == 0 || iErrCode == SQLITE_CONSTRAINT || iErrCode == SQLITE_SCHEMA) {
         if (verboseLog) {
-            ALOGV(LOG_VERBOSE, SQLITE_LOG_TAG, "(%d) %s\n", iErrCode, zMsg);
+            ALOG(LOG_VERBOSE, SQLITE_LOG_TAG, "(%d) %s\n", iErrCode, zMsg);
         }
     } else {
         ALOG(LOG_ERROR, SQLITE_LOG_TAG, "(%d) %s\n", iErrCode, zMsg);
diff --git a/core/jni/android_os_SELinux.cpp b/core/jni/android_os_SELinux.cpp
index 2b85fef..db84d000 100644
--- a/core/jni/android_os_SELinux.cpp
+++ b/core/jni/android_os_SELinux.cpp
@@ -411,7 +411,7 @@
 
     ScopedUtfChars pathname(env, pathnameStr);
     if (pathname.c_str() == NULL) {
-        ALOGV("restorecon(%p) => threw exception", pathname);
+        ALOGV("restorecon(%p) => threw exception", pathnameStr);
         return false;
     }
 
diff --git a/core/jni/android_util_AssetManager.cpp b/core/jni/android_util_AssetManager.cpp
index 8836918..f96aef8 100644
--- a/core/jni/android_util_AssetManager.cpp
+++ b/core/jni/android_util_AssetManager.cpp
@@ -88,7 +88,7 @@
 {
     env->SetIntField(outValue, gTypedValueOffsets.mType, value.dataType);
     env->SetIntField(outValue, gTypedValueOffsets.mAssetCookie,
-                        (jint)table->getTableCookie(block));
+                     static_cast<jint>(table->getTableCookie(block)));
     env->SetIntField(outValue, gTypedValueOffsets.mData, value.data);
     env->SetObjectField(outValue, gTypedValueOffsets.mString, NULL);
     env->SetIntField(outValue, gTypedValueOffsets.mResourceId, ref);
@@ -105,7 +105,8 @@
 // this guy is exported to other jni routines
 AssetManager* assetManagerForJavaObject(JNIEnv* env, jobject obj)
 {
-    AssetManager* am = (AssetManager*)env->GetIntField(obj, gAssetManagerOffsets.mObject);
+    jlong amHandle = env->GetLongField(obj, gAssetManagerOffsets.mObject);
+    AssetManager* am = reinterpret_cast<AssetManager*>(amHandle);
     if (am != NULL) {
         return am;
     }
@@ -113,7 +114,7 @@
     return NULL;
 }
 
-static jint android_content_AssetManager_openAsset(JNIEnv* env, jobject clazz,
+static jlong android_content_AssetManager_openAsset(JNIEnv* env, jobject clazz,
                                                 jstring fileName, jint mode)
 {
     AssetManager* am = assetManagerForJavaObject(env, clazz);
@@ -125,6 +126,7 @@
 
     ScopedUtfChars fileName8(env, fileName);
     if (fileName8.c_str() == NULL) {
+        jniThrowException(env, "java/lang/IllegalArgumentException", "Empty file name");
         return -1;
     }
 
@@ -143,7 +145,7 @@
 
     //printf("Created Asset Stream: %p\n", a);
 
-    return (jint)a;
+    return reinterpret_cast<jlong>(a);
 }
 
 static jobject returnParcelFileDescriptor(JNIEnv* env, Asset* a, jlongArray outOffsets)
@@ -205,7 +207,7 @@
     return returnParcelFileDescriptor(env, a, outOffsets);
 }
 
-static jint android_content_AssetManager_openNonAssetNative(JNIEnv* env, jobject clazz,
+static jlong android_content_AssetManager_openNonAssetNative(JNIEnv* env, jobject clazz,
                                                          jint cookie,
                                                          jstring fileName,
                                                          jint mode)
@@ -240,7 +242,7 @@
 
     //printf("Created Asset Stream: %p\n", a);
 
-    return (jint)a;
+    return reinterpret_cast<jlong>(a);
 }
 
 static jobject android_content_AssetManager_openNonAssetFdNative(JNIEnv* env, jobject clazz,
@@ -320,9 +322,9 @@
 }
 
 static void android_content_AssetManager_destroyAsset(JNIEnv* env, jobject clazz,
-                                                   jint asset)
+                                                      jlong assetHandle)
 {
-    Asset* a = (Asset*)asset;
+    Asset* a = reinterpret_cast<Asset*>(assetHandle);
 
     //printf("Destroying Asset Stream: %p\n", a);
 
@@ -335,9 +337,9 @@
 }
 
 static jint android_content_AssetManager_readAssetChar(JNIEnv* env, jobject clazz,
-                                                    jint asset)
+                                                       jlong assetHandle)
 {
-    Asset* a = (Asset*)asset;
+    Asset* a = reinterpret_cast<Asset*>(assetHandle);
 
     if (a == NULL) {
         jniThrowNullPointerException(env, "asset");
@@ -350,10 +352,10 @@
 }
 
 static jint android_content_AssetManager_readAsset(JNIEnv* env, jobject clazz,
-                                                jint asset, jbyteArray bArray,
+                                                jlong assetHandle, jbyteArray bArray,
                                                 jint off, jint len)
 {
-    Asset* a = (Asset*)asset;
+    Asset* a = reinterpret_cast<Asset*>(assetHandle);
 
     if (a == NULL || bArray == NULL) {
         jniThrowNullPointerException(env, "asset");
@@ -374,7 +376,7 @@
     ssize_t res = a->read(b+off, len);
     env->ReleaseByteArrayElements(bArray, b, 0);
 
-    if (res > 0) return res;
+    if (res > 0) return static_cast<jint>(res);
 
     if (res < 0) {
         jniThrowException(env, "java/io/IOException", "");
@@ -383,10 +385,10 @@
 }
 
 static jlong android_content_AssetManager_seekAsset(JNIEnv* env, jobject clazz,
-                                                 jint asset,
+                                                 jlong assetHandle,
                                                  jlong offset, jint whence)
 {
-    Asset* a = (Asset*)asset;
+    Asset* a = reinterpret_cast<Asset*>(assetHandle);
 
     if (a == NULL) {
         jniThrowNullPointerException(env, "asset");
@@ -398,9 +400,9 @@
 }
 
 static jlong android_content_AssetManager_getAssetLength(JNIEnv* env, jobject clazz,
-                                                      jint asset)
+                                                      jlong assetHandle)
 {
-    Asset* a = (Asset*)asset;
+    Asset* a = reinterpret_cast<Asset*>(assetHandle);
 
     if (a == NULL) {
         jniThrowNullPointerException(env, "asset");
@@ -411,9 +413,9 @@
 }
 
 static jlong android_content_AssetManager_getAssetRemainingLength(JNIEnv* env, jobject clazz,
-                                                               jint asset)
+                                                               jlong assetHandle)
 {
-    Asset* a = (Asset*)asset;
+    Asset* a = reinterpret_cast<Asset*>(assetHandle);
 
     if (a == NULL) {
         jniThrowNullPointerException(env, "asset");
@@ -725,7 +727,11 @@
         }
 #endif
     }
-    return block >= 0 ? copyValue(env, outValue, &res, value, ref, block, typeSpecFlags, &config) : block;
+    if (block >= 0) {
+        return copyValue(env, outValue, &res, value, ref, block, typeSpecFlags, &config);
+    }
+
+    return static_cast<jint>(block);
 }
 
 static jint android_content_AssetManager_loadResourceBagValue(JNIEnv* env, jobject clazz,
@@ -759,7 +765,7 @@
     res.unlock();
 
     if (block < 0) {
-        return block;
+        return static_cast<jint>(block);
     }
 
     uint32_t ref = ident;
@@ -772,7 +778,11 @@
         }
 #endif
     }
-    return block >= 0 ? copyValue(env, outValue, &res, value, ref, block, typeSpecFlags) : block;
+    if (block >= 0) {
+        return copyValue(env, outValue, &res, value, ref, block, typeSpecFlags);
+    }
+
+    return static_cast<jint>(block);
 }
 
 static jint android_content_AssetManager_getStringBlockCount(JNIEnv* env, jobject clazz)
@@ -784,14 +794,14 @@
     return am->getResources().getTableCount();
 }
 
-static jint android_content_AssetManager_getNativeStringBlock(JNIEnv* env, jobject clazz,
+static jlong android_content_AssetManager_getNativeStringBlock(JNIEnv* env, jobject clazz,
                                                            jint block)
 {
     AssetManager* am = assetManagerForJavaObject(env, clazz);
     if (am == NULL) {
         return 0;
     }
-    return (jint)am->getResources().getTableStringBlock(block);
+    return reinterpret_cast<jlong>(am->getResources().getTableStringBlock(block));
 }
 
 static jstring android_content_AssetManager_getCookieName(JNIEnv* env, jobject clazz,
@@ -810,43 +820,43 @@
     return str;
 }
 
-static jint android_content_AssetManager_newTheme(JNIEnv* env, jobject clazz)
+static jlong android_content_AssetManager_newTheme(JNIEnv* env, jobject clazz)
 {
     AssetManager* am = assetManagerForJavaObject(env, clazz);
     if (am == NULL) {
         return 0;
     }
-    return (jint)(new ResTable::Theme(am->getResources()));
+    return reinterpret_cast<jlong>(new ResTable::Theme(am->getResources()));
 }
 
 static void android_content_AssetManager_deleteTheme(JNIEnv* env, jobject clazz,
-                                                     jint themeInt)
+                                                     jlong themeHandle)
 {
-    ResTable::Theme* theme = (ResTable::Theme*)themeInt;
+    ResTable::Theme* theme = reinterpret_cast<ResTable::Theme*>(themeHandle);
     delete theme;
 }
 
 static void android_content_AssetManager_applyThemeStyle(JNIEnv* env, jobject clazz,
-                                                         jint themeInt,
+                                                         jlong themeHandle,
                                                          jint styleRes,
                                                          jboolean force)
 {
-    ResTable::Theme* theme = (ResTable::Theme*)themeInt;
+    ResTable::Theme* theme = reinterpret_cast<ResTable::Theme*>(themeHandle);
     theme->applyStyle(styleRes, force ? true : false);
 }
 
 static void android_content_AssetManager_copyTheme(JNIEnv* env, jobject clazz,
-                                                   jint destInt, jint srcInt)
+                                                   jlong destHandle, jlong srcHandle)
 {
-    ResTable::Theme* dest = (ResTable::Theme*)destInt;
-    ResTable::Theme* src = (ResTable::Theme*)srcInt;
+    ResTable::Theme* dest = reinterpret_cast<ResTable::Theme*>(destHandle);
+    ResTable::Theme* src = reinterpret_cast<ResTable::Theme*>(srcHandle);
     dest->setTo(*src);
 }
 
 static jint android_content_AssetManager_loadThemeAttributeValue(
-    JNIEnv* env, jobject clazz, jint themeInt, jint ident, jobject outValue, jboolean resolve)
+    JNIEnv* env, jobject clazz, jlong themeHandle, jint ident, jobject outValue, jboolean resolve)
 {
-    ResTable::Theme* theme = (ResTable::Theme*)themeInt;
+    ResTable::Theme* theme = reinterpret_cast<ResTable::Theme*>(themeHandle);
     const ResTable& res(theme->getResTable());
 
     Res_value value;
@@ -867,10 +877,10 @@
 }
 
 static void android_content_AssetManager_dumpTheme(JNIEnv* env, jobject clazz,
-                                                   jint themeInt, jint pri,
+                                                   jlong themeHandle, jint pri,
                                                    jstring tag, jstring prefix)
 {
-    ResTable::Theme* theme = (ResTable::Theme*)themeInt;
+    ResTable::Theme* theme = reinterpret_cast<ResTable::Theme*>(themeHandle);
     const ResTable& res(theme->getResTable());
 
     // XXX Need to use params.
@@ -878,10 +888,10 @@
 }
 
 static jboolean android_content_AssetManager_applyStyle(JNIEnv* env, jobject clazz,
-                                                        jint themeToken,
+                                                        jlong themeToken,
                                                         jint defStyleAttr,
                                                         jint defStyleRes,
-                                                        jint xmlParserToken,
+                                                        jlong xmlParserToken,
                                                         jintArray attrs,
                                                         jintArray outValues,
                                                         jintArray outIndices)
@@ -902,9 +912,9 @@
     DEBUG_STYLES(LOGI("APPLY STYLE: theme=0x%x defStyleAttr=0x%x defStyleRes=0x%x xml=0x%x",
         themeToken, defStyleAttr, defStyleRes, xmlParserToken));
 
-    ResTable::Theme* theme = (ResTable::Theme*)themeToken;
+    ResTable::Theme* theme = reinterpret_cast<ResTable::Theme*>(themeToken);
     const ResTable& res = theme->getResTable();
-    ResXMLParser* xmlParser = (ResXMLParser*)xmlParserToken;
+    ResXMLParser* xmlParser = reinterpret_cast<ResXMLParser*>(xmlParserToken);
     ResTable_config config;
     Res_value value;
 
@@ -1097,7 +1107,7 @@
         dest[STYLE_TYPE] = value.dataType;
         dest[STYLE_DATA] = value.data;
         dest[STYLE_ASSET_COOKIE] =
-            block != kXmlBlock ? (jint)res.getTableCookie(block) : (jint)-1;
+            block != kXmlBlock ? reinterpret_cast<jint>(res.getTableCookie(block)) : (jint)-1;
         dest[STYLE_RESOURCE_ID] = resid;
         dest[STYLE_CHANGING_CONFIGURATIONS] = typeSetFlags;
         dest[STYLE_DENSITY] = config.density;
@@ -1123,7 +1133,7 @@
 }
 
 static jboolean android_content_AssetManager_retrieveAttributes(JNIEnv* env, jobject clazz,
-                                                        jint xmlParserToken,
+                                                        jlong xmlParserToken,
                                                         jintArray attrs,
                                                         jintArray outValues,
                                                         jintArray outIndices)
@@ -1240,7 +1250,7 @@
         dest[STYLE_TYPE] = value.dataType;
         dest[STYLE_DATA] = value.data;
         dest[STYLE_ASSET_COOKIE] =
-            block != kXmlBlock ? (jint)res.getTableCookie(block) : (jint)-1;
+            block != kXmlBlock ? reinterpret_cast<jint>(res.getTableCookie(block)) : (jint)-1;
         dest[STYLE_RESOURCE_ID] = resid;
         dest[STYLE_CHANGING_CONFIGURATIONS] = typeSetFlags;
         dest[STYLE_DENSITY] = config.density;
@@ -1280,7 +1290,7 @@
     ssize_t bagOff = res.getBagLocked(id, &defStyleEnt);
     res.unlock();
 
-    return bagOff;
+    return static_cast<jint>(bagOff);
 }
 
 static jint android_content_AssetManager_retrieveArray(JNIEnv* env, jobject clazz,
@@ -1352,7 +1362,7 @@
         // Write the final value back to Java.
         dest[STYLE_TYPE] = value.dataType;
         dest[STYLE_DATA] = value.data;
-        dest[STYLE_ASSET_COOKIE] = (jint)res.getTableCookie(block);
+        dest[STYLE_ASSET_COOKIE] = reinterpret_cast<jint>(res.getTableCookie(block));
         dest[STYLE_RESOURCE_ID] = resid;
         dest[STYLE_CHANGING_CONFIGURATIONS] = typeSetFlags;
         dest[STYLE_DENSITY] = config.density;
@@ -1370,7 +1380,7 @@
     return i;
 }
 
-static jint android_content_AssetManager_openXmlAssetNative(JNIEnv* env, jobject clazz,
+static jlong android_content_AssetManager_openXmlAssetNative(JNIEnv* env, jobject clazz,
                                                          jint cookie,
                                                          jstring fileName)
 {
@@ -1405,7 +1415,7 @@
         return 0;
     }
 
-    return (jint)block;
+    return reinterpret_cast<jlong>(block);
 }
 
 static jintArray android_content_AssetManager_getArrayStringInfo(JNIEnv* env, jobject clazz,
@@ -1580,17 +1590,17 @@
     am->addDefaultAssets();
 
     ALOGV("Created AssetManager %p for Java object %p\n", am, clazz);
-    env->SetIntField(clazz, gAssetManagerOffsets.mObject, (jint)am);
+    env->SetLongField(clazz, gAssetManagerOffsets.mObject, reinterpret_cast<jlong>(am));
 }
 
 static void android_content_AssetManager_destroy(JNIEnv* env, jobject clazz)
 {
     AssetManager* am = (AssetManager*)
-        (env->GetIntField(clazz, gAssetManagerOffsets.mObject));
+        (env->GetLongField(clazz, gAssetManagerOffsets.mObject));
     ALOGV("Destroying AssetManager %p for Java object %p\n", am, clazz);
     if (am != NULL) {
         delete am;
-        env->SetIntField(clazz, gAssetManagerOffsets.mObject, 0);
+        env->SetLongField(clazz, gAssetManagerOffsets.mObject, 0);
     }
 }
 
@@ -1624,27 +1634,27 @@
     /* name, signature, funcPtr */
 
     // Basic asset stuff.
-    { "openAsset",      "(Ljava/lang/String;I)I",
+    { "openAsset",      "(Ljava/lang/String;I)J",
         (void*) android_content_AssetManager_openAsset },
     { "openAssetFd",      "(Ljava/lang/String;[J)Landroid/os/ParcelFileDescriptor;",
         (void*) android_content_AssetManager_openAssetFd },
-    { "openNonAssetNative", "(ILjava/lang/String;I)I",
+    { "openNonAssetNative", "(ILjava/lang/String;I)J",
         (void*) android_content_AssetManager_openNonAssetNative },
     { "openNonAssetFdNative", "(ILjava/lang/String;[J)Landroid/os/ParcelFileDescriptor;",
         (void*) android_content_AssetManager_openNonAssetFdNative },
     { "list",           "(Ljava/lang/String;)[Ljava/lang/String;",
         (void*) android_content_AssetManager_list },
-    { "destroyAsset",   "(I)V",
+    { "destroyAsset",   "(J)V",
         (void*) android_content_AssetManager_destroyAsset },
-    { "readAssetChar",  "(I)I",
+    { "readAssetChar",  "(J)I",
         (void*) android_content_AssetManager_readAssetChar },
-    { "readAsset",      "(I[BII)I",
+    { "readAsset",      "(J[BII)I",
         (void*) android_content_AssetManager_readAsset },
-    { "seekAsset",      "(IJI)J",
+    { "seekAsset",      "(JJI)J",
         (void*) android_content_AssetManager_seekAsset },
-    { "getAssetLength", "(I)J",
+    { "getAssetLength", "(J)J",
         (void*) android_content_AssetManager_getAssetLength },
-    { "getAssetRemainingLength", "(I)J",
+    { "getAssetRemainingLength", "(J)J",
         (void*) android_content_AssetManager_getAssetRemainingLength },
     { "addAssetPathNative", "(Ljava/lang/String;)I",
         (void*) android_content_AssetManager_addAssetPath },
@@ -1674,27 +1684,27 @@
         (void*) android_content_AssetManager_loadResourceBagValue },
     { "getStringBlockCount","()I",
         (void*) android_content_AssetManager_getStringBlockCount },
-    { "getNativeStringBlock","(I)I",
+    { "getNativeStringBlock","(I)J",
         (void*) android_content_AssetManager_getNativeStringBlock },
     { "getCookieName","(I)Ljava/lang/String;",
         (void*) android_content_AssetManager_getCookieName },
 
     // Themes.
-    { "newTheme", "()I",
+    { "newTheme", "()J",
         (void*) android_content_AssetManager_newTheme },
-    { "deleteTheme", "(I)V",
+    { "deleteTheme", "(J)V",
         (void*) android_content_AssetManager_deleteTheme },
-    { "applyThemeStyle", "(IIZ)V",
+    { "applyThemeStyle", "(JIZ)V",
         (void*) android_content_AssetManager_applyThemeStyle },
-    { "copyTheme", "(II)V",
+    { "copyTheme", "(JJ)V",
         (void*) android_content_AssetManager_copyTheme },
-    { "loadThemeAttributeValue", "(IILandroid/util/TypedValue;Z)I",
+    { "loadThemeAttributeValue", "(JILandroid/util/TypedValue;Z)I",
         (void*) android_content_AssetManager_loadThemeAttributeValue },
-    { "dumpTheme", "(IILjava/lang/String;Ljava/lang/String;)V",
+    { "dumpTheme", "(JILjava/lang/String;Ljava/lang/String;)V",
         (void*) android_content_AssetManager_dumpTheme },
-    { "applyStyle","(IIII[I[I[I)Z",
+    { "applyStyle","(JIIJ[I[I[I)Z",
         (void*) android_content_AssetManager_applyStyle },
-    { "retrieveAttributes","(I[I[I[I)Z",
+    { "retrieveAttributes","(J[I[I[I)Z",
         (void*) android_content_AssetManager_retrieveAttributes },
     { "getArraySize","(I)I",
         (void*) android_content_AssetManager_getArraySize },
@@ -1702,7 +1712,7 @@
         (void*) android_content_AssetManager_retrieveArray },
 
     // XML files.
-    { "openXmlAssetNative", "(ILjava/lang/String;)I",
+    { "openXmlAssetNative", "(ILjava/lang/String;)J",
         (void*) android_content_AssetManager_openXmlAssetNative },
 
     // Arrays.
@@ -1766,7 +1776,7 @@
     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", "I");
+        = env->GetFieldID(assetManager, "mObject", "J");
     LOG_FATAL_IF(gAssetManagerOffsets.mObject == NULL, "Unable to find AssetManager.mObject");
 
     jclass stringClass = env->FindClass("java/lang/String");
diff --git a/core/jni/android_util_StringBlock.cpp b/core/jni/android_util_StringBlock.cpp
index 463d3c0..f29250f 100644
--- a/core/jni/android_util_StringBlock.cpp
+++ b/core/jni/android_util_StringBlock.cpp
@@ -31,7 +31,7 @@
 
 // ----------------------------------------------------------------------------
 
-static jint android_content_StringBlock_nativeCreate(JNIEnv* env, jobject clazz,
+static jlong android_content_StringBlock_nativeCreate(JNIEnv* env, jobject clazz,
                                                   jbyteArray bArray,
                                                   jint off, jint len)
 {
@@ -56,13 +56,13 @@
         return 0;
     }
 
-    return (jint)osb;
+    return reinterpret_cast<jlong>(osb);
 }
 
 static jint android_content_StringBlock_nativeGetSize(JNIEnv* env, jobject clazz,
-                                                   jint token)
+                                                   jlong token)
 {
-    ResStringPool* osb = (ResStringPool*)token;
+    ResStringPool* osb = reinterpret_cast<ResStringPool*>(token);
     if (osb == NULL) {
         jniThrowNullPointerException(env, NULL);
         return 0;
@@ -72,9 +72,9 @@
 }
 
 static jstring android_content_StringBlock_nativeGetString(JNIEnv* env, jobject clazz,
-                                                        jint token, jint idx)
+                                                        jlong token, jint idx)
 {
-    ResStringPool* osb = (ResStringPool*)token;
+    ResStringPool* osb = reinterpret_cast<ResStringPool*>(token);
     if (osb == NULL) {
         jniThrowNullPointerException(env, NULL);
         return 0;
@@ -96,9 +96,9 @@
 }
 
 static jintArray android_content_StringBlock_nativeGetStyle(JNIEnv* env, jobject clazz,
-                                                         jint token, jint idx)
+                                                         jlong token, jint idx)
 {
-    ResStringPool* osb = (ResStringPool*)token;
+    ResStringPool* osb = reinterpret_cast<ResStringPool*>(token);
     if (osb == NULL) {
         jniThrowNullPointerException(env, NULL);
         return NULL;
@@ -139,9 +139,9 @@
 }
 
 static void android_content_StringBlock_nativeDestroy(JNIEnv* env, jobject clazz,
-                                                   jint token)
+                                                   jlong token)
 {
-    ResStringPool* osb = (ResStringPool*)token;
+    ResStringPool* osb = reinterpret_cast<ResStringPool*>(token);
     if (osb == NULL) {
         jniThrowNullPointerException(env, NULL);
         return;
@@ -157,15 +157,15 @@
  */
 static JNINativeMethod gStringBlockMethods[] = {
     /* name, signature, funcPtr */
-    { "nativeCreate",      "([BII)I",
+    { "nativeCreate",      "([BII)J",
             (void*) android_content_StringBlock_nativeCreate },
-    { "nativeGetSize",      "(I)I",
+    { "nativeGetSize",      "(J)I",
             (void*) android_content_StringBlock_nativeGetSize },
-    { "nativeGetString",    "(II)Ljava/lang/String;",
+    { "nativeGetString",    "(JI)Ljava/lang/String;",
             (void*) android_content_StringBlock_nativeGetString },
-    { "nativeGetStyle",    "(II)[I",
+    { "nativeGetStyle",    "(JI)[I",
             (void*) android_content_StringBlock_nativeGetStyle },
-    { "nativeDestroy",      "(I)V",
+    { "nativeDestroy",      "(J)V",
             (void*) android_content_StringBlock_nativeDestroy },
 };
 
diff --git a/core/jni/android_util_XmlBlock.cpp b/core/jni/android_util_XmlBlock.cpp
index ad6033b..03de5c0 100644
--- a/core/jni/android_util_XmlBlock.cpp
+++ b/core/jni/android_util_XmlBlock.cpp
@@ -31,7 +31,7 @@
 
 // ----------------------------------------------------------------------------
 
-static jint android_content_XmlBlock_nativeCreate(JNIEnv* env, jobject clazz,
+static jlong android_content_XmlBlock_nativeCreate(JNIEnv* env, jobject clazz,
                                                jbyteArray bArray,
                                                jint off, jint len)
 {
@@ -55,25 +55,25 @@
         return 0;
     }
 
-    return (jint)osb;
+    return reinterpret_cast<jlong>(osb);
 }
 
-static jint android_content_XmlBlock_nativeGetStringBlock(JNIEnv* env, jobject clazz,
-                                                       jint token)
+static jlong android_content_XmlBlock_nativeGetStringBlock(JNIEnv* env, jobject clazz,
+                                                       jlong token)
 {
-    ResXMLTree* osb = (ResXMLTree*)token;
+    ResXMLTree* osb = reinterpret_cast<ResXMLTree*>(token);
     if (osb == NULL) {
         jniThrowNullPointerException(env, NULL);
         return 0;
     }
 
-    return (jint)&osb->getStrings();
+    return reinterpret_cast<jlong>(&osb->getStrings());
 }
 
-static jint android_content_XmlBlock_nativeCreateParseState(JNIEnv* env, jobject clazz,
-                                                          jint token)
+static jlong android_content_XmlBlock_nativeCreateParseState(JNIEnv* env, jobject clazz,
+                                                          jlong token)
 {
-    ResXMLTree* osb = (ResXMLTree*)token;
+    ResXMLTree* osb = reinterpret_cast<ResXMLTree*>(token);
     if (osb == NULL) {
         jniThrowNullPointerException(env, NULL);
         return 0;
@@ -87,19 +87,19 @@
 
     st->restart();
 
-    return (jint)st;
+    return reinterpret_cast<jlong>(st);
 }
 
 static jint android_content_XmlBlock_nativeNext(JNIEnv* env, jobject clazz,
-                                             jint token)
+                                             jlong token)
 {
-    ResXMLParser* st = (ResXMLParser*)token;
+    ResXMLParser* st = reinterpret_cast<ResXMLParser*>(token);
     if (st == NULL) {
         return ResXMLParser::END_DOCUMENT;
     }
 
     do {
-        jint code = (jint)st->next();
+        ResXMLParser::event_code_t code = st->next();
         switch (code) {
             case ResXMLParser::START_TAG:
                 return 2;
@@ -123,139 +123,139 @@
 }
 
 static jint android_content_XmlBlock_nativeGetNamespace(JNIEnv* env, jobject clazz,
-                                                   jint token)
+                                                   jlong token)
 {
-    ResXMLParser* st = (ResXMLParser*)token;
+    ResXMLParser* st = reinterpret_cast<ResXMLParser*>(token);
     if (st == NULL) {
         return -1;
     }
 
-    return (jint)st->getElementNamespaceID();
+    return static_cast<jint>(st->getElementNamespaceID());
 }
 
 static jint android_content_XmlBlock_nativeGetName(JNIEnv* env, jobject clazz,
-                                                jint token)
+                                                jlong token)
 {
-    ResXMLParser* st = (ResXMLParser*)token;
+    ResXMLParser* st = reinterpret_cast<ResXMLParser*>(token);
     if (st == NULL) {
         return -1;
     }
 
-    return (jint)st->getElementNameID();
+    return static_cast<jint>(st->getElementNameID());
 }
 
 static jint android_content_XmlBlock_nativeGetText(JNIEnv* env, jobject clazz,
-                                                jint token)
+                                                jlong token)
 {
-    ResXMLParser* st = (ResXMLParser*)token;
+    ResXMLParser* st = reinterpret_cast<ResXMLParser*>(token);
     if (st == NULL) {
         return -1;
     }
 
-    return (jint)st->getTextID();
+    return static_cast<jint>(st->getTextID());
 }
 
 static jint android_content_XmlBlock_nativeGetLineNumber(JNIEnv* env, jobject clazz,
-                                                         jint token)
+                                                         jlong token)
 {
-    ResXMLParser* st = (ResXMLParser*)token;
+    ResXMLParser* st = reinterpret_cast<ResXMLParser*>(token);
     if (st == NULL) {
         jniThrowNullPointerException(env, NULL);
         return 0;
     }
 
-    return (jint)st->getLineNumber();
+    return static_cast<jint>(st->getLineNumber());
 }
 
 static jint android_content_XmlBlock_nativeGetAttributeCount(JNIEnv* env, jobject clazz,
-                                                          jint token)
+                                                          jlong token)
 {
-    ResXMLParser* st = (ResXMLParser*)token;
+    ResXMLParser* st = reinterpret_cast<ResXMLParser*>(token);
     if (st == NULL) {
         jniThrowNullPointerException(env, NULL);
         return 0;
     }
 
-    return (jint)st->getAttributeCount();
+    return static_cast<jint>(st->getAttributeCount());
 }
 
 static jint android_content_XmlBlock_nativeGetAttributeNamespace(JNIEnv* env, jobject clazz,
-                                                                 jint token, jint idx)
+                                                                 jlong token, jint idx)
 {
-    ResXMLParser* st = (ResXMLParser*)token;
+    ResXMLParser* st = reinterpret_cast<ResXMLParser*>(token);
     if (st == NULL) {
         jniThrowNullPointerException(env, NULL);
         return 0;
     }
 
-    return (jint)st->getAttributeNamespaceID(idx);
+    return static_cast<jint>(st->getAttributeNamespaceID(idx));
 }
 
 static jint android_content_XmlBlock_nativeGetAttributeName(JNIEnv* env, jobject clazz,
-                                                         jint token, jint idx)
+                                                         jlong token, jint idx)
 {
-    ResXMLParser* st = (ResXMLParser*)token;
+    ResXMLParser* st = reinterpret_cast<ResXMLParser*>(token);
     if (st == NULL) {
         jniThrowNullPointerException(env, NULL);
         return 0;
     }
 
-    return (jint)st->getAttributeNameID(idx);
+    return static_cast<jint>(st->getAttributeNameID(idx));
 }
 
 static jint android_content_XmlBlock_nativeGetAttributeResource(JNIEnv* env, jobject clazz,
-                                                             jint token, jint idx)
+                                                             jlong token, jint idx)
 {
-    ResXMLParser* st = (ResXMLParser*)token;
+    ResXMLParser* st = reinterpret_cast<ResXMLParser*>(token);
     if (st == NULL) {
         jniThrowNullPointerException(env, NULL);
         return 0;
     }
 
-    return (jint)st->getAttributeNameResID(idx);
+    return static_cast<jint>(st->getAttributeNameResID(idx));
 }
 
 static jint android_content_XmlBlock_nativeGetAttributeDataType(JNIEnv* env, jobject clazz,
-                                                                jint token, jint idx)
+                                                                jlong token, jint idx)
 {
-    ResXMLParser* st = (ResXMLParser*)token;
+    ResXMLParser* st = reinterpret_cast<ResXMLParser*>(token);
     if (st == NULL) {
         jniThrowNullPointerException(env, NULL);
         return 0;
     }
 
-    return (jint)st->getAttributeDataType(idx);
+    return static_cast<jint>(st->getAttributeDataType(idx));
 }
 
 static jint android_content_XmlBlock_nativeGetAttributeData(JNIEnv* env, jobject clazz,
-                                                            jint token, jint idx)
+                                                            jlong token, jint idx)
 {
-    ResXMLParser* st = (ResXMLParser*)token;
+    ResXMLParser* st = reinterpret_cast<ResXMLParser*>(token);
     if (st == NULL) {
         jniThrowNullPointerException(env, NULL);
         return 0;
     }
 
-    return (jint)st->getAttributeData(idx);
+    return static_cast<jint>(st->getAttributeData(idx));
 }
 
 static jint android_content_XmlBlock_nativeGetAttributeStringValue(JNIEnv* env, jobject clazz,
-                                                                   jint token, jint idx)
+                                                                   jlong token, jint idx)
 {
-    ResXMLParser* st = (ResXMLParser*)token;
+    ResXMLParser* st = reinterpret_cast<ResXMLParser*>(token);
     if (st == NULL) {
         jniThrowNullPointerException(env, NULL);
         return 0;
     }
 
-    return (jint)st->getAttributeValueStringID(idx);
+    return static_cast<jint>(st->getAttributeValueStringID(idx));
 }
 
 static jint android_content_XmlBlock_nativeGetAttributeIndex(JNIEnv* env, jobject clazz,
-                                                             jint token,
+                                                             jlong token,
                                                              jstring ns, jstring name)
 {
-    ResXMLParser* st = (ResXMLParser*)token;
+    ResXMLParser* st = reinterpret_cast<ResXMLParser*>(token);
     if (st == NULL || name == NULL) {
         jniThrowNullPointerException(env, NULL);
         return 0;
@@ -271,7 +271,7 @@
     const char16_t* name16 = env->GetStringChars(name, NULL);
     jsize nameLen = env->GetStringLength(name);
 
-    jint idx = (jint)st->indexOfAttribute(ns16, nsLen, name16, nameLen);
+    jint idx = static_cast<jint>(st->indexOfAttribute(ns16, nsLen, name16, nameLen));
 
     if (ns) {
         env->ReleaseStringChars(ns, ns16);
@@ -282,35 +282,35 @@
 }
 
 static jint android_content_XmlBlock_nativeGetIdAttribute(JNIEnv* env, jobject clazz,
-                                                          jint token)
+                                                          jlong token)
 {
-    ResXMLParser* st = (ResXMLParser*)token;
+    ResXMLParser* st = reinterpret_cast<ResXMLParser*>(token);
     if (st == NULL) {
         jniThrowNullPointerException(env, NULL);
         return 0;
     }
 
     ssize_t idx = st->indexOfID();
-    return idx >= 0 ? (jint)st->getAttributeValueStringID(idx) : -1;
+    return idx >= 0 ? static_cast<jint>(st->getAttributeValueStringID(idx)) : -1;
 }
 
 static jint android_content_XmlBlock_nativeGetClassAttribute(JNIEnv* env, jobject clazz,
-                                                             jint token)
+                                                             jlong token)
 {
-    ResXMLParser* st = (ResXMLParser*)token;
+    ResXMLParser* st = reinterpret_cast<ResXMLParser*>(token);
     if (st == NULL) {
         jniThrowNullPointerException(env, NULL);
         return 0;
     }
 
     ssize_t idx = st->indexOfClass();
-    return idx >= 0 ? (jint)st->getAttributeValueStringID(idx) : -1;
+    return idx >= 0 ? static_cast<jint>(st->getAttributeValueStringID(idx)) : -1;
 }
 
 static jint android_content_XmlBlock_nativeGetStyleAttribute(JNIEnv* env, jobject clazz,
-                                                             jint token)
+                                                             jlong token)
 {
-    ResXMLParser* st = (ResXMLParser*)token;
+    ResXMLParser* st = reinterpret_cast<ResXMLParser*>(token);
     if (st == NULL) {
         jniThrowNullPointerException(env, NULL);
         return 0;
@@ -332,9 +332,9 @@
 }
 
 static void android_content_XmlBlock_nativeDestroyParseState(JNIEnv* env, jobject clazz,
-                                                          jint token)
+                                                          jlong token)
 {
-    ResXMLParser* st = (ResXMLParser*)token;
+    ResXMLParser* st = reinterpret_cast<ResXMLParser*>(token);
     if (st == NULL) {
         jniThrowNullPointerException(env, NULL);
         return;
@@ -344,9 +344,9 @@
 }
 
 static void android_content_XmlBlock_nativeDestroy(JNIEnv* env, jobject clazz,
-                                                   jint token)
+                                                   jlong token)
 {
-    ResXMLTree* osb = (ResXMLTree*)token;
+    ResXMLTree* osb = reinterpret_cast<ResXMLTree*>(token);
     if (osb == NULL) {
         jniThrowNullPointerException(env, NULL);
         return;
@@ -362,47 +362,47 @@
  */
 static JNINativeMethod gXmlBlockMethods[] = {
     /* name, signature, funcPtr */
-    { "nativeCreate",               "([BII)I",
+    { "nativeCreate",               "([BII)J",
             (void*) android_content_XmlBlock_nativeCreate },
-    { "nativeGetStringBlock",       "(I)I",
+    { "nativeGetStringBlock",       "(J)J",
             (void*) android_content_XmlBlock_nativeGetStringBlock },
-    { "nativeCreateParseState",     "(I)I",
+    { "nativeCreateParseState",     "(J)J",
             (void*) android_content_XmlBlock_nativeCreateParseState },
-    { "nativeNext",                 "(I)I",
+    { "nativeNext",                 "(J)I",
             (void*) android_content_XmlBlock_nativeNext },
-    { "nativeGetNamespace",         "(I)I",
+    { "nativeGetNamespace",         "(J)I",
             (void*) android_content_XmlBlock_nativeGetNamespace },
-    { "nativeGetName",              "(I)I",
+    { "nativeGetName",              "(J)I",
             (void*) android_content_XmlBlock_nativeGetName },
-    { "nativeGetText",              "(I)I",
+    { "nativeGetText",              "(J)I",
             (void*) android_content_XmlBlock_nativeGetText },
-    { "nativeGetLineNumber",        "(I)I",
+    { "nativeGetLineNumber",        "(J)I",
             (void*) android_content_XmlBlock_nativeGetLineNumber },
-    { "nativeGetAttributeCount",    "(I)I",
+    { "nativeGetAttributeCount",    "(J)I",
             (void*) android_content_XmlBlock_nativeGetAttributeCount },
-    { "nativeGetAttributeNamespace","(II)I",
+    { "nativeGetAttributeNamespace","(JI)I",
             (void*) android_content_XmlBlock_nativeGetAttributeNamespace },
-    { "nativeGetAttributeName",     "(II)I",
+    { "nativeGetAttributeName",     "(JI)I",
             (void*) android_content_XmlBlock_nativeGetAttributeName },
-    { "nativeGetAttributeResource", "(II)I",
+    { "nativeGetAttributeResource", "(JI)I",
             (void*) android_content_XmlBlock_nativeGetAttributeResource },
-    { "nativeGetAttributeDataType", "(II)I",
+    { "nativeGetAttributeDataType", "(JI)I",
             (void*) android_content_XmlBlock_nativeGetAttributeDataType },
-    { "nativeGetAttributeData",    "(II)I",
+    { "nativeGetAttributeData",    "(JI)I",
             (void*) android_content_XmlBlock_nativeGetAttributeData },
-    { "nativeGetAttributeStringValue", "(II)I",
+    { "nativeGetAttributeStringValue", "(JI)I",
             (void*) android_content_XmlBlock_nativeGetAttributeStringValue },
-    { "nativeGetAttributeIndex",    "(ILjava/lang/String;Ljava/lang/String;)I",
+    { "nativeGetAttributeIndex",    "(JLjava/lang/String;Ljava/lang/String;)I",
             (void*) android_content_XmlBlock_nativeGetAttributeIndex },
-    { "nativeGetIdAttribute",      "(I)I",
+    { "nativeGetIdAttribute",      "(J)I",
             (void*) android_content_XmlBlock_nativeGetIdAttribute },
-    { "nativeGetClassAttribute",   "(I)I",
+    { "nativeGetClassAttribute",   "(J)I",
             (void*) android_content_XmlBlock_nativeGetClassAttribute },
-    { "nativeGetStyleAttribute",   "(I)I",
+    { "nativeGetStyleAttribute",   "(J)I",
             (void*) android_content_XmlBlock_nativeGetStyleAttribute },
-    { "nativeDestroyParseState",    "(I)V",
+    { "nativeDestroyParseState",    "(J)V",
             (void*) android_content_XmlBlock_nativeDestroyParseState },
-    { "nativeDestroy",              "(I)V",
+    { "nativeDestroy",              "(J)V",
             (void*) android_content_XmlBlock_nativeDestroy },
 };
 
diff --git a/docs/html/guide/topics/renderscript/compute.jd b/docs/html/guide/topics/renderscript/compute.jd
index c62510b..297a2dc 100644
--- a/docs/html/guide/topics/renderscript/compute.jd
+++ b/docs/html/guide/topics/renderscript/compute.jd
@@ -56,7 +56,9 @@
 RenderScript kernel language used in this script. Currently, 1 is the only valid value.</li>
 
 <li>A pragma declaration (<code>#pragma rs java_package_name(com.example.app)</code>) that
-declares the package name of the Java classes reflected from this script.</li>
+declares the package name of the Java classes reflected from this script.
+Note that your .rs file must be part of your application package, and not in a
+library project.</li>
 
 <li>Some number of invokable functions. An invokable function is a single-threaded RenderScript
 function that you can call from your Java code with arbitrary arguments. These are often useful for
@@ -308,4 +310,4 @@
 <li><strong>Tear down the RenderScript context.</strong> The RenderScript context can be destroyed
 with {@link android.renderscript.RenderScript#destroy} or by allowing the RenderScript context
 object to be garbage collected. This will cause any further use of any object belonging to that
-context to throw an exception.</li> </ol>
\ No newline at end of file
+context to throw an exception.</li> </ol>
diff --git a/graphics/jni/android_renderscript_RenderScript.cpp b/graphics/jni/android_renderscript_RenderScript.cpp
deleted file mode 100644
index aa16951..0000000
--- a/graphics/jni/android_renderscript_RenderScript.cpp
+++ /dev/null
@@ -1,1726 +0,0 @@
-/*
- * Copyright (C) 2011-2012 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 "libRS_jni"
-
-#include <stdlib.h>
-#include <stdio.h>
-#include <fcntl.h>
-#include <unistd.h>
-#include <math.h>
-#include <utils/misc.h>
-
-#include <core/SkBitmap.h>
-#include <core/SkPixelRef.h>
-#include <core/SkStream.h>
-#include <core/SkTemplates.h>
-
-#include <androidfw/Asset.h>
-#include <androidfw/AssetManager.h>
-#include <androidfw/ResourceTypes.h>
-
-#include "jni.h"
-#include "JNIHelp.h"
-#include "android_runtime/AndroidRuntime.h"
-#include "android_runtime/android_view_Surface.h"
-#include "android_runtime/android_util_AssetManager.h"
-
-#include <rs.h>
-#include <rsEnv.h>
-#include <gui/Surface.h>
-#include <gui/GLConsumer.h>
-#include <gui/Surface.h>
-#include <android_runtime/android_graphics_SurfaceTexture.h>
-
-//#define LOG_API ALOGE
-#define LOG_API(...)
-
-using namespace android;
-
-class AutoJavaStringToUTF8 {
-public:
-    AutoJavaStringToUTF8(JNIEnv* env, jstring str) : fEnv(env), fJStr(str) {
-        fCStr = env->GetStringUTFChars(str, NULL);
-        fLength = env->GetStringUTFLength(str);
-    }
-    ~AutoJavaStringToUTF8() {
-        fEnv->ReleaseStringUTFChars(fJStr, fCStr);
-    }
-    const char* c_str() const { return fCStr; }
-    jsize length() const { return fLength; }
-
-private:
-    JNIEnv*     fEnv;
-    jstring     fJStr;
-    const char* fCStr;
-    jsize       fLength;
-};
-
-class AutoJavaStringArrayToUTF8 {
-public:
-    AutoJavaStringArrayToUTF8(JNIEnv* env, jobjectArray strings, jsize stringsLength)
-    : mEnv(env), mStrings(strings), mStringsLength(stringsLength) {
-        mCStrings = NULL;
-        mSizeArray = NULL;
-        if (stringsLength > 0) {
-            mCStrings = (const char **)calloc(stringsLength, sizeof(char *));
-            mSizeArray = (size_t*)calloc(stringsLength, sizeof(size_t));
-            for (jsize ct = 0; ct < stringsLength; ct ++) {
-                jstring s = (jstring)mEnv->GetObjectArrayElement(mStrings, ct);
-                mCStrings[ct] = mEnv->GetStringUTFChars(s, NULL);
-                mSizeArray[ct] = mEnv->GetStringUTFLength(s);
-            }
-        }
-    }
-    ~AutoJavaStringArrayToUTF8() {
-        for (jsize ct=0; ct < mStringsLength; ct++) {
-            jstring s = (jstring)mEnv->GetObjectArrayElement(mStrings, ct);
-            mEnv->ReleaseStringUTFChars(s, mCStrings[ct]);
-        }
-        free(mCStrings);
-        free(mSizeArray);
-    }
-    const char **c_str() const { return mCStrings; }
-    size_t *c_str_len() const { return mSizeArray; }
-    jsize length() const { return mStringsLength; }
-
-private:
-    JNIEnv      *mEnv;
-    jobjectArray mStrings;
-    const char **mCStrings;
-    size_t      *mSizeArray;
-    jsize        mStringsLength;
-};
-
-// ---------------------------------------------------------------------------
-
-static jfieldID gContextId = 0;
-static jfieldID gNativeBitmapID = 0;
-static jfieldID gTypeNativeCache = 0;
-
-static void _nInit(JNIEnv *_env, jclass _this)
-{
-    gContextId             = _env->GetFieldID(_this, "mContext", "I");
-
-    jclass bitmapClass = _env->FindClass("android/graphics/Bitmap");
-    gNativeBitmapID = _env->GetFieldID(bitmapClass, "mNativeBitmap", "J");
-}
-
-// ---------------------------------------------------------------------------
-
-static void
-nContextFinish(JNIEnv *_env, jobject _this, RsContext con)
-{
-    LOG_API("nContextFinish, con(%p)", con);
-    rsContextFinish(con);
-}
-
-static void
-nAssignName(JNIEnv *_env, jobject _this, RsContext con, jint obj, jbyteArray str)
-{
-    LOG_API("nAssignName, con(%p), obj(%p)", con, (void *)obj);
-    jint len = _env->GetArrayLength(str);
-    jbyte * cptr = (jbyte *) _env->GetPrimitiveArrayCritical(str, 0);
-    rsAssignName(con, (void *)obj, (const char *)cptr, len);
-    _env->ReleasePrimitiveArrayCritical(str, cptr, JNI_ABORT);
-}
-
-static jstring
-nGetName(JNIEnv *_env, jobject _this, RsContext con, jint obj)
-{
-    LOG_API("nGetName, con(%p), obj(%p)", con, (void *)obj);
-    const char *name = NULL;
-    rsaGetName(con, (void *)obj, &name);
-    if(name == NULL || strlen(name) == 0) {
-        return NULL;
-    }
-    return _env->NewStringUTF(name);
-}
-
-static void
-nObjDestroy(JNIEnv *_env, jobject _this, RsContext con, jint obj)
-{
-    LOG_API("nObjDestroy, con(%p) obj(%p)", con, (void *)obj);
-    rsObjDestroy(con, (void *)obj);
-}
-
-// ---------------------------------------------------------------------------
-
-static jint
-nDeviceCreate(JNIEnv *_env, jobject _this)
-{
-    LOG_API("nDeviceCreate");
-    return (jint)rsDeviceCreate();
-}
-
-static void
-nDeviceDestroy(JNIEnv *_env, jobject _this, jint dev)
-{
-    LOG_API("nDeviceDestroy");
-    return rsDeviceDestroy((RsDevice)dev);
-}
-
-static void
-nDeviceSetConfig(JNIEnv *_env, jobject _this, jint dev, jint p, jint value)
-{
-    LOG_API("nDeviceSetConfig  dev(%p), param(%i), value(%i)", (void *)dev, p, value);
-    return rsDeviceSetConfig((RsDevice)dev, (RsDeviceParam)p, value);
-}
-
-static jint
-nContextCreate(JNIEnv *_env, jobject _this, jint dev, jint ver, jint sdkVer, jint ct)
-{
-    LOG_API("nContextCreate");
-    return (jint)rsContextCreate((RsDevice)dev, ver, sdkVer, (RsContextType)ct, 0);
-}
-
-static jint
-nContextCreateGL(JNIEnv *_env, jobject _this, jint dev, jint ver, jint sdkVer,
-                 int colorMin, int colorPref,
-                 int alphaMin, int alphaPref,
-                 int depthMin, int depthPref,
-                 int stencilMin, int stencilPref,
-                 int samplesMin, int samplesPref, float samplesQ,
-                 int dpi)
-{
-    RsSurfaceConfig sc;
-    sc.alphaMin = alphaMin;
-    sc.alphaPref = alphaPref;
-    sc.colorMin = colorMin;
-    sc.colorPref = colorPref;
-    sc.depthMin = depthMin;
-    sc.depthPref = depthPref;
-    sc.samplesMin = samplesMin;
-    sc.samplesPref = samplesPref;
-    sc.samplesQ = samplesQ;
-
-    LOG_API("nContextCreateGL");
-    return (jint)rsContextCreateGL((RsDevice)dev, ver, sdkVer, sc, dpi);
-}
-
-static void
-nContextSetPriority(JNIEnv *_env, jobject _this, RsContext con, jint p)
-{
-    LOG_API("ContextSetPriority, con(%p), priority(%i)", con, p);
-    rsContextSetPriority(con, p);
-}
-
-
-
-static void
-nContextSetSurface(JNIEnv *_env, jobject _this, RsContext con, jint width, jint height, jobject wnd)
-{
-    LOG_API("nContextSetSurface, con(%p), width(%i), height(%i), surface(%p)", con, width, height, (Surface *)wnd);
-
-    ANativeWindow * window = NULL;
-    if (wnd == NULL) {
-
-    } else {
-        window = android_view_Surface_getNativeWindow(_env, wnd).get();
-    }
-
-    rsContextSetSurface(con, width, height, window);
-}
-
-static void
-nContextDestroy(JNIEnv *_env, jobject _this, RsContext con)
-{
-    LOG_API("nContextDestroy, con(%p)", con);
-    rsContextDestroy(con);
-}
-
-static void
-nContextDump(JNIEnv *_env, jobject _this, RsContext con, jint bits)
-{
-    LOG_API("nContextDump, con(%p)  bits(%i)", (RsContext)con, bits);
-    rsContextDump((RsContext)con, bits);
-}
-
-static void
-nContextPause(JNIEnv *_env, jobject _this, RsContext con)
-{
-    LOG_API("nContextPause, con(%p)", con);
-    rsContextPause(con);
-}
-
-static void
-nContextResume(JNIEnv *_env, jobject _this, RsContext con)
-{
-    LOG_API("nContextResume, con(%p)", con);
-    rsContextResume(con);
-}
-
-
-static jstring
-nContextGetErrorMessage(JNIEnv *_env, jobject _this, RsContext con)
-{
-    LOG_API("nContextGetErrorMessage, con(%p)", con);
-    char buf[1024];
-
-    size_t receiveLen;
-    uint32_t subID;
-    int id = rsContextGetMessage(con,
-                                 buf, sizeof(buf),
-                                 &receiveLen, sizeof(receiveLen),
-                                 &subID, sizeof(subID));
-    if (!id && receiveLen) {
-        ALOGV("message receive buffer too small.  %i", receiveLen);
-    }
-    return _env->NewStringUTF(buf);
-}
-
-static jint
-nContextGetUserMessage(JNIEnv *_env, jobject _this, RsContext con, jintArray data)
-{
-    jint len = _env->GetArrayLength(data);
-    LOG_API("nContextGetMessage, con(%p), len(%i)", con, len);
-    jint *ptr = _env->GetIntArrayElements(data, NULL);
-    size_t receiveLen;
-    uint32_t subID;
-    int id = rsContextGetMessage(con,
-                                 ptr, len * 4,
-                                 &receiveLen, sizeof(receiveLen),
-                                 &subID, sizeof(subID));
-    if (!id && receiveLen) {
-        ALOGV("message receive buffer too small.  %i", receiveLen);
-    }
-    _env->ReleaseIntArrayElements(data, ptr, 0);
-    return id;
-}
-
-static jint
-nContextPeekMessage(JNIEnv *_env, jobject _this, RsContext con, jintArray auxData)
-{
-    LOG_API("nContextPeekMessage, con(%p)", con);
-    jint *auxDataPtr = _env->GetIntArrayElements(auxData, NULL);
-    size_t receiveLen;
-    uint32_t subID;
-    int id = rsContextPeekMessage(con, &receiveLen, sizeof(receiveLen),
-                                  &subID, sizeof(subID));
-    auxDataPtr[0] = (jint)subID;
-    auxDataPtr[1] = (jint)receiveLen;
-    _env->ReleaseIntArrayElements(auxData, auxDataPtr, 0);
-    return id;
-}
-
-static void nContextInitToClient(JNIEnv *_env, jobject _this, RsContext con)
-{
-    LOG_API("nContextInitToClient, con(%p)", con);
-    rsContextInitToClient(con);
-}
-
-static void nContextDeinitToClient(JNIEnv *_env, jobject _this, RsContext con)
-{
-    LOG_API("nContextDeinitToClient, con(%p)", con);
-    rsContextDeinitToClient(con);
-}
-
-static void
-nContextSendMessage(JNIEnv *_env, jobject _this, RsContext con, jint id, jintArray data)
-{
-    jint *ptr = NULL;
-    jint len = 0;
-    if (data) {
-        len = _env->GetArrayLength(data);
-        ptr = _env->GetIntArrayElements(data, NULL);
-    }
-    LOG_API("nContextSendMessage, con(%p), id(%i), len(%i)", con, id, len);
-    rsContextSendMessage(con, id, (const uint8_t *)ptr, len * sizeof(int));
-    if (data) {
-        _env->ReleaseIntArrayElements(data, ptr, JNI_ABORT);
-    }
-}
-
-
-
-static jint
-nElementCreate(JNIEnv *_env, jobject _this, RsContext con, jint type, jint kind, jboolean norm, jint size)
-{
-    LOG_API("nElementCreate, con(%p), type(%i), kind(%i), norm(%i), size(%i)", con, type, kind, norm, size);
-    return (jint)rsElementCreate(con, (RsDataType)type, (RsDataKind)kind, norm, size);
-}
-
-static jint
-nElementCreate2(JNIEnv *_env, jobject _this, RsContext con,
-                jintArray _ids, jobjectArray _names, jintArray _arraySizes)
-{
-    int fieldCount = _env->GetArrayLength(_ids);
-    LOG_API("nElementCreate2, con(%p)", con);
-
-    jint *ids = _env->GetIntArrayElements(_ids, NULL);
-    jint *arraySizes = _env->GetIntArrayElements(_arraySizes, NULL);
-
-    AutoJavaStringArrayToUTF8 names(_env, _names, fieldCount);
-
-    const char **nameArray = names.c_str();
-    size_t *sizeArray = names.c_str_len();
-
-    jint id = (jint)rsElementCreate2(con,
-                                     (RsElement *)ids, fieldCount,
-                                     nameArray, fieldCount * sizeof(size_t),  sizeArray,
-                                     (const uint32_t *)arraySizes, fieldCount);
-
-    _env->ReleaseIntArrayElements(_ids, ids, JNI_ABORT);
-    _env->ReleaseIntArrayElements(_arraySizes, arraySizes, JNI_ABORT);
-    return (jint)id;
-}
-
-static void
-nElementGetNativeData(JNIEnv *_env, jobject _this, RsContext con, jint id, jintArray _elementData)
-{
-    int dataSize = _env->GetArrayLength(_elementData);
-    LOG_API("nElementGetNativeData, con(%p)", con);
-
-    // we will pack mType; mKind; mNormalized; mVectorSize; NumSubElements
-    assert(dataSize == 5);
-
-    uint32_t elementData[5];
-    rsaElementGetNativeData(con, (RsElement)id, elementData, dataSize);
-
-    for(jint i = 0; i < dataSize; i ++) {
-        _env->SetIntArrayRegion(_elementData, i, 1, (const jint*)&elementData[i]);
-    }
-}
-
-
-static void
-nElementGetSubElements(JNIEnv *_env, jobject _this, RsContext con, jint id,
-                       jintArray _IDs,
-                       jobjectArray _names,
-                       jintArray _arraySizes)
-{
-    int dataSize = _env->GetArrayLength(_IDs);
-    LOG_API("nElementGetSubElements, con(%p)", con);
-
-    uint32_t *ids = (uint32_t *)malloc((uint32_t)dataSize * sizeof(uint32_t));
-    const char **names = (const char **)malloc((uint32_t)dataSize * sizeof(const char *));
-    uint32_t *arraySizes = (uint32_t *)malloc((uint32_t)dataSize * sizeof(uint32_t));
-
-    rsaElementGetSubElements(con, (RsElement)id, ids, names, arraySizes, (uint32_t)dataSize);
-
-    for(jint i = 0; i < dataSize; i++) {
-        _env->SetObjectArrayElement(_names, i, _env->NewStringUTF(names[i]));
-        _env->SetIntArrayRegion(_IDs, i, 1, (const jint*)&ids[i]);
-        _env->SetIntArrayRegion(_arraySizes, i, 1, (const jint*)&arraySizes[i]);
-    }
-
-    free(ids);
-    free(names);
-    free(arraySizes);
-}
-
-// -----------------------------------
-
-static int
-nTypeCreate(JNIEnv *_env, jobject _this, RsContext con, RsElement 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)",
-            con, eid, dimx, dimy, dimz, mips, faces, yuv);
-
-    jint id = (jint)rsTypeCreate(con, (RsElement)eid, dimx, dimy, dimz, mips, faces, yuv);
-    return (jint)id;
-}
-
-static void
-nTypeGetNativeData(JNIEnv *_env, jobject _this, RsContext con, jint id, jintArray _typeData)
-{
-    // We are packing 6 items: mDimX; mDimY; mDimZ;
-    // mDimLOD; mDimFaces; mElement; into typeData
-    int elementCount = _env->GetArrayLength(_typeData);
-
-    assert(elementCount == 6);
-    LOG_API("nTypeCreate, con(%p)", con);
-
-    uint32_t typeData[6];
-    rsaTypeGetNativeData(con, (RsType)id, typeData, 6);
-
-    for(jint i = 0; i < elementCount; i ++) {
-        _env->SetIntArrayRegion(_typeData, i, 1, (const jint*)&typeData[i]);
-    }
-}
-
-// -----------------------------------
-
-static jint
-nAllocationCreateTyped(JNIEnv *_env, jobject _this, RsContext con, jint type, jint mips, jint usage, jint pointer)
-{
-    LOG_API("nAllocationCreateTyped, con(%p), type(%p), mip(%i), usage(%i), ptr(%p)", con, (RsElement)type, mips, usage, (void *)pointer);
-    return (jint) rsAllocationCreateTyped(con, (RsType)type, (RsAllocationMipmapControl)mips, (uint32_t)usage, (uint32_t)pointer);
-}
-
-static void
-nAllocationSyncAll(JNIEnv *_env, jobject _this, RsContext con, jint a, jint bits)
-{
-    LOG_API("nAllocationSyncAll, con(%p), a(%p), bits(0x%08x)", con, (RsAllocation)a, bits);
-    rsAllocationSyncAll(con, (RsAllocation)a, (RsAllocationUsageType)bits);
-}
-
-static jobject
-nAllocationGetSurface(JNIEnv *_env, jobject _this, RsContext con, jint a)
-{
-    LOG_API("nAllocationGetSurface, con(%p), a(%p)", con, (RsAllocation)a);
-
-    IGraphicBufferProducer *v = (IGraphicBufferProducer *)rsAllocationGetSurface(con, (RsAllocation)a);
-    sp<IGraphicBufferProducer> bp = v;
-    v->decStrong(NULL);
-
-    jobject o = android_view_Surface_createFromIGraphicBufferProducer(_env, bp);
-    return o;
-}
-
-static void
-nAllocationSetSurface(JNIEnv *_env, jobject _this, RsContext con, RsAllocation alloc, jobject sur)
-{
-    LOG_API("nAllocationSetSurface, con(%p), alloc(%p), surface(%p)",
-            con, alloc, (Surface *)sur);
-
-    sp<Surface> s;
-    if (sur != 0) {
-        s = android_view_Surface_getSurface(_env, sur);
-    }
-
-    rsAllocationSetSurface(con, alloc, static_cast<ANativeWindow *>(s.get()));
-}
-
-static void
-nAllocationIoSend(JNIEnv *_env, jobject _this, RsContext con, RsAllocation alloc)
-{
-    LOG_API("nAllocationIoSend, con(%p), alloc(%p)", con, alloc);
-    rsAllocationIoSend(con, alloc);
-}
-
-static void
-nAllocationIoReceive(JNIEnv *_env, jobject _this, RsContext con, RsAllocation alloc)
-{
-    LOG_API("nAllocationIoReceive, con(%p), alloc(%p)", con, alloc);
-    rsAllocationIoReceive(con, alloc);
-}
-
-
-static void
-nAllocationGenerateMipmaps(JNIEnv *_env, jobject _this, RsContext con, jint alloc)
-{
-    LOG_API("nAllocationGenerateMipmaps, con(%p), a(%p)", con, (RsAllocation)alloc);
-    rsAllocationGenerateMipmaps(con, (RsAllocation)alloc);
-}
-
-static int
-nAllocationCreateFromBitmap(JNIEnv *_env, jobject _this, RsContext con, jint type, jint mip, jobject jbitmap, jint usage)
-{
-    SkBitmap const * nativeBitmap =
-            (SkBitmap const *)_env->GetLongField(jbitmap, gNativeBitmapID);
-    const SkBitmap& bitmap(*nativeBitmap);
-
-    bitmap.lockPixels();
-    const void* ptr = bitmap.getPixels();
-    jint id = (jint)rsAllocationCreateFromBitmap(con,
-                                                  (RsType)type, (RsAllocationMipmapControl)mip,
-                                                  ptr, bitmap.getSize(), usage);
-    bitmap.unlockPixels();
-    return id;
-}
-
-static int
-nAllocationCreateBitmapBackedAllocation(JNIEnv *_env, jobject _this, RsContext con, jint type, jint mip, jobject jbitmap, jint usage)
-{
-    SkBitmap const * nativeBitmap =
-            (SkBitmap const *)_env->GetLongField(jbitmap, gNativeBitmapID);
-    const SkBitmap& bitmap(*nativeBitmap);
-
-    bitmap.lockPixels();
-    const void* ptr = bitmap.getPixels();
-    jint id = (jint)rsAllocationCreateTyped(con,
-                                            (RsType)type, (RsAllocationMipmapControl)mip,
-                                            (uint32_t)usage, (size_t)ptr);
-    bitmap.unlockPixels();
-    return id;
-}
-
-static int
-nAllocationCubeCreateFromBitmap(JNIEnv *_env, jobject _this, RsContext con, jint type, jint mip, jobject jbitmap, jint usage)
-{
-    SkBitmap const * nativeBitmap =
-            (SkBitmap const *)_env->GetLongField(jbitmap, gNativeBitmapID);
-    const SkBitmap& bitmap(*nativeBitmap);
-
-    bitmap.lockPixels();
-    const void* ptr = bitmap.getPixels();
-    jint id = (jint)rsAllocationCubeCreateFromBitmap(con,
-                                                      (RsType)type, (RsAllocationMipmapControl)mip,
-                                                      ptr, bitmap.getSize(), usage);
-    bitmap.unlockPixels();
-    return id;
-}
-
-static void
-nAllocationCopyFromBitmap(JNIEnv *_env, jobject _this, RsContext con, jint alloc, jobject jbitmap)
-{
-    SkBitmap const * nativeBitmap =
-            (SkBitmap const *)_env->GetLongField(jbitmap, gNativeBitmapID);
-    const SkBitmap& bitmap(*nativeBitmap);
-    int w = bitmap.width();
-    int h = bitmap.height();
-
-    bitmap.lockPixels();
-    const void* ptr = bitmap.getPixels();
-    rsAllocation2DData(con, (RsAllocation)alloc, 0, 0,
-                       0, RS_ALLOCATION_CUBEMAP_FACE_POSITIVE_X,
-                       w, h, ptr, bitmap.getSize(), 0);
-    bitmap.unlockPixels();
-}
-
-static void
-nAllocationCopyToBitmap(JNIEnv *_env, jobject _this, RsContext con, jint alloc, jobject jbitmap)
-{
-    SkBitmap const * nativeBitmap =
-            (SkBitmap const *)_env->GetLongField(jbitmap, gNativeBitmapID);
-    const SkBitmap& bitmap(*nativeBitmap);
-
-    bitmap.lockPixels();
-    void* ptr = bitmap.getPixels();
-    rsAllocationCopyToBitmap(con, (RsAllocation)alloc, ptr, bitmap.getSize());
-    bitmap.unlockPixels();
-    bitmap.notifyPixelsChanged();
-}
-
-static void ReleaseBitmapCallback(void *bmp)
-{
-    SkBitmap const * nativeBitmap = (SkBitmap const *)bmp;
-    nativeBitmap->unlockPixels();
-}
-
-
-static void
-nAllocationData1D_i(JNIEnv *_env, jobject _this, RsContext con, jint alloc, jint offset, jint lod, jint count, jintArray data, int sizeBytes)
-{
-    jint len = _env->GetArrayLength(data);
-    LOG_API("nAllocation1DData_i, con(%p), adapter(%p), offset(%i), count(%i), len(%i), sizeBytes(%i)", con, (RsAllocation)alloc, offset, count, len, sizeBytes);
-    jint *ptr = _env->GetIntArrayElements(data, NULL);
-    rsAllocation1DData(con, (RsAllocation)alloc, offset, lod, count, ptr, sizeBytes);
-    _env->ReleaseIntArrayElements(data, ptr, JNI_ABORT);
-}
-
-static void
-nAllocationData1D_s(JNIEnv *_env, jobject _this, RsContext con, jint alloc, jint offset, jint lod, jint count, jshortArray data, int sizeBytes)
-{
-    jint len = _env->GetArrayLength(data);
-    LOG_API("nAllocation1DData_s, con(%p), adapter(%p), offset(%i), count(%i), len(%i), sizeBytes(%i)", con, (RsAllocation)alloc, offset, count, len, sizeBytes);
-    jshort *ptr = _env->GetShortArrayElements(data, NULL);
-    rsAllocation1DData(con, (RsAllocation)alloc, offset, lod, count, ptr, sizeBytes);
-    _env->ReleaseShortArrayElements(data, ptr, JNI_ABORT);
-}
-
-static void
-nAllocationData1D_b(JNIEnv *_env, jobject _this, RsContext con, jint alloc, jint offset, jint lod, jint count, jbyteArray data, int sizeBytes)
-{
-    jint len = _env->GetArrayLength(data);
-    LOG_API("nAllocation1DData_b, con(%p), adapter(%p), offset(%i), count(%i), len(%i), sizeBytes(%i)", con, (RsAllocation)alloc, offset, count, len, sizeBytes);
-    jbyte *ptr = _env->GetByteArrayElements(data, NULL);
-    rsAllocation1DData(con, (RsAllocation)alloc, offset, lod, count, ptr, sizeBytes);
-    _env->ReleaseByteArrayElements(data, ptr, JNI_ABORT);
-}
-
-static void
-nAllocationData1D_f(JNIEnv *_env, jobject _this, RsContext con, jint alloc, jint offset, jint lod, jint count, jfloatArray data, int sizeBytes)
-{
-    jint len = _env->GetArrayLength(data);
-    LOG_API("nAllocation1DData_f, con(%p), adapter(%p), offset(%i), count(%i), len(%i), sizeBytes(%i)", con, (RsAllocation)alloc, offset, count, len, sizeBytes);
-    jfloat *ptr = _env->GetFloatArrayElements(data, NULL);
-    rsAllocation1DData(con, (RsAllocation)alloc, offset, lod, count, ptr, sizeBytes);
-    _env->ReleaseFloatArrayElements(data, ptr, JNI_ABORT);
-}
-
-static void
-//    native void rsnAllocationElementData1D(int con, int id, int xoff, int compIdx, byte[] d, int sizeBytes);
-nAllocationElementData1D(JNIEnv *_env, jobject _this, RsContext con, jint alloc, jint offset, jint lod, jint compIdx, jbyteArray data, int sizeBytes)
-{
-    jint len = _env->GetArrayLength(data);
-    LOG_API("nAllocationElementData1D, con(%p), alloc(%p), offset(%i), comp(%i), len(%i), sizeBytes(%i)", con, (RsAllocation)alloc, offset, compIdx, len, sizeBytes);
-    jbyte *ptr = _env->GetByteArrayElements(data, NULL);
-    rsAllocation1DElementData(con, (RsAllocation)alloc, offset, lod, ptr, sizeBytes, compIdx);
-    _env->ReleaseByteArrayElements(data, ptr, JNI_ABORT);
-}
-
-static void
-nAllocationData2D_s(JNIEnv *_env, jobject _this, RsContext con, jint alloc, jint xoff, jint yoff, jint lod, jint face,
-                    jint w, jint h, jshortArray data, int sizeBytes)
-{
-    jint len = _env->GetArrayLength(data);
-    LOG_API("nAllocation2DData_s, con(%p), adapter(%p), xoff(%i), yoff(%i), w(%i), h(%i), len(%i)", con, (RsAllocation)alloc, xoff, yoff, w, h, len);
-    jshort *ptr = _env->GetShortArrayElements(data, NULL);
-    rsAllocation2DData(con, (RsAllocation)alloc, xoff, yoff, lod, (RsAllocationCubemapFace)face, w, h, ptr, sizeBytes, 0);
-    _env->ReleaseShortArrayElements(data, ptr, JNI_ABORT);
-}
-
-static void
-nAllocationData2D_b(JNIEnv *_env, jobject _this, RsContext con, jint alloc, jint xoff, jint yoff, jint lod, jint face,
-                    jint w, jint h, jbyteArray data, int sizeBytes)
-{
-    jint len = _env->GetArrayLength(data);
-    LOG_API("nAllocation2DData_b, con(%p), adapter(%p), xoff(%i), yoff(%i), w(%i), h(%i), len(%i)", con, (RsAllocation)alloc, xoff, yoff, w, h, len);
-    jbyte *ptr = _env->GetByteArrayElements(data, NULL);
-    rsAllocation2DData(con, (RsAllocation)alloc, xoff, yoff, lod, (RsAllocationCubemapFace)face, w, h, ptr, sizeBytes, 0);
-    _env->ReleaseByteArrayElements(data, ptr, JNI_ABORT);
-}
-
-static void
-nAllocationData2D_i(JNIEnv *_env, jobject _this, RsContext con, jint alloc, jint xoff, jint yoff, jint lod, jint face,
-                    jint w, jint h, jintArray data, int sizeBytes)
-{
-    jint len = _env->GetArrayLength(data);
-    LOG_API("nAllocation2DData_i, con(%p), adapter(%p), xoff(%i), yoff(%i), w(%i), h(%i), len(%i)", con, (RsAllocation)alloc, xoff, yoff, w, h, len);
-    jint *ptr = _env->GetIntArrayElements(data, NULL);
-    rsAllocation2DData(con, (RsAllocation)alloc, xoff, yoff, lod, (RsAllocationCubemapFace)face, w, h, ptr, sizeBytes, 0);
-    _env->ReleaseIntArrayElements(data, ptr, JNI_ABORT);
-}
-
-static void
-nAllocationData2D_f(JNIEnv *_env, jobject _this, RsContext con, jint alloc, jint xoff, jint yoff, jint lod, jint face,
-                    jint w, jint h, jfloatArray data, int sizeBytes)
-{
-    jint len = _env->GetArrayLength(data);
-    LOG_API("nAllocation2DData_i, con(%p), adapter(%p), xoff(%i), yoff(%i), w(%i), h(%i), len(%i)", con, (RsAllocation)alloc, xoff, yoff, w, h, len);
-    jfloat *ptr = _env->GetFloatArrayElements(data, NULL);
-    rsAllocation2DData(con, (RsAllocation)alloc, xoff, yoff, lod, (RsAllocationCubemapFace)face, w, h, ptr, sizeBytes, 0);
-    _env->ReleaseFloatArrayElements(data, ptr, JNI_ABORT);
-}
-
-static void
-nAllocationData2D_alloc(JNIEnv *_env, jobject _this, RsContext con,
-                        jint dstAlloc, jint dstXoff, jint dstYoff,
-                        jint dstMip, jint dstFace,
-                        jint width, jint height,
-                        jint 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)",
-            con, (RsAllocation)dstAlloc, dstXoff, dstYoff, dstMip, dstFace,
-            width, height, (RsAllocation)srcAlloc, srcXoff, srcYoff, srcMip, srcFace);
-
-    rsAllocationCopy2DRange(con,
-                            (RsAllocation)dstAlloc,
-                            dstXoff, dstYoff,
-                            dstMip, dstFace,
-                            width, height,
-                            (RsAllocation)srcAlloc,
-                            srcXoff, srcYoff,
-                            srcMip, srcFace);
-}
-
-static void
-nAllocationData3D_s(JNIEnv *_env, jobject _this, RsContext con, jint alloc, jint xoff, jint yoff, jint zoff, jint lod,
-                    jint w, jint h, jint d, jshortArray data, int sizeBytes)
-{
-    jint len = _env->GetArrayLength(data);
-    LOG_API("nAllocation3DData_s, con(%p), adapter(%p), xoff(%i), yoff(%i), w(%i), h(%i), len(%i)", con, (RsAllocation)alloc, xoff, yoff, zoff, w, h, d, len);
-    jshort *ptr = _env->GetShortArrayElements(data, NULL);
-    rsAllocation3DData(con, (RsAllocation)alloc, xoff, yoff, zoff, lod, w, h, d, ptr, sizeBytes, 0);
-    _env->ReleaseShortArrayElements(data, ptr, JNI_ABORT);
-}
-
-static void
-nAllocationData3D_b(JNIEnv *_env, jobject _this, RsContext con, jint alloc, jint xoff, jint yoff, jint zoff, jint lod,
-                    jint w, jint h, jint d, jbyteArray data, int sizeBytes)
-{
-    jint len = _env->GetArrayLength(data);
-    LOG_API("nAllocation3DData_b, con(%p), adapter(%p), xoff(%i), yoff(%i), w(%i), h(%i), len(%i)", con, (RsAllocation)alloc, xoff, yoff, zoff, w, h, d, len);
-    jbyte *ptr = _env->GetByteArrayElements(data, NULL);
-    rsAllocation3DData(con, (RsAllocation)alloc, xoff, yoff, zoff, lod, w, h, d, ptr, sizeBytes, 0);
-    _env->ReleaseByteArrayElements(data, ptr, JNI_ABORT);
-}
-
-static void
-nAllocationData3D_i(JNIEnv *_env, jobject _this, RsContext con, jint alloc, jint xoff, jint yoff, jint zoff, jint lod,
-                    jint w, jint h, jint d, jintArray data, int sizeBytes)
-{
-    jint len = _env->GetArrayLength(data);
-    LOG_API("nAllocation3DData_i, con(%p), adapter(%p), xoff(%i), yoff(%i), w(%i), h(%i), len(%i)", con, (RsAllocation)alloc, xoff, yoff, zoff, w, h, d, len);
-    jint *ptr = _env->GetIntArrayElements(data, NULL);
-    rsAllocation3DData(con, (RsAllocation)alloc, xoff, yoff, zoff, lod, w, h, d, ptr, sizeBytes, 0);
-    _env->ReleaseIntArrayElements(data, ptr, JNI_ABORT);
-}
-
-static void
-nAllocationData3D_f(JNIEnv *_env, jobject _this, RsContext con, jint alloc, jint xoff, jint yoff, jint zoff, jint lod,
-                    jint w, jint h, jint d, jfloatArray data, int sizeBytes)
-{
-    jint len = _env->GetArrayLength(data);
-    LOG_API("nAllocation3DData_f, con(%p), adapter(%p), xoff(%i), yoff(%i), w(%i), h(%i), len(%i)", con, (RsAllocation)alloc, xoff, yoff, zoff, w, h, d, len);
-    jfloat *ptr = _env->GetFloatArrayElements(data, NULL);
-    rsAllocation3DData(con, (RsAllocation)alloc, xoff, yoff, zoff, lod, w, h, d, ptr, sizeBytes, 0);
-    _env->ReleaseFloatArrayElements(data, ptr, JNI_ABORT);
-}
-
-static void
-nAllocationData3D_alloc(JNIEnv *_env, jobject _this, RsContext con,
-                        jint dstAlloc, jint dstXoff, jint dstYoff, jint dstZoff,
-                        jint dstMip,
-                        jint width, jint height, jint depth,
-                        jint 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)",
-            con, (RsAllocation)dstAlloc, dstXoff, dstYoff, dstMip, dstFace,
-            width, height, (RsAllocation)srcAlloc, srcXoff, srcYoff, srcMip, srcFace);
-
-    rsAllocationCopy3DRange(con,
-                            (RsAllocation)dstAlloc,
-                            dstXoff, dstYoff, dstZoff, dstMip,
-                            width, height, depth,
-                            (RsAllocation)srcAlloc,
-                            srcXoff, srcYoff, srcZoff, srcMip);
-}
-
-static void
-nAllocationRead_i(JNIEnv *_env, jobject _this, RsContext con, jint alloc, jintArray data)
-{
-    jint len = _env->GetArrayLength(data);
-    LOG_API("nAllocationRead_i, con(%p), alloc(%p), len(%i)", con, (RsAllocation)alloc, len);
-    jint *ptr = _env->GetIntArrayElements(data, NULL);
-    jsize length = _env->GetArrayLength(data);
-    rsAllocationRead(con, (RsAllocation)alloc, ptr, length * sizeof(int));
-    _env->ReleaseIntArrayElements(data, ptr, 0);
-}
-
-static void
-nAllocationRead_s(JNIEnv *_env, jobject _this, RsContext con, jint alloc, jshortArray data)
-{
-    jint len = _env->GetArrayLength(data);
-    LOG_API("nAllocationRead_i, con(%p), alloc(%p), len(%i)", con, (RsAllocation)alloc, len);
-    jshort *ptr = _env->GetShortArrayElements(data, NULL);
-    jsize length = _env->GetArrayLength(data);
-    rsAllocationRead(con, (RsAllocation)alloc, ptr, length * sizeof(short));
-    _env->ReleaseShortArrayElements(data, ptr, 0);
-}
-
-static void
-nAllocationRead_b(JNIEnv *_env, jobject _this, RsContext con, jint alloc, jbyteArray data)
-{
-    jint len = _env->GetArrayLength(data);
-    LOG_API("nAllocationRead_i, con(%p), alloc(%p), len(%i)", con, (RsAllocation)alloc, len);
-    jbyte *ptr = _env->GetByteArrayElements(data, NULL);
-    jsize length = _env->GetArrayLength(data);
-    rsAllocationRead(con, (RsAllocation)alloc, ptr, length * sizeof(char));
-    _env->ReleaseByteArrayElements(data, ptr, 0);
-}
-
-static void
-nAllocationRead_f(JNIEnv *_env, jobject _this, RsContext con, jint alloc, jfloatArray data)
-{
-    jint len = _env->GetArrayLength(data);
-    LOG_API("nAllocationRead_f, con(%p), alloc(%p), len(%i)", con, (RsAllocation)alloc, len);
-    jfloat *ptr = _env->GetFloatArrayElements(data, NULL);
-    jsize length = _env->GetArrayLength(data);
-    rsAllocationRead(con, (RsAllocation)alloc, ptr, length * sizeof(float));
-    _env->ReleaseFloatArrayElements(data, ptr, 0);
-}
-
-static jint
-nAllocationGetType(JNIEnv *_env, jobject _this, RsContext con, jint a)
-{
-    LOG_API("nAllocationGetType, con(%p), a(%p)", con, (RsAllocation)a);
-    return (jint) rsaAllocationGetType(con, (RsAllocation)a);
-}
-
-static void
-nAllocationResize1D(JNIEnv *_env, jobject _this, RsContext con, jint alloc, jint dimX)
-{
-    LOG_API("nAllocationResize1D, con(%p), alloc(%p), sizeX(%i)", con, (RsAllocation)alloc, dimX);
-    rsAllocationResize1D(con, (RsAllocation)alloc, dimX);
-}
-
-// -----------------------------------
-
-static int
-nFileA3DCreateFromAssetStream(JNIEnv *_env, jobject _this, RsContext con, jint native_asset)
-{
-    ALOGV("______nFileA3D %u", (uint32_t) native_asset);
-
-    Asset* asset = reinterpret_cast<Asset*>(native_asset);
-
-    jint id = (jint)rsaFileA3DCreateFromMemory(con, asset->getBuffer(false), asset->getLength());
-    return id;
-}
-
-static int
-nFileA3DCreateFromAsset(JNIEnv *_env, jobject _this, RsContext con, jobject _assetMgr, jstring _path)
-{
-    AssetManager* mgr = assetManagerForJavaObject(_env, _assetMgr);
-    if (mgr == NULL) {
-        return 0;
-    }
-
-    AutoJavaStringToUTF8 str(_env, _path);
-    Asset* asset = mgr->open(str.c_str(), Asset::ACCESS_BUFFER);
-    if (asset == NULL) {
-        return 0;
-    }
-
-    jint id = (jint)rsaFileA3DCreateFromAsset(con, asset);
-    return id;
-}
-
-static int
-nFileA3DCreateFromFile(JNIEnv *_env, jobject _this, RsContext con, jstring fileName)
-{
-    AutoJavaStringToUTF8 fileNameUTF(_env, fileName);
-    jint id = (jint)rsaFileA3DCreateFromFile(con, fileNameUTF.c_str());
-
-    return id;
-}
-
-static int
-nFileA3DGetNumIndexEntries(JNIEnv *_env, jobject _this, RsContext con, jint fileA3D)
-{
-    int32_t numEntries = 0;
-    rsaFileA3DGetNumIndexEntries(con, &numEntries, (RsFile)fileA3D);
-    return numEntries;
-}
-
-static void
-nFileA3DGetIndexEntries(JNIEnv *_env, jobject _this, RsContext con, jint fileA3D, jint numEntries, jintArray _ids, jobjectArray _entries)
-{
-    ALOGV("______nFileA3D %u", (uint32_t) fileA3D);
-    RsFileIndexEntry *fileEntries = (RsFileIndexEntry*)malloc((uint32_t)numEntries * sizeof(RsFileIndexEntry));
-
-    rsaFileA3DGetIndexEntries(con, fileEntries, (uint32_t)numEntries, (RsFile)fileA3D);
-
-    for(jint i = 0; i < numEntries; i ++) {
-        _env->SetObjectArrayElement(_entries, i, _env->NewStringUTF(fileEntries[i].objectName));
-        _env->SetIntArrayRegion(_ids, i, 1, (const jint*)&fileEntries[i].classID);
-    }
-
-    free(fileEntries);
-}
-
-static int
-nFileA3DGetEntryByIndex(JNIEnv *_env, jobject _this, RsContext con, jint fileA3D, jint index)
-{
-    ALOGV("______nFileA3D %u", (uint32_t) fileA3D);
-    jint id = (jint)rsaFileA3DGetEntryByIndex(con, (uint32_t)index, (RsFile)fileA3D);
-    return id;
-}
-
-// -----------------------------------
-
-static int
-nFontCreateFromFile(JNIEnv *_env, jobject _this, RsContext con,
-                    jstring fileName, jfloat fontSize, jint dpi)
-{
-    AutoJavaStringToUTF8 fileNameUTF(_env, fileName);
-    jint id = (jint)rsFontCreateFromFile(con,
-                                         fileNameUTF.c_str(), fileNameUTF.length(),
-                                         fontSize, dpi);
-
-    return id;
-}
-
-static int
-nFontCreateFromAssetStream(JNIEnv *_env, jobject _this, RsContext con,
-                           jstring name, jfloat fontSize, jint dpi, jint native_asset)
-{
-    Asset* asset = reinterpret_cast<Asset*>(native_asset);
-    AutoJavaStringToUTF8 nameUTF(_env, name);
-
-    jint id = (jint)rsFontCreateFromMemory(con,
-                                           nameUTF.c_str(), nameUTF.length(),
-                                           fontSize, dpi,
-                                           asset->getBuffer(false), asset->getLength());
-    return id;
-}
-
-static int
-nFontCreateFromAsset(JNIEnv *_env, jobject _this, RsContext con, jobject _assetMgr, jstring _path,
-                     jfloat fontSize, jint dpi)
-{
-    AssetManager* mgr = assetManagerForJavaObject(_env, _assetMgr);
-    if (mgr == NULL) {
-        return 0;
-    }
-
-    AutoJavaStringToUTF8 str(_env, _path);
-    Asset* asset = mgr->open(str.c_str(), Asset::ACCESS_BUFFER);
-    if (asset == NULL) {
-        return 0;
-    }
-
-    jint id = (jint)rsFontCreateFromMemory(con,
-                                           str.c_str(), str.length(),
-                                           fontSize, dpi,
-                                           asset->getBuffer(false), asset->getLength());
-    delete asset;
-    return id;
-}
-
-// -----------------------------------
-
-static void
-nScriptBindAllocation(JNIEnv *_env, jobject _this, RsContext con, jint script, jint alloc, jint slot)
-{
-    LOG_API("nScriptBindAllocation, con(%p), script(%p), alloc(%p), slot(%i)", con, (RsScript)script, (RsAllocation)alloc, slot);
-    rsScriptBindAllocation(con, (RsScript)script, (RsAllocation)alloc, slot);
-}
-
-static void
-nScriptSetVarI(JNIEnv *_env, jobject _this, RsContext con, jint script, jint slot, jint val)
-{
-    LOG_API("nScriptSetVarI, con(%p), s(%p), slot(%i), val(%i)", con, (void *)script, slot, val);
-    rsScriptSetVarI(con, (RsScript)script, slot, val);
-}
-
-static jint
-nScriptGetVarI(JNIEnv *_env, jobject _this, RsContext con, jint script, jint slot)
-{
-    LOG_API("nScriptGetVarI, con(%p), s(%p), slot(%i)", con, (void *)script, slot);
-    int value = 0;
-    rsScriptGetVarV(con, (RsScript)script, slot, &value, sizeof(value));
-    return value;
-}
-
-static void
-nScriptSetVarObj(JNIEnv *_env, jobject _this, RsContext con, jint script, jint slot, jint val)
-{
-    LOG_API("nScriptSetVarObj, con(%p), s(%p), slot(%i), val(%i)", con, (void *)script, slot, val);
-    rsScriptSetVarObj(con, (RsScript)script, slot, (RsObjectBase)val);
-}
-
-static void
-nScriptSetVarJ(JNIEnv *_env, jobject _this, RsContext con, jint script, jint slot, jlong val)
-{
-    LOG_API("nScriptSetVarJ, con(%p), s(%p), slot(%i), val(%lli)", con, (void *)script, slot, val);
-    rsScriptSetVarJ(con, (RsScript)script, slot, val);
-}
-
-static jlong
-nScriptGetVarJ(JNIEnv *_env, jobject _this, RsContext con, jint script, jint slot)
-{
-    LOG_API("nScriptGetVarJ, con(%p), s(%p), slot(%i)", con, (void *)script, slot);
-    jlong value = 0;
-    rsScriptGetVarV(con, (RsScript)script, slot, &value, sizeof(value));
-    return value;
-}
-
-static void
-nScriptSetVarF(JNIEnv *_env, jobject _this, RsContext con, jint script, jint slot, float val)
-{
-    LOG_API("nScriptSetVarF, con(%p), s(%p), slot(%i), val(%f)", con, (void *)script, slot, val);
-    rsScriptSetVarF(con, (RsScript)script, slot, val);
-}
-
-static jfloat
-nScriptGetVarF(JNIEnv *_env, jobject _this, RsContext con, jint script, jint slot)
-{
-    LOG_API("nScriptGetVarF, con(%p), s(%p), slot(%i)", con, (void *)script, slot);
-    jfloat value = 0;
-    rsScriptGetVarV(con, (RsScript)script, slot, &value, sizeof(value));
-    return value;
-}
-
-static void
-nScriptSetVarD(JNIEnv *_env, jobject _this, RsContext con, jint script, jint slot, double val)
-{
-    LOG_API("nScriptSetVarD, con(%p), s(%p), slot(%i), val(%lf)", con, (void *)script, slot, val);
-    rsScriptSetVarD(con, (RsScript)script, slot, val);
-}
-
-static jdouble
-nScriptGetVarD(JNIEnv *_env, jobject _this, RsContext con, jint script, jint slot)
-{
-    LOG_API("nScriptGetVarD, con(%p), s(%p), slot(%i)", con, (void *)script, slot);
-    jdouble value = 0;
-    rsScriptGetVarV(con, (RsScript)script, slot, &value, sizeof(value));
-    return value;
-}
-
-static void
-nScriptSetVarV(JNIEnv *_env, jobject _this, RsContext con, jint script, jint slot, jbyteArray data)
-{
-    LOG_API("nScriptSetVarV, con(%p), s(%p), slot(%i)", con, (void *)script, slot);
-    jint len = _env->GetArrayLength(data);
-    jbyte *ptr = _env->GetByteArrayElements(data, NULL);
-    rsScriptSetVarV(con, (RsScript)script, slot, ptr, len);
-    _env->ReleaseByteArrayElements(data, ptr, JNI_ABORT);
-}
-
-static void
-nScriptGetVarV(JNIEnv *_env, jobject _this, RsContext con, jint script, jint slot, jbyteArray data)
-{
-    LOG_API("nScriptSetVarV, con(%p), s(%p), slot(%i)", con, (void *)script, slot);
-    jint len = _env->GetArrayLength(data);
-    jbyte *ptr = _env->GetByteArrayElements(data, NULL);
-    rsScriptGetVarV(con, (RsScript)script, slot, ptr, len);
-    _env->ReleaseByteArrayElements(data, ptr, JNI_ABORT);
-}
-
-static void
-nScriptSetVarVE(JNIEnv *_env, jobject _this, RsContext con, jint script, jint slot, jbyteArray data, jint elem, jintArray dims)
-{
-    LOG_API("nScriptSetVarVE, con(%p), s(%p), slot(%i)", con, (void *)script, slot);
-    jint len = _env->GetArrayLength(data);
-    jbyte *ptr = _env->GetByteArrayElements(data, NULL);
-    jint dimsLen = _env->GetArrayLength(dims) * sizeof(int);
-    jint *dimsPtr = _env->GetIntArrayElements(dims, NULL);
-    rsScriptSetVarVE(con, (RsScript)script, slot, ptr, len, (RsElement)elem,
-                     (const size_t*) dimsPtr, dimsLen);
-    _env->ReleaseByteArrayElements(data, ptr, JNI_ABORT);
-    _env->ReleaseIntArrayElements(dims, dimsPtr, JNI_ABORT);
-}
-
-
-static void
-nScriptSetTimeZone(JNIEnv *_env, jobject _this, RsContext con, jint script, jbyteArray timeZone)
-{
-    LOG_API("nScriptCSetTimeZone, con(%p), s(%p), timeZone(%s)", con, (void *)script, (const char *)timeZone);
-
-    jint length = _env->GetArrayLength(timeZone);
-    jbyte* timeZone_ptr;
-    timeZone_ptr = (jbyte *) _env->GetPrimitiveArrayCritical(timeZone, (jboolean *)0);
-
-    rsScriptSetTimeZone(con, (RsScript)script, (const char *)timeZone_ptr, length);
-
-    if (timeZone_ptr) {
-        _env->ReleasePrimitiveArrayCritical(timeZone, timeZone_ptr, 0);
-    }
-}
-
-static void
-nScriptInvoke(JNIEnv *_env, jobject _this, RsContext con, jint obj, jint slot)
-{
-    LOG_API("nScriptInvoke, con(%p), script(%p)", con, (void *)obj);
-    rsScriptInvoke(con, (RsScript)obj, slot);
-}
-
-static void
-nScriptInvokeV(JNIEnv *_env, jobject _this, RsContext con, jint script, jint slot, jbyteArray data)
-{
-    LOG_API("nScriptInvokeV, con(%p), s(%p), slot(%i)", con, (void *)script, slot);
-    jint len = _env->GetArrayLength(data);
-    jbyte *ptr = _env->GetByteArrayElements(data, NULL);
-    rsScriptInvokeV(con, (RsScript)script, slot, ptr, len);
-    _env->ReleaseByteArrayElements(data, ptr, JNI_ABORT);
-}
-
-static void
-nScriptForEach(JNIEnv *_env, jobject _this, RsContext con,
-               jint script, jint slot, jint ain, jint aout)
-{
-    LOG_API("nScriptForEach, con(%p), s(%p), slot(%i)", con, (void *)script, slot);
-    rsScriptForEach(con, (RsScript)script, slot, (RsAllocation)ain, (RsAllocation)aout, NULL, 0, NULL, 0);
-}
-static void
-nScriptForEachV(JNIEnv *_env, jobject _this, RsContext con,
-                jint script, jint slot, jint ain, jint aout, jbyteArray params)
-{
-    LOG_API("nScriptForEach, con(%p), s(%p), slot(%i)", con, (void *)script, slot);
-    jint len = _env->GetArrayLength(params);
-    jbyte *ptr = _env->GetByteArrayElements(params, NULL);
-    rsScriptForEach(con, (RsScript)script, slot, (RsAllocation)ain, (RsAllocation)aout, ptr, len, NULL, 0);
-    _env->ReleaseByteArrayElements(params, ptr, JNI_ABORT);
-}
-
-static void
-nScriptForEachClipped(JNIEnv *_env, jobject _this, RsContext con,
-                      jint script, jint slot, jint ain, jint aout,
-                      jint xstart, jint xend,
-                      jint ystart, jint yend, jint zstart, jint zend)
-{
-    LOG_API("nScriptForEachClipped, con(%p), s(%p), slot(%i)", con, (void *)script, slot);
-    RsScriptCall sc;
-    sc.xStart = xstart;
-    sc.xEnd = xend;
-    sc.yStart = ystart;
-    sc.yEnd = yend;
-    sc.zStart = zstart;
-    sc.zEnd = zend;
-    sc.strategy = RS_FOR_EACH_STRATEGY_DONT_CARE;
-    sc.arrayStart = 0;
-    sc.arrayEnd = 0;
-    rsScriptForEach(con, (RsScript)script, slot, (RsAllocation)ain, (RsAllocation)aout, NULL, 0, &sc, sizeof(sc));
-}
-
-static void
-nScriptForEachClippedV(JNIEnv *_env, jobject _this, RsContext con,
-                       jint script, jint slot, jint ain, jint aout,
-                       jbyteArray params, jint xstart, jint xend,
-                       jint ystart, jint yend, jint zstart, jint zend)
-{
-    LOG_API("nScriptForEachClipped, con(%p), s(%p), slot(%i)", con, (void *)script, slot);
-    jint len = _env->GetArrayLength(params);
-    jbyte *ptr = _env->GetByteArrayElements(params, NULL);
-    RsScriptCall sc;
-    sc.xStart = xstart;
-    sc.xEnd = xend;
-    sc.yStart = ystart;
-    sc.yEnd = yend;
-    sc.zStart = zstart;
-    sc.zEnd = zend;
-    sc.strategy = RS_FOR_EACH_STRATEGY_DONT_CARE;
-    sc.arrayStart = 0;
-    sc.arrayEnd = 0;
-    rsScriptForEach(con, (RsScript)script, slot, (RsAllocation)ain, (RsAllocation)aout, ptr, len, &sc, sizeof(sc));
-    _env->ReleaseByteArrayElements(params, ptr, JNI_ABORT);
-}
-
-// -----------------------------------
-
-static jint
-nScriptCCreate(JNIEnv *_env, jobject _this, RsContext con,
-               jstring resName, jstring cacheDir,
-               jbyteArray scriptRef, jint length)
-{
-    LOG_API("nScriptCCreate, con(%p)", con);
-
-    AutoJavaStringToUTF8 resNameUTF(_env, resName);
-    AutoJavaStringToUTF8 cacheDirUTF(_env, cacheDir);
-    jint ret = 0;
-    jbyte* script_ptr = NULL;
-    jint _exception = 0;
-    jint remaining;
-    if (!scriptRef) {
-        _exception = 1;
-        //jniThrowException(_env, "java/lang/IllegalArgumentException", "script == null");
-        goto exit;
-    }
-    if (length < 0) {
-        _exception = 1;
-        //jniThrowException(_env, "java/lang/IllegalArgumentException", "length < 0");
-        goto exit;
-    }
-    remaining = _env->GetArrayLength(scriptRef);
-    if (remaining < length) {
-        _exception = 1;
-        //jniThrowException(_env, "java/lang/IllegalArgumentException",
-        //        "length > script.length - offset");
-        goto exit;
-    }
-    script_ptr = (jbyte *)
-        _env->GetPrimitiveArrayCritical(scriptRef, (jboolean *)0);
-
-    //rsScriptCSetText(con, (const char *)script_ptr, length);
-
-    ret = (jint)rsScriptCCreate(con,
-                                resNameUTF.c_str(), resNameUTF.length(),
-                                cacheDirUTF.c_str(), cacheDirUTF.length(),
-                                (const char *)script_ptr, length);
-
-exit:
-    if (script_ptr) {
-        _env->ReleasePrimitiveArrayCritical(scriptRef, script_ptr,
-                _exception ? JNI_ABORT: 0);
-    }
-
-    return ret;
-}
-
-static jint
-nScriptIntrinsicCreate(JNIEnv *_env, jobject _this, RsContext con, jint id, jint eid)
-{
-    LOG_API("nScriptIntrinsicCreate, con(%p) id(%i) element(%p)", con, id, (void *)eid);
-    return (jint)rsScriptIntrinsicCreate(con, id, (RsElement)eid);
-}
-
-static jint
-nScriptKernelIDCreate(JNIEnv *_env, jobject _this, RsContext con, jint sid, jint slot, jint sig)
-{
-    LOG_API("nScriptKernelIDCreate, con(%p) script(%p), slot(%i), sig(%i)", con, (void *)sid, slot, sig);
-    return (jint)rsScriptKernelIDCreate(con, (RsScript)sid, slot, sig);
-}
-
-static jint
-nScriptFieldIDCreate(JNIEnv *_env, jobject _this, RsContext con, jint sid, jint slot)
-{
-    LOG_API("nScriptFieldIDCreate, con(%p) script(%p), slot(%i)", con, (void *)sid, slot);
-    return (jint)rsScriptFieldIDCreate(con, (RsScript)sid, slot);
-}
-
-static jint
-nScriptGroupCreate(JNIEnv *_env, jobject _this, RsContext con, jintArray _kernels, jintArray _src,
-    jintArray _dstk, jintArray _dstf, jintArray _types)
-{
-    LOG_API("nScriptGroupCreate, con(%p)", con);
-
-    jint kernelsLen = _env->GetArrayLength(_kernels) * sizeof(int);
-    jint *kernelsPtr = _env->GetIntArrayElements(_kernels, NULL);
-    jint srcLen = _env->GetArrayLength(_src) * sizeof(int);
-    jint *srcPtr = _env->GetIntArrayElements(_src, NULL);
-    jint dstkLen = _env->GetArrayLength(_dstk) * sizeof(int);
-    jint *dstkPtr = _env->GetIntArrayElements(_dstk, NULL);
-    jint dstfLen = _env->GetArrayLength(_dstf) * sizeof(int);
-    jint *dstfPtr = _env->GetIntArrayElements(_dstf, NULL);
-    jint typesLen = _env->GetArrayLength(_types) * sizeof(int);
-    jint *typesPtr = _env->GetIntArrayElements(_types, NULL);
-
-    int id = (int)rsScriptGroupCreate(con,
-                               (RsScriptKernelID *)kernelsPtr, kernelsLen,
-                               (RsScriptKernelID *)srcPtr, srcLen,
-                               (RsScriptKernelID *)dstkPtr, dstkLen,
-                               (RsScriptFieldID *)dstfPtr, dstfLen,
-                               (RsType *)typesPtr, typesLen);
-
-    _env->ReleaseIntArrayElements(_kernels, kernelsPtr, 0);
-    _env->ReleaseIntArrayElements(_src, srcPtr, 0);
-    _env->ReleaseIntArrayElements(_dstk, dstkPtr, 0);
-    _env->ReleaseIntArrayElements(_dstf, dstfPtr, 0);
-    _env->ReleaseIntArrayElements(_types, typesPtr, 0);
-    return id;
-}
-
-static void
-nScriptGroupSetInput(JNIEnv *_env, jobject _this, RsContext con, jint gid, jint kid, jint alloc)
-{
-    LOG_API("nScriptGroupSetInput, con(%p) group(%p), kernelId(%p), alloc(%p)", con,
-        (void *)gid, (void *)kid, (void *)alloc);
-    rsScriptGroupSetInput(con, (RsScriptGroup)gid, (RsScriptKernelID)kid, (RsAllocation)alloc);
-}
-
-static void
-nScriptGroupSetOutput(JNIEnv *_env, jobject _this, RsContext con, jint gid, jint kid, jint alloc)
-{
-    LOG_API("nScriptGroupSetOutput, con(%p) group(%p), kernelId(%p), alloc(%p)", con,
-        (void *)gid, (void *)kid, (void *)alloc);
-    rsScriptGroupSetOutput(con, (RsScriptGroup)gid, (RsScriptKernelID)kid, (RsAllocation)alloc);
-}
-
-static void
-nScriptGroupExecute(JNIEnv *_env, jobject _this, RsContext con, jint gid)
-{
-    LOG_API("nScriptGroupSetOutput, con(%p) group(%p)", con, (void *)gid);
-    rsScriptGroupExecute(con, (RsScriptGroup)gid);
-}
-
-// ---------------------------------------------------------------------------
-
-static jint
-nProgramStoreCreate(JNIEnv *_env, jobject _this, RsContext con,
-                    jboolean colorMaskR, jboolean colorMaskG, jboolean colorMaskB, jboolean colorMaskA,
-                    jboolean depthMask, jboolean ditherEnable,
-                    jint srcFunc, jint destFunc,
-                    jint depthFunc)
-{
-    LOG_API("nProgramStoreCreate, con(%p)", con);
-    return (jint)rsProgramStoreCreate(con, colorMaskR, colorMaskG, colorMaskB, colorMaskA,
-                                      depthMask, ditherEnable, (RsBlendSrcFunc)srcFunc,
-                                      (RsBlendDstFunc)destFunc, (RsDepthFunc)depthFunc);
-}
-
-// ---------------------------------------------------------------------------
-
-static void
-nProgramBindConstants(JNIEnv *_env, jobject _this, RsContext con, jint vpv, jint slot, jint a)
-{
-    LOG_API("nProgramBindConstants, con(%p), vpf(%p), sloat(%i), a(%p)", con, (RsProgramVertex)vpv, slot, (RsAllocation)a);
-    rsProgramBindConstants(con, (RsProgram)vpv, slot, (RsAllocation)a);
-}
-
-static void
-nProgramBindTexture(JNIEnv *_env, jobject _this, RsContext con, jint vpf, jint slot, jint a)
-{
-    LOG_API("nProgramBindTexture, con(%p), vpf(%p), slot(%i), a(%p)", con, (RsProgramFragment)vpf, slot, (RsAllocation)a);
-    rsProgramBindTexture(con, (RsProgramFragment)vpf, slot, (RsAllocation)a);
-}
-
-static void
-nProgramBindSampler(JNIEnv *_env, jobject _this, RsContext con, jint vpf, jint slot, jint a)
-{
-    LOG_API("nProgramBindSampler, con(%p), vpf(%p), slot(%i), a(%p)", con, (RsProgramFragment)vpf, slot, (RsSampler)a);
-    rsProgramBindSampler(con, (RsProgramFragment)vpf, slot, (RsSampler)a);
-}
-
-// ---------------------------------------------------------------------------
-
-static jint
-nProgramFragmentCreate(JNIEnv *_env, jobject _this, RsContext con, jstring shader,
-                       jobjectArray texNames, jintArray params)
-{
-    AutoJavaStringToUTF8 shaderUTF(_env, shader);
-    jint *paramPtr = _env->GetIntArrayElements(params, NULL);
-    jint paramLen = _env->GetArrayLength(params);
-
-    int texCount = _env->GetArrayLength(texNames);
-    AutoJavaStringArrayToUTF8 names(_env, texNames, texCount);
-    const char ** nameArray = names.c_str();
-    size_t* sizeArray = names.c_str_len();
-
-    LOG_API("nProgramFragmentCreate, con(%p), paramLen(%i)", con, paramLen);
-
-    jint ret = (jint)rsProgramFragmentCreate(con, shaderUTF.c_str(), shaderUTF.length(),
-                                             nameArray, texCount, sizeArray,
-                                             (uint32_t *)paramPtr, paramLen);
-
-    _env->ReleaseIntArrayElements(params, paramPtr, JNI_ABORT);
-    return ret;
-}
-
-
-// ---------------------------------------------------------------------------
-
-static jint
-nProgramVertexCreate(JNIEnv *_env, jobject _this, RsContext con, jstring shader,
-                     jobjectArray texNames, jintArray params)
-{
-    AutoJavaStringToUTF8 shaderUTF(_env, shader);
-    jint *paramPtr = _env->GetIntArrayElements(params, NULL);
-    jint paramLen = _env->GetArrayLength(params);
-
-    LOG_API("nProgramVertexCreate, con(%p), paramLen(%i)", con, paramLen);
-
-    int texCount = _env->GetArrayLength(texNames);
-    AutoJavaStringArrayToUTF8 names(_env, texNames, texCount);
-    const char ** nameArray = names.c_str();
-    size_t* sizeArray = names.c_str_len();
-
-    jint ret = (jint)rsProgramVertexCreate(con, shaderUTF.c_str(), shaderUTF.length(),
-                                           nameArray, texCount, sizeArray,
-                                           (uint32_t *)paramPtr, paramLen);
-
-    _env->ReleaseIntArrayElements(params, paramPtr, JNI_ABORT);
-    return ret;
-}
-
-// ---------------------------------------------------------------------------
-
-static jint
-nProgramRasterCreate(JNIEnv *_env, jobject _this, RsContext con, jboolean pointSprite, jint cull)
-{
-    LOG_API("nProgramRasterCreate, con(%p), pointSprite(%i), cull(%i)", con, pointSprite, cull);
-    return (jint)rsProgramRasterCreate(con, pointSprite, (RsCullMode)cull);
-}
-
-
-// ---------------------------------------------------------------------------
-
-static void
-nContextBindRootScript(JNIEnv *_env, jobject _this, RsContext con, jint script)
-{
-    LOG_API("nContextBindRootScript, con(%p), script(%p)", con, (RsScript)script);
-    rsContextBindRootScript(con, (RsScript)script);
-}
-
-static void
-nContextBindProgramStore(JNIEnv *_env, jobject _this, RsContext con, jint pfs)
-{
-    LOG_API("nContextBindProgramStore, con(%p), pfs(%p)", con, (RsProgramStore)pfs);
-    rsContextBindProgramStore(con, (RsProgramStore)pfs);
-}
-
-static void
-nContextBindProgramFragment(JNIEnv *_env, jobject _this, RsContext con, jint pf)
-{
-    LOG_API("nContextBindProgramFragment, con(%p), pf(%p)", con, (RsProgramFragment)pf);
-    rsContextBindProgramFragment(con, (RsProgramFragment)pf);
-}
-
-static void
-nContextBindProgramVertex(JNIEnv *_env, jobject _this, RsContext con, jint pf)
-{
-    LOG_API("nContextBindProgramVertex, con(%p), pf(%p)", con, (RsProgramVertex)pf);
-    rsContextBindProgramVertex(con, (RsProgramVertex)pf);
-}
-
-static void
-nContextBindProgramRaster(JNIEnv *_env, jobject _this, RsContext con, jint pf)
-{
-    LOG_API("nContextBindProgramRaster, con(%p), pf(%p)", con, (RsProgramRaster)pf);
-    rsContextBindProgramRaster(con, (RsProgramRaster)pf);
-}
-
-
-// ---------------------------------------------------------------------------
-
-static jint
-nSamplerCreate(JNIEnv *_env, jobject _this, RsContext con, jint magFilter, jint minFilter,
-               jint wrapS, jint wrapT, jint wrapR, jfloat aniso)
-{
-    LOG_API("nSamplerCreate, con(%p)", con);
-    return (jint)rsSamplerCreate(con,
-                                 (RsSamplerValue)magFilter,
-                                 (RsSamplerValue)minFilter,
-                                 (RsSamplerValue)wrapS,
-                                 (RsSamplerValue)wrapT,
-                                 (RsSamplerValue)wrapR,
-                                 aniso);
-}
-
-// ---------------------------------------------------------------------------
-
-//native int  rsnPathCreate(int con, int prim, boolean isStatic, int vtx, int loop, float q);
-static jint
-nPathCreate(JNIEnv *_env, jobject _this, RsContext con, jint prim, jboolean isStatic, jint _vtx, jint _loop, jfloat q) {
-    LOG_API("nPathCreate, con(%p)", con);
-
-    int id = (int)rsPathCreate(con, (RsPathPrimitive)prim, isStatic,
-                               (RsAllocation)_vtx,
-                               (RsAllocation)_loop, q);
-    return id;
-}
-
-static jint
-nMeshCreate(JNIEnv *_env, jobject _this, RsContext con, jintArray _vtx, jintArray _idx, jintArray _prim)
-{
-    LOG_API("nMeshCreate, con(%p)", con);
-
-    jint vtxLen = _env->GetArrayLength(_vtx);
-    jint *vtxPtr = _env->GetIntArrayElements(_vtx, NULL);
-    jint idxLen = _env->GetArrayLength(_idx);
-    jint *idxPtr = _env->GetIntArrayElements(_idx, NULL);
-    jint primLen = _env->GetArrayLength(_prim);
-    jint *primPtr = _env->GetIntArrayElements(_prim, NULL);
-
-    int id = (int)rsMeshCreate(con,
-                               (RsAllocation *)vtxPtr, vtxLen,
-                               (RsAllocation *)idxPtr, idxLen,
-                               (uint32_t *)primPtr, primLen);
-
-    _env->ReleaseIntArrayElements(_vtx, vtxPtr, 0);
-    _env->ReleaseIntArrayElements(_idx, idxPtr, 0);
-    _env->ReleaseIntArrayElements(_prim, primPtr, 0);
-    return id;
-}
-
-static jint
-nMeshGetVertexBufferCount(JNIEnv *_env, jobject _this, RsContext con, jint mesh)
-{
-    LOG_API("nMeshGetVertexBufferCount, con(%p), Mesh(%p)", con, (RsMesh)mesh);
-    jint vtxCount = 0;
-    rsaMeshGetVertexBufferCount(con, (RsMesh)mesh, &vtxCount);
-    return vtxCount;
-}
-
-static jint
-nMeshGetIndexCount(JNIEnv *_env, jobject _this, RsContext con, jint mesh)
-{
-    LOG_API("nMeshGetIndexCount, con(%p), Mesh(%p)", con, (RsMesh)mesh);
-    jint idxCount = 0;
-    rsaMeshGetIndexCount(con, (RsMesh)mesh, &idxCount);
-    return idxCount;
-}
-
-static void
-nMeshGetVertices(JNIEnv *_env, jobject _this, RsContext con, jint mesh, jintArray _ids, int numVtxIDs)
-{
-    LOG_API("nMeshGetVertices, con(%p), Mesh(%p)", con, (RsMesh)mesh);
-
-    RsAllocation *allocs = (RsAllocation*)malloc((uint32_t)numVtxIDs * sizeof(RsAllocation));
-    rsaMeshGetVertices(con, (RsMesh)mesh, allocs, (uint32_t)numVtxIDs);
-
-    for(jint i = 0; i < numVtxIDs; i ++) {
-        _env->SetIntArrayRegion(_ids, i, 1, (const jint*)&allocs[i]);
-    }
-
-    free(allocs);
-}
-
-static void
-nMeshGetIndices(JNIEnv *_env, jobject _this, RsContext con, jint mesh, jintArray _idxIds, jintArray _primitives, int numIndices)
-{
-    LOG_API("nMeshGetVertices, con(%p), Mesh(%p)", con, (RsMesh)mesh);
-
-    RsAllocation *allocs = (RsAllocation*)malloc((uint32_t)numIndices * sizeof(RsAllocation));
-    uint32_t *prims= (uint32_t*)malloc((uint32_t)numIndices * sizeof(uint32_t));
-
-    rsaMeshGetIndices(con, (RsMesh)mesh, allocs, prims, (uint32_t)numIndices);
-
-    for(jint i = 0; i < numIndices; i ++) {
-        _env->SetIntArrayRegion(_idxIds, i, 1, (const jint*)&allocs[i]);
-        _env->SetIntArrayRegion(_primitives, i, 1, (const jint*)&prims[i]);
-    }
-
-    free(allocs);
-    free(prims);
-}
-
-// ---------------------------------------------------------------------------
-
-
-static const char *classPathName = "android/renderscript/RenderScript";
-
-static JNINativeMethod methods[] = {
-{"_nInit",                         "()V",                                     (void*)_nInit },
-
-{"nDeviceCreate",                  "()I",                                     (void*)nDeviceCreate },
-{"nDeviceDestroy",                 "(I)V",                                    (void*)nDeviceDestroy },
-{"nDeviceSetConfig",               "(III)V",                                  (void*)nDeviceSetConfig },
-{"nContextGetUserMessage",         "(I[I)I",                                  (void*)nContextGetUserMessage },
-{"nContextGetErrorMessage",        "(I)Ljava/lang/String;",                   (void*)nContextGetErrorMessage },
-{"nContextPeekMessage",            "(I[I)I",                                  (void*)nContextPeekMessage },
-
-{"nContextInitToClient",           "(I)V",                                    (void*)nContextInitToClient },
-{"nContextDeinitToClient",         "(I)V",                                    (void*)nContextDeinitToClient },
-
-
-// All methods below are thread protected in java.
-{"rsnContextCreate",                 "(IIII)I",                               (void*)nContextCreate },
-{"rsnContextCreateGL",               "(IIIIIIIIIIIIIFI)I",                    (void*)nContextCreateGL },
-{"rsnContextFinish",                 "(I)V",                                  (void*)nContextFinish },
-{"rsnContextSetPriority",            "(II)V",                                 (void*)nContextSetPriority },
-{"rsnContextSetSurface",             "(IIILandroid/view/Surface;)V",          (void*)nContextSetSurface },
-{"rsnContextDestroy",                "(I)V",                                  (void*)nContextDestroy },
-{"rsnContextDump",                   "(II)V",                                 (void*)nContextDump },
-{"rsnContextPause",                  "(I)V",                                  (void*)nContextPause },
-{"rsnContextResume",                 "(I)V",                                  (void*)nContextResume },
-{"rsnContextSendMessage",            "(II[I)V",                               (void*)nContextSendMessage },
-{"rsnAssignName",                    "(II[B)V",                               (void*)nAssignName },
-{"rsnGetName",                       "(II)Ljava/lang/String;",                (void*)nGetName },
-{"rsnObjDestroy",                    "(II)V",                                 (void*)nObjDestroy },
-
-{"rsnFileA3DCreateFromFile",         "(ILjava/lang/String;)I",                (void*)nFileA3DCreateFromFile },
-{"rsnFileA3DCreateFromAssetStream",  "(II)I",                                 (void*)nFileA3DCreateFromAssetStream },
-{"rsnFileA3DCreateFromAsset",        "(ILandroid/content/res/AssetManager;Ljava/lang/String;)I",            (void*)nFileA3DCreateFromAsset },
-{"rsnFileA3DGetNumIndexEntries",     "(II)I",                                 (void*)nFileA3DGetNumIndexEntries },
-{"rsnFileA3DGetIndexEntries",        "(III[I[Ljava/lang/String;)V",           (void*)nFileA3DGetIndexEntries },
-{"rsnFileA3DGetEntryByIndex",        "(III)I",                                (void*)nFileA3DGetEntryByIndex },
-
-{"rsnFontCreateFromFile",            "(ILjava/lang/String;FI)I",              (void*)nFontCreateFromFile },
-{"rsnFontCreateFromAssetStream",     "(ILjava/lang/String;FII)I",             (void*)nFontCreateFromAssetStream },
-{"rsnFontCreateFromAsset",        "(ILandroid/content/res/AssetManager;Ljava/lang/String;FI)I",            (void*)nFontCreateFromAsset },
-
-{"rsnElementCreate",                 "(IIIZI)I",                              (void*)nElementCreate },
-{"rsnElementCreate2",                "(I[I[Ljava/lang/String;[I)I",           (void*)nElementCreate2 },
-{"rsnElementGetNativeData",          "(II[I)V",                               (void*)nElementGetNativeData },
-{"rsnElementGetSubElements",         "(II[I[Ljava/lang/String;[I)V",          (void*)nElementGetSubElements },
-
-{"rsnTypeCreate",                    "(IIIIIZZI)I",                           (void*)nTypeCreate },
-{"rsnTypeGetNativeData",             "(II[I)V",                               (void*)nTypeGetNativeData },
-
-{"rsnAllocationCreateTyped",         "(IIIII)I",                               (void*)nAllocationCreateTyped },
-{"rsnAllocationCreateFromBitmap",    "(IIILandroid/graphics/Bitmap;I)I",      (void*)nAllocationCreateFromBitmap },
-{"rsnAllocationCreateBitmapBackedAllocation",    "(IIILandroid/graphics/Bitmap;I)I",      (void*)nAllocationCreateBitmapBackedAllocation },
-{"rsnAllocationCubeCreateFromBitmap","(IIILandroid/graphics/Bitmap;I)I",      (void*)nAllocationCubeCreateFromBitmap },
-
-{"rsnAllocationCopyFromBitmap",      "(IILandroid/graphics/Bitmap;)V",        (void*)nAllocationCopyFromBitmap },
-{"rsnAllocationCopyToBitmap",        "(IILandroid/graphics/Bitmap;)V",        (void*)nAllocationCopyToBitmap },
-
-{"rsnAllocationSyncAll",             "(III)V",                                (void*)nAllocationSyncAll },
-{"rsnAllocationGetSurface",          "(II)Landroid/view/Surface;",            (void*)nAllocationGetSurface },
-{"rsnAllocationSetSurface",          "(IILandroid/view/Surface;)V",           (void*)nAllocationSetSurface },
-{"rsnAllocationIoSend",              "(II)V",                                 (void*)nAllocationIoSend },
-{"rsnAllocationIoReceive",           "(II)V",                                 (void*)nAllocationIoReceive },
-{"rsnAllocationData1D",              "(IIIII[II)V",                           (void*)nAllocationData1D_i },
-{"rsnAllocationData1D",              "(IIIII[SI)V",                           (void*)nAllocationData1D_s },
-{"rsnAllocationData1D",              "(IIIII[BI)V",                           (void*)nAllocationData1D_b },
-{"rsnAllocationData1D",              "(IIIII[FI)V",                           (void*)nAllocationData1D_f },
-{"rsnAllocationElementData1D",       "(IIIII[BI)V",                           (void*)nAllocationElementData1D },
-{"rsnAllocationData2D",              "(IIIIIIII[II)V",                        (void*)nAllocationData2D_i },
-{"rsnAllocationData2D",              "(IIIIIIII[SI)V",                        (void*)nAllocationData2D_s },
-{"rsnAllocationData2D",              "(IIIIIIII[BI)V",                        (void*)nAllocationData2D_b },
-{"rsnAllocationData2D",              "(IIIIIIII[FI)V",                        (void*)nAllocationData2D_f },
-{"rsnAllocationData2D",              "(IIIIIIIIIIIII)V",                      (void*)nAllocationData2D_alloc },
-{"rsnAllocationData3D",              "(IIIIIIIII[II)V",                       (void*)nAllocationData3D_i },
-{"rsnAllocationData3D",              "(IIIIIIIII[SI)V",                       (void*)nAllocationData3D_s },
-{"rsnAllocationData3D",              "(IIIIIIIII[BI)V",                       (void*)nAllocationData3D_b },
-{"rsnAllocationData3D",              "(IIIIIIIII[FI)V",                       (void*)nAllocationData3D_f },
-{"rsnAllocationData3D",              "(IIIIIIIIIIIIII)V",                     (void*)nAllocationData3D_alloc },
-{"rsnAllocationRead",                "(II[I)V",                               (void*)nAllocationRead_i },
-{"rsnAllocationRead",                "(II[S)V",                               (void*)nAllocationRead_s },
-{"rsnAllocationRead",                "(II[B)V",                               (void*)nAllocationRead_b },
-{"rsnAllocationRead",                "(II[F)V",                               (void*)nAllocationRead_f },
-{"rsnAllocationGetType",             "(II)I",                                 (void*)nAllocationGetType},
-{"rsnAllocationResize1D",            "(III)V",                                (void*)nAllocationResize1D },
-{"rsnAllocationGenerateMipmaps",     "(II)V",                                 (void*)nAllocationGenerateMipmaps },
-
-{"rsnScriptBindAllocation",          "(IIII)V",                               (void*)nScriptBindAllocation },
-{"rsnScriptSetTimeZone",             "(II[B)V",                               (void*)nScriptSetTimeZone },
-{"rsnScriptInvoke",                  "(III)V",                                (void*)nScriptInvoke },
-{"rsnScriptInvokeV",                 "(III[B)V",                              (void*)nScriptInvokeV },
-{"rsnScriptForEach",                 "(IIIII)V",                              (void*)nScriptForEach },
-{"rsnScriptForEach",                 "(IIIII[B)V",                            (void*)nScriptForEachV },
-{"rsnScriptForEachClipped",          "(IIIIIIIIIII)V",                        (void*)nScriptForEachClipped },
-{"rsnScriptForEachClipped",          "(IIIII[BIIIIII)V",                      (void*)nScriptForEachClippedV },
-{"rsnScriptSetVarI",                 "(IIII)V",                               (void*)nScriptSetVarI },
-{"rsnScriptGetVarI",                 "(III)I",                                (void*)nScriptGetVarI },
-{"rsnScriptSetVarJ",                 "(IIIJ)V",                               (void*)nScriptSetVarJ },
-{"rsnScriptGetVarJ",                 "(III)J",                                (void*)nScriptGetVarJ },
-{"rsnScriptSetVarF",                 "(IIIF)V",                               (void*)nScriptSetVarF },
-{"rsnScriptGetVarF",                 "(III)F",                                (void*)nScriptGetVarF },
-{"rsnScriptSetVarD",                 "(IIID)V",                               (void*)nScriptSetVarD },
-{"rsnScriptGetVarD",                 "(III)D",                                (void*)nScriptGetVarD },
-{"rsnScriptSetVarV",                 "(III[B)V",                              (void*)nScriptSetVarV },
-{"rsnScriptGetVarV",                 "(III[B)V",                              (void*)nScriptGetVarV },
-{"rsnScriptSetVarVE",                "(III[BI[I)V",                           (void*)nScriptSetVarVE },
-{"rsnScriptSetVarObj",               "(IIII)V",                               (void*)nScriptSetVarObj },
-
-{"rsnScriptCCreate",                 "(ILjava/lang/String;Ljava/lang/String;[BI)I",  (void*)nScriptCCreate },
-{"rsnScriptIntrinsicCreate",         "(III)I",                                (void*)nScriptIntrinsicCreate },
-{"rsnScriptKernelIDCreate",          "(IIII)I",                               (void*)nScriptKernelIDCreate },
-{"rsnScriptFieldIDCreate",           "(III)I",                                (void*)nScriptFieldIDCreate },
-{"rsnScriptGroupCreate",             "(I[I[I[I[I[I)I",                        (void*)nScriptGroupCreate },
-{"rsnScriptGroupSetInput",           "(IIII)V",                               (void*)nScriptGroupSetInput },
-{"rsnScriptGroupSetOutput",          "(IIII)V",                               (void*)nScriptGroupSetOutput },
-{"rsnScriptGroupExecute",            "(II)V",                                 (void*)nScriptGroupExecute },
-
-{"rsnProgramStoreCreate",            "(IZZZZZZIII)I",                         (void*)nProgramStoreCreate },
-
-{"rsnProgramBindConstants",          "(IIII)V",                               (void*)nProgramBindConstants },
-{"rsnProgramBindTexture",            "(IIII)V",                               (void*)nProgramBindTexture },
-{"rsnProgramBindSampler",            "(IIII)V",                               (void*)nProgramBindSampler },
-
-{"rsnProgramFragmentCreate",         "(ILjava/lang/String;[Ljava/lang/String;[I)I",              (void*)nProgramFragmentCreate },
-{"rsnProgramRasterCreate",           "(IZI)I",                                (void*)nProgramRasterCreate },
-{"rsnProgramVertexCreate",           "(ILjava/lang/String;[Ljava/lang/String;[I)I",              (void*)nProgramVertexCreate },
-
-{"rsnContextBindRootScript",         "(II)V",                                 (void*)nContextBindRootScript },
-{"rsnContextBindProgramStore",       "(II)V",                                 (void*)nContextBindProgramStore },
-{"rsnContextBindProgramFragment",    "(II)V",                                 (void*)nContextBindProgramFragment },
-{"rsnContextBindProgramVertex",      "(II)V",                                 (void*)nContextBindProgramVertex },
-{"rsnContextBindProgramRaster",      "(II)V",                                 (void*)nContextBindProgramRaster },
-
-{"rsnSamplerCreate",                 "(IIIIIIF)I",                            (void*)nSamplerCreate },
-
-{"rsnPathCreate",                    "(IIZIIF)I",                             (void*)nPathCreate },
-{"rsnMeshCreate",                    "(I[I[I[I)I",                            (void*)nMeshCreate },
-
-{"rsnMeshGetVertexBufferCount",      "(II)I",                                 (void*)nMeshGetVertexBufferCount },
-{"rsnMeshGetIndexCount",             "(II)I",                                 (void*)nMeshGetIndexCount },
-{"rsnMeshGetVertices",               "(II[II)V",                              (void*)nMeshGetVertices },
-{"rsnMeshGetIndices",                "(II[I[II)V",                            (void*)nMeshGetIndices },
-
-};
-
-static int registerFuncs(JNIEnv *_env)
-{
-    return android::AndroidRuntime::registerNativeMethods(
-            _env, classPathName, methods, NELEM(methods));
-}
-
-// ---------------------------------------------------------------------------
-
-jint JNI_OnLoad(JavaVM* vm, void* reserved)
-{
-    JNIEnv* env = NULL;
-    jint result = -1;
-
-    if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {
-        ALOGE("ERROR: GetEnv failed\n");
-        goto bail;
-    }
-    assert(env != NULL);
-
-    if (registerFuncs(env) < 0) {
-        ALOGE("ERROR: MediaPlayer native registration failed\n");
-        goto bail;
-    }
-
-    /* success -- return valid version number */
-    result = JNI_VERSION_1_4;
-
-bail:
-    return result;
-}
diff --git a/include/androidfw/ResourceTypes.h b/include/androidfw/ResourceTypes.h
index 5151b06..6799766 100644
--- a/include/androidfw/ResourceTypes.h
+++ b/include/androidfw/ResourceTypes.h
@@ -1279,14 +1279,13 @@
 {
 public:
     ResTable();
-    ResTable(const void* data, size_t size, void* cookie,
+    ResTable(const void* data, size_t size, const int32_t cookie,
              bool copyData=false);
     ~ResTable();
 
-    status_t add(const void* data, size_t size, void* cookie,
-                 bool copyData=false, const void* idmap = NULL);
-    status_t add(Asset* asset, void* cookie,
-                 bool copyData=false, const void* idmap = NULL);
+    status_t add(Asset* asset, const int32_t cookie, bool copyData,
+                 const void* idmap);
+    status_t add(const void *data, size_t size);
     status_t add(ResTable* src);
 
     status_t getError() const;
@@ -1534,7 +1533,7 @@
     // but not the names their entries or types.
     const ResStringPool* getTableStringBlock(size_t index) const;
     // Return unique cookie identifier for the given resource table.
-    void* getTableCookie(size_t index) const;
+    int32_t getTableCookie(size_t index) const;
 
     // Return the configurations (ResTable_config) that we know about
     void getConfigurations(Vector<ResTable_config>* configs) const;
@@ -1569,7 +1568,7 @@
     struct PackageGroup;
     struct bag_set;
 
-    status_t add(const void* data, size_t size, void* cookie,
+    status_t addInternal(const void* data, size_t size, const int32_t cookie,
                  Asset* asset, bool copyData, const Asset* idmap);
 
     ssize_t getResourcePackageIndex(uint32_t resID) const;
diff --git a/libs/androidfw/AssetManager.cpp b/libs/androidfw/AssetManager.cpp
index 52ab361..08328d0 100644
--- a/libs/androidfw/AssetManager.cpp
+++ b/libs/androidfw/AssetManager.cpp
@@ -335,7 +335,7 @@
             ALOGW("failed to find resources.arsc in %s\n", ap.path.string());
             goto error;
         }
-        tables[i].add(ass, (void*)1, false);
+        tables[i].add(ass, 1, false /* copyData */, NULL /* idMap */);
     }
 
     if (!getZipEntryCrcLocked(originalPath, "resources.arsc", &originalCrc)) {
@@ -682,7 +682,7 @@
                     // can quickly copy it out for others.
                     ALOGV("Creating shared resources for %s", ap.path.string());
                     sharedRes = new ResTable();
-                    sharedRes->add(ass, (void*)(i+1), false, idmap);
+                    sharedRes->add(ass, i + 1, false, idmap);
                     sharedRes = const_cast<AssetManager*>(this)->
                         mZipSet.setZipResourceTable(ap.path, sharedRes);
                 }
@@ -706,7 +706,7 @@
                 rt->add(sharedRes);
             } else {
                 ALOGV("Parsing resources for %s", ap.path.string());
-                rt->add(ass, (void*)(i+1), !shared, idmap);
+                rt->add(ass, i + 1, !shared, idmap);
             }
 
             if (!shared) {
diff --git a/libs/androidfw/ResourceTypes.cpp b/libs/androidfw/ResourceTypes.cpp
index 1cc3563..72d331c 100644
--- a/libs/androidfw/ResourceTypes.cpp
+++ b/libs/androidfw/ResourceTypes.cpp
@@ -66,9 +66,9 @@
 // size measured in sizeof(uint32_t)
 #define IDMAP_HEADER_SIZE (ResTable::IDMAP_HEADER_SIZE_BYTES / sizeof(uint32_t))
 
-static void printToLogFunc(void* cookie, const char* txt)
+static void printToLogFunc(int32_t cookie, const char* txt)
 {
-    ALOGV("%s", txt);
+    ALOGV("[cookie=%d] %s", cookie, txt);
 }
 
 // Standard C isspace() is only required to look at the low byte of its input, so
@@ -2461,7 +2461,7 @@
     size_t                          size;
     const uint8_t*                  dataEnd;
     size_t                          index;
-    void*                           cookie;
+    int32_t                         cookie;
 
     ResStringPool                   values;
     uint32_t*                       resourceIDMap;
@@ -2860,12 +2860,12 @@
     //ALOGI("Creating ResTable %p\n", this);
 }
 
-ResTable::ResTable(const void* data, size_t size, void* cookie, bool copyData)
+ResTable::ResTable(const void* data, size_t size, const int32_t cookie, bool copyData)
     : mError(NO_INIT)
 {
     memset(&mParams, 0, sizeof(mParams));
     memset(mPackageMap, 0, sizeof(mPackageMap));
-    add(data, size, cookie, copyData);
+    addInternal(data, size, cookie, NULL /* asset */, copyData, NULL /* idMap */);
     LOG_FATAL_IF(mError != NO_ERROR, "Error parsing resource table");
     //ALOGI("Creating ResTable %p\n", this);
 }
@@ -2881,13 +2881,12 @@
     return ((ssize_t)mPackageMap[Res_GETPACKAGE(resID)+1])-1;
 }
 
-status_t ResTable::add(const void* data, size_t size, void* cookie, bool copyData,
-                       const void* idmap)
-{
-    return add(data, size, cookie, NULL, copyData, reinterpret_cast<const Asset*>(idmap));
+status_t ResTable::add(const void* data, size_t size) {
+    return addInternal(data, size, 0 /* cookie */, NULL /* asset */,
+            false /* copyData */, NULL /* idMap */);
 }
 
-status_t ResTable::add(Asset* asset, void* cookie, bool copyData, const void* idmap)
+status_t ResTable::add(Asset* asset, const int32_t cookie, bool copyData, const void* idmap)
 {
     const void* data = asset->getBuffer(true);
     if (data == NULL) {
@@ -2895,7 +2894,8 @@
         return UNKNOWN_ERROR;
     }
     size_t size = (size_t)asset->getLength();
-    return add(data, size, cookie, asset, copyData, reinterpret_cast<const Asset*>(idmap));
+    return addInternal(data, size, cookie, asset, copyData,
+            reinterpret_cast<const Asset*>(idmap));
 }
 
 status_t ResTable::add(ResTable* src)
@@ -2922,7 +2922,7 @@
     return mError;
 }
 
-status_t ResTable::add(const void* data, size_t size, void* cookie,
+status_t ResTable::addInternal(const void* data, size_t size, const int32_t cookie,
                        Asset* asset, bool copyData, const Asset* idmap)
 {
     if (!data) return NO_ERROR;
@@ -2945,7 +2945,7 @@
     const bool notDeviceEndian = htods(0xf0) != 0xf0;
 
     LOAD_TABLE_NOISY(
-        ALOGV("Adding resources to ResTable: data=%p, size=0x%x, cookie=%p, asset=%p, copy=%d "
+        ALOGV("Adding resources to ResTable: data=%p, size=0x%x, cookie=%d, asset=%p, copy=%d "
              "idmap=%p\n", data, size, cookie, asset, copyData, idmap));
     
     if (copyData || notDeviceEndian) {
@@ -4930,7 +4930,7 @@
     return &mHeaders[index]->values;
 }
 
-void* ResTable::getTableCookie(size_t index) const
+int32_t ResTable::getTableCookie(size_t index) const
 {
     return mHeaders[index]->cookie;
 }
diff --git a/libs/hwui/font/Font.cpp b/libs/hwui/font/Font.cpp
index 18983d8..8f5beb8 100644
--- a/libs/hwui/font/Font.cpp
+++ b/libs/hwui/font/Font.cpp
@@ -404,10 +404,10 @@
         // If it's still not valid, we couldn't cache it, so we shouldn't
         // draw garbage; also skip empty glyphs (spaces)
         if (cachedGlyph->mIsValid && cachedGlyph->mCacheTexture) {
-            float penX = x + positions[(glyphsCount << 1)];
-            float penY = y + positions[(glyphsCount << 1) + 1];
+            int penX = x + (int) roundf(positions[(glyphsCount << 1)]);
+            int penY = y + (int) roundf(positions[(glyphsCount << 1) + 1]);
 
-            (*this.*render)(cachedGlyph, roundf(penX), roundf(penY),
+            (*this.*render)(cachedGlyph, penX, penY,
                     bitmap, bitmapW, bitmapH, bounds, positions);
         }
 
diff --git a/libs/hwui/utils/TinyHashMap.h b/libs/hwui/utils/TinyHashMap.h
index 8855140..4ff9a42 100644
--- a/libs/hwui/utils/TinyHashMap.h
+++ b/libs/hwui/utils/TinyHashMap.h
@@ -24,8 +24,6 @@
 
 /**
  * A very simple hash map that doesn't allow duplicate keys, overwriting the older entry.
- *
- * Currently, expects simple keys that are handled by hash_t()
  */
 template <typename TKey, typename TValue>
 class TinyHashMap {
@@ -36,7 +34,7 @@
      * Puts an entry in the hash, removing any existing entry with the same key
      */
     void put(TKey key, TValue value) {
-        hash_t hash = hash_t(key);
+        hash_t hash = android::hash_type(key);
 
         ssize_t index = mTable.find(-1, hash, key);
         if (index != -1) {
@@ -51,7 +49,7 @@
      * Return true if key is in the map, in which case stores the value in the output ref
      */
     bool get(TKey key, TValue& outValue) {
-        hash_t hash = hash_t(key);
+        hash_t hash = android::hash_type(key);
         ssize_t index = mTable.find(-1, hash, key);
         if (index == -1) {
             return false;
diff --git a/native/android/asset_manager.cpp b/native/android/asset_manager.cpp
index 01db1d3..dee3f8c 100644
--- a/native/android/asset_manager.cpp
+++ b/native/android/asset_manager.cpp
@@ -76,12 +76,12 @@
 
         if (gJNIConfigured == false) {
             jclass amClass = env->FindClass("android/content/res/AssetManager");
-            gAssetManagerOffsets.mObject = env->GetFieldID(amClass, "mObject", "I");
+            gAssetManagerOffsets.mObject = env->GetFieldID(amClass, "mObject", "J");
             gJNIConfigured = true;
         }
     }
 
-    return (AAssetManager*) env->GetIntField(assetManager, gAssetManagerOffsets.mObject);
+    return (AAssetManager*) env->GetLongField(assetManager, gAssetManagerOffsets.mObject);
 }
 
 AAsset* AAssetManager_open(AAssetManager* amgr, const char* filename, int mode)
diff --git a/preloaded-classes b/preloaded-classes
index 342126d..02bd0bc 100644
--- a/preloaded-classes
+++ b/preloaded-classes
@@ -2456,8 +2456,6 @@
 org.apache.harmony.security.fortress.Engine$SpiAndProvider
 org.apache.harmony.security.fortress.SecurityAccess
 org.apache.harmony.security.fortress.Services
-org.apache.harmony.security.provider.cert.DRLCertFactory
-org.apache.harmony.security.provider.cert.X509CertImpl
 org.apache.harmony.security.provider.crypto.CryptoProvider
 org.apache.harmony.security.utils.AlgNameMapper
 org.apache.harmony.security.utils.ObjectIdentifier
diff --git a/graphics/java/android/renderscript/Allocation.java b/rs/java/android/renderscript/Allocation.java
similarity index 85%
rename from graphics/java/android/renderscript/Allocation.java
rename to rs/java/android/renderscript/Allocation.java
index dca934f..c2bab91 100644
--- a/graphics/java/android/renderscript/Allocation.java
+++ b/rs/java/android/renderscript/Allocation.java
@@ -24,7 +24,6 @@
 import android.graphics.Bitmap;
 import android.graphics.BitmapFactory;
 import android.view.Surface;
-import android.graphics.SurfaceTexture;
 import android.util.Log;
 import android.util.TypedValue;
 import android.graphics.Canvas;
@@ -78,10 +77,69 @@
     int mCurrentDimY;
     int mCurrentDimZ;
     int mCurrentCount;
-    static HashMap<Integer, Allocation> mAllocationMap =
-            new HashMap<Integer, Allocation>();
+    static HashMap<Long, Allocation> mAllocationMap =
+            new HashMap<Long, Allocation>();
     OnBufferAvailableListener mBufferNotifier;
 
+    private Element.DataType validateObjectIsPrimitiveArray(Object d, boolean checkType) {
+        final Class c = d.getClass();
+        if (!c.isArray()) {
+            throw new RSIllegalArgumentException("Object passed is not an array of primitives.");
+        }
+        final Class cmp = c.getComponentType();
+        if (!cmp.isPrimitive()) {
+            throw new RSIllegalArgumentException("Object passed is not an Array of primitives.");
+        }
+
+        if (cmp == Long.TYPE) {
+            if (checkType) {
+                validateIsInt64();
+                return mType.mElement.mType;
+            }
+            return Element.DataType.SIGNED_64;
+        }
+
+        if (cmp == Integer.TYPE) {
+            if (checkType) {
+                validateIsInt32();
+                return mType.mElement.mType;
+            }
+            return Element.DataType.SIGNED_32;
+        }
+
+        if (cmp == Short.TYPE) {
+            if (checkType) {
+                validateIsInt16();
+                return mType.mElement.mType;
+            }
+            return Element.DataType.SIGNED_16;
+        }
+
+        if (cmp == Byte.TYPE) {
+            if (checkType) {
+                validateIsInt8();
+                return mType.mElement.mType;
+            }
+            return Element.DataType.SIGNED_8;
+        }
+
+        if (cmp == Float.TYPE) {
+            if (checkType) {
+                validateIsFloat32();
+            }
+            return Element.DataType.FLOAT_32;
+        }
+
+        if (cmp == Double.TYPE) {
+            if (checkType) {
+                validateIsFloat64();
+            }
+            return Element.DataType.FLOAT_64;
+        }
+        return null;
+    }
+
+
     /**
      * The usage of the Allocation.  These signal to RenderScript where to place
      * the Allocation in memory.
@@ -127,17 +185,17 @@
     public static final int USAGE_GRAPHICS_RENDER_TARGET = 0x0010;
 
     /**
-     * The Allocation will be used as a {@link android.graphics.SurfaceTexture}
-     * consumer.  This usage will cause the Allocation to be created as
-     * read-only.
+     * The Allocation will be used as a {@link android.view.Surface}
+     * consumer.  This usage will cause the Allocation to be created
+     * as read-only.
      *
      */
     public static final int USAGE_IO_INPUT = 0x0020;
 
     /**
-     * The Allocation will be used as a {@link android.graphics.SurfaceTexture}
+     * The Allocation will be used as a {@link android.view.Surface}
      * producer.  The dimensions and format of the {@link
-     * android.graphics.SurfaceTexture} will be forced to those of the
+     * android.view.Surface} will be forced to those of the
      * Allocation.
      *
      */
@@ -188,7 +246,7 @@
     }
 
 
-    private int getIDSafe() {
+    private long getIDSafe() {
         if (mAdaptedAllocation != null) {
             return mAdaptedAllocation.getID(mRS);
         }
@@ -224,6 +282,9 @@
      *
      */
     public int getBytesSize() {
+        if (mType.mDimYuv != 0) {
+            return (int)Math.ceil(mType.getCount() * mType.getElement().getBytesSize() * 1.5);
+        }
         return mType.getCount() * mType.getElement().getBytesSize();
     }
 
@@ -244,7 +305,7 @@
         mBitmap = b;
     }
 
-    Allocation(int id, RenderScript rs, Type t, int usage) {
+    Allocation(long id, RenderScript rs, Type t, int usage) {
         super(id, rs);
         if ((usage & ~(USAGE_SCRIPT |
                        USAGE_GRAPHICS_TEXTURE |
@@ -290,6 +351,15 @@
         super.finalize();
     }
 
+    private void validateIsInt64() {
+        if ((mType.mElement.mType == Element.DataType.SIGNED_64) ||
+            (mType.mElement.mType == Element.DataType.UNSIGNED_64)) {
+            return;
+        }
+        throw new RSIllegalArgumentException(
+            "64 bit integer source does not match allocation type " + mType.mElement.mType);
+    }
+
     private void validateIsInt32() {
         if ((mType.mElement.mType == Element.DataType.SIGNED_32) ||
             (mType.mElement.mType == Element.DataType.UNSIGNED_32)) {
@@ -325,6 +395,14 @@
             "32 bit float source does not match allocation type " + mType.mElement.mType);
     }
 
+    private void validateIsFloat64() {
+        if (mType.mElement.mType == Element.DataType.FLOAT_64) {
+            return;
+        }
+        throw new RSIllegalArgumentException(
+            "64 bit float source does not match allocation type " + mType.mElement.mType);
+    }
+
     private void validateIsObject() {
         if ((mType.mElement.mType == Element.DataType.RS_ELEMENT) ||
             (mType.mElement.mType == Element.DataType.RS_TYPE) ||
@@ -345,7 +423,7 @@
     @Override
     void updateFromNative() {
         super.updateFromNative();
-        int typeID = mRS.nAllocationGetType(getID(mRS));
+        long typeID = mRS.nAllocationGetType(getID(mRS));
         if(typeID != 0) {
             mType = new Type(typeID, mRS);
             mType.updateFromNative();
@@ -412,14 +490,6 @@
     }
 
     /**
-     * Delete once code is updated.
-     * @hide
-     */
-    public void ioSendOutput() {
-        ioSend();
-    }
-
-    /**
      * Receive the latest input into the Allocation. This operation
      * is only valid if {@link #USAGE_IO_INPUT} is set on the Allocation.
      *
@@ -448,9 +518,11 @@
             throw new RSIllegalArgumentException("Array size mismatch, allocation sizeX = " +
                                                  mCurrentCount + ", array length = " + d.length);
         }
+        // FIXME: requires 64-bit path
+
         int i[] = new int[d.length];
         for (int ct=0; ct < d.length; ct++) {
-            i[ct] = d[ct].getID(mRS);
+            i[ct] = (int)d[ct].getID(mRS);
         }
         copy1DRangeFromUnchecked(0, mCurrentCount, i);
         Trace.traceEnd(RenderScript.TRACE_TAG);
@@ -511,6 +583,34 @@
         }
     }
 
+    private void copyFromUnchecked(Object array, Element.DataType dt, int arrayLen) {
+        Trace.traceBegin(RenderScript.TRACE_TAG, "copyFromUnchecked");
+        mRS.validate();
+        if (mCurrentDimZ > 0) {
+            copy3DRangeFromUnchecked(0, 0, 0, mCurrentDimX, mCurrentDimY, mCurrentDimZ, array, dt, arrayLen);
+        } else if (mCurrentDimY > 0) {
+            copy2DRangeFromUnchecked(0, 0, mCurrentDimX, mCurrentDimY, array, dt, arrayLen);
+        } else {
+            copy1DRangeFromUnchecked(0, mCurrentCount, array, dt, arrayLen);
+        }
+        Trace.traceEnd(RenderScript.TRACE_TAG);
+    }
+
+    /**
+     * Copy into this Allocation from an array. This method does not guarantee
+     * that the Allocation is compatible with the input buffer; it copies memory
+     * without reinterpretation.
+     *
+     * @param array The source data array
+     * @hide
+     */
+    public void copyFromUnchecked(Object array) {
+        Trace.traceBegin(RenderScript.TRACE_TAG, "copyFromUnchecked");
+        copyFromUnchecked(array, validateObjectIsPrimitiveArray(array, false),
+                          java.lang.reflect.Array.getLength(array));
+        Trace.traceEnd(RenderScript.TRACE_TAG);
+    }
+
     /**
      * Copy into this Allocation from an array. This method does not guarantee
      * that the Allocation is compatible with the input buffer; it copies memory
@@ -519,16 +619,7 @@
      * @param d the source data array
      */
     public void copyFromUnchecked(int[] d) {
-        Trace.traceBegin(RenderScript.TRACE_TAG, "copyFromUnchecked");
-        mRS.validate();
-        if (mCurrentDimZ > 0) {
-            copy3DRangeFromUnchecked(0, 0, 0, mCurrentDimX, mCurrentDimY, mCurrentDimZ, d);
-        } else if (mCurrentDimY > 0) {
-            copy2DRangeFromUnchecked(0, 0, mCurrentDimX, mCurrentDimY, d);
-        } else {
-            copy1DRangeFromUnchecked(0, mCurrentCount, d);
-        }
-        Trace.traceEnd(RenderScript.TRACE_TAG);
+        copyFromUnchecked(d, Element.DataType.SIGNED_32, d.length);
     }
 
     /**
@@ -539,16 +630,7 @@
      * @param d the source data array
      */
     public void copyFromUnchecked(short[] d) {
-        Trace.traceBegin(RenderScript.TRACE_TAG, "copyFromUnchecked");
-        mRS.validate();
-        if (mCurrentDimZ > 0) {
-            copy3DRangeFromUnchecked(0, 0, 0, mCurrentDimX, mCurrentDimY, mCurrentDimZ, d);
-        } else if (mCurrentDimY > 0) {
-            copy2DRangeFromUnchecked(0, 0, mCurrentDimX, mCurrentDimY, d);
-        } else {
-            copy1DRangeFromUnchecked(0, mCurrentCount, d);
-        }
-        Trace.traceEnd(RenderScript.TRACE_TAG);
+        copyFromUnchecked(d, Element.DataType.SIGNED_16, d.length);
     }
 
     /**
@@ -559,16 +641,7 @@
      * @param d the source data array
      */
     public void copyFromUnchecked(byte[] d) {
-        Trace.traceBegin(RenderScript.TRACE_TAG, "copyFromUnchecked");
-        mRS.validate();
-        if (mCurrentDimZ > 0) {
-            copy3DRangeFromUnchecked(0, 0, 0, mCurrentDimX, mCurrentDimY, mCurrentDimZ, d);
-        } else if (mCurrentDimY > 0) {
-            copy2DRangeFromUnchecked(0, 0, mCurrentDimX, mCurrentDimY, d);
-        } else {
-            copy1DRangeFromUnchecked(0, mCurrentCount, d);
-        }
-        Trace.traceEnd(RenderScript.TRACE_TAG);
+        copyFromUnchecked(d, Element.DataType.SIGNED_8, d.length);
     }
 
     /**
@@ -579,37 +652,36 @@
      * @param d the source data array
      */
     public void copyFromUnchecked(float[] d) {
-        Trace.traceBegin(RenderScript.TRACE_TAG, "copyFromUnchecked");
-        mRS.validate();
-        if (mCurrentDimZ > 0) {
-            copy3DRangeFromUnchecked(0, 0, 0, mCurrentDimX, mCurrentDimY, mCurrentDimZ, d);
-        } else if (mCurrentDimY > 0) {
-            copy2DRangeFromUnchecked(0, 0, mCurrentDimX, mCurrentDimY, d);
-        } else {
-            copy1DRangeFromUnchecked(0, mCurrentCount, d);
-        }
-        Trace.traceEnd(RenderScript.TRACE_TAG);
+        copyFromUnchecked(d, Element.DataType.FLOAT_32, d.length);
     }
 
 
     /**
      * Copy into this Allocation from an array.  This variant is type checked
      * and will generate exceptions if the Allocation's {@link
+     * android.renderscript.Element} does not match the array's
+     * primitive type.
+     *
+     * @param d the source data array
+     * @hide
+     */
+    public void copyFrom(Object array) {
+        Trace.traceBegin(RenderScript.TRACE_TAG, "copyFrom");
+        copyFromUnchecked(array, validateObjectIsPrimitiveArray(array, true),
+                          java.lang.reflect.Array.getLength(array));
+        Trace.traceEnd(RenderScript.TRACE_TAG);
+    }
+
+    /**
+     * Copy into this Allocation from an array.  This variant is type checked
+     * and will generate exceptions if the Allocation's {@link
      * android.renderscript.Element} is not a 32 bit integer type.
      *
      * @param d the source data array
      */
     public void copyFrom(int[] d) {
-        Trace.traceBegin(RenderScript.TRACE_TAG, "copyFrom");
-        mRS.validate();
-        if (mCurrentDimZ > 0) {
-            copy3DRangeFrom(0, 0, 0, mCurrentDimX, mCurrentDimY, mCurrentDimZ, d);
-        } else if (mCurrentDimY > 0) {
-            copy2DRangeFrom(0, 0, mCurrentDimX, mCurrentDimY, d);
-        } else {
-            copy1DRangeFrom(0, mCurrentCount, d);
-        }
-        Trace.traceEnd(RenderScript.TRACE_TAG);
+        validateIsInt32();
+        copyFromUnchecked(d, Element.DataType.SIGNED_32, d.length);
     }
 
     /**
@@ -620,16 +692,8 @@
      * @param d the source data array
      */
     public void copyFrom(short[] d) {
-        Trace.traceBegin(RenderScript.TRACE_TAG, "copyFrom");
-        mRS.validate();
-        if (mCurrentDimZ > 0) {
-            copy3DRangeFrom(0, 0, 0, mCurrentDimX, mCurrentDimY, mCurrentDimZ, d);
-        } else if (mCurrentDimY > 0) {
-            copy2DRangeFrom(0, 0, mCurrentDimX, mCurrentDimY, d);
-        } else {
-            copy1DRangeFrom(0, mCurrentCount, d);
-        }
-        Trace.traceEnd(RenderScript.TRACE_TAG);
+        validateIsInt16();
+        copyFromUnchecked(d, Element.DataType.SIGNED_16, d.length);
     }
 
     /**
@@ -640,16 +704,8 @@
      * @param d the source data array
      */
     public void copyFrom(byte[] d) {
-        Trace.traceBegin(RenderScript.TRACE_TAG, "copyFrom");
-        mRS.validate();
-        if (mCurrentDimZ > 0) {
-            copy3DRangeFrom(0, 0, 0, mCurrentDimX, mCurrentDimY, mCurrentDimZ, d);
-        } else if (mCurrentDimY > 0) {
-            copy2DRangeFrom(0, 0, mCurrentDimX, mCurrentDimY, d);
-        } else {
-            copy1DRangeFrom(0, mCurrentCount, d);
-        }
-        Trace.traceEnd(RenderScript.TRACE_TAG);
+        validateIsInt8();
+        copyFromUnchecked(d, Element.DataType.SIGNED_8, d.length);
     }
 
     /**
@@ -660,16 +716,8 @@
      * @param d the source data array
      */
     public void copyFrom(float[] d) {
-        Trace.traceBegin(RenderScript.TRACE_TAG, "copyFrom");
-        mRS.validate();
-        if (mCurrentDimZ > 0) {
-            copy3DRangeFrom(0, 0, 0, mCurrentDimX, mCurrentDimY, mCurrentDimZ, d);
-        } else if (mCurrentDimY > 0) {
-            copy2DRangeFrom(0, 0, mCurrentDimX, mCurrentDimY, d);
-        } else {
-            copy1DRangeFrom(0, mCurrentCount, d);
-        }
-        Trace.traceEnd(RenderScript.TRACE_TAG);
+        validateIsFloat32();
+        copyFromUnchecked(d, Element.DataType.FLOAT_32, d.length);
     }
 
     /**
@@ -798,6 +846,30 @@
         mRS.nAllocationGenerateMipmaps(getID(mRS));
     }
 
+    private void copy1DRangeFromUnchecked(int off, int count, Object array,
+                                          Element.DataType dt, int arrayLen) {
+        Trace.traceBegin(RenderScript.TRACE_TAG, "copy1DRangeFromUnchecked");
+        final int dataSize = mType.mElement.getBytesSize() * count;
+        data1DChecks(off, count, arrayLen * dt.mSize, dataSize);
+        mRS.nAllocationData1D(getIDSafe(), off, mSelectedLOD, count, array, dataSize, dt);
+        Trace.traceEnd(RenderScript.TRACE_TAG);
+    }
+
+    /**
+     * Copy an array into part of this Allocation.  This method does not
+     * guarantee that the Allocation is compatible with the input buffer.
+     *
+     * @param off The offset of the first element to be copied.
+     * @param count The number of elements to be copied.
+     * @param array The source data array
+     * @hide
+     */
+    public void copy1DRangeFromUnchecked(int off, int count, Object array) {
+        copy1DRangeFromUnchecked(off, count, array,
+                                 validateObjectIsPrimitiveArray(array, false),
+                                 java.lang.reflect.Array.getLength(array));
+    }
+
     /**
      * Copy an array into part of this Allocation.  This method does not
      * guarantee that the Allocation is compatible with the input buffer.
@@ -807,11 +879,7 @@
      * @param d the source data array
      */
     public void copy1DRangeFromUnchecked(int off, int count, int[] d) {
-        Trace.traceBegin(RenderScript.TRACE_TAG, "copy1DRangeFromUnchecked");
-        int dataSize = mType.mElement.getBytesSize() * count;
-        data1DChecks(off, count, d.length * 4, dataSize);
-        mRS.nAllocationData1D(getIDSafe(), off, mSelectedLOD, count, d, dataSize);
-        Trace.traceEnd(RenderScript.TRACE_TAG);
+        copy1DRangeFromUnchecked(off, count, (Object)d, Element.DataType.SIGNED_32, d.length);
     }
 
     /**
@@ -823,11 +891,7 @@
      * @param d the source data array
      */
     public void copy1DRangeFromUnchecked(int off, int count, short[] d) {
-        Trace.traceBegin(RenderScript.TRACE_TAG, "copy1DRangeFromUnchecked");
-        int dataSize = mType.mElement.getBytesSize() * count;
-        data1DChecks(off, count, d.length * 2, dataSize);
-        mRS.nAllocationData1D(getIDSafe(), off, mSelectedLOD, count, d, dataSize);
-        Trace.traceEnd(RenderScript.TRACE_TAG);
+        copy1DRangeFromUnchecked(off, count, (Object)d, Element.DataType.SIGNED_16, d.length);
     }
 
     /**
@@ -839,11 +903,7 @@
      * @param d the source data array
      */
     public void copy1DRangeFromUnchecked(int off, int count, byte[] d) {
-        Trace.traceBegin(RenderScript.TRACE_TAG, "copy1DRangeFromUnchecked");
-        int dataSize = mType.mElement.getBytesSize() * count;
-        data1DChecks(off, count, d.length, dataSize);
-        mRS.nAllocationData1D(getIDSafe(), off, mSelectedLOD, count, d, dataSize);
-        Trace.traceEnd(RenderScript.TRACE_TAG);
+        copy1DRangeFromUnchecked(off, count, (Object)d, Element.DataType.SIGNED_8, d.length);
     }
 
     /**
@@ -855,11 +915,24 @@
      * @param d the source data array
      */
     public void copy1DRangeFromUnchecked(int off, int count, float[] d) {
-        Trace.traceBegin(RenderScript.TRACE_TAG, "copy1DRangeFromUnchecked");
-        int dataSize = mType.mElement.getBytesSize() * count;
-        data1DChecks(off, count, d.length * 4, dataSize);
-        mRS.nAllocationData1D(getIDSafe(), off, mSelectedLOD, count, d, dataSize);
-        Trace.traceEnd(RenderScript.TRACE_TAG);
+        copy1DRangeFromUnchecked(off, count, (Object)d, Element.DataType.FLOAT_32, d.length);
+    }
+
+
+    /**
+     * Copy an array into part of this Allocation.  This variant is type checked
+     * and will generate exceptions if the Allocation type does not
+     * match the component type of the array passed in.
+     *
+     * @param off The offset of the first element to be copied.
+     * @param count The number of elements to be copied.
+     * @param array The source data array.
+     * @hide
+     */
+    public void copy1DRangeFrom(int off, int count, Object array) {
+        copy1DRangeFromUnchecked(off, count, array,
+                                 validateObjectIsPrimitiveArray(array, true),
+                                 java.lang.reflect.Array.getLength(array));
     }
 
     /**
@@ -872,10 +945,8 @@
      * @param d the source data array
      */
     public void copy1DRangeFrom(int off, int count, int[] d) {
-        Trace.traceBegin(RenderScript.TRACE_TAG, "copy1DRangeFrom");
         validateIsInt32();
-        copy1DRangeFromUnchecked(off, count, d);
-        Trace.traceEnd(RenderScript.TRACE_TAG);
+        copy1DRangeFromUnchecked(off, count, d, Element.DataType.SIGNED_32, d.length);
     }
 
     /**
@@ -888,10 +959,8 @@
      * @param d the source data array
      */
     public void copy1DRangeFrom(int off, int count, short[] d) {
-        Trace.traceBegin(RenderScript.TRACE_TAG, "copy1DRangeFrom");
         validateIsInt16();
-        copy1DRangeFromUnchecked(off, count, d);
-        Trace.traceEnd(RenderScript.TRACE_TAG);
+        copy1DRangeFromUnchecked(off, count, d, Element.DataType.SIGNED_16, d.length);
     }
 
     /**
@@ -904,10 +973,8 @@
      * @param d the source data array
      */
     public void copy1DRangeFrom(int off, int count, byte[] d) {
-        Trace.traceBegin(RenderScript.TRACE_TAG, "copy1DRangeFrom");
         validateIsInt8();
-        copy1DRangeFromUnchecked(off, count, d);
-        Trace.traceEnd(RenderScript.TRACE_TAG);
+        copy1DRangeFromUnchecked(off, count, d, Element.DataType.SIGNED_8, d.length);
     }
 
     /**
@@ -920,11 +987,10 @@
      * @param d the source data array.
      */
     public void copy1DRangeFrom(int off, int count, float[] d) {
-        Trace.traceBegin(RenderScript.TRACE_TAG, "copy1DRangeFrom");
         validateIsFloat32();
-        copy1DRangeFromUnchecked(off, count, d);
-        Trace.traceEnd(RenderScript.TRACE_TAG);
+        copy1DRangeFromUnchecked(off, count, d, Element.DataType.FLOAT_32, d.length);
     }
+
      /**
      * Copy part of an Allocation into this Allocation.
      *
@@ -959,39 +1025,32 @@
         }
     }
 
-    void copy2DRangeFromUnchecked(int xoff, int yoff, int w, int h, byte[] data) {
+    void copy2DRangeFromUnchecked(int xoff, int yoff, int w, int h, Object array,
+                                  Element.DataType dt, int arrayLen) {
         Trace.traceBegin(RenderScript.TRACE_TAG, "copy2DRangeFromUnchecked");
         mRS.validate();
         validate2DRange(xoff, yoff, w, h);
-        mRS.nAllocationData2D(getIDSafe(), xoff, yoff, mSelectedLOD, mSelectedFace.mID,
-                              w, h, data, data.length);
+        mRS.nAllocationData2D(getIDSafe(), xoff, yoff, mSelectedLOD, mSelectedFace.mID, w, h,
+                              array, arrayLen * dt.mSize, dt);
         Trace.traceEnd(RenderScript.TRACE_TAG);
     }
 
-    void copy2DRangeFromUnchecked(int xoff, int yoff, int w, int h, short[] data) {
-        Trace.traceBegin(RenderScript.TRACE_TAG, "copy2DRangeFromUnchecked");
-        mRS.validate();
-        validate2DRange(xoff, yoff, w, h);
-        mRS.nAllocationData2D(getIDSafe(), xoff, yoff, mSelectedLOD, mSelectedFace.mID,
-                              w, h, data, data.length * 2);
-        Trace.traceEnd(RenderScript.TRACE_TAG);
-    }
-
-    void copy2DRangeFromUnchecked(int xoff, int yoff, int w, int h, int[] data) {
-        Trace.traceBegin(RenderScript.TRACE_TAG, "copy2DRangeFromUnchecked");
-        mRS.validate();
-        validate2DRange(xoff, yoff, w, h);
-        mRS.nAllocationData2D(getIDSafe(), xoff, yoff, mSelectedLOD, mSelectedFace.mID,
-                              w, h, data, data.length * 4);
-        Trace.traceEnd(RenderScript.TRACE_TAG);
-    }
-
-    void copy2DRangeFromUnchecked(int xoff, int yoff, int w, int h, float[] data) {
-        Trace.traceBegin(RenderScript.TRACE_TAG, "copy2DRangeFromUnchecked");
-        mRS.validate();
-        validate2DRange(xoff, yoff, w, h);
-        mRS.nAllocationData2D(getIDSafe(), xoff, yoff, mSelectedLOD, mSelectedFace.mID,
-                              w, h, data, data.length * 4);
+    /**
+     * Copy from an array into a rectangular region in this Allocation.  The
+     * array is assumed to be tightly packed.
+     *
+     * @param xoff X offset of the region to update in this Allocation
+     * @param yoff Y offset of the region to update in this Allocation
+     * @param w Width of the region to update
+     * @param h Height of the region to update
+     * @param data to be placed into the Allocation
+     * @hide
+     */
+    public void copy2DRangeFrom(int xoff, int yoff, int w, int h, Object array) {
+        Trace.traceBegin(RenderScript.TRACE_TAG, "copy2DRangeFrom");
+        copy2DRangeFromUnchecked(xoff, yoff, w, h, array,
+                                 validateObjectIsPrimitiveArray(array, true),
+                                 java.lang.reflect.Array.getLength(array));
         Trace.traceEnd(RenderScript.TRACE_TAG);
     }
 
@@ -1006,10 +1065,9 @@
      * @param data to be placed into the Allocation
      */
     public void copy2DRangeFrom(int xoff, int yoff, int w, int h, byte[] data) {
-        Trace.traceBegin(RenderScript.TRACE_TAG, "copy2DRangeFrom");
         validateIsInt8();
-        copy2DRangeFromUnchecked(xoff, yoff, w, h, data);
-        Trace.traceEnd(RenderScript.TRACE_TAG);
+        copy2DRangeFromUnchecked(xoff, yoff, w, h, data,
+                                 Element.DataType.SIGNED_8, data.length);
     }
 
     /**
@@ -1023,10 +1081,9 @@
      * @param data to be placed into the Allocation
      */
     public void copy2DRangeFrom(int xoff, int yoff, int w, int h, short[] data) {
-        Trace.traceBegin(RenderScript.TRACE_TAG, "copy2DRangeFrom");
         validateIsInt16();
-        copy2DRangeFromUnchecked(xoff, yoff, w, h, data);
-        Trace.traceEnd(RenderScript.TRACE_TAG);
+        copy2DRangeFromUnchecked(xoff, yoff, w, h, data,
+                                 Element.DataType.SIGNED_16, data.length);
     }
 
     /**
@@ -1040,10 +1097,9 @@
      * @param data to be placed into the Allocation
      */
     public void copy2DRangeFrom(int xoff, int yoff, int w, int h, int[] data) {
-        Trace.traceBegin(RenderScript.TRACE_TAG, "copy2DRangeFrom");
         validateIsInt32();
-        copy2DRangeFromUnchecked(xoff, yoff, w, h, data);
-        Trace.traceEnd(RenderScript.TRACE_TAG);
+        copy2DRangeFromUnchecked(xoff, yoff, w, h, data,
+                                 Element.DataType.SIGNED_32, data.length);
     }
 
     /**
@@ -1057,10 +1113,9 @@
      * @param data to be placed into the Allocation
      */
     public void copy2DRangeFrom(int xoff, int yoff, int w, int h, float[] data) {
-        Trace.traceBegin(RenderScript.TRACE_TAG, "copy2DRangeFrom");
         validateIsFloat32();
-        copy2DRangeFromUnchecked(xoff, yoff, w, h, data);
-        Trace.traceEnd(RenderScript.TRACE_TAG);
+        copy2DRangeFromUnchecked(xoff, yoff, w, h, data,
+                                 Element.DataType.FLOAT_32, data.length);
     }
 
     /**
@@ -1133,49 +1188,18 @@
      * @hide
      *
      */
-    void copy3DRangeFromUnchecked(int xoff, int yoff, int zoff, int w, int h, int d, byte[] data) {
+    private void copy3DRangeFromUnchecked(int xoff, int yoff, int zoff, int w, int h, int d,
+                                          Object array, Element.DataType dt, int arrayLen) {
+        Trace.traceBegin(RenderScript.TRACE_TAG, "copy3DRangeFromUnchecked");
         mRS.validate();
         validate3DRange(xoff, yoff, zoff, w, h, d);
-        mRS.nAllocationData3D(getIDSafe(), xoff, yoff, zoff, mSelectedLOD,
-                              w, h, d, data, data.length);
+        mRS.nAllocationData3D(getIDSafe(), xoff, yoff, zoff, mSelectedLOD, w, h, d,
+                              array, arrayLen * dt.mSize, dt);
+        Trace.traceEnd(RenderScript.TRACE_TAG);
     }
 
     /**
      * @hide
-     *
-     */
-    void copy3DRangeFromUnchecked(int xoff, int yoff, int zoff, int w, int h, int d, short[] data) {
-        mRS.validate();
-        validate3DRange(xoff, yoff, zoff, w, h, d);
-        mRS.nAllocationData3D(getIDSafe(), xoff, yoff, zoff, mSelectedLOD,
-                              w, h, d, data, data.length * 2);
-    }
-
-    /**
-     * @hide
-     *
-     */
-    void copy3DRangeFromUnchecked(int xoff, int yoff, int zoff, int w, int h, int d, int[] data) {
-        mRS.validate();
-        validate3DRange(xoff, yoff, zoff, w, h, d);
-        mRS.nAllocationData3D(getIDSafe(), xoff, yoff, zoff, mSelectedLOD,
-                              w, h, d, data, data.length * 4);
-    }
-
-    /**
-     * @hide
-     *
-     */
-    void copy3DRangeFromUnchecked(int xoff, int yoff, int zoff, int w, int h, int d, float[] data) {
-        mRS.validate();
-        validate3DRange(xoff, yoff, zoff, w, h, d);
-        mRS.nAllocationData3D(getIDSafe(), xoff, yoff, zoff, mSelectedLOD,
-                              w, h, d, data, data.length * 4);
-    }
-
-
-    /**
-     * @hide
      * Copy a rectangular region from the array into the allocation.
      * The array is assumed to be tightly packed.
      *
@@ -1187,36 +1211,12 @@
      * @param d Depth of the region to update
      * @param data to be placed into the allocation
      */
-    public void copy3DRangeFrom(int xoff, int yoff, int zoff, int w, int h, int d, byte[] data) {
-        validateIsInt8();
-        copy3DRangeFromUnchecked(xoff, yoff, zoff, w, h, d, data);
-    }
-
-    /**
-     * @hide
-     *
-     */
-    public void copy3DRangeFrom(int xoff, int yoff, int zoff, int w, int h, int d, short[] data) {
-        validateIsInt16();
-        copy3DRangeFromUnchecked(xoff, yoff, zoff, w, h, d, data);
-    }
-
-    /**
-     * @hide
-     *
-     */
-    public void copy3DRangeFrom(int xoff, int yoff, int zoff, int w, int h, int d, int[] data) {
-        validateIsInt32();
-        copy3DRangeFromUnchecked(xoff, yoff, zoff, w, h, d, data);
-    }
-
-    /**
-     * @hide
-     *
-     */
-    public void copy3DRangeFrom(int xoff, int yoff, int zoff, int w, int h, int d, float[] data) {
-        validateIsFloat32();
-        copy3DRangeFromUnchecked(xoff, yoff, zoff, w, h, d, data);
+    public void copy3DRangeFrom(int xoff, int yoff, int zoff, int w, int h, int d, Object array) {
+        Trace.traceBegin(RenderScript.TRACE_TAG, "copy3DRangeFrom");
+        copy3DRangeFromUnchecked(xoff, yoff, zoff, w, h, d, array,
+                                 validateObjectIsPrimitiveArray(array, true),
+                                 java.lang.reflect.Array.getLength(array));
+        Trace.traceEnd(RenderScript.TRACE_TAG);
     }
 
     /**
@@ -1260,6 +1260,27 @@
         Trace.traceEnd(RenderScript.TRACE_TAG);
     }
 
+    private void copyTo(Object array, Element.DataType dt, int arrayLen) {
+        Trace.traceBegin(RenderScript.TRACE_TAG, "copyTo");
+        mRS.validate();
+        mRS.nAllocationRead(getID(mRS), array, dt);
+        Trace.traceEnd(RenderScript.TRACE_TAG);
+    }
+
+    /**
+     * Copy from the Allocation into an array.  The array must be at
+     * least as large as the Allocation.  The
+     * {@link android.renderscript.Element} must match the component
+     * type of the array passed in.
+     *
+     * @param array The array to be set from the Allocation.
+     * @hide
+     */
+    public void copyTo(Object array) {
+        copyTo(array, validateObjectIsPrimitiveArray(array, true),
+               java.lang.reflect.Array.getLength(array));
+    }
+
     /**
      * Copy from the Allocation into a byte array.  The array must be at least
      * as large as the Allocation.  The allocation must be of an 8 bit integer
@@ -1268,11 +1289,8 @@
      * @param d The array to be set from the Allocation.
      */
     public void copyTo(byte[] d) {
-        Trace.traceBegin(RenderScript.TRACE_TAG, "copyTo");
         validateIsInt8();
-        mRS.validate();
-        mRS.nAllocationRead(getID(mRS), d);
-        Trace.traceEnd(RenderScript.TRACE_TAG);
+        copyTo(d, Element.DataType.SIGNED_8, d.length);
     }
 
     /**
@@ -1283,11 +1301,8 @@
      * @param d The array to be set from the Allocation.
      */
     public void copyTo(short[] d) {
-        Trace.traceBegin(RenderScript.TRACE_TAG, "copyTo");
         validateIsInt16();
-        mRS.validate();
-        mRS.nAllocationRead(getID(mRS), d);
-        Trace.traceEnd(RenderScript.TRACE_TAG);
+        copyTo(d, Element.DataType.SIGNED_16, d.length);
     }
 
     /**
@@ -1298,11 +1313,8 @@
      * @param d The array to be set from the Allocation.
      */
     public void copyTo(int[] d) {
-        Trace.traceBegin(RenderScript.TRACE_TAG, "copyTo");
         validateIsInt32();
-        mRS.validate();
-        mRS.nAllocationRead(getID(mRS), d);
-        Trace.traceEnd(RenderScript.TRACE_TAG);
+        copyTo(d, Element.DataType.SIGNED_32, d.length);
     }
 
     /**
@@ -1313,11 +1325,8 @@
      * @param d The array to be set from the Allocation.
      */
     public void copyTo(float[] d) {
-        Trace.traceBegin(RenderScript.TRACE_TAG, "copyTo");
         validateIsFloat32();
-        mRS.validate();
-        mRS.nAllocationRead(getID(mRS), d);
-        Trace.traceEnd(RenderScript.TRACE_TAG);
+        copyTo(d, Element.DataType.FLOAT_32, d.length);
     }
 
     /**
@@ -1342,7 +1351,7 @@
         mRS.nAllocationResize1D(getID(mRS), dimX);
         mRS.finish();  // Necessary because resize is fifoed and update is async.
 
-        int typeID = mRS.nAllocationGetType(getID(mRS));
+        long typeID = mRS.nAllocationGetType(getID(mRS));
         mType = new Type(typeID, mRS);
         mType.updateFromNative();
         updateCacheInfo(mType);
@@ -1372,7 +1381,7 @@
         if (type.getID(rs) == 0) {
             throw new RSInvalidStateException("Bad Type");
         }
-        int id = rs.nAllocationCreateTyped(type.getID(rs), mips.mID, usage, 0);
+        long id = rs.nAllocationCreateTyped(type.getID(rs), mips.mID, usage, 0);
         if (id == 0) {
             throw new RSRuntimeException("Allocation creation failed.");
         }
@@ -1427,7 +1436,7 @@
         b.setX(count);
         Type t = b.create();
 
-        int id = rs.nAllocationCreateTyped(t.getID(rs), MipmapControl.MIPMAP_NONE.mID, usage, 0);
+        long id = rs.nAllocationCreateTyped(t.getID(rs), MipmapControl.MIPMAP_NONE.mID, usage, 0);
         if (id == 0) {
             throw new RSRuntimeException("Allocation creation failed.");
         }
@@ -1511,7 +1520,7 @@
         if (mips == MipmapControl.MIPMAP_NONE &&
             t.getElement().isCompatible(Element.RGBA_8888(rs)) &&
             usage == (USAGE_SHARED | USAGE_SCRIPT | USAGE_GRAPHICS_TEXTURE)) {
-            int id = rs.nAllocationCreateBitmapBackedAllocation(t.getID(rs), mips.mID, b, usage);
+            long id = rs.nAllocationCreateBitmapBackedAllocation(t.getID(rs), mips.mID, b, usage);
             if (id == 0) {
                 throw new RSRuntimeException("Load failed.");
             }
@@ -1523,7 +1532,7 @@
         }
 
 
-        int id = rs.nAllocationCreateFromBitmap(t.getID(rs), mips.mID, b, usage);
+        long id = rs.nAllocationCreateFromBitmap(t.getID(rs), mips.mID, b, usage);
         if (id == 0) {
             throw new RSRuntimeException("Load failed.");
         }
@@ -1547,13 +1556,6 @@
     }
 
     /**
-     * @hide
-     */
-    public void setSurfaceTexture(SurfaceTexture st) {
-        setSurface(new Surface(st));
-    }
-
-    /**
      * Associate a {@link android.view.Surface} with this Allocation. This
      * operation is only valid for Allocations with {@link #USAGE_IO_OUTPUT}.
      *
@@ -1633,7 +1635,7 @@
         tb.setMipmaps(mips == MipmapControl.MIPMAP_FULL);
         Type t = tb.create();
 
-        int id = rs.nAllocationCubeCreateFromBitmap(t.getID(rs), mips.mID, b, usage);
+        long id = rs.nAllocationCubeCreateFromBitmap(t.getID(rs), mips.mID, b, usage);
         if(id == 0) {
             throw new RSRuntimeException("Load failed for bitmap " + b + " element " + e);
         }
@@ -1858,14 +1860,14 @@
      */
     public void setOnBufferAvailableListener(OnBufferAvailableListener callback) {
         synchronized(mAllocationMap) {
-            mAllocationMap.put(new Integer(getID(mRS)), this);
+            mAllocationMap.put(new Long(getID(mRS)), this);
             mBufferNotifier = callback;
         }
     }
 
     static void sendBufferNotification(int id) {
         synchronized(mAllocationMap) {
-            Allocation a = mAllocationMap.get(new Integer(id));
+            Allocation a = mAllocationMap.get(new Long(id));
 
             if ((a != null) && (a.mBufferNotifier != null)) {
                 a.mBufferNotifier.onBufferAvailable(a);
diff --git a/graphics/java/android/renderscript/AllocationAdapter.java b/rs/java/android/renderscript/AllocationAdapter.java
similarity index 98%
rename from graphics/java/android/renderscript/AllocationAdapter.java
rename to rs/java/android/renderscript/AllocationAdapter.java
index a6645bb..b77d087 100644
--- a/graphics/java/android/renderscript/AllocationAdapter.java
+++ b/rs/java/android/renderscript/AllocationAdapter.java
@@ -26,12 +26,12 @@
  *
  **/
 public class AllocationAdapter extends Allocation {
-    AllocationAdapter(int id, RenderScript rs, Allocation alloc) {
+    AllocationAdapter(long id, RenderScript rs, Allocation alloc) {
         super(id, rs, alloc.mType, alloc.mUsage);
         mAdaptedAllocation = alloc;
     }
 
-    int getID(RenderScript rs) {
+    long getID(RenderScript rs) {
         throw new RSInvalidStateException(
             "This operation is not supported with adapters at this time.");
     }
diff --git a/graphics/java/android/renderscript/BaseObj.java b/rs/java/android/renderscript/BaseObj.java
similarity index 84%
rename from graphics/java/android/renderscript/BaseObj.java
rename to rs/java/android/renderscript/BaseObj.java
index e17d79a..842aa23 100644
--- a/graphics/java/android/renderscript/BaseObj.java
+++ b/rs/java/android/renderscript/BaseObj.java
@@ -16,7 +16,7 @@
 
 package android.renderscript;
 
-import android.util.Log;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
 
 /**
  * BaseObj is the base class for all RenderScript objects owned by a RS context.
@@ -25,14 +25,14 @@
  *
  **/
 public class BaseObj {
-    BaseObj(int id, RenderScript rs) {
+    BaseObj(long id, RenderScript rs) {
         rs.validate();
         mRS = rs;
         mID = id;
         mDestroyed = false;
     }
 
-    void setID(int id) {
+    void setID(long id) {
         if (mID != 0) {
             throw new RSRuntimeException("Internal Error, reset of object ID.");
         }
@@ -46,9 +46,9 @@
      * @param rs Context to verify against internal context for
      *           match.
      *
-     * @return int
+     * @return long
      */
-    int getID(RenderScript rs) {
+    long getID(RenderScript rs) {
         mRS.validate();
         if (mDestroyed) {
             throw new RSInvalidStateException("using a destroyed object.");
@@ -68,7 +68,7 @@
         }
     }
 
-    private int mID;
+    private long mID;
     private boolean mDestroyed;
     private String mName;
     RenderScript mRS;
@@ -109,17 +109,30 @@
         return mName;
     }
 
-    protected void finalize() throws Throwable {
-        if (!mDestroyed) {
-            if(mID != 0 && mRS.isAlive()) {
+    private void helpDestroy() {
+        boolean shouldDestroy = false;
+        synchronized(this) {
+            if (!mDestroyed) {
+                shouldDestroy = true;
+                mDestroyed = true;
+            }
+        }
+
+        if (shouldDestroy) {
+            // must include nObjDestroy in the critical section
+            ReentrantReadWriteLock.ReadLock rlock = mRS.mRWLock.readLock();
+            rlock.lock();
+            if(mRS.isAlive()) {
                 mRS.nObjDestroy(mID);
             }
+            rlock.unlock();
             mRS = null;
             mID = 0;
-            mDestroyed = true;
-            //Log.v(RenderScript.LOG_TAG, getClass() +
-            // " auto finalizing object without having released the RS reference.");
         }
+    }
+
+    protected void finalize() throws Throwable {
+        helpDestroy();
         super.finalize();
     }
 
@@ -128,12 +141,11 @@
      * primary use is to force immediate cleanup of resources when it is
      * believed the GC will not respond quickly enough.
      */
-    synchronized public void destroy() {
+    public void destroy() {
         if(mDestroyed) {
             throw new RSInvalidStateException("Object already destroyed.");
         }
-        mDestroyed = true;
-        mRS.nObjDestroy(mID);
+        helpDestroy();
     }
 
     /**
@@ -152,7 +164,7 @@
      */
     @Override
     public int hashCode() {
-        return mID;
+        return (int)((mID & 0xfffffff) ^ (mID >> 32));
     }
 
     /**
diff --git a/graphics/java/android/renderscript/Byte2.java b/rs/java/android/renderscript/Byte2.java
similarity index 100%
rename from graphics/java/android/renderscript/Byte2.java
rename to rs/java/android/renderscript/Byte2.java
diff --git a/graphics/java/android/renderscript/Byte3.java b/rs/java/android/renderscript/Byte3.java
similarity index 100%
rename from graphics/java/android/renderscript/Byte3.java
rename to rs/java/android/renderscript/Byte3.java
diff --git a/graphics/java/android/renderscript/Byte4.java b/rs/java/android/renderscript/Byte4.java
similarity index 100%
rename from graphics/java/android/renderscript/Byte4.java
rename to rs/java/android/renderscript/Byte4.java
diff --git a/graphics/java/android/renderscript/Double2.java b/rs/java/android/renderscript/Double2.java
similarity index 100%
rename from graphics/java/android/renderscript/Double2.java
rename to rs/java/android/renderscript/Double2.java
diff --git a/graphics/java/android/renderscript/Double3.java b/rs/java/android/renderscript/Double3.java
similarity index 100%
rename from graphics/java/android/renderscript/Double3.java
rename to rs/java/android/renderscript/Double3.java
diff --git a/graphics/java/android/renderscript/Double4.java b/rs/java/android/renderscript/Double4.java
similarity index 100%
rename from graphics/java/android/renderscript/Double4.java
rename to rs/java/android/renderscript/Double4.java
diff --git a/graphics/java/android/renderscript/Element.java b/rs/java/android/renderscript/Element.java
similarity index 98%
rename from graphics/java/android/renderscript/Element.java
rename to rs/java/android/renderscript/Element.java
index 68badfa..2932770 100644
--- a/graphics/java/android/renderscript/Element.java
+++ b/rs/java/android/renderscript/Element.java
@@ -759,7 +759,7 @@
         return rs.mElement_MATRIX_2X2;
     }
 
-    Element(int id, RenderScript rs, Element[] e, String[] n, int[] as) {
+    Element(long id, RenderScript rs, Element[] e, String[] n, int[] as) {
         super(id, rs);
         mSize = 0;
         mVectorSize = 1;
@@ -776,7 +776,7 @@
         updateVisibleSubElements();
     }
 
-    Element(int id, RenderScript rs, DataType dt, DataKind dk, boolean norm, int size) {
+    Element(long id, RenderScript rs, DataType dt, DataKind dk, boolean norm, int size) {
         super(id, rs);
         if ((dt != DataType.UNSIGNED_5_6_5) &&
             (dt != DataType.UNSIGNED_4_4_4_4) &&
@@ -795,7 +795,7 @@
         mVectorSize = size;
     }
 
-    Element(int id, RenderScript rs) {
+    Element(long id, RenderScript rs) {
         super(id, rs);
     }
 
@@ -803,6 +803,8 @@
     void updateFromNative() {
         super.updateFromNative();
 
+        // FIXME: updateFromNative is broken in JNI for 64-bit
+
         // we will pack mType; mKind; mNormalized; mVectorSize; NumSubElements
         int[] dataBuffer = new int[5];
         mRS.nElementGetNativeData(getID(mRS), dataBuffer);
@@ -853,7 +855,7 @@
         DataKind dk = DataKind.USER;
         boolean norm = false;
         int vecSize = 1;
-        int id = rs.nElementCreate(dt.mID, dk.mID, norm, vecSize);
+        long id = rs.nElementCreate(dt.mID, dk.mID, norm, vecSize);
         return new Element(id, rs, dt, dk, norm, vecSize);
     }
 
@@ -890,7 +892,7 @@
         case BOOLEAN: {
             DataKind dk = DataKind.USER;
             boolean norm = false;
-            int id = rs.nElementCreate(dt.mID, dk.mID, norm, size);
+            long id = rs.nElementCreate(dt.mID, dk.mID, norm, size);
             return new Element(id, rs, dt, dk, norm, size);
         }
 
@@ -961,7 +963,7 @@
         }
 
         boolean norm = true;
-        int id = rs.nElementCreate(dt.mID, dk.mID, norm, size);
+        long id = rs.nElementCreate(dt.mID, dk.mID, norm, size);
         return new Element(id, rs, dt, dk, norm, size);
     }
 
@@ -1088,11 +1090,12 @@
             java.lang.System.arraycopy(mElementNames, 0, sin, 0, mCount);
             java.lang.System.arraycopy(mArraySizes, 0, asin, 0, mCount);
 
+            // FIXME: broken for 64-bit
             int[] ids = new int[ein.length];
             for (int ct = 0; ct < ein.length; ct++ ) {
-                ids[ct] = ein[ct].getID(mRS);
+                ids[ct] = (int)ein[ct].getID(mRS);
             }
-            int id = mRS.nElementCreate2(ids, sin, asin);
+            long id = mRS.nElementCreate2(ids, sin, asin);
             return new Element(id, mRS, ein, sin, asin);
         }
     }
diff --git a/graphics/java/android/renderscript/FieldPacker.java b/rs/java/android/renderscript/FieldPacker.java
similarity index 98%
rename from graphics/java/android/renderscript/FieldPacker.java
rename to rs/java/android/renderscript/FieldPacker.java
index fed97d6..cf20e63 100644
--- a/graphics/java/android/renderscript/FieldPacker.java
+++ b/rs/java/android/renderscript/FieldPacker.java
@@ -232,7 +232,8 @@
 
     public void addObj(BaseObj obj) {
         if (obj != null) {
-            addI32(obj.getID(null));
+            // FIXME: this is fine for 32-bit but needs a path for 64-bit
+            addI32((int)obj.getID(null));
         } else {
             addI32(0);
         }
diff --git a/graphics/java/android/renderscript/FileA3D.java b/rs/java/android/renderscript/FileA3D.java
similarity index 94%
rename from graphics/java/android/renderscript/FileA3D.java
rename to rs/java/android/renderscript/FileA3D.java
index e41f02d..04bc7c6 100644
--- a/graphics/java/android/renderscript/FileA3D.java
+++ b/rs/java/android/renderscript/FileA3D.java
@@ -80,7 +80,7 @@
     public static class IndexEntry {
         RenderScript mRS;
         int mIndex;
-        int mID;
+        long mID;
         String mName;
         EntryType mEntryType;
         BaseObj mLoadedObj;
@@ -141,7 +141,7 @@
                 return null;
             }
 
-            int objectID = rs.nFileA3DGetEntryByIndex(entry.mID, entry.mIndex);
+            long objectID = rs.nFileA3DGetEntryByIndex(entry.mID, entry.mIndex);
             if(objectID == 0) {
                 return null;
             }
@@ -156,7 +156,7 @@
             return entry.mLoadedObj;
         }
 
-        IndexEntry(RenderScript rs, int index, int id, String name, EntryType type) {
+        IndexEntry(RenderScript rs, int index, long id, String name, EntryType type) {
             mRS = rs;
             mIndex = index;
             mID = id;
@@ -169,7 +169,7 @@
     IndexEntry[] mFileEntries;
     InputStream mInputStream;
 
-    FileA3D(int id, RenderScript rs, InputStream stream) {
+    FileA3D(long id, RenderScript rs, InputStream stream) {
         super(id, rs);
         mInputStream = stream;
     }
@@ -232,7 +232,7 @@
     */
     static public FileA3D createFromAsset(RenderScript rs, AssetManager mgr, String path) {
         rs.validate();
-        int fileId = rs.nFileA3DCreateFromAsset(mgr, path);
+        long fileId = rs.nFileA3DCreateFromAsset(mgr, path);
 
         if(fileId == 0) {
             throw new RSRuntimeException("Unable to create a3d file from asset " + path);
@@ -252,7 +252,7 @@
     * @return a3d file containing renderscript objects
     */
     static public FileA3D createFromFile(RenderScript rs, String path) {
-        int fileId = rs.nFileA3DCreateFromFile(path);
+        long fileId = rs.nFileA3DCreateFromFile(path);
 
         if(fileId == 0) {
             throw new RSRuntimeException("Unable to create a3d file from " + path);
@@ -295,9 +295,9 @@
             throw new RSRuntimeException("Unable to open resource " + id);
         }
 
-        int fileId = 0;
+        long fileId = 0;
         if (is instanceof AssetManager.AssetInputStream) {
-            int asset = ((AssetManager.AssetInputStream) is).getAssetInt();
+            long asset = ((AssetManager.AssetInputStream) is).getNativeAsset();
             fileId = rs.nFileA3DCreateFromAssetStream(asset);
         } else {
             throw new RSRuntimeException("Unsupported asset stream");
diff --git a/graphics/java/android/renderscript/Float2.java b/rs/java/android/renderscript/Float2.java
similarity index 100%
rename from graphics/java/android/renderscript/Float2.java
rename to rs/java/android/renderscript/Float2.java
diff --git a/graphics/java/android/renderscript/Float3.java b/rs/java/android/renderscript/Float3.java
similarity index 100%
rename from graphics/java/android/renderscript/Float3.java
rename to rs/java/android/renderscript/Float3.java
diff --git a/graphics/java/android/renderscript/Float4.java b/rs/java/android/renderscript/Float4.java
similarity index 100%
rename from graphics/java/android/renderscript/Float4.java
rename to rs/java/android/renderscript/Float4.java
diff --git a/graphics/java/android/renderscript/Font.java b/rs/java/android/renderscript/Font.java
similarity index 96%
rename from graphics/java/android/renderscript/Font.java
rename to rs/java/android/renderscript/Font.java
index 0375d2b..cfd11c0 100644
--- a/graphics/java/android/renderscript/Font.java
+++ b/rs/java/android/renderscript/Font.java
@@ -151,7 +151,7 @@
         return "DroidSans.ttf";
     }
 
-    Font(int id, RenderScript rs) {
+    Font(long id, RenderScript rs) {
         super(id, rs);
     }
 
@@ -162,7 +162,7 @@
     static public Font createFromFile(RenderScript rs, Resources res, String path, float pointSize) {
         rs.validate();
         int dpi = res.getDisplayMetrics().densityDpi;
-        int fontId = rs.nFontCreateFromFile(path, pointSize, dpi);
+        long fontId = rs.nFontCreateFromFile(path, pointSize, dpi);
 
         if(fontId == 0) {
             throw new RSRuntimeException("Unable to create font from file " + path);
@@ -187,7 +187,7 @@
         AssetManager mgr = res.getAssets();
         int dpi = res.getDisplayMetrics().densityDpi;
 
-        int fontId = rs.nFontCreateFromAsset(mgr, path, pointSize, dpi);
+        long fontId = rs.nFontCreateFromAsset(mgr, path, pointSize, dpi);
         if(fontId == 0) {
             throw new RSRuntimeException("Unable to create font from asset " + path);
         }
@@ -211,9 +211,9 @@
 
         int dpi = res.getDisplayMetrics().densityDpi;
 
-        int fontId = 0;
+        long fontId = 0;
         if (is instanceof AssetManager.AssetInputStream) {
-            int asset = ((AssetManager.AssetInputStream) is).getAssetInt();
+            long asset = ((AssetManager.AssetInputStream) is).getNativeAsset();
             fontId = rs.nFontCreateFromAssetStream(name, pointSize, dpi, asset);
         } else {
             throw new RSRuntimeException("Unsupported asset stream created");
diff --git a/graphics/java/android/renderscript/Int2.java b/rs/java/android/renderscript/Int2.java
similarity index 100%
rename from graphics/java/android/renderscript/Int2.java
rename to rs/java/android/renderscript/Int2.java
diff --git a/graphics/java/android/renderscript/Int3.java b/rs/java/android/renderscript/Int3.java
similarity index 100%
rename from graphics/java/android/renderscript/Int3.java
rename to rs/java/android/renderscript/Int3.java
diff --git a/graphics/java/android/renderscript/Int4.java b/rs/java/android/renderscript/Int4.java
similarity index 100%
rename from graphics/java/android/renderscript/Int4.java
rename to rs/java/android/renderscript/Int4.java
diff --git a/graphics/java/android/renderscript/Long2.java b/rs/java/android/renderscript/Long2.java
similarity index 100%
rename from graphics/java/android/renderscript/Long2.java
rename to rs/java/android/renderscript/Long2.java
diff --git a/graphics/java/android/renderscript/Long3.java b/rs/java/android/renderscript/Long3.java
similarity index 100%
rename from graphics/java/android/renderscript/Long3.java
rename to rs/java/android/renderscript/Long3.java
diff --git a/graphics/java/android/renderscript/Long4.java b/rs/java/android/renderscript/Long4.java
similarity index 99%
rename from graphics/java/android/renderscript/Long4.java
rename to rs/java/android/renderscript/Long4.java
index 757b910..1a1ad74 100644
--- a/graphics/java/android/renderscript/Long4.java
+++ b/rs/java/android/renderscript/Long4.java
@@ -505,7 +505,7 @@
      * @param data
      * @param offset
      */
-    public void copyTo(Long[] data, int offset) {
+    public void copyTo(long[] data, int offset) {
         data[offset] = (long)(x);
         data[offset + 1] = (long)(y);
         data[offset + 2] = (long)(z);
diff --git a/graphics/java/android/renderscript/Matrix2f.java b/rs/java/android/renderscript/Matrix2f.java
similarity index 100%
rename from graphics/java/android/renderscript/Matrix2f.java
rename to rs/java/android/renderscript/Matrix2f.java
diff --git a/graphics/java/android/renderscript/Matrix3f.java b/rs/java/android/renderscript/Matrix3f.java
similarity index 100%
rename from graphics/java/android/renderscript/Matrix3f.java
rename to rs/java/android/renderscript/Matrix3f.java
diff --git a/graphics/java/android/renderscript/Matrix4f.java b/rs/java/android/renderscript/Matrix4f.java
similarity index 100%
rename from graphics/java/android/renderscript/Matrix4f.java
rename to rs/java/android/renderscript/Matrix4f.java
diff --git a/graphics/java/android/renderscript/Mesh.java b/rs/java/android/renderscript/Mesh.java
similarity index 97%
rename from graphics/java/android/renderscript/Mesh.java
rename to rs/java/android/renderscript/Mesh.java
index bca4aa3..9ce3fb2 100644
--- a/graphics/java/android/renderscript/Mesh.java
+++ b/rs/java/android/renderscript/Mesh.java
@@ -91,7 +91,7 @@
     Allocation[] mIndexBuffers;
     Primitive[] mPrimitives;
 
-    Mesh(int id, RenderScript rs) {
+    Mesh(long id, RenderScript rs) {
         super(id, rs);
     }
 
@@ -367,7 +367,7 @@
                     alloc = Allocation.createSized(mRS, entry.e, entry.size, mUsage);
                 }
                 vertexBuffers[ct] = alloc;
-                vtx[ct] = alloc.getID(mRS);
+                vtx[ct] = (int)alloc.getID(mRS);
             }
 
             for(int ct = 0; ct < mIndexTypes.size(); ct ++) {
@@ -378,15 +378,15 @@
                 } else if(entry.e != null) {
                     alloc = Allocation.createSized(mRS, entry.e, entry.size, mUsage);
                 }
-                int allocID = (alloc == null) ? 0 : alloc.getID(mRS);
+                long allocID = (alloc == null) ? 0 : alloc.getID(mRS);
                 indexBuffers[ct] = alloc;
                 primitives[ct] = entry.prim;
 
-                idx[ct] = allocID;
+                idx[ct] = (int)allocID;
                 prim[ct] = entry.prim.mID;
             }
 
-            int id = mRS.nMeshCreate(vtx, idx, prim);
+            long id = mRS.nMeshCreate(vtx, idx, prim);
             Mesh newMesh = new Mesh(id, mRS);
             newMesh.mVertexBuffers = vertexBuffers;
             newMesh.mIndexBuffers = indexBuffers;
@@ -517,20 +517,20 @@
             for(int ct = 0; ct < mVertexTypeCount; ct ++) {
                 Entry entry = mVertexTypes[ct];
                 vertexBuffers[ct] = entry.a;
-                vtx[ct] = entry.a.getID(mRS);
+                vtx[ct] = (int)entry.a.getID(mRS);
             }
 
             for(int ct = 0; ct < mIndexTypes.size(); ct ++) {
                 Entry entry = (Entry)mIndexTypes.elementAt(ct);
-                int allocID = (entry.a == null) ? 0 : entry.a.getID(mRS);
+                long allocID = (entry.a == null) ? 0 : entry.a.getID(mRS);
                 indexBuffers[ct] = entry.a;
                 primitives[ct] = entry.prim;
 
-                idx[ct] = allocID;
+                idx[ct] = (int)allocID;
                 prim[ct] = entry.prim.mID;
             }
 
-            int id = mRS.nMeshCreate(vtx, idx, prim);
+            long id = mRS.nMeshCreate(vtx, idx, prim);
             Mesh newMesh = new Mesh(id, mRS);
             newMesh.mVertexBuffers = vertexBuffers;
             newMesh.mIndexBuffers = indexBuffers;
diff --git a/graphics/java/android/renderscript/Path.java b/rs/java/android/renderscript/Path.java
similarity index 92%
rename from graphics/java/android/renderscript/Path.java
rename to rs/java/android/renderscript/Path.java
index 9c4d41b..5cc67de 100644
--- a/graphics/java/android/renderscript/Path.java
+++ b/rs/java/android/renderscript/Path.java
@@ -41,7 +41,7 @@
     float mQuality;
     boolean mCoverageToAlpha;
 
-    Path(int id, RenderScript rs, Primitive p, Allocation vtx, Allocation loop, float q) {
+    Path(long id, RenderScript rs, Primitive p, Allocation vtx, Allocation loop, float q) {
         super(id, rs);
         mVertexBuffer = vtx;
         mLoopBuffer = loop;
@@ -67,7 +67,7 @@
 
 
     public static Path createStaticPath(RenderScript rs, Primitive p, float quality, Allocation vtx) {
-        int id = rs.nPathCreate(p.mID, false, vtx.getID(rs), 0, quality);
+        long id = rs.nPathCreate(p.mID, false, vtx.getID(rs), 0, quality);
         Path newPath = new Path(id, rs, p, null, null, quality);
         return newPath;
     }
diff --git a/graphics/java/android/renderscript/Program.java b/rs/java/android/renderscript/Program.java
similarity index 98%
rename from graphics/java/android/renderscript/Program.java
rename to rs/java/android/renderscript/Program.java
index bc2ca35..3eb9b75 100644
--- a/graphics/java/android/renderscript/Program.java
+++ b/rs/java/android/renderscript/Program.java
@@ -74,7 +74,7 @@
     int mTextureCount;
     String mShader;
 
-    Program(int id, RenderScript rs) {
+    Program(long id, RenderScript rs) {
         super(id, rs);
     }
 
@@ -150,7 +150,7 @@
             a.getType().getID(mRS) != mConstants[slot].getID(mRS)) {
             throw new IllegalArgumentException("Allocation type does not match slot type.");
         }
-        int id = a != null ? a.getID(mRS) : 0;
+        long id = a != null ? a.getID(mRS) : 0;
         mRS.nProgramBindConstants(getID(mRS), slot, id);
     }
 
@@ -172,7 +172,7 @@
             throw new IllegalArgumentException("Cannot bind cubemap to 2d texture slot");
         }
 
-        int id = va != null ? va.getID(mRS) : 0;
+        long id = va != null ? va.getID(mRS) : 0;
         mRS.nProgramBindTexture(getID(mRS), slot, id);
     }
 
@@ -192,7 +192,7 @@
             throw new IllegalArgumentException("Slot ID out of range.");
         }
 
-        int id = vs != null ? vs.getID(mRS) : 0;
+        long id = vs != null ? vs.getID(mRS) : 0;
         mRS.nProgramBindSampler(getID(mRS), slot, id);
     }
 
diff --git a/graphics/java/android/renderscript/ProgramFragment.java b/rs/java/android/renderscript/ProgramFragment.java
similarity index 89%
rename from graphics/java/android/renderscript/ProgramFragment.java
rename to rs/java/android/renderscript/ProgramFragment.java
index b9ba3fd..5e886a3 100644
--- a/graphics/java/android/renderscript/ProgramFragment.java
+++ b/rs/java/android/renderscript/ProgramFragment.java
@@ -39,7 +39,7 @@
  *
  **/
 public class ProgramFragment extends Program {
-    ProgramFragment(int id, RenderScript rs) {
+    ProgramFragment(long id, RenderScript rs) {
         super(id, rs);
     }
 
@@ -71,23 +71,23 @@
 
             for (int i=0; i < mInputCount; i++) {
                 tmp[idx++] = ProgramParam.INPUT.mID;
-                tmp[idx++] = mInputs[i].getID(mRS);
+                tmp[idx++] = (int)mInputs[i].getID(mRS);
             }
             for (int i=0; i < mOutputCount; i++) {
                 tmp[idx++] = ProgramParam.OUTPUT.mID;
-                tmp[idx++] = mOutputs[i].getID(mRS);
+                tmp[idx++] = (int)mOutputs[i].getID(mRS);
             }
             for (int i=0; i < mConstantCount; i++) {
                 tmp[idx++] = ProgramParam.CONSTANT.mID;
-                tmp[idx++] = mConstants[i].getID(mRS);
+                tmp[idx++] = (int)mConstants[i].getID(mRS);
             }
             for (int i=0; i < mTextureCount; i++) {
                 tmp[idx++] = ProgramParam.TEXTURE_TYPE.mID;
-                tmp[idx++] = mTextureTypes[i].mID;
+                tmp[idx++] = (int)mTextureTypes[i].mID;
                 texNames[i] = mTextureNames[i];
             }
 
-            int id = mRS.nProgramFragmentCreate(mShader, texNames, tmp);
+            long id = mRS.nProgramFragmentCreate(mShader, texNames, tmp);
             ProgramFragment pf = new ProgramFragment(id, mRS);
             initProgram(pf);
             return pf;
diff --git a/graphics/java/android/renderscript/ProgramFragmentFixedFunction.java b/rs/java/android/renderscript/ProgramFragmentFixedFunction.java
similarity index 96%
rename from graphics/java/android/renderscript/ProgramFragmentFixedFunction.java
rename to rs/java/android/renderscript/ProgramFragmentFixedFunction.java
index 8ae1777..22aed0a 100644
--- a/graphics/java/android/renderscript/ProgramFragmentFixedFunction.java
+++ b/rs/java/android/renderscript/ProgramFragmentFixedFunction.java
@@ -31,7 +31,7 @@
  *
  **/
 public class ProgramFragmentFixedFunction extends ProgramFragment {
-    ProgramFragmentFixedFunction(int id, RenderScript rs) {
+    ProgramFragmentFixedFunction(long id, RenderScript rs) {
         super(id, rs);
     }
 
@@ -58,23 +58,23 @@
 
             for (int i=0; i < mInputCount; i++) {
                 tmp[idx++] = ProgramParam.INPUT.mID;
-                tmp[idx++] = mInputs[i].getID(mRS);
+                tmp[idx++] = (int)mInputs[i].getID(mRS);
             }
             for (int i=0; i < mOutputCount; i++) {
                 tmp[idx++] = ProgramParam.OUTPUT.mID;
-                tmp[idx++] = mOutputs[i].getID(mRS);
+                tmp[idx++] = (int)mOutputs[i].getID(mRS);
             }
             for (int i=0; i < mConstantCount; i++) {
                 tmp[idx++] = ProgramParam.CONSTANT.mID;
-                tmp[idx++] = mConstants[i].getID(mRS);
+                tmp[idx++] = (int)mConstants[i].getID(mRS);
             }
             for (int i=0; i < mTextureCount; i++) {
                 tmp[idx++] = ProgramParam.TEXTURE_TYPE.mID;
-                tmp[idx++] = mTextureTypes[i].mID;
+                tmp[idx++] = (int)mTextureTypes[i].mID;
                 texNames[i] = mTextureNames[i];
             }
 
-            int id = mRS.nProgramFragmentCreate(mShader, texNames, tmp);
+            long id = mRS.nProgramFragmentCreate(mShader, texNames, tmp);
             ProgramFragmentFixedFunction pf = new ProgramFragmentFixedFunction(id, mRS);
             initProgram(pf);
             return pf;
diff --git a/graphics/java/android/renderscript/ProgramRaster.java b/rs/java/android/renderscript/ProgramRaster.java
similarity index 96%
rename from graphics/java/android/renderscript/ProgramRaster.java
rename to rs/java/android/renderscript/ProgramRaster.java
index 216cb4e..e294b05 100644
--- a/graphics/java/android/renderscript/ProgramRaster.java
+++ b/rs/java/android/renderscript/ProgramRaster.java
@@ -54,7 +54,7 @@
     boolean mPointSprite;
     CullMode mCullMode;
 
-    ProgramRaster(int id, RenderScript rs) {
+    ProgramRaster(long id, RenderScript rs) {
         super(id, rs);
 
         mPointSprite = false;
@@ -154,7 +154,7 @@
          */
         public ProgramRaster create() {
             mRS.validate();
-            int id = mRS.nProgramRasterCreate(mPointSprite, mCullMode.mID);
+            long id = mRS.nProgramRasterCreate(mPointSprite, mCullMode.mID);
             ProgramRaster programRaster = new ProgramRaster(id, mRS);
             programRaster.mPointSprite = mPointSprite;
             programRaster.mCullMode = mCullMode;
diff --git a/graphics/java/android/renderscript/ProgramStore.java b/rs/java/android/renderscript/ProgramStore.java
similarity index 98%
rename from graphics/java/android/renderscript/ProgramStore.java
rename to rs/java/android/renderscript/ProgramStore.java
index dac9e76..969cc25 100644
--- a/graphics/java/android/renderscript/ProgramStore.java
+++ b/rs/java/android/renderscript/ProgramStore.java
@@ -146,7 +146,7 @@
     BlendDstFunc mBlendDst;
     boolean mDither;
 
-    ProgramStore(int id, RenderScript rs) {
+    ProgramStore(long id, RenderScript rs) {
         super(id, rs);
     }
 
@@ -421,7 +421,7 @@
         */
         public ProgramStore create() {
             mRS.validate();
-            int id = mRS.nProgramStoreCreate(mColorMaskR, mColorMaskG, mColorMaskB, mColorMaskA,
+            long id = mRS.nProgramStoreCreate(mColorMaskR, mColorMaskG, mColorMaskB, mColorMaskA,
                                              mDepthMask, mDither,
                                              mBlendSrc.mID, mBlendDst.mID, mDepthFunc.mID);
             ProgramStore programStore = new ProgramStore(id, mRS);
diff --git a/graphics/java/android/renderscript/ProgramVertex.java b/rs/java/android/renderscript/ProgramVertex.java
similarity index 93%
rename from graphics/java/android/renderscript/ProgramVertex.java
rename to rs/java/android/renderscript/ProgramVertex.java
index 1c5a191..b6886e1 100644
--- a/graphics/java/android/renderscript/ProgramVertex.java
+++ b/rs/java/android/renderscript/ProgramVertex.java
@@ -53,7 +53,7 @@
  **/
 public class ProgramVertex extends Program {
 
-    ProgramVertex(int id, RenderScript rs) {
+    ProgramVertex(long id, RenderScript rs) {
         super(id, rs);
     }
 
@@ -132,23 +132,23 @@
 
             for (int i=0; i < mInputCount; i++) {
                 tmp[idx++] = ProgramParam.INPUT.mID;
-                tmp[idx++] = mInputs[i].getID(mRS);
+                tmp[idx++] = (int)mInputs[i].getID(mRS);
             }
             for (int i=0; i < mOutputCount; i++) {
                 tmp[idx++] = ProgramParam.OUTPUT.mID;
-                tmp[idx++] = mOutputs[i].getID(mRS);
+                tmp[idx++] = (int)mOutputs[i].getID(mRS);
             }
             for (int i=0; i < mConstantCount; i++) {
                 tmp[idx++] = ProgramParam.CONSTANT.mID;
-                tmp[idx++] = mConstants[i].getID(mRS);
+                tmp[idx++] = (int)mConstants[i].getID(mRS);
             }
             for (int i=0; i < mTextureCount; i++) {
                 tmp[idx++] = ProgramParam.TEXTURE_TYPE.mID;
-                tmp[idx++] = mTextureTypes[i].mID;
+                tmp[idx++] = (int)mTextureTypes[i].mID;
                 texNames[i] = mTextureNames[i];
             }
 
-            int id = mRS.nProgramVertexCreate(mShader, texNames, tmp);
+            long id = mRS.nProgramVertexCreate(mShader, texNames, tmp);
             ProgramVertex pv = new ProgramVertex(id, mRS);
             initProgram(pv);
             return pv;
diff --git a/graphics/java/android/renderscript/ProgramVertexFixedFunction.java b/rs/java/android/renderscript/ProgramVertexFixedFunction.java
similarity index 95%
rename from graphics/java/android/renderscript/ProgramVertexFixedFunction.java
rename to rs/java/android/renderscript/ProgramVertexFixedFunction.java
index ad486f3..c479c77 100644
--- a/graphics/java/android/renderscript/ProgramVertexFixedFunction.java
+++ b/rs/java/android/renderscript/ProgramVertexFixedFunction.java
@@ -31,7 +31,7 @@
  **/
 public class ProgramVertexFixedFunction extends ProgramVertex {
 
-    ProgramVertexFixedFunction(int id, RenderScript rs) {
+    ProgramVertexFixedFunction(long id, RenderScript rs) {
         super(id, rs);
     }
 
@@ -85,23 +85,23 @@
 
             for (int i=0; i < mInputCount; i++) {
                 tmp[idx++] = ProgramParam.INPUT.mID;
-                tmp[idx++] = mInputs[i].getID(mRS);
+                tmp[idx++] = (int)mInputs[i].getID(mRS);
             }
             for (int i=0; i < mOutputCount; i++) {
                 tmp[idx++] = ProgramParam.OUTPUT.mID;
-                tmp[idx++] = mOutputs[i].getID(mRS);
+                tmp[idx++] = (int)mOutputs[i].getID(mRS);
             }
             for (int i=0; i < mConstantCount; i++) {
                 tmp[idx++] = ProgramParam.CONSTANT.mID;
-                tmp[idx++] = mConstants[i].getID(mRS);
+                tmp[idx++] = (int)mConstants[i].getID(mRS);
             }
             for (int i=0; i < mTextureCount; i++) {
                 tmp[idx++] = ProgramParam.TEXTURE_TYPE.mID;
-                tmp[idx++] = mTextureTypes[i].mID;
+                tmp[idx++] = (int)mTextureTypes[i].mID;
                 texNames[i] = mTextureNames[i];
             }
 
-            int id = mRS.nProgramVertexCreate(mShader, texNames, tmp);
+            long id = mRS.nProgramVertexCreate(mShader, texNames, tmp);
             ProgramVertexFixedFunction pv = new ProgramVertexFixedFunction(id, mRS);
             initProgram(pv);
             return pv;
diff --git a/graphics/java/android/renderscript/RSDriverException.java b/rs/java/android/renderscript/RSDriverException.java
similarity index 100%
rename from graphics/java/android/renderscript/RSDriverException.java
rename to rs/java/android/renderscript/RSDriverException.java
diff --git a/graphics/java/android/renderscript/RSIllegalArgumentException.java b/rs/java/android/renderscript/RSIllegalArgumentException.java
similarity index 100%
rename from graphics/java/android/renderscript/RSIllegalArgumentException.java
rename to rs/java/android/renderscript/RSIllegalArgumentException.java
diff --git a/graphics/java/android/renderscript/RSInvalidStateException.java b/rs/java/android/renderscript/RSInvalidStateException.java
similarity index 100%
rename from graphics/java/android/renderscript/RSInvalidStateException.java
rename to rs/java/android/renderscript/RSInvalidStateException.java
diff --git a/graphics/java/android/renderscript/RSRuntimeException.java b/rs/java/android/renderscript/RSRuntimeException.java
similarity index 100%
rename from graphics/java/android/renderscript/RSRuntimeException.java
rename to rs/java/android/renderscript/RSRuntimeException.java
diff --git a/graphics/java/android/renderscript/RSSurfaceView.java b/rs/java/android/renderscript/RSSurfaceView.java
similarity index 100%
rename from graphics/java/android/renderscript/RSSurfaceView.java
rename to rs/java/android/renderscript/RSSurfaceView.java
diff --git a/graphics/java/android/renderscript/RSTextureView.java b/rs/java/android/renderscript/RSTextureView.java
similarity index 100%
rename from graphics/java/android/renderscript/RSTextureView.java
rename to rs/java/android/renderscript/RSTextureView.java
diff --git a/graphics/java/android/renderscript/RenderScript.java b/rs/java/android/renderscript/RenderScript.java
similarity index 62%
rename from graphics/java/android/renderscript/RenderScript.java
rename to rs/java/android/renderscript/RenderScript.java
index 7d4a5c4..8618764 100644
--- a/graphics/java/android/renderscript/RenderScript.java
+++ b/rs/java/android/renderscript/RenderScript.java
@@ -19,6 +19,7 @@
 import java.io.File;
 import java.lang.reflect.Field;
 import java.lang.reflect.Method;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
 
 import android.content.Context;
 import android.content.pm.ApplicationInfo;
@@ -91,14 +92,14 @@
     }
 
     // Non-threadsafe functions.
-    native int  nDeviceCreate();
-    native void nDeviceDestroy(int dev);
-    native void nDeviceSetConfig(int dev, int param, int value);
-    native int nContextGetUserMessage(int con, int[] data);
-    native String nContextGetErrorMessage(int con);
-    native int  nContextPeekMessage(int con, int[] subID);
-    native void nContextInitToClient(int con);
-    native void nContextDeinitToClient(int con);
+    native long  nDeviceCreate();
+    native void nDeviceDestroy(long dev);
+    native void nDeviceSetConfig(long dev, int param, int value);
+    native int nContextGetUserMessage(long con, int[] data);
+    native String nContextGetErrorMessage(long con);
+    native int  nContextPeekMessage(long con, int[] subID);
+    native void nContextInitToClient(long con);
+    native void nContextDeinitToClient(long con);
 
     static File mCacheDir;
 
@@ -151,16 +152,17 @@
     }
 
     ContextType mContextType;
+    ReentrantReadWriteLock mRWLock;
 
     // Methods below are wrapped to protect the non-threadsafe
     // lockless fifo.
-    native int  rsnContextCreateGL(int dev, int ver, int sdkVer,
+    native long  rsnContextCreateGL(long dev, int ver, int sdkVer,
                  int colorMin, int colorPref,
                  int alphaMin, int alphaPref,
                  int depthMin, int depthPref,
                  int stencilMin, int stencilPref,
                  int samplesMin, int samplesPref, float samplesQ, int dpi);
-    synchronized int nContextCreateGL(int dev, int ver, int sdkVer,
+    synchronized long nContextCreateGL(long dev, int ver, int sdkVer,
                  int colorMin, int colorPref,
                  int alphaMin, int alphaPref,
                  int depthMin, int depthPref,
@@ -171,100 +173,113 @@
                                   stencilMin, stencilPref,
                                   samplesMin, samplesPref, samplesQ, dpi);
     }
-    native int  rsnContextCreate(int dev, int ver, int sdkVer, int contextType);
-    synchronized int nContextCreate(int dev, int ver, int sdkVer, int contextType) {
+    native long  rsnContextCreate(long dev, int ver, int sdkVer, int contextType);
+    synchronized long nContextCreate(long dev, int ver, int sdkVer, int contextType) {
         return rsnContextCreate(dev, ver, sdkVer, contextType);
     }
-    native void rsnContextDestroy(int con);
+    native void rsnContextDestroy(long con);
     synchronized void nContextDestroy() {
         validate();
-        rsnContextDestroy(mContext);
+
+        // take teardown lock
+        // teardown lock can only be taken when no objects are being destroyed
+        ReentrantReadWriteLock.WriteLock wlock = mRWLock.writeLock();
+        wlock.lock();
+
+        long curCon = mContext;
+        // context is considered dead as of this point
+        mContext = 0;
+
+        wlock.unlock();
+        rsnContextDestroy(curCon);
     }
-    native void rsnContextSetSurface(int con, int w, int h, Surface sur);
+    native void rsnContextSetSurface(long con, int w, int h, Surface sur);
     synchronized void nContextSetSurface(int w, int h, Surface sur) {
         validate();
         rsnContextSetSurface(mContext, w, h, sur);
     }
-    native void rsnContextSetSurfaceTexture(int con, int w, int h, SurfaceTexture sur);
+    native void rsnContextSetSurfaceTexture(long con, int w, int h, SurfaceTexture sur);
     synchronized void nContextSetSurfaceTexture(int w, int h, SurfaceTexture sur) {
         validate();
         rsnContextSetSurfaceTexture(mContext, w, h, sur);
     }
-    native void rsnContextSetPriority(int con, int p);
+    native void rsnContextSetPriority(long con, int p);
     synchronized void nContextSetPriority(int p) {
         validate();
         rsnContextSetPriority(mContext, p);
     }
-    native void rsnContextDump(int con, int bits);
+    native void rsnContextDump(long con, int bits);
     synchronized void nContextDump(int bits) {
         validate();
         rsnContextDump(mContext, bits);
     }
-    native void rsnContextFinish(int con);
+    native void rsnContextFinish(long con);
     synchronized void nContextFinish() {
         validate();
         rsnContextFinish(mContext);
     }
 
-    native void rsnContextSendMessage(int con, int id, int[] data);
+    native void rsnContextSendMessage(long con, int id, int[] data);
     synchronized void nContextSendMessage(int id, int[] data) {
         validate();
         rsnContextSendMessage(mContext, id, data);
     }
 
-    native void rsnContextBindRootScript(int con, int script);
+    native void rsnContextBindRootScript(long con, int script);
     synchronized void nContextBindRootScript(int script) {
         validate();
         rsnContextBindRootScript(mContext, script);
     }
-    native void rsnContextBindSampler(int con, int sampler, int slot);
+    native void rsnContextBindSampler(long con, int sampler, int slot);
     synchronized void nContextBindSampler(int sampler, int slot) {
         validate();
         rsnContextBindSampler(mContext, sampler, slot);
     }
-    native void rsnContextBindProgramStore(int con, int pfs);
+    native void rsnContextBindProgramStore(long con, int pfs);
     synchronized void nContextBindProgramStore(int pfs) {
         validate();
         rsnContextBindProgramStore(mContext, pfs);
     }
-    native void rsnContextBindProgramFragment(int con, int pf);
+    native void rsnContextBindProgramFragment(long con, int pf);
     synchronized void nContextBindProgramFragment(int pf) {
         validate();
         rsnContextBindProgramFragment(mContext, pf);
     }
-    native void rsnContextBindProgramVertex(int con, int pv);
+    native void rsnContextBindProgramVertex(long con, int pv);
     synchronized void nContextBindProgramVertex(int pv) {
         validate();
         rsnContextBindProgramVertex(mContext, pv);
     }
-    native void rsnContextBindProgramRaster(int con, int pr);
+    native void rsnContextBindProgramRaster(long con, int pr);
     synchronized void nContextBindProgramRaster(int pr) {
         validate();
         rsnContextBindProgramRaster(mContext, pr);
     }
-    native void rsnContextPause(int con);
+    native void rsnContextPause(long con);
     synchronized void nContextPause() {
         validate();
         rsnContextPause(mContext);
     }
-    native void rsnContextResume(int con);
+    native void rsnContextResume(long con);
     synchronized void nContextResume() {
         validate();
         rsnContextResume(mContext);
     }
 
-    native void rsnAssignName(int con, int obj, byte[] name);
-    synchronized void nAssignName(int obj, byte[] name) {
+    native void rsnAssignName(long con, long obj, byte[] name);
+    synchronized void nAssignName(long obj, byte[] name) {
         validate();
         rsnAssignName(mContext, obj, name);
     }
-    native String rsnGetName(int con, int obj);
-    synchronized String nGetName(int obj) {
+    native String rsnGetName(long con, long obj);
+    synchronized String nGetName(long obj) {
         validate();
         return rsnGetName(mContext, obj);
     }
-    native void rsnObjDestroy(int con, int id);
-    synchronized void nObjDestroy(int id) {
+
+    // nObjDestroy is explicitly _not_ synchronous to prevent crashes in finalizers
+    native void rsnObjDestroy(long con, long id);
+    void nObjDestroy(long id) {
         // There is a race condition here.  The calling code may be run
         // by the gc while teardown is occuring.  This protects againts
         // deleting dead objects.
@@ -273,156 +288,140 @@
         }
     }
 
-    native int  rsnElementCreate(int con, int type, int kind, boolean norm, int vecSize);
-    synchronized int nElementCreate(int type, int kind, boolean norm, int vecSize) {
+    native long rsnElementCreate(long con, long type, int kind, boolean norm, int vecSize);
+    synchronized long nElementCreate(long type, int kind, boolean norm, int vecSize) {
         validate();
         return rsnElementCreate(mContext, type, kind, norm, vecSize);
     }
-    native int  rsnElementCreate2(int con, int[] elements, String[] names, int[] arraySizes);
-    synchronized int nElementCreate2(int[] elements, String[] names, int[] arraySizes) {
+    native long rsnElementCreate2(long con, int[]elements, String[] names, int[] arraySizes);
+    synchronized long nElementCreate2(int[] elements, String[] names, int[] arraySizes) {
         validate();
         return rsnElementCreate2(mContext, elements, names, arraySizes);
     }
-    native void rsnElementGetNativeData(int con, int id, int[] elementData);
-    synchronized void nElementGetNativeData(int id, int[] elementData) {
+    native void rsnElementGetNativeData(long con, long id, int[] elementData);
+    synchronized void nElementGetNativeData(long id, int[] elementData) {
         validate();
         rsnElementGetNativeData(mContext, id, elementData);
     }
-    native void rsnElementGetSubElements(int con, int id,
+    native void rsnElementGetSubElements(long con, long id,
                                          int[] IDs, String[] names, int[] arraySizes);
-    synchronized void nElementGetSubElements(int id, int[] IDs, String[] names, int[] arraySizes) {
+    synchronized void nElementGetSubElements(long id, int[] IDs, String[] names, int[] arraySizes) {
         validate();
         rsnElementGetSubElements(mContext, id, IDs, names, arraySizes);
     }
 
-    native int rsnTypeCreate(int con, int eid, int x, int y, int z, boolean mips, boolean faces, int yuv);
-    synchronized int nTypeCreate(int eid, int x, int y, int z, boolean mips, boolean faces, int yuv) {
+    native long rsnTypeCreate(long con, long eid, int x, int y, int z, boolean mips, boolean faces, int yuv);
+    synchronized long nTypeCreate(long eid, int x, int y, int z, boolean mips, boolean faces, int yuv) {
         validate();
         return rsnTypeCreate(mContext, eid, x, y, z, mips, faces, yuv);
     }
-    native void rsnTypeGetNativeData(int con, int id, int[] typeData);
-    synchronized void nTypeGetNativeData(int id, int[] typeData) {
+    native void rsnTypeGetNativeData(long con, long id, int[] typeData);
+    synchronized void nTypeGetNativeData(long id, int[] typeData) {
         validate();
         rsnTypeGetNativeData(mContext, id, typeData);
     }
 
-    native int  rsnAllocationCreateTyped(int con, int type, int mip, int usage, int pointer);
-    synchronized int nAllocationCreateTyped(int type, int mip, int usage, int pointer) {
+    native long rsnAllocationCreateTyped(long con, long type, int mip, int usage, int pointer);
+    synchronized long nAllocationCreateTyped(long type, int mip, int usage, int pointer) {
         validate();
         return rsnAllocationCreateTyped(mContext, type, mip, usage, pointer);
     }
-    native int  rsnAllocationCreateFromBitmap(int con, int type, int mip, Bitmap bmp, int usage);
-    synchronized int nAllocationCreateFromBitmap(int type, int mip, Bitmap bmp, int usage) {
+    native long rsnAllocationCreateFromBitmap(long con, long type, int mip, Bitmap bmp, int usage);
+    synchronized long nAllocationCreateFromBitmap(long type, int mip, Bitmap bmp, int usage) {
         validate();
         return rsnAllocationCreateFromBitmap(mContext, type, mip, bmp, usage);
     }
 
-    native int  rsnAllocationCreateBitmapBackedAllocation(int con, int type, int mip, Bitmap bmp, int usage);
-    synchronized int nAllocationCreateBitmapBackedAllocation(int type, int mip, Bitmap bmp, int usage) {
+    native long rsnAllocationCreateBitmapBackedAllocation(long con, long type, int mip, Bitmap bmp, int usage);
+    synchronized long nAllocationCreateBitmapBackedAllocation(long type, int mip, Bitmap bmp, int usage) {
         validate();
         return rsnAllocationCreateBitmapBackedAllocation(mContext, type, mip, bmp, usage);
     }
 
-
-    native int  rsnAllocationCubeCreateFromBitmap(int con, int type, int mip, Bitmap bmp, int usage);
-    synchronized int nAllocationCubeCreateFromBitmap(int type, int mip, Bitmap bmp, int usage) {
+    native long rsnAllocationCubeCreateFromBitmap(long con, long type, int mip, Bitmap bmp, int usage);
+    synchronized long nAllocationCubeCreateFromBitmap(long type, int mip, Bitmap bmp, int usage) {
         validate();
         return rsnAllocationCubeCreateFromBitmap(mContext, type, mip, bmp, usage);
     }
-    native int  rsnAllocationCreateBitmapRef(int con, int type, Bitmap bmp);
-    synchronized int nAllocationCreateBitmapRef(int type, Bitmap bmp) {
+    native long  rsnAllocationCreateBitmapRef(long con, long type, Bitmap bmp);
+    synchronized long nAllocationCreateBitmapRef(long type, Bitmap bmp) {
         validate();
         return rsnAllocationCreateBitmapRef(mContext, type, bmp);
     }
-    native int  rsnAllocationCreateFromAssetStream(int con, int mips, int assetStream, int usage);
-    synchronized int nAllocationCreateFromAssetStream(int mips, int assetStream, int usage) {
+    native long  rsnAllocationCreateFromAssetStream(long con, int mips, int assetStream, int usage);
+    synchronized long nAllocationCreateFromAssetStream(int mips, int assetStream, int usage) {
         validate();
         return rsnAllocationCreateFromAssetStream(mContext, mips, assetStream, usage);
     }
 
-    native void  rsnAllocationCopyToBitmap(int con, int alloc, Bitmap bmp);
-    synchronized void nAllocationCopyToBitmap(int alloc, Bitmap bmp) {
+    native void  rsnAllocationCopyToBitmap(long con, long alloc, Bitmap bmp);
+    synchronized void nAllocationCopyToBitmap(long alloc, Bitmap bmp) {
         validate();
         rsnAllocationCopyToBitmap(mContext, alloc, bmp);
     }
 
 
-    native void rsnAllocationSyncAll(int con, int alloc, int src);
-    synchronized void nAllocationSyncAll(int alloc, int src) {
+    native void rsnAllocationSyncAll(long con, long alloc, int src);
+    synchronized void nAllocationSyncAll(long alloc, int src) {
         validate();
         rsnAllocationSyncAll(mContext, alloc, src);
     }
-    native Surface rsnAllocationGetSurface(int con, int alloc);
-    synchronized Surface nAllocationGetSurface(int alloc) {
+    native Surface rsnAllocationGetSurface(long con, long alloc);
+    synchronized Surface nAllocationGetSurface(long alloc) {
         validate();
         return rsnAllocationGetSurface(mContext, alloc);
     }
-    native void rsnAllocationSetSurface(int con, int alloc, Surface sur);
-    synchronized void nAllocationSetSurface(int alloc, Surface sur) {
+    native void rsnAllocationSetSurface(long con, long alloc, Surface sur);
+    synchronized void nAllocationSetSurface(long alloc, Surface sur) {
         validate();
         rsnAllocationSetSurface(mContext, alloc, sur);
     }
-    native void rsnAllocationIoSend(int con, int alloc);
-    synchronized void nAllocationIoSend(int alloc) {
+    native void rsnAllocationIoSend(long con, long alloc);
+    synchronized void nAllocationIoSend(long alloc) {
         validate();
         rsnAllocationIoSend(mContext, alloc);
     }
-    native void rsnAllocationIoReceive(int con, int alloc);
-    synchronized void nAllocationIoReceive(int alloc) {
+    native void rsnAllocationIoReceive(long con, long alloc);
+    synchronized void nAllocationIoReceive(long alloc) {
         validate();
         rsnAllocationIoReceive(mContext, alloc);
     }
 
 
-    native void rsnAllocationGenerateMipmaps(int con, int alloc);
-    synchronized void nAllocationGenerateMipmaps(int alloc) {
+    native void rsnAllocationGenerateMipmaps(long con, long alloc);
+    synchronized void nAllocationGenerateMipmaps(long alloc) {
         validate();
         rsnAllocationGenerateMipmaps(mContext, alloc);
     }
-    native void  rsnAllocationCopyFromBitmap(int con, int alloc, Bitmap bmp);
-    synchronized void nAllocationCopyFromBitmap(int alloc, Bitmap bmp) {
+    native void  rsnAllocationCopyFromBitmap(long con, long alloc, Bitmap bmp);
+    synchronized void nAllocationCopyFromBitmap(long alloc, Bitmap bmp) {
         validate();
         rsnAllocationCopyFromBitmap(mContext, alloc, bmp);
     }
 
 
-    native void rsnAllocationData1D(int con, int id, int off, int mip, int count, int[] d, int sizeBytes);
-    synchronized void nAllocationData1D(int id, int off, int mip, int count, int[] d, int sizeBytes) {
+    native void rsnAllocationData1D(long con, long id, int off, int mip, int count, Object d, int sizeBytes, int dt);
+    synchronized void nAllocationData1D(long id, int off, int mip, int count, Object d, int sizeBytes, Element.DataType dt) {
         validate();
-        rsnAllocationData1D(mContext, id, off, mip, count, d, sizeBytes);
-    }
-    native void rsnAllocationData1D(int con, int id, int off, int mip, int count, short[] d, int sizeBytes);
-    synchronized void nAllocationData1D(int id, int off, int mip, int count, short[] d, int sizeBytes) {
-        validate();
-        rsnAllocationData1D(mContext, id, off, mip, count, d, sizeBytes);
-    }
-    native void rsnAllocationData1D(int con, int id, int off, int mip, int count, byte[] d, int sizeBytes);
-    synchronized void nAllocationData1D(int id, int off, int mip, int count, byte[] d, int sizeBytes) {
-        validate();
-        rsnAllocationData1D(mContext, id, off, mip, count, d, sizeBytes);
-    }
-    native void rsnAllocationData1D(int con, int id, int off, int mip, int count, float[] d, int sizeBytes);
-    synchronized void nAllocationData1D(int id, int off, int mip, int count, float[] d, int sizeBytes) {
-        validate();
-        rsnAllocationData1D(mContext, id, off, mip, count, d, sizeBytes);
+        rsnAllocationData1D(mContext, id, off, mip, count, d, sizeBytes, dt.mID);
     }
 
-    native void rsnAllocationElementData1D(int con, int id, int xoff, int mip, int compIdx, byte[] d, int sizeBytes);
-    synchronized void nAllocationElementData1D(int id, int xoff, int mip, int compIdx, byte[] d, int sizeBytes) {
+    native void rsnAllocationElementData1D(long con,long id, int xoff, int mip, int compIdx, byte[] d, int sizeBytes);
+    synchronized void nAllocationElementData1D(long id, int xoff, int mip, int compIdx, byte[] d, int sizeBytes) {
         validate();
         rsnAllocationElementData1D(mContext, id, xoff, mip, compIdx, d, sizeBytes);
     }
 
-    native void rsnAllocationData2D(int con,
-                                    int dstAlloc, int dstXoff, int dstYoff,
+    native void rsnAllocationData2D(long con,
+                                    long dstAlloc, int dstXoff, int dstYoff,
                                     int dstMip, int dstFace,
                                     int width, int height,
-                                    int srcAlloc, int srcXoff, int srcYoff,
+                                    long srcAlloc, int srcXoff, int srcYoff,
                                     int srcMip, int srcFace);
-    synchronized void nAllocationData2D(int dstAlloc, int dstXoff, int dstYoff,
+    synchronized void nAllocationData2D(long dstAlloc, int dstXoff, int dstYoff,
                                         int dstMip, int dstFace,
                                         int width, int height,
-                                        int srcAlloc, int srcXoff, int srcYoff,
+                                        long srcAlloc, int srcXoff, int srcYoff,
                                         int srcMip, int srcFace) {
         validate();
         rsnAllocationData2D(mContext,
@@ -433,42 +432,30 @@
                             srcMip, srcFace);
     }
 
-    native void rsnAllocationData2D(int con, int id, int xoff, int yoff, int mip, int face, int w, int h, byte[] d, int sizeBytes);
-    synchronized void nAllocationData2D(int id, int xoff, int yoff, int mip, int face, int w, int h, byte[] d, int sizeBytes) {
+    native void rsnAllocationData2D(long con, long id, int xoff, int yoff, int mip, int face,
+                                    int w, int h, Object d, int sizeBytes, int dt);
+    synchronized void nAllocationData2D(long id, int xoff, int yoff, int mip, int face,
+                                        int w, int h, Object d, int sizeBytes, Element.DataType dt) {
         validate();
-        rsnAllocationData2D(mContext, id, xoff, yoff, mip, face, w, h, d, sizeBytes);
+        rsnAllocationData2D(mContext, id, xoff, yoff, mip, face, w, h, d, sizeBytes, dt.mID);
     }
-    native void rsnAllocationData2D(int con, int id, int xoff, int yoff, int mip, int face, int w, int h, short[] d, int sizeBytes);
-    synchronized void nAllocationData2D(int id, int xoff, int yoff, int mip, int face, int w, int h, short[] d, int sizeBytes) {
-        validate();
-        rsnAllocationData2D(mContext, id, xoff, yoff, mip, face, w, h, d, sizeBytes);
-    }
-    native void rsnAllocationData2D(int con, int id, int xoff, int yoff, int mip, int face, int w, int h, int[] d, int sizeBytes);
-    synchronized void nAllocationData2D(int id, int xoff, int yoff, int mip, int face, int w, int h, int[] d, int sizeBytes) {
-        validate();
-        rsnAllocationData2D(mContext, id, xoff, yoff, mip, face, w, h, d, sizeBytes);
-    }
-    native void rsnAllocationData2D(int con, int id, int xoff, int yoff, int mip, int face, int w, int h, float[] d, int sizeBytes);
-    synchronized void nAllocationData2D(int id, int xoff, int yoff, int mip, int face, int w, int h, float[] d, int sizeBytes) {
-        validate();
-        rsnAllocationData2D(mContext, id, xoff, yoff, mip, face, w, h, d, sizeBytes);
-    }
-    native void rsnAllocationData2D(int con, int id, int xoff, int yoff, int mip, int face, Bitmap b);
-    synchronized void nAllocationData2D(int id, int xoff, int yoff, int mip, int face, Bitmap b) {
+
+    native void rsnAllocationData2D(long con, long id, int xoff, int yoff, int mip, int face, Bitmap b);
+    synchronized void nAllocationData2D(long id, int xoff, int yoff, int mip, int face, Bitmap b) {
         validate();
         rsnAllocationData2D(mContext, id, xoff, yoff, mip, face, b);
     }
 
-    native void rsnAllocationData3D(int con,
-                                    int dstAlloc, int dstXoff, int dstYoff, int dstZoff,
+    native void rsnAllocationData3D(long con,
+                                    long dstAlloc, int dstXoff, int dstYoff, int dstZoff,
                                     int dstMip,
                                     int width, int height, int depth,
-                                    int srcAlloc, int srcXoff, int srcYoff, int srcZoff,
+                                    long srcAlloc, int srcXoff, int srcYoff, int srcZoff,
                                     int srcMip);
-    synchronized void nAllocationData3D(int dstAlloc, int dstXoff, int dstYoff, int dstZoff,
+    synchronized void nAllocationData3D(long dstAlloc, int dstXoff, int dstYoff, int dstZoff,
                                         int dstMip,
                                         int width, int height, int depth,
-                                        int srcAlloc, int srcXoff, int srcYoff, int srcZoff,
+                                        long srcAlloc, int srcXoff, int srcYoff, int srcZoff,
                                         int srcMip) {
         validate();
         rsnAllocationData3D(mContext,
@@ -477,130 +464,118 @@
                             srcAlloc, srcXoff, srcYoff, srcZoff, srcMip);
     }
 
-    native void rsnAllocationData3D(int con, int id, int xoff, int yoff, int zoff, int mip, int w, int h, int depth, byte[] d, int sizeBytes);
-    synchronized void nAllocationData3D(int id, int xoff, int yoff, int zoff, int mip, int w, int h, int depth, byte[] d, int sizeBytes) {
+    native void rsnAllocationData3D(long con, long id, int xoff, int yoff, int zoff, int mip,
+                                    int w, int h, int depth, Object d, int sizeBytes, int dt);
+    synchronized void nAllocationData3D(long id, int xoff, int yoff, int zoff, int mip,
+                                        int w, int h, int depth, Object d, int sizeBytes, Element.DataType dt) {
         validate();
-        rsnAllocationData3D(mContext, id, xoff, yoff, zoff, mip, w, h, depth, d, sizeBytes);
-    }
-    native void rsnAllocationData3D(int con, int id, int xoff, int yoff, int zoff, int mip, int w, int h, int depth, short[] d, int sizeBytes);
-    synchronized void nAllocationData3D(int id, int xoff, int yoff, int zoff, int mip, int w, int h, int depth, short[] d, int sizeBytes) {
-        validate();
-        rsnAllocationData3D(mContext, id, xoff, yoff, zoff, mip, w, h, depth, d, sizeBytes);
-    }
-    native void rsnAllocationData3D(int con, int id, int xoff, int yoff, int zoff, int mip, int w, int h, int depth, int[] d, int sizeBytes);
-    synchronized void nAllocationData3D(int id, int xoff, int yoff, int zoff, int mip, int w, int h, int depth, int[] d, int sizeBytes) {
-        validate();
-        rsnAllocationData3D(mContext, id, xoff, yoff, zoff, mip, w, h, depth, d, sizeBytes);
-    }
-    native void rsnAllocationData3D(int con, int id, int xoff, int yoff, int zoff, int mip, int w, int h, int depth, float[] d, int sizeBytes);
-    synchronized void nAllocationData3D(int id, int xoff, int yoff, int zoff, int mip, int w, int h, int depth, float[] d, int sizeBytes) {
-        validate();
-        rsnAllocationData3D(mContext, id, xoff, yoff, zoff, mip, w, h, depth, d, sizeBytes);
+        rsnAllocationData3D(mContext, id, xoff, yoff, zoff, mip, w, h, depth, d, sizeBytes, dt.mID);
     }
 
+    native void rsnAllocationRead(long con, long id, Object d, int dt);
+    synchronized void nAllocationRead(long id, Object d, Element.DataType dt) {
+        validate();
+        rsnAllocationRead(mContext, id, d, dt.mID);
+    }
 
-    native void rsnAllocationRead(int con, int id, byte[] d);
-    synchronized void nAllocationRead(int id, byte[] d) {
+    native void rsnAllocationRead1D(long con, long id, int off, int mip, int count, Object d,
+                                    int sizeBytes, int dt);
+    synchronized void nAllocationRead1D(long id, int off, int mip, int count, Object d,
+                                        int sizeBytes, Element.DataType dt) {
         validate();
-        rsnAllocationRead(mContext, id, d);
+        rsnAllocationRead1D(mContext, id, off, mip, count, d, sizeBytes, dt.mID);
     }
-    native void rsnAllocationRead(int con, int id, short[] d);
-    synchronized void nAllocationRead(int id, short[] d) {
+
+    native void rsnAllocationRead2D(long con, long id, int xoff, int yoff, int mip, int face,
+                                    int w, int h, Object d, int sizeBytes, int dt);
+    synchronized void nAllocationRead2D(long id, int xoff, int yoff, int mip, int face,
+                                        int w, int h, Object d, int sizeBytes, Element.DataType dt) {
         validate();
-        rsnAllocationRead(mContext, id, d);
+        rsnAllocationRead2D(mContext, id, xoff, yoff, mip, face, w, h, d, sizeBytes, dt.mID);
     }
-    native void rsnAllocationRead(int con, int id, int[] d);
-    synchronized void nAllocationRead(int id, int[] d) {
-        validate();
-        rsnAllocationRead(mContext, id, d);
-    }
-    native void rsnAllocationRead(int con, int id, float[] d);
-    synchronized void nAllocationRead(int id, float[] d) {
-        validate();
-        rsnAllocationRead(mContext, id, d);
-    }
-    native int  rsnAllocationGetType(int con, int id);
-    synchronized int nAllocationGetType(int id) {
+
+    native long  rsnAllocationGetType(long con, long id);
+    synchronized long nAllocationGetType(long id) {
         validate();
         return rsnAllocationGetType(mContext, id);
     }
 
-    native void rsnAllocationResize1D(int con, int id, int dimX);
-    synchronized void nAllocationResize1D(int id, int dimX) {
+    native void rsnAllocationResize1D(long con, long id, int dimX);
+    synchronized void nAllocationResize1D(long id, int dimX) {
         validate();
         rsnAllocationResize1D(mContext, id, dimX);
     }
 
-    native int  rsnFileA3DCreateFromAssetStream(int con, int assetStream);
-    synchronized int nFileA3DCreateFromAssetStream(int assetStream) {
+    native long rsnFileA3DCreateFromAssetStream(long con, long assetStream);
+    synchronized long nFileA3DCreateFromAssetStream(long assetStream) {
         validate();
         return rsnFileA3DCreateFromAssetStream(mContext, assetStream);
     }
-    native int  rsnFileA3DCreateFromFile(int con, String path);
-    synchronized int nFileA3DCreateFromFile(String path) {
+    native long rsnFileA3DCreateFromFile(long con, String path);
+    synchronized long nFileA3DCreateFromFile(String path) {
         validate();
         return rsnFileA3DCreateFromFile(mContext, path);
     }
-    native int  rsnFileA3DCreateFromAsset(int con, AssetManager mgr, String path);
-    synchronized int nFileA3DCreateFromAsset(AssetManager mgr, String path) {
+    native long rsnFileA3DCreateFromAsset(long con, AssetManager mgr, String path);
+    synchronized long nFileA3DCreateFromAsset(AssetManager mgr, String path) {
         validate();
         return rsnFileA3DCreateFromAsset(mContext, mgr, path);
     }
-    native int  rsnFileA3DGetNumIndexEntries(int con, int fileA3D);
-    synchronized int nFileA3DGetNumIndexEntries(int fileA3D) {
+    native int  rsnFileA3DGetNumIndexEntries(long con, long fileA3D);
+    synchronized int nFileA3DGetNumIndexEntries(long fileA3D) {
         validate();
         return rsnFileA3DGetNumIndexEntries(mContext, fileA3D);
     }
-    native void rsnFileA3DGetIndexEntries(int con, int fileA3D, int numEntries, int[] IDs, String[] names);
-    synchronized void nFileA3DGetIndexEntries(int fileA3D, int numEntries, int[] IDs, String[] names) {
+    native void rsnFileA3DGetIndexEntries(long con, long fileA3D, int numEntries, int[] IDs, String[] names);
+    synchronized void nFileA3DGetIndexEntries(long fileA3D, int numEntries, int[] IDs, String[] names) {
         validate();
         rsnFileA3DGetIndexEntries(mContext, fileA3D, numEntries, IDs, names);
     }
-    native int  rsnFileA3DGetEntryByIndex(int con, int fileA3D, int index);
-    synchronized int nFileA3DGetEntryByIndex(int fileA3D, int index) {
+    native long rsnFileA3DGetEntryByIndex(long con, long fileA3D, int index);
+    synchronized long nFileA3DGetEntryByIndex(long fileA3D, int index) {
         validate();
         return rsnFileA3DGetEntryByIndex(mContext, fileA3D, index);
     }
 
-    native int  rsnFontCreateFromFile(int con, String fileName, float size, int dpi);
-    synchronized int nFontCreateFromFile(String fileName, float size, int dpi) {
+    native long rsnFontCreateFromFile(long con, String fileName, float size, int dpi);
+    synchronized long nFontCreateFromFile(String fileName, float size, int dpi) {
         validate();
         return rsnFontCreateFromFile(mContext, fileName, size, dpi);
     }
-    native int  rsnFontCreateFromAssetStream(int con, String name, float size, int dpi, int assetStream);
-    synchronized int nFontCreateFromAssetStream(String name, float size, int dpi, int assetStream) {
+    native long rsnFontCreateFromAssetStream(long con, String name, float size, int dpi, long assetStream);
+    synchronized long nFontCreateFromAssetStream(String name, float size, int dpi, long assetStream) {
         validate();
         return rsnFontCreateFromAssetStream(mContext, name, size, dpi, assetStream);
     }
-    native int  rsnFontCreateFromAsset(int con, AssetManager mgr, String path, float size, int dpi);
-    synchronized int nFontCreateFromAsset(AssetManager mgr, String path, float size, int dpi) {
+    native long rsnFontCreateFromAsset(long con, AssetManager mgr, String path, float size, int dpi);
+    synchronized long nFontCreateFromAsset(AssetManager mgr, String path, float size, int dpi) {
         validate();
         return rsnFontCreateFromAsset(mContext, mgr, path, size, dpi);
     }
 
 
-    native void rsnScriptBindAllocation(int con, int script, int alloc, int slot);
-    synchronized void nScriptBindAllocation(int script, int alloc, int slot) {
+    native void rsnScriptBindAllocation(long con, long script, long alloc, int slot);
+    synchronized void nScriptBindAllocation(long script, long alloc, int slot) {
         validate();
         rsnScriptBindAllocation(mContext, script, alloc, slot);
     }
-    native void rsnScriptSetTimeZone(int con, int script, byte[] timeZone);
-    synchronized void nScriptSetTimeZone(int script, byte[] timeZone) {
+    native void rsnScriptSetTimeZone(long con, long script, byte[] timeZone);
+    synchronized void nScriptSetTimeZone(long script, byte[] timeZone) {
         validate();
         rsnScriptSetTimeZone(mContext, script, timeZone);
     }
-    native void rsnScriptInvoke(int con, int id, int slot);
-    synchronized void nScriptInvoke(int id, int slot) {
+    native void rsnScriptInvoke(long con, long id, int slot);
+    synchronized void nScriptInvoke(long id, int slot) {
         validate();
         rsnScriptInvoke(mContext, id, slot);
     }
-    native void rsnScriptForEach(int con, int id, int slot, int ain, int aout, byte[] params);
-    native void rsnScriptForEach(int con, int id, int slot, int ain, int aout);
-    native void rsnScriptForEachClipped(int con, int id, int slot, int ain, int aout, byte[] params,
+    native void rsnScriptForEach(long con, long id, int slot, long ain, long aout, byte[] params);
+    native void rsnScriptForEach(long con, long id, int slot, long ain, long aout);
+    native void rsnScriptForEachClipped(long con, long id, int slot, long ain, long aout, byte[] params,
                                         int xstart, int xend, int ystart, int yend, int zstart, int zend);
-    native void rsnScriptForEachClipped(int con, int id, int slot, int ain, int aout,
+    native void rsnScriptForEachClipped(long con, long id, int slot, long ain, long aout,
                                         int xstart, int xend, int ystart, int yend, int zstart, int zend);
-    synchronized void nScriptForEach(int id, int slot, int ain, int aout, byte[] params) {
+    synchronized void nScriptForEach(long id, int slot, long ain, long aout, byte[] params) {
         validate();
         if (params == null) {
             rsnScriptForEach(mContext, id, slot, ain, aout);
@@ -609,7 +584,7 @@
         }
     }
 
-    synchronized void nScriptForEachClipped(int id, int slot, int ain, int aout, byte[] params,
+    synchronized void nScriptForEachClipped(long id, int slot, long ain, long aout, byte[] params,
                                             int xstart, int xend, int ystart, int yend, int zstart, int zend) {
         validate();
         if (params == null) {
@@ -619,138 +594,138 @@
         }
     }
 
-    native void rsnScriptInvokeV(int con, int id, int slot, byte[] params);
-    synchronized void nScriptInvokeV(int id, int slot, byte[] params) {
+    native void rsnScriptInvokeV(long con, long id, int slot, byte[] params);
+    synchronized void nScriptInvokeV(long id, int slot, byte[] params) {
         validate();
         rsnScriptInvokeV(mContext, id, slot, params);
     }
 
-    native void rsnScriptSetVarI(int con, int id, int slot, int val);
-    synchronized void nScriptSetVarI(int id, int slot, int val) {
+    native void rsnScriptSetVarI(long con, long id, int slot, int val);
+    synchronized void nScriptSetVarI(long id, int slot, int val) {
         validate();
         rsnScriptSetVarI(mContext, id, slot, val);
     }
-    native int rsnScriptGetVarI(int con, int id, int slot);
-    synchronized int nScriptGetVarI(int id, int slot) {
+    native int rsnScriptGetVarI(long con, long id, int slot);
+    synchronized int nScriptGetVarI(long id, int slot) {
         validate();
         return rsnScriptGetVarI(mContext, id, slot);
     }
 
-    native void rsnScriptSetVarJ(int con, int id, int slot, long val);
-    synchronized void nScriptSetVarJ(int id, int slot, long val) {
+    native void rsnScriptSetVarJ(long con, long id, int slot, long val);
+    synchronized void nScriptSetVarJ(long id, int slot, long val) {
         validate();
         rsnScriptSetVarJ(mContext, id, slot, val);
     }
-    native long rsnScriptGetVarJ(int con, int id, int slot);
-    synchronized long nScriptGetVarJ(int id, int slot) {
+    native long rsnScriptGetVarJ(long con, long id, int slot);
+    synchronized long nScriptGetVarJ(long id, int slot) {
         validate();
         return rsnScriptGetVarJ(mContext, id, slot);
     }
 
-    native void rsnScriptSetVarF(int con, int id, int slot, float val);
-    synchronized void nScriptSetVarF(int id, int slot, float val) {
+    native void rsnScriptSetVarF(long con, long id, int slot, float val);
+    synchronized void nScriptSetVarF(long id, int slot, float val) {
         validate();
         rsnScriptSetVarF(mContext, id, slot, val);
     }
-    native float rsnScriptGetVarF(int con, int id, int slot);
-    synchronized float nScriptGetVarF(int id, int slot) {
+    native float rsnScriptGetVarF(long con, long id, int slot);
+    synchronized float nScriptGetVarF(long id, int slot) {
         validate();
         return rsnScriptGetVarF(mContext, id, slot);
     }
-    native void rsnScriptSetVarD(int con, int id, int slot, double val);
-    synchronized void nScriptSetVarD(int id, int slot, double val) {
+    native void rsnScriptSetVarD(long con, long id, int slot, double val);
+    synchronized void nScriptSetVarD(long id, int slot, double val) {
         validate();
         rsnScriptSetVarD(mContext, id, slot, val);
     }
-    native double rsnScriptGetVarD(int con, int id, int slot);
-    synchronized double nScriptGetVarD(int id, int slot) {
+    native double rsnScriptGetVarD(long con, long id, int slot);
+    synchronized double nScriptGetVarD(long id, int slot) {
         validate();
         return rsnScriptGetVarD(mContext, id, slot);
     }
-    native void rsnScriptSetVarV(int con, int id, int slot, byte[] val);
-    synchronized void nScriptSetVarV(int id, int slot, byte[] val) {
+    native void rsnScriptSetVarV(long con, long id, int slot, byte[] val);
+    synchronized void nScriptSetVarV(long id, int slot, byte[] val) {
         validate();
         rsnScriptSetVarV(mContext, id, slot, val);
     }
-    native void rsnScriptGetVarV(int con, int id, int slot, byte[] val);
-    synchronized void nScriptGetVarV(int id, int slot, byte[] val) {
+    native void rsnScriptGetVarV(long con, long id, int slot, byte[] val);
+    synchronized void nScriptGetVarV(long id, int slot, byte[] val) {
         validate();
         rsnScriptGetVarV(mContext, id, slot, val);
     }
-    native void rsnScriptSetVarVE(int con, int id, int slot, byte[] val,
-                                  int e, int[] dims);
-    synchronized void nScriptSetVarVE(int id, int slot, byte[] val,
-                                      int e, int[] dims) {
+    native void rsnScriptSetVarVE(long con, long id, int slot, byte[] val,
+                                  long e, int[] dims);
+    synchronized void nScriptSetVarVE(long id, int slot, byte[] val,
+                                      long e, int[] dims) {
         validate();
         rsnScriptSetVarVE(mContext, id, slot, val, e, dims);
     }
-    native void rsnScriptSetVarObj(int con, int id, int slot, int val);
-    synchronized void nScriptSetVarObj(int id, int slot, int val) {
+    native void rsnScriptSetVarObj(long con, long id, int slot, long val);
+    synchronized void nScriptSetVarObj(long id, int slot, long val) {
         validate();
         rsnScriptSetVarObj(mContext, id, slot, val);
     }
 
-    native int  rsnScriptCCreate(int con, String resName, String cacheDir,
+    native long rsnScriptCCreate(long con, String resName, String cacheDir,
                                  byte[] script, int length);
-    synchronized int nScriptCCreate(String resName, String cacheDir, byte[] script, int length) {
+    synchronized long nScriptCCreate(String resName, String cacheDir, byte[] script, int length) {
         validate();
         return rsnScriptCCreate(mContext, resName, cacheDir, script, length);
     }
 
-    native int  rsnScriptIntrinsicCreate(int con, int id, int eid);
-    synchronized int nScriptIntrinsicCreate(int id, int eid) {
+    native long rsnScriptIntrinsicCreate(long con, int id, long eid);
+    synchronized long nScriptIntrinsicCreate(int id, long eid) {
         validate();
         return rsnScriptIntrinsicCreate(mContext, id, eid);
     }
 
-    native int  rsnScriptKernelIDCreate(int con, int sid, int slot, int sig);
-    synchronized int nScriptKernelIDCreate(int sid, int slot, int sig) {
+    native long  rsnScriptKernelIDCreate(long con, long sid, int slot, int sig);
+    synchronized long nScriptKernelIDCreate(long sid, int slot, int sig) {
         validate();
         return rsnScriptKernelIDCreate(mContext, sid, slot, sig);
     }
 
-    native int  rsnScriptFieldIDCreate(int con, int sid, int slot);
-    synchronized int nScriptFieldIDCreate(int sid, int slot) {
+    native long  rsnScriptFieldIDCreate(long con, long sid, int slot);
+    synchronized long nScriptFieldIDCreate(long sid, int slot) {
         validate();
         return rsnScriptFieldIDCreate(mContext, sid, slot);
     }
 
-    native int  rsnScriptGroupCreate(int con, int[] kernels, int[] src, int[] dstk, int[] dstf, int[] types);
-    synchronized int nScriptGroupCreate(int[] kernels, int[] src, int[] dstk, int[] dstf, int[] types) {
+    native long rsnScriptGroupCreate(long con, int[] kernels, int[] src, int[] dstk, int[] dstf, int[] types);
+    synchronized long nScriptGroupCreate(int[] kernels, int[] src, int[] dstk, int[] dstf, int[] types) {
         validate();
         return rsnScriptGroupCreate(mContext, kernels, src, dstk, dstf, types);
     }
 
-    native void rsnScriptGroupSetInput(int con, int group, int kernel, int alloc);
-    synchronized void nScriptGroupSetInput(int group, int kernel, int alloc) {
+    native void rsnScriptGroupSetInput(long con, long group, long kernel, long alloc);
+    synchronized void nScriptGroupSetInput(long group, long kernel, long alloc) {
         validate();
         rsnScriptGroupSetInput(mContext, group, kernel, alloc);
     }
 
-    native void rsnScriptGroupSetOutput(int con, int group, int kernel, int alloc);
-    synchronized void nScriptGroupSetOutput(int group, int kernel, int alloc) {
+    native void rsnScriptGroupSetOutput(long con, long group, long kernel, long alloc);
+    synchronized void nScriptGroupSetOutput(long group, long kernel, long alloc) {
         validate();
         rsnScriptGroupSetOutput(mContext, group, kernel, alloc);
     }
 
-    native void rsnScriptGroupExecute(int con, int group);
-    synchronized void nScriptGroupExecute(int group) {
+    native void rsnScriptGroupExecute(long con, long group);
+    synchronized void nScriptGroupExecute(long group) {
         validate();
         rsnScriptGroupExecute(mContext, group);
     }
 
-    native int  rsnSamplerCreate(int con, int magFilter, int minFilter,
+    native long  rsnSamplerCreate(long con, int magFilter, int minFilter,
                                  int wrapS, int wrapT, int wrapR, float aniso);
-    synchronized int nSamplerCreate(int magFilter, int minFilter,
+    synchronized long nSamplerCreate(int magFilter, int minFilter,
                                  int wrapS, int wrapT, int wrapR, float aniso) {
         validate();
         return rsnSamplerCreate(mContext, magFilter, minFilter, wrapS, wrapT, wrapR, aniso);
     }
 
-    native int  rsnProgramStoreCreate(int con, boolean r, boolean g, boolean b, boolean a,
+    native long rsnProgramStoreCreate(long con, boolean r, boolean g, boolean b, boolean a,
                                       boolean depthMask, boolean dither,
                                       int srcMode, int dstMode, int depthFunc);
-    synchronized int nProgramStoreCreate(boolean r, boolean g, boolean b, boolean a,
+    synchronized long nProgramStoreCreate(boolean r, boolean g, boolean b, boolean a,
                                          boolean depthMask, boolean dither,
                                          int srcMode, int dstMode, int depthFunc) {
         validate();
@@ -758,72 +733,72 @@
                                      dstMode, depthFunc);
     }
 
-    native int  rsnProgramRasterCreate(int con, boolean pointSprite, int cullMode);
-    synchronized int nProgramRasterCreate(boolean pointSprite, int cullMode) {
+    native long rsnProgramRasterCreate(long con, boolean pointSprite, int cullMode);
+    synchronized long nProgramRasterCreate(boolean pointSprite, int cullMode) {
         validate();
         return rsnProgramRasterCreate(mContext, pointSprite, cullMode);
     }
 
-    native void rsnProgramBindConstants(int con, int pv, int slot, int mID);
-    synchronized void nProgramBindConstants(int pv, int slot, int mID) {
+    native void rsnProgramBindConstants(long con, long pv, int slot, long mID);
+    synchronized void nProgramBindConstants(long pv, int slot, long mID) {
         validate();
         rsnProgramBindConstants(mContext, pv, slot, mID);
     }
-    native void rsnProgramBindTexture(int con, int vpf, int slot, int a);
-    synchronized void nProgramBindTexture(int vpf, int slot, int a) {
+    native void rsnProgramBindTexture(long con, long vpf, int slot, long a);
+    synchronized void nProgramBindTexture(long vpf, int slot, long a) {
         validate();
         rsnProgramBindTexture(mContext, vpf, slot, a);
     }
-    native void rsnProgramBindSampler(int con, int vpf, int slot, int s);
-    synchronized void nProgramBindSampler(int vpf, int slot, int s) {
+    native void rsnProgramBindSampler(long con, long vpf, int slot, long s);
+    synchronized void nProgramBindSampler(long vpf, int slot, long s) {
         validate();
         rsnProgramBindSampler(mContext, vpf, slot, s);
     }
-    native int  rsnProgramFragmentCreate(int con, String shader, String[] texNames, int[] params);
-    synchronized int nProgramFragmentCreate(String shader, String[] texNames, int[] params) {
+    native long rsnProgramFragmentCreate(long con, String shader, String[] texNames, int[] params);
+    synchronized long nProgramFragmentCreate(String shader, String[] texNames, int[] params) {
         validate();
         return rsnProgramFragmentCreate(mContext, shader, texNames, params);
     }
-    native int  rsnProgramVertexCreate(int con, String shader, String[] texNames, int[] params);
-    synchronized int nProgramVertexCreate(String shader, String[] texNames, int[] params) {
+    native long rsnProgramVertexCreate(long con, String shader, String[] texNames, int[] params);
+    synchronized long nProgramVertexCreate(String shader, String[] texNames, int[] params) {
         validate();
         return rsnProgramVertexCreate(mContext, shader, texNames, params);
     }
 
-    native int  rsnMeshCreate(int con, int[] vtx, int[] idx, int[] prim);
-    synchronized int nMeshCreate(int[] vtx, int[] idx, int[] prim) {
+    native long rsnMeshCreate(long con, int[] vtx, int[] idx, int[] prim);
+    synchronized long nMeshCreate(int[] vtx, int[] idx, int[] prim) {
         validate();
         return rsnMeshCreate(mContext, vtx, idx, prim);
     }
-    native int  rsnMeshGetVertexBufferCount(int con, int id);
-    synchronized int nMeshGetVertexBufferCount(int id) {
+    native int  rsnMeshGetVertexBufferCount(long con, long id);
+    synchronized int nMeshGetVertexBufferCount(long id) {
         validate();
         return rsnMeshGetVertexBufferCount(mContext, id);
     }
-    native int  rsnMeshGetIndexCount(int con, int id);
-    synchronized int nMeshGetIndexCount(int id) {
+    native int  rsnMeshGetIndexCount(long con, long id);
+    synchronized int nMeshGetIndexCount(long id) {
         validate();
         return rsnMeshGetIndexCount(mContext, id);
     }
-    native void rsnMeshGetVertices(int con, int id, int[] vtxIds, int vtxIdCount);
-    synchronized void nMeshGetVertices(int id, int[] vtxIds, int vtxIdCount) {
+    native void rsnMeshGetVertices(long con, long id, int[] vtxIds, int vtxIdCount);
+    synchronized void nMeshGetVertices(long id, int[] vtxIds, int vtxIdCount) {
         validate();
         rsnMeshGetVertices(mContext, id, vtxIds, vtxIdCount);
     }
-    native void rsnMeshGetIndices(int con, int id, int[] idxIds, int[] primitives, int vtxIdCount);
-    synchronized void nMeshGetIndices(int id, int[] idxIds, int[] primitives, int vtxIdCount) {
+    native void rsnMeshGetIndices(long con, long id, int[] idxIds, int[] primitives, int vtxIdCount);
+    synchronized void nMeshGetIndices(long id, int[] idxIds, int[] primitives, int vtxIdCount) {
         validate();
         rsnMeshGetIndices(mContext, id, idxIds, primitives, vtxIdCount);
     }
 
-    native int  rsnPathCreate(int con, int prim, boolean isStatic, int vtx, int loop, float q);
-    synchronized int nPathCreate(int prim, boolean isStatic, int vtx, int loop, float q) {
+    native long rsnPathCreate(long con, int prim, boolean isStatic, long vtx, long loop, float q);
+    synchronized long nPathCreate(int prim, boolean isStatic, long vtx, long loop, float q) {
         validate();
         return rsnPathCreate(mContext, prim, isStatic, vtx, loop, q);
     }
 
-    int     mDev;
-    int     mContext;
+    long     mDev;
+    long     mContext;
     @SuppressWarnings({"FieldCanBeLocal"})
     MessageThread mMessageThread;
 
@@ -1136,6 +1111,7 @@
         if (ctx != null) {
             mApplicationContext = ctx.getApplicationContext();
         }
+        mRWLock = new ReentrantReadWriteLock();
     }
 
     /**
@@ -1230,6 +1206,8 @@
      */
     public void destroy() {
         validate();
+        nContextFinish();
+
         nContextDeinitToClient(mContext);
         mMessageThread.mRun = false;
         try {
@@ -1238,7 +1216,6 @@
         }
 
         nContextDestroy();
-        mContext = 0;
 
         nDeviceDestroy(mDev);
         mDev = 0;
@@ -1248,7 +1225,7 @@
         return mContext != 0;
     }
 
-    int safeID(BaseObj o) {
+    long safeID(BaseObj o) {
         if(o != null) {
             return o.getID(this);
         }
diff --git a/graphics/java/android/renderscript/RenderScriptGL.java b/rs/java/android/renderscript/RenderScriptGL.java
similarity index 97%
rename from graphics/java/android/renderscript/RenderScriptGL.java
rename to rs/java/android/renderscript/RenderScriptGL.java
index bac9c68..c9cbe3e 100644
--- a/graphics/java/android/renderscript/RenderScriptGL.java
+++ b/rs/java/android/renderscript/RenderScriptGL.java
@@ -286,7 +286,7 @@
      */
     public void bindRootScript(Script s) {
         validate();
-        nContextBindRootScript(safeID(s));
+        nContextBindRootScript((int)safeID(s));
     }
 
     /**
@@ -298,7 +298,7 @@
      */
     public void bindProgramStore(ProgramStore p) {
         validate();
-        nContextBindProgramStore(safeID(p));
+        nContextBindProgramStore((int)safeID(p));
     }
 
     /**
@@ -310,7 +310,7 @@
      */
     public void bindProgramFragment(ProgramFragment p) {
         validate();
-        nContextBindProgramFragment(safeID(p));
+        nContextBindProgramFragment((int)safeID(p));
     }
 
     /**
@@ -322,7 +322,7 @@
      */
     public void bindProgramRaster(ProgramRaster p) {
         validate();
-        nContextBindProgramRaster(safeID(p));
+        nContextBindProgramRaster((int)safeID(p));
     }
 
     /**
@@ -334,7 +334,7 @@
      */
     public void bindProgramVertex(ProgramVertex p) {
         validate();
-        nContextBindProgramVertex(safeID(p));
+        nContextBindProgramVertex((int)safeID(p));
     }
 
 }
diff --git a/graphics/java/android/renderscript/Sampler.java b/rs/java/android/renderscript/Sampler.java
similarity index 98%
rename from graphics/java/android/renderscript/Sampler.java
rename to rs/java/android/renderscript/Sampler.java
index 623055fe..8d0e29e 100644
--- a/graphics/java/android/renderscript/Sampler.java
+++ b/rs/java/android/renderscript/Sampler.java
@@ -60,7 +60,7 @@
     Value mWrapR;
     float mAniso;
 
-    Sampler(int id, RenderScript rs) {
+    Sampler(long id, RenderScript rs) {
         super(id, rs);
     }
 
@@ -347,7 +347,7 @@
 
         public Sampler create() {
             mRS.validate();
-            int id = mRS.nSamplerCreate(mMag.mID, mMin.mID,
+            long id = mRS.nSamplerCreate(mMag.mID, mMin.mID,
                                         mWrapS.mID, mWrapT.mID, mWrapR.mID, mAniso);
             Sampler sampler = new Sampler(id, mRS);
             sampler.mMin = mMin;
diff --git a/graphics/java/android/renderscript/Script.java b/rs/java/android/renderscript/Script.java
similarity index 93%
rename from graphics/java/android/renderscript/Script.java
rename to rs/java/android/renderscript/Script.java
index 0026e0e..a1f2287 100644
--- a/graphics/java/android/renderscript/Script.java
+++ b/rs/java/android/renderscript/Script.java
@@ -36,7 +36,7 @@
         Script mScript;
         int mSlot;
         int mSig;
-        KernelID(int id, RenderScript rs, Script s, int slot, int sig) {
+        KernelID(long id, RenderScript rs, Script s, int slot, int sig) {
             super(id, rs);
             mScript = s;
             mSlot = slot;
@@ -54,7 +54,7 @@
             return k;
         }
 
-        int id = mRS.nScriptKernelIDCreate(getID(mRS), slot, sig);
+        long id = mRS.nScriptKernelIDCreate(getID(mRS), slot, sig);
         if (id == 0) {
             throw new RSDriverException("Failed to create KernelID");
         }
@@ -75,7 +75,7 @@
     public static final class FieldID extends BaseObj {
         Script mScript;
         int mSlot;
-        FieldID(int id, RenderScript rs, Script s, int slot) {
+        FieldID(long id, RenderScript rs, Script s, int slot) {
             super(id, rs);
             mScript = s;
             mSlot = slot;
@@ -92,7 +92,7 @@
             return f;
         }
 
-        int id = mRS.nScriptFieldIDCreate(getID(mRS), slot);
+        long id = mRS.nScriptFieldIDCreate(getID(mRS), slot);
         if (id == 0) {
             throw new RSDriverException("Failed to create FieldID");
         }
@@ -132,11 +132,11 @@
             throw new RSIllegalArgumentException(
                 "At least one of ain or aout is required to be non-null.");
         }
-        int in_id = 0;
+        long in_id = 0;
         if (ain != null) {
             in_id = ain.getID(mRS);
         }
-        int out_id = 0;
+        long out_id = 0;
         if (aout != null) {
             out_id = aout.getID(mRS);
         }
@@ -161,11 +161,11 @@
             forEach(slot, ain, aout, v);
             return;
         }
-        int in_id = 0;
+        long in_id = 0;
         if (ain != null) {
             in_id = ain.getID(mRS);
         }
-        int out_id = 0;
+        long out_id = 0;
         if (aout != null) {
             out_id = aout.getID(mRS);
         }
@@ -176,7 +176,7 @@
         mRS.nScriptForEachClipped(getID(mRS), slot, in_id, out_id, params, sc.xstart, sc.xend, sc.ystart, sc.yend, sc.zstart, sc.zend);
     }
 
-    Script(int id, RenderScript rs) {
+    Script(long id, RenderScript rs) {
         super(id, rs);
     }
 
@@ -188,6 +188,13 @@
     public void bindAllocation(Allocation va, int slot) {
         mRS.validate();
         if (va != null) {
+            if (mRS.getApplicationContext().getApplicationInfo().targetSdkVersion >= 20) {
+                final Type t = va.mType;
+                if (t.hasMipmaps() || t.hasFaces() || (t.getY() != 0) || (t.getZ() != 0)) {
+                    throw new RSIllegalArgumentException(
+                        "API 20+ only allows simple 1D allocations to be used with bind.");
+                }
+            }
             mRS.nScriptBindAllocation(getID(mRS), va.getID(mRS), slot);
         } else {
             mRS.nScriptBindAllocation(getID(mRS), 0, slot);
diff --git a/graphics/java/android/renderscript/ScriptC.java b/rs/java/android/renderscript/ScriptC.java
similarity index 89%
rename from graphics/java/android/renderscript/ScriptC.java
rename to rs/java/android/renderscript/ScriptC.java
index b0a5759..cdb2b08 100644
--- a/graphics/java/android/renderscript/ScriptC.java
+++ b/rs/java/android/renderscript/ScriptC.java
@@ -45,7 +45,17 @@
     protected ScriptC(int id, RenderScript rs) {
         super(id, rs);
     }
-
+    /**
+     * Only intended for use by the generated derived classes.
+     *
+     * @param id
+     * @param rs
+     *
+     * @hide
+     */
+    protected ScriptC(long id, RenderScript rs) {
+        super(id, rs);
+    }
     /**
      * Only intended for use by the generated derived classes.
      *
@@ -56,7 +66,7 @@
      */
     protected ScriptC(RenderScript rs, Resources resources, int resourceID) {
         super(0, rs);
-        int id = internalCreate(rs, resources, resourceID);
+        long id = internalCreate(rs, resources, resourceID);
         if (id == 0) {
             throw new RSRuntimeException("Loading of ScriptC script failed.");
         }
@@ -70,7 +80,7 @@
 
     static String mCachePath;
 
-    private static synchronized int internalCreate(RenderScript rs, Resources resources, int resourceID) {
+    private static synchronized long internalCreate(RenderScript rs, Resources resources, int resourceID) {
         byte[] pgm;
         int pgmLength;
         InputStream is = resources.openRawResource(resourceID);
diff --git a/graphics/java/android/renderscript/ScriptGroup.java b/rs/java/android/renderscript/ScriptGroup.java
similarity index 96%
rename from graphics/java/android/renderscript/ScriptGroup.java
rename to rs/java/android/renderscript/ScriptGroup.java
index 1416641..48dba30 100644
--- a/graphics/java/android/renderscript/ScriptGroup.java
+++ b/rs/java/android/renderscript/ScriptGroup.java
@@ -89,7 +89,7 @@
     }
 
 
-    ScriptGroup(int id, RenderScript rs) {
+    ScriptGroup(long id, RenderScript rs) {
         super(id, rs);
     }
 
@@ -380,6 +380,7 @@
          * @return ScriptGroup The new ScriptGroup
          */
         public ScriptGroup create() {
+            // FIXME: this is broken for 64-bit
 
             if (mNodes.size() == 0) {
                 throw new RSInvalidStateException("Empty script groups are not allowed");
@@ -400,7 +401,7 @@
                 Node n = mNodes.get(ct);
                 for (int ct2=0; ct2 < n.mKernels.size(); ct2++) {
                     final Script.KernelID kid = n.mKernels.get(ct2);
-                    kernels[idx++] = kid.getID(mRS);
+                    kernels[idx++] = (int)kid.getID(mRS);
 
                     boolean hasInput = false;
                     boolean hasOutput = false;
@@ -434,17 +435,17 @@
 
             for (int ct=0; ct < mLines.size(); ct++) {
                 ConnectLine cl = mLines.get(ct);
-                src[ct] = cl.mFrom.getID(mRS);
+                src[ct] = (int)cl.mFrom.getID(mRS);
                 if (cl.mToK != null) {
-                    dstk[ct] = cl.mToK.getID(mRS);
+                    dstk[ct] = (int)cl.mToK.getID(mRS);
                 }
                 if (cl.mToF != null) {
-                    dstf[ct] = cl.mToF.getID(mRS);
+                    dstf[ct] = (int)cl.mToF.getID(mRS);
                 }
-                types[ct] = cl.mAllocationType.getID(mRS);
+                types[ct] = (int)cl.mAllocationType.getID(mRS);
             }
 
-            int id = mRS.nScriptGroupCreate(kernels, src, dstk, dstf, types);
+            long id = mRS.nScriptGroupCreate(kernels, src, dstk, dstf, types);
             if (id == 0) {
                 throw new RSRuntimeException("Object creation error, should not happen.");
             }
diff --git a/graphics/java/android/renderscript/ScriptIntrinsic.java b/rs/java/android/renderscript/ScriptIntrinsic.java
similarity index 95%
rename from graphics/java/android/renderscript/ScriptIntrinsic.java
rename to rs/java/android/renderscript/ScriptIntrinsic.java
index 096268a..8719e017 100644
--- a/graphics/java/android/renderscript/ScriptIntrinsic.java
+++ b/rs/java/android/renderscript/ScriptIntrinsic.java
@@ -25,7 +25,7 @@
  * Not intended for direct use.
  **/
 public abstract class ScriptIntrinsic extends Script {
-    ScriptIntrinsic(int id, RenderScript rs) {
+    ScriptIntrinsic(long id, RenderScript rs) {
         super(id, rs);
     }
 }
diff --git a/graphics/java/android/renderscript/ScriptIntrinsic3DLUT.java b/rs/java/android/renderscript/ScriptIntrinsic3DLUT.java
similarity index 95%
rename from graphics/java/android/renderscript/ScriptIntrinsic3DLUT.java
rename to rs/java/android/renderscript/ScriptIntrinsic3DLUT.java
index 34540a1..96ec875 100644
--- a/graphics/java/android/renderscript/ScriptIntrinsic3DLUT.java
+++ b/rs/java/android/renderscript/ScriptIntrinsic3DLUT.java
@@ -30,7 +30,7 @@
     private Allocation mLUT;
     private Element mElement;
 
-    private ScriptIntrinsic3DLUT(int id, RenderScript rs, Element e) {
+    private ScriptIntrinsic3DLUT(long id, RenderScript rs, Element e) {
         super(id, rs);
         mElement = e;
     }
@@ -46,7 +46,7 @@
      * @return ScriptIntrinsic3DLUT
      */
     public static ScriptIntrinsic3DLUT create(RenderScript rs, Element e) {
-        int id = rs.nScriptIntrinsicCreate(8, e.getID(rs));
+        long id = rs.nScriptIntrinsicCreate(8, e.getID(rs));
 
         if (!e.isCompatible(Element.U8_4(rs))) {
             throw new RSIllegalArgumentException("Element must be compatible with uchar4.");
diff --git a/graphics/java/android/renderscript/ScriptIntrinsicBlend.java b/rs/java/android/renderscript/ScriptIntrinsicBlend.java
similarity index 98%
rename from graphics/java/android/renderscript/ScriptIntrinsicBlend.java
rename to rs/java/android/renderscript/ScriptIntrinsicBlend.java
index 0e05bc8..40f1a3e 100644
--- a/graphics/java/android/renderscript/ScriptIntrinsicBlend.java
+++ b/rs/java/android/renderscript/ScriptIntrinsicBlend.java
@@ -21,7 +21,7 @@
  * Intrinsic kernels for blending two {@link android.renderscript.Allocation} objects.
  **/
 public class ScriptIntrinsicBlend extends ScriptIntrinsic {
-    ScriptIntrinsicBlend(int id, RenderScript rs) {
+    ScriptIntrinsicBlend(long id, RenderScript rs) {
         super(id, rs);
     }
 
@@ -35,7 +35,7 @@
      */
     public static ScriptIntrinsicBlend create(RenderScript rs, Element e) {
         // 7 comes from RS_SCRIPT_INTRINSIC_ID_BLEND in rsDefines.h
-        int id = rs.nScriptIntrinsicCreate(7, e.getID(rs));
+        long id = rs.nScriptIntrinsicCreate(7, e.getID(rs));
         return new ScriptIntrinsicBlend(id, rs);
 
     }
diff --git a/graphics/java/android/renderscript/ScriptIntrinsicBlur.java b/rs/java/android/renderscript/ScriptIntrinsicBlur.java
similarity index 95%
rename from graphics/java/android/renderscript/ScriptIntrinsicBlur.java
rename to rs/java/android/renderscript/ScriptIntrinsicBlur.java
index aaf5ffc..d1a6fed 100644
--- a/graphics/java/android/renderscript/ScriptIntrinsicBlur.java
+++ b/rs/java/android/renderscript/ScriptIntrinsicBlur.java
@@ -30,7 +30,7 @@
     private final float[] mValues = new float[9];
     private Allocation mInput;
 
-    private ScriptIntrinsicBlur(int id, RenderScript rs) {
+    private ScriptIntrinsicBlur(long id, RenderScript rs) {
         super(id, rs);
     }
 
@@ -49,7 +49,7 @@
         if ((!e.isCompatible(Element.U8_4(rs))) && (!e.isCompatible(Element.U8(rs)))) {
             throw new RSIllegalArgumentException("Unsuported element type.");
         }
-        int id = rs.nScriptIntrinsicCreate(5, e.getID(rs));
+        long id = rs.nScriptIntrinsicCreate(5, e.getID(rs));
         ScriptIntrinsicBlur sib = new ScriptIntrinsicBlur(id, rs);
         sib.setRadius(5.f);
         return sib;
diff --git a/graphics/java/android/renderscript/ScriptIntrinsicColorMatrix.java b/rs/java/android/renderscript/ScriptIntrinsicColorMatrix.java
similarity index 98%
rename from graphics/java/android/renderscript/ScriptIntrinsicColorMatrix.java
rename to rs/java/android/renderscript/ScriptIntrinsicColorMatrix.java
index 32c3d15..601db17 100644
--- a/graphics/java/android/renderscript/ScriptIntrinsicColorMatrix.java
+++ b/rs/java/android/renderscript/ScriptIntrinsicColorMatrix.java
@@ -43,7 +43,7 @@
     private final Matrix4f mMatrix = new Matrix4f();
     private final Float4 mAdd = new Float4();
 
-    private ScriptIntrinsicColorMatrix(int id, RenderScript rs) {
+    private ScriptIntrinsicColorMatrix(long id, RenderScript rs) {
         super(id, rs);
     }
 
@@ -75,7 +75,7 @@
      * @return ScriptIntrinsicColorMatrix
      */
     public static ScriptIntrinsicColorMatrix create(RenderScript rs) {
-        int id = rs.nScriptIntrinsicCreate(2, 0);
+        long id = rs.nScriptIntrinsicCreate(2, 0);
         return new ScriptIntrinsicColorMatrix(id, rs);
 
     }
diff --git a/graphics/java/android/renderscript/ScriptIntrinsicConvolve3x3.java b/rs/java/android/renderscript/ScriptIntrinsicConvolve3x3.java
similarity index 96%
rename from graphics/java/android/renderscript/ScriptIntrinsicConvolve3x3.java
rename to rs/java/android/renderscript/ScriptIntrinsicConvolve3x3.java
index 5d3c1d3..25f3ee8 100644
--- a/graphics/java/android/renderscript/ScriptIntrinsicConvolve3x3.java
+++ b/rs/java/android/renderscript/ScriptIntrinsicConvolve3x3.java
@@ -26,7 +26,7 @@
     private final float[] mValues = new float[9];
     private Allocation mInput;
 
-    private ScriptIntrinsicConvolve3x3(int id, RenderScript rs) {
+    private ScriptIntrinsicConvolve3x3(long id, RenderScript rs) {
         super(id, rs);
     }
 
@@ -61,7 +61,7 @@
             !e.isCompatible(Element.F32_4(rs))) {
             throw new RSIllegalArgumentException("Unsuported element type.");
         }
-        int id = rs.nScriptIntrinsicCreate(1, e.getID(rs));
+        long id = rs.nScriptIntrinsicCreate(1, e.getID(rs));
         ScriptIntrinsicConvolve3x3 si = new ScriptIntrinsicConvolve3x3(id, rs);
         si.setCoefficients(f);
         return si;
diff --git a/graphics/java/android/renderscript/ScriptIntrinsicConvolve5x5.java b/rs/java/android/renderscript/ScriptIntrinsicConvolve5x5.java
similarity index 96%
rename from graphics/java/android/renderscript/ScriptIntrinsicConvolve5x5.java
rename to rs/java/android/renderscript/ScriptIntrinsicConvolve5x5.java
index ad09f95..71ea4cbc 100644
--- a/graphics/java/android/renderscript/ScriptIntrinsicConvolve5x5.java
+++ b/rs/java/android/renderscript/ScriptIntrinsicConvolve5x5.java
@@ -26,7 +26,7 @@
     private final float[] mValues = new float[25];
     private Allocation mInput;
 
-    private ScriptIntrinsicConvolve5x5(int id, RenderScript rs) {
+    private ScriptIntrinsicConvolve5x5(long id, RenderScript rs) {
         super(id, rs);
     }
 
@@ -62,7 +62,7 @@
             throw new RSIllegalArgumentException("Unsuported element type.");
         }
 
-        int id = rs.nScriptIntrinsicCreate(4, e.getID(rs));
+        long id = rs.nScriptIntrinsicCreate(4, e.getID(rs));
         return new ScriptIntrinsicConvolve5x5(id, rs);
 
     }
diff --git a/graphics/java/android/renderscript/ScriptIntrinsicHistogram.java b/rs/java/android/renderscript/ScriptIntrinsicHistogram.java
similarity index 97%
rename from graphics/java/android/renderscript/ScriptIntrinsicHistogram.java
rename to rs/java/android/renderscript/ScriptIntrinsicHistogram.java
index adc2d95..42e4d04 100644
--- a/graphics/java/android/renderscript/ScriptIntrinsicHistogram.java
+++ b/rs/java/android/renderscript/ScriptIntrinsicHistogram.java
@@ -28,7 +28,7 @@
 public final class ScriptIntrinsicHistogram extends ScriptIntrinsic {
     private Allocation mOut;
 
-    private ScriptIntrinsicHistogram(int id, RenderScript rs) {
+    private ScriptIntrinsicHistogram(long id, RenderScript rs) {
         super(id, rs);
     }
 
@@ -52,7 +52,7 @@
             (!e.isCompatible(Element.U8(rs)))) {
             throw new RSIllegalArgumentException("Unsuported element type.");
         }
-        int id = rs.nScriptIntrinsicCreate(9, e.getID(rs));
+        long id = rs.nScriptIntrinsicCreate(9, e.getID(rs));
         ScriptIntrinsicHistogram sib = new ScriptIntrinsicHistogram(id, rs);
         return sib;
     }
diff --git a/graphics/java/android/renderscript/ScriptIntrinsicLUT.java b/rs/java/android/renderscript/ScriptIntrinsicLUT.java
similarity index 96%
rename from graphics/java/android/renderscript/ScriptIntrinsicLUT.java
rename to rs/java/android/renderscript/ScriptIntrinsicLUT.java
index 0f7ab38..c45c015 100644
--- a/graphics/java/android/renderscript/ScriptIntrinsicLUT.java
+++ b/rs/java/android/renderscript/ScriptIntrinsicLUT.java
@@ -30,7 +30,7 @@
     private final byte mCache[] = new byte[1024];
     private boolean mDirty = true;
 
-    private ScriptIntrinsicLUT(int id, RenderScript rs) {
+    private ScriptIntrinsicLUT(long id, RenderScript rs) {
         super(id, rs);
         mTables = Allocation.createSized(rs, Element.U8(rs), 1024);
         for (int ct=0; ct < 256; ct++) {
@@ -53,7 +53,7 @@
      * @return ScriptIntrinsicLUT
      */
     public static ScriptIntrinsicLUT create(RenderScript rs, Element e) {
-        int id = rs.nScriptIntrinsicCreate(3, e.getID(rs));
+        long id = rs.nScriptIntrinsicCreate(3, e.getID(rs));
         return new ScriptIntrinsicLUT(id, rs);
 
     }
diff --git a/graphics/java/android/renderscript/ScriptIntrinsicYuvToRGB.java b/rs/java/android/renderscript/ScriptIntrinsicYuvToRGB.java
similarity index 95%
rename from graphics/java/android/renderscript/ScriptIntrinsicYuvToRGB.java
rename to rs/java/android/renderscript/ScriptIntrinsicYuvToRGB.java
index 845625d..f942982 100644
--- a/graphics/java/android/renderscript/ScriptIntrinsicYuvToRGB.java
+++ b/rs/java/android/renderscript/ScriptIntrinsicYuvToRGB.java
@@ -27,7 +27,7 @@
 public final class ScriptIntrinsicYuvToRGB extends ScriptIntrinsic {
     private Allocation mInput;
 
-    ScriptIntrinsicYuvToRGB(int id, RenderScript rs) {
+    ScriptIntrinsicYuvToRGB(long id, RenderScript rs) {
         super(id, rs);
     }
 
@@ -43,7 +43,7 @@
      */
     public static ScriptIntrinsicYuvToRGB create(RenderScript rs, Element e) {
         // 6 comes from RS_SCRIPT_INTRINSIC_YUV_TO_RGB in rsDefines.h
-        int id = rs.nScriptIntrinsicCreate(6, e.getID(rs));
+        long id = rs.nScriptIntrinsicCreate(6, e.getID(rs));
         ScriptIntrinsicYuvToRGB si = new ScriptIntrinsicYuvToRGB(id, rs);
         return si;
     }
diff --git a/graphics/java/android/renderscript/Short2.java b/rs/java/android/renderscript/Short2.java
similarity index 100%
rename from graphics/java/android/renderscript/Short2.java
rename to rs/java/android/renderscript/Short2.java
diff --git a/graphics/java/android/renderscript/Short3.java b/rs/java/android/renderscript/Short3.java
similarity index 100%
rename from graphics/java/android/renderscript/Short3.java
rename to rs/java/android/renderscript/Short3.java
diff --git a/graphics/java/android/renderscript/Short4.java b/rs/java/android/renderscript/Short4.java
similarity index 100%
rename from graphics/java/android/renderscript/Short4.java
rename to rs/java/android/renderscript/Short4.java
diff --git a/graphics/java/android/renderscript/Type.java b/rs/java/android/renderscript/Type.java
similarity index 78%
rename from graphics/java/android/renderscript/Type.java
rename to rs/java/android/renderscript/Type.java
index e023739..7bdd360 100644
--- a/graphics/java/android/renderscript/Type.java
+++ b/rs/java/android/renderscript/Type.java
@@ -190,16 +190,18 @@
     }
 
 
-    Type(int id, RenderScript rs) {
+    Type(long id, RenderScript rs) {
         super(id, rs);
     }
 
     @Override
     void updateFromNative() {
+        // FIXME: rsaTypeGetNativeData needs 32-bit and 64-bit paths
+
         // We have 6 integer to obtain mDimX; mDimY; mDimZ;
         // mDimLOD; mDimFaces; mElement;
         int[] dataBuffer = new int[6];
-        mRS.nTypeGetNativeData(getID(mRS), dataBuffer);
+        mRS.nTypeGetNativeData((int)getID(mRS), dataBuffer);
 
         mDimX = dataBuffer[0];
         mDimY = dataBuffer[1];
@@ -216,6 +218,84 @@
     }
 
     /**
+     * @hide
+     * Utility function for creating basic 1D types. The type is
+     * created without mipmaps enabled.
+     *
+     * @param rs The RenderScript context
+     * @param e The Element for the Type
+     * @param dimX The X dimension, must be > 0
+     *
+     * @return Type
+     */
+    static public Type createX(RenderScript rs, Element e, int dimX) {
+        if (dimX < 1) {
+            throw new RSInvalidStateException("Dimension must be >= 1.");
+        }
+
+        long id = rs.nTypeCreate(e.getID(rs), dimX, 0, 0, false, false, 0);
+        Type t = new Type(id, rs);
+        t.mElement = e;
+        t.mDimX = dimX;
+        t.calcElementCount();
+        return t;
+    }
+
+    /**
+     * @hide
+     * Utility function for creating basic 2D types. The type is
+     * created without mipmaps or cubemaps.
+     *
+     * @param rs The RenderScript context
+     * @param e The Element for the Type
+     * @param dimX The X dimension, must be > 0
+     * @param dimY The Y dimension, must be > 0
+     *
+     * @return Type
+     */
+    static public Type createXY(RenderScript rs, Element e, int dimX, int dimY) {
+        if ((dimX < 1) || (dimY < 1)) {
+            throw new RSInvalidStateException("Dimension must be >= 1.");
+        }
+
+        long id = rs.nTypeCreate(e.getID(rs), dimX, dimY, 0, false, false, 0);
+        Type t = new Type(id, rs);
+        t.mElement = e;
+        t.mDimX = dimX;
+        t.mDimY = dimY;
+        t.calcElementCount();
+        return t;
+    }
+
+    /**
+     * @hide
+     * Utility function for creating basic 3D types. The type is
+     * created without mipmaps.
+     *
+     * @param rs The RenderScript context
+     * @param e The Element for the Type
+     * @param dimX The X dimension, must be > 0
+     * @param dimY The Y dimension, must be > 0
+     * @param dimZ The Z dimension, must be > 0
+     *
+     * @return Type
+     */
+    static public Type createXYZ(RenderScript rs, Element e, int dimX, int dimY, int dimZ) {
+        if ((dimX < 1) || (dimY < 1) || (dimZ < 1)) {
+            throw new RSInvalidStateException("Dimension must be >= 1.");
+        }
+
+        long id = rs.nTypeCreate(e.getID(rs), dimX, dimY, dimZ, false, false, 0);
+        Type t = new Type(id, rs);
+        t.mElement = e;
+        t.mDimX = dimX;
+        t.mDimY = dimY;
+        t.mDimZ = dimZ;
+        t.calcElementCount();
+        return t;
+    }
+
+    /**
      * Builder class for Type.
      *
      */
@@ -336,7 +416,7 @@
                 }
             }
 
-            int id = mRS.nTypeCreate(mElement.getID(mRS),
+            long id = mRS.nTypeCreate(mElement.getID(mRS),
                                      mDimX, mDimY, mDimZ, mDimMipmaps, mDimFaces, mYuv);
             Type t = new Type(id, mRS);
             t.mElement = mElement;
diff --git a/graphics/java/android/renderscript/package.html b/rs/java/android/renderscript/package.html
similarity index 100%
rename from graphics/java/android/renderscript/package.html
rename to rs/java/android/renderscript/package.html
diff --git a/graphics/jni/Android.mk b/rs/jni/Android.mk
similarity index 95%
rename from graphics/jni/Android.mk
rename to rs/jni/Android.mk
index e8beae53..cbb5b3b 100644
--- a/graphics/jni/Android.mk
+++ b/rs/jni/Android.mk
@@ -26,7 +26,7 @@
 	$(rs_generated_include_dir) \
 	$(call include-path-for, corecg graphics)
 
-LOCAL_CFLAGS +=
+LOCAL_CFLAGS += -Wno-unused-parameter
 
 LOCAL_LDLIBS := -lpthread
 LOCAL_ADDITIONAL_DEPENDENCIES := $(addprefix $(rs_generated_include_dir)/,rsgApiFuncDecl.h)
diff --git a/rs/jni/android_renderscript_RenderScript.cpp b/rs/jni/android_renderscript_RenderScript.cpp
new file mode 100644
index 0000000..80a5da2
--- /dev/null
+++ b/rs/jni/android_renderscript_RenderScript.cpp
@@ -0,0 +1,1659 @@
+/*
+ * Copyright (C) 2011-2012 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 "libRS_jni"
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <math.h>
+#include <utils/misc.h>
+
+#include <core/SkBitmap.h>
+#include <core/SkPixelRef.h>
+#include <core/SkStream.h>
+#include <core/SkTemplates.h>
+
+#include <androidfw/Asset.h>
+#include <androidfw/AssetManager.h>
+#include <androidfw/ResourceTypes.h>
+
+#include "jni.h"
+#include "JNIHelp.h"
+#include "android_runtime/AndroidRuntime.h"
+#include "android_runtime/android_view_Surface.h"
+#include "android_runtime/android_util_AssetManager.h"
+
+#include <rs.h>
+#include <rsEnv.h>
+#include <gui/Surface.h>
+#include <gui/GLConsumer.h>
+#include <gui/Surface.h>
+#include <android_runtime/android_graphics_SurfaceTexture.h>
+
+//#define LOG_API ALOGE
+#define LOG_API(...)
+
+using namespace android;
+
+#define PER_ARRAY_TYPE(flag, fnc, ...) {                                                \
+    jint len = 0;                                                                       \
+    void *ptr = NULL;                                                                   \
+    size_t typeBytes = 0;                                                               \
+    switch(dataType) {                                                                  \
+    case RS_TYPE_FLOAT_32:                                                              \
+        len = _env->GetArrayLength((jfloatArray)data);                                  \
+        ptr = _env->GetFloatArrayElements((jfloatArray)data, flag);                     \
+        typeBytes = 4;                                                                  \
+        fnc(__VA_ARGS__);                                                               \
+        _env->ReleaseFloatArrayElements((jfloatArray)data, (jfloat *)ptr, JNI_ABORT);   \
+        return;                                                                         \
+    case RS_TYPE_FLOAT_64:                                                              \
+        len = _env->GetArrayLength((jdoubleArray)data);                                 \
+        ptr = _env->GetDoubleArrayElements((jdoubleArray)data, flag);                   \
+        typeBytes = 8;                                                                  \
+        fnc(__VA_ARGS__);                                                               \
+        _env->ReleaseDoubleArrayElements((jdoubleArray)data, (jdouble *)ptr, JNI_ABORT);\
+        return;                                                                         \
+    case RS_TYPE_SIGNED_8:                                                              \
+    case RS_TYPE_UNSIGNED_8:                                                            \
+        len = _env->GetArrayLength((jbyteArray)data);                                   \
+        ptr = _env->GetByteArrayElements((jbyteArray)data, flag);                       \
+        typeBytes = 1;                                                                  \
+        fnc(__VA_ARGS__);                                                               \
+        _env->ReleaseByteArrayElements((jbyteArray)data, (jbyte*)ptr, JNI_ABORT);       \
+        return;                                                                         \
+    case RS_TYPE_SIGNED_16:                                                             \
+    case RS_TYPE_UNSIGNED_16:                                                           \
+        len = _env->GetArrayLength((jshortArray)data);                                  \
+        ptr = _env->GetShortArrayElements((jshortArray)data, flag);                     \
+        typeBytes = 2;                                                                  \
+        fnc(__VA_ARGS__);                                                               \
+        _env->ReleaseShortArrayElements((jshortArray)data, (jshort *)ptr, JNI_ABORT);   \
+        return;                                                                         \
+    case RS_TYPE_SIGNED_32:                                                             \
+    case RS_TYPE_UNSIGNED_32:                                                           \
+        len = _env->GetArrayLength((jintArray)data);                                    \
+        ptr = _env->GetIntArrayElements((jintArray)data, flag);                         \
+        typeBytes = 4;                                                                  \
+        fnc(__VA_ARGS__);                                                               \
+        _env->ReleaseIntArrayElements((jintArray)data, (jint *)ptr, JNI_ABORT);         \
+        return;                                                                         \
+    case RS_TYPE_SIGNED_64:                                                             \
+    case RS_TYPE_UNSIGNED_64:                                                           \
+        len = _env->GetArrayLength((jlongArray)data);                                   \
+        ptr = _env->GetLongArrayElements((jlongArray)data, flag);                       \
+        typeBytes = 8;                                                                  \
+        fnc(__VA_ARGS__);                                                               \
+        _env->ReleaseLongArrayElements((jlongArray)data, (jlong *)ptr, JNI_ABORT);      \
+        return;                                                                         \
+    default:                                                                            \
+        break;                                                                          \
+    }                                                                                   \
+}
+
+
+class AutoJavaStringToUTF8 {
+public:
+    AutoJavaStringToUTF8(JNIEnv* env, jstring str) : fEnv(env), fJStr(str) {
+        fCStr = env->GetStringUTFChars(str, NULL);
+        fLength = env->GetStringUTFLength(str);
+    }
+    ~AutoJavaStringToUTF8() {
+        fEnv->ReleaseStringUTFChars(fJStr, fCStr);
+    }
+    const char* c_str() const { return fCStr; }
+    jsize length() const { return fLength; }
+
+private:
+    JNIEnv*     fEnv;
+    jstring     fJStr;
+    const char* fCStr;
+    jsize       fLength;
+};
+
+class AutoJavaStringArrayToUTF8 {
+public:
+    AutoJavaStringArrayToUTF8(JNIEnv* env, jobjectArray strings, jsize stringsLength)
+    : mEnv(env), mStrings(strings), mStringsLength(stringsLength) {
+        mCStrings = NULL;
+        mSizeArray = NULL;
+        if (stringsLength > 0) {
+            mCStrings = (const char **)calloc(stringsLength, sizeof(char *));
+            mSizeArray = (size_t*)calloc(stringsLength, sizeof(size_t));
+            for (jsize ct = 0; ct < stringsLength; ct ++) {
+                jstring s = (jstring)mEnv->GetObjectArrayElement(mStrings, ct);
+                mCStrings[ct] = mEnv->GetStringUTFChars(s, NULL);
+                mSizeArray[ct] = mEnv->GetStringUTFLength(s);
+            }
+        }
+    }
+    ~AutoJavaStringArrayToUTF8() {
+        for (jsize ct=0; ct < mStringsLength; ct++) {
+            jstring s = (jstring)mEnv->GetObjectArrayElement(mStrings, ct);
+            mEnv->ReleaseStringUTFChars(s, mCStrings[ct]);
+        }
+        free(mCStrings);
+        free(mSizeArray);
+    }
+    const char **c_str() const { return mCStrings; }
+    size_t *c_str_len() const { return mSizeArray; }
+    jsize length() const { return mStringsLength; }
+
+private:
+    JNIEnv      *mEnv;
+    jobjectArray mStrings;
+    const char **mCStrings;
+    size_t      *mSizeArray;
+    jsize        mStringsLength;
+};
+
+// ---------------------------------------------------------------------------
+
+static jfieldID gContextId = 0;
+static jfieldID gNativeBitmapID = 0;
+static jfieldID gTypeNativeCache = 0;
+
+static void _nInit(JNIEnv *_env, jclass _this)
+{
+    gContextId             = _env->GetFieldID(_this, "mContext", "J");
+
+    jclass bitmapClass = _env->FindClass("android/graphics/Bitmap");
+    gNativeBitmapID = _env->GetFieldID(bitmapClass, "mNativeBitmap", "J");
+}
+
+// ---------------------------------------------------------------------------
+
+static void
+nContextFinish(JNIEnv *_env, jobject _this, jlong con)
+{
+    LOG_API("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);
+    jint len = _env->GetArrayLength(str);
+    jbyte * cptr = (jbyte *) _env->GetPrimitiveArrayCritical(str, 0);
+    rsAssignName((RsContext)con, (void *)obj, (const char *)cptr, len);
+    _env->ReleasePrimitiveArrayCritical(str, cptr, JNI_ABORT);
+}
+
+static jstring
+nGetName(JNIEnv *_env, jobject _this, jlong con, jlong obj)
+{
+    LOG_API("nGetName, con(%p), obj(%p)", (RsContext)con, (void *)obj);
+    const char *name = NULL;
+    rsaGetName((RsContext)con, (void *)obj, &name);
+    if(name == NULL || strlen(name) == 0) {
+        return NULL;
+    }
+    return _env->NewStringUTF(name);
+}
+
+static void
+nObjDestroy(JNIEnv *_env, jobject _this, jlong con, jlong obj)
+{
+    LOG_API("nObjDestroy, con(%p) obj(%p)", (RsContext)con, (void *)obj);
+    rsObjDestroy((RsContext)con, (void *)obj);
+}
+
+// ---------------------------------------------------------------------------
+
+static jlong
+nDeviceCreate(JNIEnv *_env, jobject _this)
+{
+    LOG_API("nDeviceCreate");
+    return (jlong)rsDeviceCreate();
+}
+
+static void
+nDeviceDestroy(JNIEnv *_env, jobject _this, jlong dev)
+{
+    LOG_API("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);
+    return rsDeviceSetConfig((RsDevice)dev, (RsDeviceParam)p, value);
+}
+
+static jlong
+nContextCreate(JNIEnv *_env, jobject _this, jlong dev, jint ver, jint sdkVer, jint ct)
+{
+    LOG_API("nContextCreate");
+    return (jlong)rsContextCreate((RsDevice)dev, ver, sdkVer, (RsContextType)ct, 0);
+}
+
+static jlong
+nContextCreateGL(JNIEnv *_env, jobject _this, jlong dev, jint ver, jint sdkVer,
+                 jint colorMin, jint colorPref,
+                 jint alphaMin, jint alphaPref,
+                 jint depthMin, jint depthPref,
+                 jint stencilMin, jint stencilPref,
+                 jint samplesMin, jint samplesPref, jfloat samplesQ,
+                 jint dpi)
+{
+    RsSurfaceConfig sc;
+    sc.alphaMin = alphaMin;
+    sc.alphaPref = alphaPref;
+    sc.colorMin = colorMin;
+    sc.colorPref = colorPref;
+    sc.depthMin = depthMin;
+    sc.depthPref = depthPref;
+    sc.samplesMin = samplesMin;
+    sc.samplesPref = samplesPref;
+    sc.samplesQ = samplesQ;
+
+    LOG_API("nContextCreateGL");
+    return (jlong)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);
+    rsContextSetPriority((RsContext)con, p);
+}
+
+
+
+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);
+
+    ANativeWindow * window = NULL;
+    if (wnd == NULL) {
+
+    } else {
+        window = android_view_Surface_getNativeWindow(_env, wnd).get();
+    }
+
+    rsContextSetSurface((RsContext)con, width, height, window);
+}
+
+static void
+nContextDestroy(JNIEnv *_env, jobject _this, jlong con)
+{
+    LOG_API("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);
+    rsContextDump((RsContext)con, bits);
+}
+
+static void
+nContextPause(JNIEnv *_env, jobject _this, jlong con)
+{
+    LOG_API("nContextPause, con(%p)", (RsContext)con);
+    rsContextPause((RsContext)con);
+}
+
+static void
+nContextResume(JNIEnv *_env, jobject _this, jlong con)
+{
+    LOG_API("nContextResume, con(%p)", (RsContext)con);
+    rsContextResume((RsContext)con);
+}
+
+
+static jstring
+nContextGetErrorMessage(JNIEnv *_env, jobject _this, jlong con)
+{
+    LOG_API("nContextGetErrorMessage, con(%p)", (RsContext)con);
+    char buf[1024];
+
+    size_t receiveLen;
+    uint32_t subID;
+    int id = rsContextGetMessage((RsContext)con,
+                                 buf, sizeof(buf),
+                                 &receiveLen, sizeof(receiveLen),
+                                 &subID, sizeof(subID));
+    if (!id && receiveLen) {
+        ALOGV("message receive buffer too small.  %i", receiveLen);
+    }
+    return _env->NewStringUTF(buf);
+}
+
+static jint
+nContextGetUserMessage(JNIEnv *_env, jobject _this, jlong con, jintArray data)
+{
+    jint len = _env->GetArrayLength(data);
+    LOG_API("nContextGetMessage, con(%p), len(%i)", (RsContext)con, len);
+    jint *ptr = _env->GetIntArrayElements(data, NULL);
+    size_t receiveLen;
+    uint32_t subID;
+    int id = rsContextGetMessage((RsContext)con,
+                                 ptr, len * 4,
+                                 &receiveLen, sizeof(receiveLen),
+                                 &subID, sizeof(subID));
+    if (!id && receiveLen) {
+        ALOGV("message receive buffer too small.  %i", receiveLen);
+    }
+    _env->ReleaseIntArrayElements(data, ptr, 0);
+    return (jint)id;
+}
+
+static jint
+nContextPeekMessage(JNIEnv *_env, jobject _this, jlong con, jintArray auxData)
+{
+    LOG_API("nContextPeekMessage, con(%p)", (RsContext)con);
+    jint *auxDataPtr = _env->GetIntArrayElements(auxData, NULL);
+    size_t receiveLen;
+    uint32_t subID;
+    int id = rsContextPeekMessage((RsContext)con, &receiveLen, sizeof(receiveLen),
+                                  &subID, sizeof(subID));
+    auxDataPtr[0] = (jint)subID;
+    auxDataPtr[1] = (jint)receiveLen;
+    _env->ReleaseIntArrayElements(auxData, auxDataPtr, 0);
+    return (jint)id;
+}
+
+static void nContextInitToClient(JNIEnv *_env, jobject _this, jlong con)
+{
+    LOG_API("nContextInitToClient, con(%p)", (RsContext)con);
+    rsContextInitToClient((RsContext)con);
+}
+
+static void nContextDeinitToClient(JNIEnv *_env, jobject _this, jlong con)
+{
+    LOG_API("nContextDeinitToClient, con(%p)", (RsContext)con);
+    rsContextDeinitToClient((RsContext)con);
+}
+
+static void
+nContextSendMessage(JNIEnv *_env, jobject _this, jlong con, jint id, jintArray data)
+{
+    jint *ptr = NULL;
+    jint len = 0;
+    if (data) {
+        len = _env->GetArrayLength(data);
+        ptr = _env->GetIntArrayElements(data, NULL);
+    }
+    LOG_API("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);
+    }
+}
+
+
+
+static jlong
+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)rsElementCreate((RsContext)con, (RsDataType)type, (RsDataKind)kind, norm, size);
+}
+
+static jlong
+nElementCreate2(JNIEnv *_env, jobject _this, jlong con,
+                jintArray _ids, jobjectArray _names, jintArray _arraySizes)
+{
+    int fieldCount = _env->GetArrayLength(_ids);
+    LOG_API("nElementCreate2, con(%p)", (RsContext)con);
+
+    jint *ids = _env->GetIntArrayElements(_ids, NULL);
+    jint *arraySizes = _env->GetIntArrayElements(_arraySizes, NULL);
+
+    AutoJavaStringArrayToUTF8 names(_env, _names, fieldCount);
+
+    const char **nameArray = names.c_str();
+    size_t *sizeArray = names.c_str_len();
+
+    jlong id = (jlong)rsElementCreate2((RsContext)con,
+                                     (RsElement *)ids, fieldCount,
+                                     nameArray, fieldCount * sizeof(size_t),  sizeArray,
+                                     (const uint32_t *)arraySizes, fieldCount);
+
+    _env->ReleaseIntArrayElements(_ids, ids, JNI_ABORT);
+    _env->ReleaseIntArrayElements(_arraySizes, arraySizes, JNI_ABORT);
+    return (jlong)id;
+}
+
+static void
+nElementGetNativeData(JNIEnv *_env, jobject _this, jlong con, jlong id, jintArray _elementData)
+{
+    int dataSize = _env->GetArrayLength(_elementData);
+    LOG_API("nElementGetNativeData, con(%p)", (RsContext)con);
+
+    // we will pack mType; mKind; mNormalized; mVectorSize; NumSubElements
+    assert(dataSize == 5);
+
+    uint32_t elementData[5];
+    rsaElementGetNativeData((RsContext)con, (RsElement)id, elementData, dataSize);
+
+    for(jint i = 0; i < dataSize; i ++) {
+        _env->SetIntArrayRegion(_elementData, i, 1, (const jint*)&elementData[i]);
+    }
+}
+
+
+static void
+nElementGetSubElements(JNIEnv *_env, jobject _this, jlong con, jlong id,
+                       jintArray _IDs,
+                       jobjectArray _names,
+                       jintArray _arraySizes)
+{
+    int dataSize = _env->GetArrayLength(_IDs);
+    LOG_API("nElementGetSubElements, con(%p)", (RsContext)con);
+
+    uint32_t *ids = (uint32_t *)malloc((uint32_t)dataSize * sizeof(uint32_t));
+    const char **names = (const char **)malloc((uint32_t)dataSize * sizeof(const char *));
+    uint32_t *arraySizes = (uint32_t *)malloc((uint32_t)dataSize * sizeof(uint32_t));
+
+    rsaElementGetSubElements((RsContext)con, (RsElement)id, ids, names, arraySizes, (uint32_t)dataSize);
+
+    for(jint i = 0; i < dataSize; i++) {
+        _env->SetObjectArrayElement(_names, i, _env->NewStringUTF(names[i]));
+        _env->SetIntArrayRegion(_IDs, i, 1, (const jint*)&ids[i]);
+        _env->SetIntArrayRegion(_arraySizes, i, 1, (const jint*)&arraySizes[i]);
+    }
+
+    free(ids);
+    free(names);
+    free(arraySizes);
+}
+
+// -----------------------------------
+
+static jlong
+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);
+
+    return (jlong)rsTypeCreate((RsContext)con, (RsElement)eid, dimx, dimy, dimz, mips, faces, yuv);
+}
+
+static void
+nTypeGetNativeData(JNIEnv *_env, jobject _this, jlong con, jlong id, jintArray _typeData)
+{
+    // We are packing 6 items: mDimX; mDimY; mDimZ;
+    // mDimLOD; mDimFaces; mElement; into typeData
+    int elementCount = _env->GetArrayLength(_typeData);
+
+    assert(elementCount == 6);
+    LOG_API("nTypeGetNativeData, con(%p)", (RsContext)con);
+
+    uint32_t typeData[6];
+    rsaTypeGetNativeData((RsContext)con, (RsType)id, typeData, 6);
+
+    for(jint i = 0; i < elementCount; i ++) {
+        _env->SetIntArrayRegion(_typeData, i, 1, (const jint*)&typeData[i]);
+    }
+}
+
+// -----------------------------------
+
+static jlong
+nAllocationCreateTyped(JNIEnv *_env, jobject _this, jlong con, jlong type, jint mips, jint usage, jint pointer)
+{
+    LOG_API("nAllocationCreateTyped, con(%p), type(%p), mip(%i), usage(%i), ptr(%p)", (RsContext)con, (RsElement)type, mips, usage, (void *)pointer);
+    return (jlong) rsAllocationCreateTyped((RsContext)con, (RsType)type, (RsAllocationMipmapControl)mips, (uint32_t)usage, (uint32_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);
+    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);
+
+    IGraphicBufferProducer *v = (IGraphicBufferProducer *)rsAllocationGetSurface((RsContext)con, (RsAllocation)a);
+    sp<IGraphicBufferProducer> bp = v;
+    v->decStrong(NULL);
+
+    jobject o = android_view_Surface_createFromIGraphicBufferProducer(_env, bp);
+    return o;
+}
+
+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);
+
+    sp<Surface> s;
+    if (sur != 0) {
+        s = android_view_Surface_getSurface(_env, sur);
+    }
+
+    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);
+    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);
+    rsAllocationIoReceive((RsContext)con, (RsAllocation)alloc);
+}
+
+
+static void
+nAllocationGenerateMipmaps(JNIEnv *_env, jobject _this, jlong con, jlong alloc)
+{
+    LOG_API("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)
+{
+    SkBitmap const * nativeBitmap =
+            (SkBitmap const *)_env->GetLongField(jbitmap, gNativeBitmapID);
+    const SkBitmap& bitmap(*nativeBitmap);
+
+    bitmap.lockPixels();
+    const void* ptr = bitmap.getPixels();
+    jlong id = (jlong)rsAllocationCreateFromBitmap((RsContext)con,
+                                                  (RsType)type, (RsAllocationMipmapControl)mip,
+                                                  ptr, bitmap.getSize(), usage);
+    bitmap.unlockPixels();
+    return id;
+}
+
+static jlong
+nAllocationCreateBitmapBackedAllocation(JNIEnv *_env, jobject _this, jlong con, jlong type, jint mip, jobject jbitmap, jint usage)
+{
+    SkBitmap const * nativeBitmap =
+            (SkBitmap const *)_env->GetLongField(jbitmap, gNativeBitmapID);
+    const SkBitmap& bitmap(*nativeBitmap);
+
+    bitmap.lockPixels();
+    const void* ptr = bitmap.getPixels();
+    jlong id = (jlong)rsAllocationCreateTyped((RsContext)con,
+                                            (RsType)type, (RsAllocationMipmapControl)mip,
+                                            (uint32_t)usage, (size_t)ptr);
+    bitmap.unlockPixels();
+    return id;
+}
+
+static jlong
+nAllocationCubeCreateFromBitmap(JNIEnv *_env, jobject _this, jlong con, jlong type, jint mip, jobject jbitmap, jint usage)
+{
+    SkBitmap const * nativeBitmap =
+            (SkBitmap const *)_env->GetLongField(jbitmap, gNativeBitmapID);
+    const SkBitmap& bitmap(*nativeBitmap);
+
+    bitmap.lockPixels();
+    const void* ptr = bitmap.getPixels();
+    jlong id = (jlong)rsAllocationCubeCreateFromBitmap((RsContext)con,
+                                                      (RsType)type, (RsAllocationMipmapControl)mip,
+                                                      ptr, bitmap.getSize(), usage);
+    bitmap.unlockPixels();
+    return id;
+}
+
+static void
+nAllocationCopyFromBitmap(JNIEnv *_env, jobject _this, jlong con, jlong alloc, jobject jbitmap)
+{
+    SkBitmap const * nativeBitmap =
+            (SkBitmap const *)_env->GetLongField(jbitmap, gNativeBitmapID);
+    const SkBitmap& bitmap(*nativeBitmap);
+    int w = bitmap.width();
+    int h = bitmap.height();
+
+    bitmap.lockPixels();
+    const void* ptr = bitmap.getPixels();
+    rsAllocation2DData((RsContext)con, (RsAllocation)alloc, 0, 0,
+                       0, RS_ALLOCATION_CUBEMAP_FACE_POSITIVE_X,
+                       w, h, ptr, bitmap.getSize(), 0);
+    bitmap.unlockPixels();
+}
+
+static void
+nAllocationCopyToBitmap(JNIEnv *_env, jobject _this, jlong con, jlong alloc, jobject jbitmap)
+{
+    SkBitmap const * nativeBitmap =
+            (SkBitmap const *)_env->GetLongField(jbitmap, gNativeBitmapID);
+    const SkBitmap& bitmap(*nativeBitmap);
+
+    bitmap.lockPixels();
+    void* ptr = bitmap.getPixels();
+    rsAllocationCopyToBitmap((RsContext)con, (RsAllocation)alloc, ptr, bitmap.getSize());
+    bitmap.unlockPixels();
+    bitmap.notifyPixelsChanged();
+}
+
+static void ReleaseBitmapCallback(void *bmp)
+{
+    SkBitmap const * nativeBitmap = (SkBitmap const *)bmp;
+    nativeBitmap->unlockPixels();
+}
+
+
+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(NULL, rsAllocation1DData, (RsContext)con, alloc, offset, lod, count, ptr, sizeBytes);
+}
+
+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)
+{
+    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);
+    jbyte *ptr = _env->GetByteArrayElements(data, NULL);
+    rsAllocation1DElementData((RsContext)con, (RsAllocation)alloc, offset, lod, ptr, sizeBytes, compIdx);
+    _env->ReleaseByteArrayElements(data, ptr, JNI_ABORT);
+}
+
+static void
+nAllocationData2D(JNIEnv *_env, jobject _this, jlong con, jlong _alloc, jint xoff, jint yoff, jint lod, jint _face,
+                  jint w, jint h, jobject data, jint sizeBytes, jint dataType)
+{
+    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);
+    PER_ARRAY_TYPE(NULL, rsAllocation2DData, (RsContext)con, alloc, xoff, yoff, lod, face, w, h, ptr, sizeBytes, 0);
+}
+
+static void
+nAllocationData2D_alloc(JNIEnv *_env, jobject _this, jlong con,
+                        jlong dstAlloc, jint dstXoff, jint dstYoff,
+                        jint dstMip, jint dstFace,
+                        jint width, jint height,
+                        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);
+
+    rsAllocationCopy2DRange((RsContext)con,
+                            (RsAllocation)dstAlloc,
+                            dstXoff, dstYoff,
+                            dstMip, dstFace,
+                            width, height,
+                            (RsAllocation)srcAlloc,
+                            srcXoff, srcYoff,
+                            srcMip, srcFace);
+}
+
+static void
+nAllocationData3D(JNIEnv *_env, jobject _this, jlong con, jlong _alloc, jint xoff, jint yoff, jint zoff, jint lod,
+                    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);
+    PER_ARRAY_TYPE(NULL, rsAllocation3DData, (RsContext)con, alloc, xoff, yoff, zoff, lod, w, h, d, ptr, sizeBytes, 0);
+}
+
+static void
+nAllocationData3D_alloc(JNIEnv *_env, jobject _this, jlong con,
+                        jlong dstAlloc, jint dstXoff, jint dstYoff, jint dstZoff,
+                        jint dstMip,
+                        jint width, jint height, jint depth,
+                        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);
+
+    rsAllocationCopy3DRange((RsContext)con,
+                            (RsAllocation)dstAlloc,
+                            dstXoff, dstYoff, dstZoff, dstMip,
+                            width, height, depth,
+                            (RsAllocation)srcAlloc,
+                            srcXoff, srcYoff, srcZoff, srcMip);
+}
+
+
+static void
+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);
+    PER_ARRAY_TYPE(0, rsAllocationRead, (RsContext)con, alloc, ptr, len * typeBytes);
+}
+
+static void
+nAllocationRead1D(JNIEnv *_env, jobject _this, jlong con, jlong _alloc, jint offset, jint lod,
+                  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);
+    PER_ARRAY_TYPE(0, rsAllocation1DRead, (RsContext)con, alloc, offset, lod, count, ptr, sizeBytes);
+}
+
+static void
+nAllocationRead2D(JNIEnv *_env, jobject _this, jlong con, jlong _alloc, jint xoff, jint yoff, jint lod, jint _face,
+                  jint w, jint h, jobject data, int sizeBytes, int dataType)
+{
+    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, (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);
+    return (jlong) 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);
+    rsAllocationResize1D((RsContext)con, (RsAllocation)alloc, dimX);
+}
+
+// -----------------------------------
+
+static jlong
+nFileA3DCreateFromAssetStream(JNIEnv *_env, jobject _this, jlong con, jlong native_asset)
+{
+    Asset* asset = reinterpret_cast<Asset*>(native_asset);
+    ALOGV("______nFileA3D %p", asset);
+
+    jlong id = (jlong)rsaFileA3DCreateFromMemory((RsContext)con, asset->getBuffer(false), asset->getLength());
+    return id;
+}
+
+static jlong
+nFileA3DCreateFromAsset(JNIEnv *_env, jobject _this, jlong con, jobject _assetMgr, jstring _path)
+{
+    AssetManager* mgr = assetManagerForJavaObject(_env, _assetMgr);
+    if (mgr == NULL) {
+        return 0;
+    }
+
+    AutoJavaStringToUTF8 str(_env, _path);
+    Asset* asset = mgr->open(str.c_str(), Asset::ACCESS_BUFFER);
+    if (asset == NULL) {
+        return 0;
+    }
+
+    jlong id = (jlong)rsaFileA3DCreateFromAsset((RsContext)con, asset);
+    return id;
+}
+
+static jlong
+nFileA3DCreateFromFile(JNIEnv *_env, jobject _this, jlong con, jstring fileName)
+{
+    AutoJavaStringToUTF8 fileNameUTF(_env, fileName);
+    jlong id = (jlong)rsaFileA3DCreateFromFile((RsContext)con, fileNameUTF.c_str());
+
+    return id;
+}
+
+static jint
+nFileA3DGetNumIndexEntries(JNIEnv *_env, jobject _this, jlong con, jlong fileA3D)
+{
+    int32_t numEntries = 0;
+    rsaFileA3DGetNumIndexEntries((RsContext)con, &numEntries, (RsFile)fileA3D);
+    return (jint)numEntries;
+}
+
+static void
+nFileA3DGetIndexEntries(JNIEnv *_env, jobject _this, jlong con, jlong fileA3D, jint numEntries, jintArray _ids, jobjectArray _entries)
+{
+    ALOGV("______nFileA3D %p", (RsFile) fileA3D);
+    RsFileIndexEntry *fileEntries = (RsFileIndexEntry*)malloc((uint32_t)numEntries * sizeof(RsFileIndexEntry));
+
+    rsaFileA3DGetIndexEntries((RsContext)con, fileEntries, (uint32_t)numEntries, (RsFile)fileA3D);
+
+    for(jint i = 0; i < numEntries; i ++) {
+        _env->SetObjectArrayElement(_entries, i, _env->NewStringUTF(fileEntries[i].objectName));
+        _env->SetIntArrayRegion(_ids, i, 1, (const jint*)&fileEntries[i].classID);
+    }
+
+    free(fileEntries);
+}
+
+static jlong
+nFileA3DGetEntryByIndex(JNIEnv *_env, jobject _this, jlong con, jlong fileA3D, jint index)
+{
+    ALOGV("______nFileA3D %p", (RsFile) fileA3D);
+    jlong id = (jlong)rsaFileA3DGetEntryByIndex((RsContext)con, (uint32_t)index, (RsFile)fileA3D);
+    return id;
+}
+
+// -----------------------------------
+
+static jlong
+nFontCreateFromFile(JNIEnv *_env, jobject _this, jlong con,
+                    jstring fileName, jfloat fontSize, jint dpi)
+{
+    AutoJavaStringToUTF8 fileNameUTF(_env, fileName);
+    jlong id = (jlong)rsFontCreateFromFile((RsContext)con,
+                                         fileNameUTF.c_str(), fileNameUTF.length(),
+                                         fontSize, dpi);
+
+    return id;
+}
+
+static jlong
+nFontCreateFromAssetStream(JNIEnv *_env, jobject _this, jlong con,
+                           jstring name, jfloat fontSize, jint dpi, jlong native_asset)
+{
+    Asset* asset = reinterpret_cast<Asset*>(native_asset);
+    AutoJavaStringToUTF8 nameUTF(_env, name);
+
+    jlong id = (jlong)rsFontCreateFromMemory((RsContext)con,
+                                           nameUTF.c_str(), nameUTF.length(),
+                                           fontSize, dpi,
+                                           asset->getBuffer(false), asset->getLength());
+    return id;
+}
+
+static jlong
+nFontCreateFromAsset(JNIEnv *_env, jobject _this, jlong con, jobject _assetMgr, jstring _path,
+                     jfloat fontSize, jint dpi)
+{
+    AssetManager* mgr = assetManagerForJavaObject(_env, _assetMgr);
+    if (mgr == NULL) {
+        return 0;
+    }
+
+    AutoJavaStringToUTF8 str(_env, _path);
+    Asset* asset = mgr->open(str.c_str(), Asset::ACCESS_BUFFER);
+    if (asset == NULL) {
+        return 0;
+    }
+
+    jlong id = (jlong)rsFontCreateFromMemory((RsContext)con,
+                                           str.c_str(), str.length(),
+                                           fontSize, dpi,
+                                           asset->getBuffer(false), asset->getLength());
+    delete asset;
+    return id;
+}
+
+// -----------------------------------
+
+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);
+    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);
+    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);
+    int value = 0;
+    rsScriptGetVarV((RsContext)con, (RsScript)script, slot, &value, sizeof(value));
+    return value;
+}
+
+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);
+    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);
+    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);
+    jlong value = 0;
+    rsScriptGetVarV((RsContext)con, (RsScript)script, slot, &value, sizeof(value));
+    return value;
+}
+
+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);
+    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);
+    jfloat value = 0;
+    rsScriptGetVarV((RsContext)con, (RsScript)script, slot, &value, sizeof(value));
+    return value;
+}
+
+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);
+    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);
+    jdouble value = 0;
+    rsScriptGetVarV((RsContext)con, (RsScript)script, slot, &value, sizeof(value));
+    return value;
+}
+
+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);
+    jint len = _env->GetArrayLength(data);
+    jbyte *ptr = _env->GetByteArrayElements(data, NULL);
+    rsScriptSetVarV((RsContext)con, (RsScript)script, slot, ptr, len);
+    _env->ReleaseByteArrayElements(data, ptr, JNI_ABORT);
+}
+
+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);
+    jint len = _env->GetArrayLength(data);
+    jbyte *ptr = _env->GetByteArrayElements(data, NULL);
+    rsScriptGetVarV((RsContext)con, (RsScript)script, slot, ptr, len);
+    _env->ReleaseByteArrayElements(data, ptr, JNI_ABORT);
+}
+
+static void
+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);
+    jint len = _env->GetArrayLength(data);
+    jbyte *ptr = _env->GetByteArrayElements(data, NULL);
+    jint dimsLen = _env->GetArrayLength(dims) * sizeof(int);
+    jint *dimsPtr = _env->GetIntArrayElements(dims, NULL);
+    rsScriptSetVarVE((RsContext)con, (RsScript)script, slot, ptr, len, (RsElement)elem,
+                     (const size_t*) dimsPtr, dimsLen);
+    _env->ReleaseByteArrayElements(data, ptr, JNI_ABORT);
+    _env->ReleaseIntArrayElements(dims, dimsPtr, JNI_ABORT);
+}
+
+
+static void
+nScriptSetTimeZone(JNIEnv *_env, jobject _this, jlong con, jlong script, jbyteArray timeZone)
+{
+    LOG_API("nScriptCSetTimeZone, con(%p), s(%p)", (RsContext)con, (void *)script);
+
+    jint length = _env->GetArrayLength(timeZone);
+    jbyte* timeZone_ptr;
+    timeZone_ptr = (jbyte *) _env->GetPrimitiveArrayCritical(timeZone, (jboolean *)0);
+
+    rsScriptSetTimeZone((RsContext)con, (RsScript)script, (const char *)timeZone_ptr, length);
+
+    if (timeZone_ptr) {
+        _env->ReleasePrimitiveArrayCritical(timeZone, timeZone_ptr, 0);
+    }
+}
+
+static void
+nScriptInvoke(JNIEnv *_env, jobject _this, jlong con, jlong obj, jint slot)
+{
+    LOG_API("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);
+    jint len = _env->GetArrayLength(data);
+    jbyte *ptr = _env->GetByteArrayElements(data, NULL);
+    rsScriptInvokeV((RsContext)con, (RsScript)script, slot, ptr, len);
+    _env->ReleaseByteArrayElements(data, ptr, JNI_ABORT);
+}
+
+static void
+nScriptForEach(JNIEnv *_env, jobject _this, jlong con,
+               jlong script, jint slot, jlong ain, jlong aout)
+{
+    LOG_API("nScriptForEach, con(%p), s(%p), slot(%i)", (RsContext)con, (void *)script, slot);
+    rsScriptForEach((RsContext)con, (RsScript)script, slot, (RsAllocation)ain, (RsAllocation)aout, NULL, 0, NULL, 0);
+}
+static void
+nScriptForEachV(JNIEnv *_env, jobject _this, jlong con,
+                jlong script, jint slot, jlong ain, jlong aout, jbyteArray params)
+{
+    LOG_API("nScriptForEach, con(%p), s(%p), slot(%i)", (RsContext)con, (void *)script, slot);
+    jint len = _env->GetArrayLength(params);
+    jbyte *ptr = _env->GetByteArrayElements(params, NULL);
+    rsScriptForEach((RsContext)con, (RsScript)script, slot, (RsAllocation)ain, (RsAllocation)aout, ptr, len, NULL, 0);
+    _env->ReleaseByteArrayElements(params, ptr, JNI_ABORT);
+}
+
+static void
+nScriptForEachClipped(JNIEnv *_env, jobject _this, jlong con,
+                      jlong script, jint slot, jlong ain, jlong aout,
+                      jint xstart, jint xend,
+                      jint ystart, jint yend, jint zstart, jint zend)
+{
+    LOG_API("nScriptForEachClipped, con(%p), s(%p), slot(%i)", (RsContext)con, (void *)script, slot);
+    RsScriptCall sc;
+    sc.xStart = xstart;
+    sc.xEnd = xend;
+    sc.yStart = ystart;
+    sc.yEnd = yend;
+    sc.zStart = zstart;
+    sc.zEnd = zend;
+    sc.strategy = RS_FOR_EACH_STRATEGY_DONT_CARE;
+    sc.arrayStart = 0;
+    sc.arrayEnd = 0;
+    rsScriptForEach((RsContext)con, (RsScript)script, slot, (RsAllocation)ain, (RsAllocation)aout, NULL, 0, &sc, sizeof(sc));
+}
+
+static void
+nScriptForEachClippedV(JNIEnv *_env, jobject _this, jlong con,
+                       jlong script, jint slot, jlong ain, jlong aout,
+                       jbyteArray params, jint xstart, jint xend,
+                       jint ystart, jint yend, jint zstart, jint zend)
+{
+    LOG_API("nScriptForEachClipped, con(%p), s(%p), slot(%i)", (RsContext)con, (void *)script, slot);
+    jint len = _env->GetArrayLength(params);
+    jbyte *ptr = _env->GetByteArrayElements(params, NULL);
+    RsScriptCall sc;
+    sc.xStart = xstart;
+    sc.xEnd = xend;
+    sc.yStart = ystart;
+    sc.yEnd = yend;
+    sc.zStart = zstart;
+    sc.zEnd = zend;
+    sc.strategy = RS_FOR_EACH_STRATEGY_DONT_CARE;
+    sc.arrayStart = 0;
+    sc.arrayEnd = 0;
+    rsScriptForEach((RsContext)con, (RsScript)script, slot, (RsAllocation)ain, (RsAllocation)aout, ptr, len, &sc, sizeof(sc));
+    _env->ReleaseByteArrayElements(params, ptr, JNI_ABORT);
+}
+
+// -----------------------------------
+
+static jlong
+nScriptCCreate(JNIEnv *_env, jobject _this, jlong con,
+               jstring resName, jstring cacheDir,
+               jbyteArray scriptRef, jint length)
+{
+    LOG_API("nScriptCCreate, con(%p)", (RsContext)con);
+
+    AutoJavaStringToUTF8 resNameUTF(_env, resName);
+    AutoJavaStringToUTF8 cacheDirUTF(_env, cacheDir);
+    jlong ret = 0;
+    jbyte* script_ptr = NULL;
+    jint _exception = 0;
+    jint remaining;
+    if (!scriptRef) {
+        _exception = 1;
+        //jniThrowException(_env, "java/lang/IllegalArgumentException", "script == null");
+        goto exit;
+    }
+    if (length < 0) {
+        _exception = 1;
+        //jniThrowException(_env, "java/lang/IllegalArgumentException", "length < 0");
+        goto exit;
+    }
+    remaining = _env->GetArrayLength(scriptRef);
+    if (remaining < length) {
+        _exception = 1;
+        //jniThrowException(_env, "java/lang/IllegalArgumentException",
+        //        "length > script.length - offset");
+        goto exit;
+    }
+    script_ptr = (jbyte *)
+        _env->GetPrimitiveArrayCritical(scriptRef, (jboolean *)0);
+
+    //rsScriptCSetText((RsContext)con, (const char *)script_ptr, length);
+
+    ret = (jlong)rsScriptCCreate((RsContext)con,
+                                resNameUTF.c_str(), resNameUTF.length(),
+                                cacheDirUTF.c_str(), cacheDirUTF.length(),
+                                (const char *)script_ptr, length);
+
+exit:
+    if (script_ptr) {
+        _env->ReleasePrimitiveArrayCritical(scriptRef, script_ptr,
+                _exception ? JNI_ABORT: 0);
+    }
+
+    return (jlong)ret;
+}
+
+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);
+    return (jlong)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);
+    return (jlong)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);
+    return (jlong)rsScriptFieldIDCreate((RsContext)con, (RsScript)sid, slot);
+}
+
+static jlong
+nScriptGroupCreate(JNIEnv *_env, jobject _this, jlong con, jintArray _kernels, jintArray _src,
+    jintArray _dstk, jintArray _dstf, jintArray _types)
+{
+    LOG_API("nScriptGroupCreate, con(%p)", (RsContext)con);
+
+    jint kernelsLen = _env->GetArrayLength(_kernels) * sizeof(int);
+    jint *kernelsPtr = _env->GetIntArrayElements(_kernels, NULL);
+    jint srcLen = _env->GetArrayLength(_src) * sizeof(int);
+    jint *srcPtr = _env->GetIntArrayElements(_src, NULL);
+    jint dstkLen = _env->GetArrayLength(_dstk) * sizeof(int);
+    jint *dstkPtr = _env->GetIntArrayElements(_dstk, NULL);
+    jint dstfLen = _env->GetArrayLength(_dstf) * sizeof(int);
+    jint *dstfPtr = _env->GetIntArrayElements(_dstf, NULL);
+    jint typesLen = _env->GetArrayLength(_types) * sizeof(int);
+    jint *typesPtr = _env->GetIntArrayElements(_types, NULL);
+
+    int id = (int)rsScriptGroupCreate((RsContext)con,
+                               (RsScriptKernelID *)kernelsPtr, kernelsLen,
+                               (RsScriptKernelID *)srcPtr, srcLen,
+                               (RsScriptKernelID *)dstkPtr, dstkLen,
+                               (RsScriptFieldID *)dstfPtr, dstfLen,
+                               (RsType *)typesPtr, typesLen);
+
+    _env->ReleaseIntArrayElements(_kernels, kernelsPtr, 0);
+    _env->ReleaseIntArrayElements(_src, srcPtr, 0);
+    _env->ReleaseIntArrayElements(_dstk, dstkPtr, 0);
+    _env->ReleaseIntArrayElements(_dstf, dstfPtr, 0);
+    _env->ReleaseIntArrayElements(_types, typesPtr, 0);
+    return id;
+}
+
+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);
+    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);
+    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);
+    rsScriptGroupExecute((RsContext)con, (RsScriptGroup)gid);
+}
+
+// ---------------------------------------------------------------------------
+
+static jlong
+nProgramStoreCreate(JNIEnv *_env, jobject _this, jlong con,
+                    jboolean colorMaskR, jboolean colorMaskG, jboolean colorMaskB, jboolean colorMaskA,
+                    jboolean depthMask, jboolean ditherEnable,
+                    jint srcFunc, jint destFunc,
+                    jint depthFunc)
+{
+    LOG_API("nProgramStoreCreate, con(%p)", (RsContext)con);
+    return (jlong)rsProgramStoreCreate((RsContext)con, colorMaskR, colorMaskG, colorMaskB, colorMaskA,
+                                      depthMask, ditherEnable, (RsBlendSrcFunc)srcFunc,
+                                      (RsBlendDstFunc)destFunc, (RsDepthFunc)depthFunc);
+}
+
+// ---------------------------------------------------------------------------
+
+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);
+    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);
+    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);
+    rsProgramBindSampler((RsContext)con, (RsProgramFragment)vpf, slot, (RsSampler)a);
+}
+
+// ---------------------------------------------------------------------------
+
+static jlong
+nProgramFragmentCreate(JNIEnv *_env, jobject _this, jlong con, jstring shader,
+                       jobjectArray texNames, jintArray params)
+{
+    AutoJavaStringToUTF8 shaderUTF(_env, shader);
+    jint *paramPtr = _env->GetIntArrayElements(params, NULL);
+    jint paramLen = _env->GetArrayLength(params);
+
+    int texCount = _env->GetArrayLength(texNames);
+    AutoJavaStringArrayToUTF8 names(_env, texNames, texCount);
+    const char ** nameArray = names.c_str();
+    size_t* sizeArray = names.c_str_len();
+
+    LOG_API("nProgramFragmentCreate, con(%p), paramLen(%i)", (RsContext)con, paramLen);
+
+    jlong ret = (jlong)rsProgramFragmentCreate((RsContext)con, shaderUTF.c_str(), shaderUTF.length(),
+                                             nameArray, texCount, sizeArray,
+                                             (uint32_t *)paramPtr, paramLen);
+
+    _env->ReleaseIntArrayElements(params, paramPtr, JNI_ABORT);
+    return ret;
+}
+
+
+// ---------------------------------------------------------------------------
+
+static jlong
+nProgramVertexCreate(JNIEnv *_env, jobject _this, jlong con, jstring shader,
+                     jobjectArray texNames, jintArray params)
+{
+    AutoJavaStringToUTF8 shaderUTF(_env, shader);
+    jint *paramPtr = _env->GetIntArrayElements(params, NULL);
+    jint paramLen = _env->GetArrayLength(params);
+
+    LOG_API("nProgramVertexCreate, con(%p), paramLen(%i)", (RsContext)con, paramLen);
+
+    int texCount = _env->GetArrayLength(texNames);
+    AutoJavaStringArrayToUTF8 names(_env, texNames, texCount);
+    const char ** nameArray = names.c_str();
+    size_t* sizeArray = names.c_str_len();
+
+    jlong ret = (jlong)rsProgramVertexCreate((RsContext)con, shaderUTF.c_str(), shaderUTF.length(),
+                                           nameArray, texCount, sizeArray,
+                                           (uint32_t *)paramPtr, paramLen);
+
+    _env->ReleaseIntArrayElements(params, paramPtr, JNI_ABORT);
+    return ret;
+}
+
+// ---------------------------------------------------------------------------
+
+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);
+    return (jlong)rsProgramRasterCreate((RsContext)con, pointSprite, (RsCullMode)cull);
+}
+
+
+// ---------------------------------------------------------------------------
+
+static void
+nContextBindRootScript(JNIEnv *_env, jobject _this, jlong con, jint script)
+{
+    LOG_API("nContextBindRootScript, con(%p), script(%p)", (RsContext)con, (RsScript)script);
+    rsContextBindRootScript((RsContext)con, (RsScript)script);
+}
+
+static void
+nContextBindProgramStore(JNIEnv *_env, jobject _this, jlong con, jint pfs)
+{
+    LOG_API("nContextBindProgramStore, con(%p), pfs(%p)", (RsContext)con, (RsProgramStore)pfs);
+    rsContextBindProgramStore((RsContext)con, (RsProgramStore)pfs);
+}
+
+static void
+nContextBindProgramFragment(JNIEnv *_env, jobject _this, jlong con, jint pf)
+{
+    LOG_API("nContextBindProgramFragment, con(%p), pf(%p)", (RsContext)con, (RsProgramFragment)pf);
+    rsContextBindProgramFragment((RsContext)con, (RsProgramFragment)pf);
+}
+
+static void
+nContextBindProgramVertex(JNIEnv *_env, jobject _this, jlong con, jint pf)
+{
+    LOG_API("nContextBindProgramVertex, con(%p), pf(%p)", (RsContext)con, (RsProgramVertex)pf);
+    rsContextBindProgramVertex((RsContext)con, (RsProgramVertex)pf);
+}
+
+static void
+nContextBindProgramRaster(JNIEnv *_env, jobject _this, jlong con, jint pf)
+{
+    LOG_API("nContextBindProgramRaster, con(%p), pf(%p)", (RsContext)con, (RsProgramRaster)pf);
+    rsContextBindProgramRaster((RsContext)con, (RsProgramRaster)pf);
+}
+
+
+// ---------------------------------------------------------------------------
+
+static jlong
+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);
+    return (jlong)rsSamplerCreate((RsContext)con,
+                                 (RsSamplerValue)magFilter,
+                                 (RsSamplerValue)minFilter,
+                                 (RsSamplerValue)wrapS,
+                                 (RsSamplerValue)wrapT,
+                                 (RsSamplerValue)wrapR,
+                                 aniso);
+}
+
+// ---------------------------------------------------------------------------
+
+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);
+
+    jlong id = (jlong)rsPathCreate((RsContext)con, (RsPathPrimitive)prim, isStatic,
+                                   (RsAllocation)_vtx,
+                                   (RsAllocation)_loop, q);
+    return id;
+}
+
+static jlong
+nMeshCreate(JNIEnv *_env, jobject _this, jlong con, jintArray _vtx, jintArray _idx, jintArray _prim)
+{
+    LOG_API("nMeshCreate, con(%p)", (RsContext)con);
+
+    jint vtxLen = _env->GetArrayLength(_vtx);
+    jint *vtxPtr = _env->GetIntArrayElements(_vtx, NULL);
+    jint idxLen = _env->GetArrayLength(_idx);
+    jint *idxPtr = _env->GetIntArrayElements(_idx, NULL);
+    jint primLen = _env->GetArrayLength(_prim);
+    jint *primPtr = _env->GetIntArrayElements(_prim, NULL);
+
+    int id = (int)rsMeshCreate((RsContext)con,
+                               (RsAllocation *)vtxPtr, vtxLen,
+                               (RsAllocation *)idxPtr, idxLen,
+                               (uint32_t *)primPtr, primLen);
+
+    _env->ReleaseIntArrayElements(_vtx, vtxPtr, 0);
+    _env->ReleaseIntArrayElements(_idx, idxPtr, 0);
+    _env->ReleaseIntArrayElements(_prim, primPtr, 0);
+    return id;
+}
+
+static jint
+nMeshGetVertexBufferCount(JNIEnv *_env, jobject _this, jlong con, jlong mesh)
+{
+    LOG_API("nMeshGetVertexBufferCount, con(%p), Mesh(%p)", (RsContext)con, (RsMesh)mesh);
+    jint vtxCount = 0;
+    rsaMeshGetVertexBufferCount((RsContext)con, (RsMesh)mesh, &vtxCount);
+    return vtxCount;
+}
+
+static jint
+nMeshGetIndexCount(JNIEnv *_env, jobject _this, jlong con, jlong mesh)
+{
+    LOG_API("nMeshGetIndexCount, con(%p), Mesh(%p)", (RsContext)con, (RsMesh)mesh);
+    jint idxCount = 0;
+    rsaMeshGetIndexCount((RsContext)con, (RsMesh)mesh, &idxCount);
+    return idxCount;
+}
+
+static void
+nMeshGetVertices(JNIEnv *_env, jobject _this, jlong con, jlong mesh, jintArray _ids, int numVtxIDs)
+{
+    LOG_API("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);
+
+    for(jint i = 0; i < numVtxIDs; i ++) {
+        _env->SetIntArrayRegion(_ids, i, 1, (const jint*)&allocs[i]);
+    }
+
+    free(allocs);
+}
+
+static void
+nMeshGetIndices(JNIEnv *_env, jobject _this, jlong con, jlong mesh, jintArray _idxIds, jintArray _primitives, int numIndices)
+{
+    LOG_API("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));
+
+    rsaMeshGetIndices((RsContext)con, (RsMesh)mesh, allocs, prims, (uint32_t)numIndices);
+
+    for(jint i = 0; i < numIndices; i ++) {
+        _env->SetIntArrayRegion(_idxIds, i, 1, (const jint*)&allocs[i]);
+        _env->SetIntArrayRegion(_primitives, i, 1, (const jint*)&prims[i]);
+    }
+
+    free(allocs);
+    free(prims);
+}
+
+// ---------------------------------------------------------------------------
+
+
+static const char *classPathName = "android/renderscript/RenderScript";
+
+static JNINativeMethod methods[] = {
+{"_nInit",                         "()V",                                     (void*)_nInit },
+
+{"nDeviceCreate",                  "()J",                                     (void*)nDeviceCreate },
+{"nDeviceDestroy",                 "(J)V",                                    (void*)nDeviceDestroy },
+{"nDeviceSetConfig",               "(JII)V",                                  (void*)nDeviceSetConfig },
+{"nContextGetUserMessage",         "(J[I)I",                                  (void*)nContextGetUserMessage },
+{"nContextGetErrorMessage",        "(J)Ljava/lang/String;",                   (void*)nContextGetErrorMessage },
+{"nContextPeekMessage",            "(J[I)I",                                  (void*)nContextPeekMessage },
+
+{"nContextInitToClient",           "(J)V",                                    (void*)nContextInitToClient },
+{"nContextDeinitToClient",         "(J)V",                                    (void*)nContextDeinitToClient },
+
+
+// All methods below are thread protected in java.
+{"rsnContextCreate",                 "(JIII)J",                               (void*)nContextCreate },
+{"rsnContextCreateGL",               "(JIIIIIIIIIIIIFI)J",                    (void*)nContextCreateGL },
+{"rsnContextFinish",                 "(J)V",                                  (void*)nContextFinish },
+{"rsnContextSetPriority",            "(JI)V",                                 (void*)nContextSetPriority },
+{"rsnContextSetSurface",             "(JIILandroid/view/Surface;)V",          (void*)nContextSetSurface },
+{"rsnContextDestroy",                "(J)V",                                  (void*)nContextDestroy },
+{"rsnContextDump",                   "(JI)V",                                 (void*)nContextDump },
+{"rsnContextPause",                  "(J)V",                                  (void*)nContextPause },
+{"rsnContextResume",                 "(J)V",                                  (void*)nContextResume },
+{"rsnContextSendMessage",            "(JI[I)V",                               (void*)nContextSendMessage },
+{"rsnAssignName",                    "(JJ[B)V",                               (void*)nAssignName },
+{"rsnGetName",                       "(JJ)Ljava/lang/String;",                (void*)nGetName },
+{"rsnObjDestroy",                    "(JJ)V",                                 (void*)nObjDestroy },
+
+{"rsnFileA3DCreateFromFile",         "(JLjava/lang/String;)J",                (void*)nFileA3DCreateFromFile },
+{"rsnFileA3DCreateFromAssetStream",  "(JJ)J",                                 (void*)nFileA3DCreateFromAssetStream },
+{"rsnFileA3DCreateFromAsset",        "(JLandroid/content/res/AssetManager;Ljava/lang/String;)J",            (void*)nFileA3DCreateFromAsset },
+{"rsnFileA3DGetNumIndexEntries",     "(JJ)I",                                 (void*)nFileA3DGetNumIndexEntries },
+{"rsnFileA3DGetIndexEntries",        "(JJI[I[Ljava/lang/String;)V",           (void*)nFileA3DGetIndexEntries },
+{"rsnFileA3DGetEntryByIndex",        "(JJI)J",                                (void*)nFileA3DGetEntryByIndex },
+
+{"rsnFontCreateFromFile",            "(JLjava/lang/String;FI)J",              (void*)nFontCreateFromFile },
+{"rsnFontCreateFromAssetStream",     "(JLjava/lang/String;FIJ)J",             (void*)nFontCreateFromAssetStream },
+{"rsnFontCreateFromAsset",        "(JLandroid/content/res/AssetManager;Ljava/lang/String;FI)J",            (void*)nFontCreateFromAsset },
+
+{"rsnElementCreate",                 "(JJIZI)J",                              (void*)nElementCreate },
+{"rsnElementCreate2",                "(J[I[Ljava/lang/String;[I)J",           (void*)nElementCreate2 },
+{"rsnElementGetNativeData",          "(JJ[I)V",                               (void*)nElementGetNativeData },
+{"rsnElementGetSubElements",         "(JJ[I[Ljava/lang/String;[I)V",          (void*)nElementGetSubElements },
+
+{"rsnTypeCreate",                    "(JJIIIZZI)J",                           (void*)nTypeCreate },
+{"rsnTypeGetNativeData",             "(JJ[I)V",                               (void*)nTypeGetNativeData },
+
+{"rsnAllocationCreateTyped",         "(JJIII)J",                               (void*)nAllocationCreateTyped },
+{"rsnAllocationCreateFromBitmap",    "(JJILandroid/graphics/Bitmap;I)J",      (void*)nAllocationCreateFromBitmap },
+{"rsnAllocationCreateBitmapBackedAllocation",    "(JJILandroid/graphics/Bitmap;I)J",      (void*)nAllocationCreateBitmapBackedAllocation },
+{"rsnAllocationCubeCreateFromBitmap","(JJILandroid/graphics/Bitmap;I)J",      (void*)nAllocationCubeCreateFromBitmap },
+
+{"rsnAllocationCopyFromBitmap",      "(JJLandroid/graphics/Bitmap;)V",        (void*)nAllocationCopyFromBitmap },
+{"rsnAllocationCopyToBitmap",        "(JJLandroid/graphics/Bitmap;)V",        (void*)nAllocationCopyToBitmap },
+
+{"rsnAllocationSyncAll",             "(JJI)V",                                (void*)nAllocationSyncAll },
+{"rsnAllocationGetSurface",          "(JJ)Landroid/view/Surface;",            (void*)nAllocationGetSurface },
+{"rsnAllocationSetSurface",          "(JJLandroid/view/Surface;)V",           (void*)nAllocationSetSurface },
+{"rsnAllocationIoSend",              "(JJ)V",                                 (void*)nAllocationIoSend },
+{"rsnAllocationIoReceive",           "(JJ)V",                                 (void*)nAllocationIoReceive },
+{"rsnAllocationData1D",              "(JJIIILjava/lang/Object;II)V",          (void*)nAllocationData1D },
+{"rsnAllocationElementData1D",       "(JJIII[BI)V",                           (void*)nAllocationElementData1D },
+{"rsnAllocationData2D",              "(JJIIIIIILjava/lang/Object;II)V",       (void*)nAllocationData2D },
+{"rsnAllocationData2D",              "(JJIIIIIIJIIII)V",                      (void*)nAllocationData2D_alloc },
+{"rsnAllocationData3D",              "(JJIIIIIIILjava/lang/Object;II)V",      (void*)nAllocationData3D },
+{"rsnAllocationData3D",              "(JJIIIIIIIJIIII)V",                     (void*)nAllocationData3D_alloc },
+{"rsnAllocationRead",                "(JJLjava/lang/Object;I)V",              (void*)nAllocationRead },
+{"rsnAllocationRead1D",              "(JJIIILjava/lang/Object;II)V",          (void*)nAllocationRead1D },
+{"rsnAllocationRead2D",              "(JJIIIIIILjava/lang/Object;II)V",       (void*)nAllocationRead2D },
+{"rsnAllocationGetType",             "(JJ)J",                                 (void*)nAllocationGetType},
+{"rsnAllocationResize1D",            "(JJI)V",                                (void*)nAllocationResize1D },
+{"rsnAllocationGenerateMipmaps",     "(JJ)V",                                 (void*)nAllocationGenerateMipmaps },
+
+{"rsnScriptBindAllocation",          "(JJJI)V",                               (void*)nScriptBindAllocation },
+{"rsnScriptSetTimeZone",             "(JJ[B)V",                               (void*)nScriptSetTimeZone },
+{"rsnScriptInvoke",                  "(JJI)V",                                (void*)nScriptInvoke },
+{"rsnScriptInvokeV",                 "(JJI[B)V",                              (void*)nScriptInvokeV },
+{"rsnScriptForEach",                 "(JJIJJ)V",                              (void*)nScriptForEach },
+{"rsnScriptForEach",                 "(JJIJJ[B)V",                            (void*)nScriptForEachV },
+{"rsnScriptForEachClipped",          "(JJIJJIIIIII)V",                        (void*)nScriptForEachClipped },
+{"rsnScriptForEachClipped",          "(JJIJJ[BIIIIII)V",                      (void*)nScriptForEachClippedV },
+{"rsnScriptSetVarI",                 "(JJII)V",                               (void*)nScriptSetVarI },
+{"rsnScriptGetVarI",                 "(JJI)I",                                (void*)nScriptGetVarI },
+{"rsnScriptSetVarJ",                 "(JJIJ)V",                               (void*)nScriptSetVarJ },
+{"rsnScriptGetVarJ",                 "(JJI)J",                                (void*)nScriptGetVarJ },
+{"rsnScriptSetVarF",                 "(JJIF)V",                               (void*)nScriptSetVarF },
+{"rsnScriptGetVarF",                 "(JJI)F",                                (void*)nScriptGetVarF },
+{"rsnScriptSetVarD",                 "(JJID)V",                               (void*)nScriptSetVarD },
+{"rsnScriptGetVarD",                 "(JJI)D",                                (void*)nScriptGetVarD },
+{"rsnScriptSetVarV",                 "(JJI[B)V",                              (void*)nScriptSetVarV },
+{"rsnScriptGetVarV",                 "(JJI[B)V",                              (void*)nScriptGetVarV },
+{"rsnScriptSetVarVE",                "(JJI[BJ[I)V",                           (void*)nScriptSetVarVE },
+{"rsnScriptSetVarObj",               "(JJIJ)V",                               (void*)nScriptSetVarObj },
+
+{"rsnScriptCCreate",                 "(JLjava/lang/String;Ljava/lang/String;[BI)J",  (void*)nScriptCCreate },
+{"rsnScriptIntrinsicCreate",         "(JIJ)J",                                (void*)nScriptIntrinsicCreate },
+{"rsnScriptKernelIDCreate",          "(JJII)J",                               (void*)nScriptKernelIDCreate },
+{"rsnScriptFieldIDCreate",           "(JJI)J",                                (void*)nScriptFieldIDCreate },
+{"rsnScriptGroupCreate",             "(J[I[I[I[I[I)J",                        (void*)nScriptGroupCreate },
+{"rsnScriptGroupSetInput",           "(JJJJ)V",                               (void*)nScriptGroupSetInput },
+{"rsnScriptGroupSetOutput",          "(JJJJ)V",                               (void*)nScriptGroupSetOutput },
+{"rsnScriptGroupExecute",            "(JJ)V",                                 (void*)nScriptGroupExecute },
+
+{"rsnProgramStoreCreate",            "(JZZZZZZIII)J",                         (void*)nProgramStoreCreate },
+
+{"rsnProgramBindConstants",          "(JJIJ)V",                               (void*)nProgramBindConstants },
+{"rsnProgramBindTexture",            "(JJIJ)V",                               (void*)nProgramBindTexture },
+{"rsnProgramBindSampler",            "(JJIJ)V",                               (void*)nProgramBindSampler },
+
+{"rsnProgramFragmentCreate",         "(JLjava/lang/String;[Ljava/lang/String;[I)J",              (void*)nProgramFragmentCreate },
+{"rsnProgramRasterCreate",           "(JZI)J",                                (void*)nProgramRasterCreate },
+{"rsnProgramVertexCreate",           "(JLjava/lang/String;[Ljava/lang/String;[I)J",              (void*)nProgramVertexCreate },
+
+{"rsnContextBindRootScript",         "(JI)V",                                 (void*)nContextBindRootScript },
+{"rsnContextBindProgramStore",       "(JI)V",                                 (void*)nContextBindProgramStore },
+{"rsnContextBindProgramFragment",    "(JI)V",                                 (void*)nContextBindProgramFragment },
+{"rsnContextBindProgramVertex",      "(JI)V",                                 (void*)nContextBindProgramVertex },
+{"rsnContextBindProgramRaster",      "(JI)V",                                 (void*)nContextBindProgramRaster },
+
+{"rsnSamplerCreate",                 "(JIIIIIF)J",                            (void*)nSamplerCreate },
+
+{"rsnPathCreate",                    "(JIZJJF)J",                             (void*)nPathCreate },
+{"rsnMeshCreate",                    "(J[I[I[I)J",                            (void*)nMeshCreate },
+
+{"rsnMeshGetVertexBufferCount",      "(JJ)I",                                 (void*)nMeshGetVertexBufferCount },
+{"rsnMeshGetIndexCount",             "(JJ)I",                                 (void*)nMeshGetIndexCount },
+{"rsnMeshGetVertices",               "(JJ[II)V",                              (void*)nMeshGetVertices },
+{"rsnMeshGetIndices",                "(JJ[I[II)V",                            (void*)nMeshGetIndices },
+
+};
+
+static int registerFuncs(JNIEnv *_env)
+{
+    return android::AndroidRuntime::registerNativeMethods(
+            _env, classPathName, methods, NELEM(methods));
+}
+
+// ---------------------------------------------------------------------------
+
+jint JNI_OnLoad(JavaVM* vm, void* reserved)
+{
+    JNIEnv* env = NULL;
+    jint result = -1;
+
+    if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {
+        ALOGE("ERROR: GetEnv failed\n");
+        goto bail;
+    }
+    assert(env != NULL);
+
+    if (registerFuncs(env) < 0) {
+        ALOGE("ERROR: Renderscript native registration failed\n");
+        goto bail;
+    }
+
+    /* success -- return valid version number */
+    result = JNI_VERSION_1_4;
+
+bail:
+    return result;
+}
diff --git a/services/java/com/android/server/LightsService.java b/services/java/com/android/server/LightsService.java
index a1d655b..e99a3a4 100644
--- a/services/java/com/android/server/LightsService.java
+++ b/services/java/com/android/server/LightsService.java
@@ -96,6 +96,7 @@
             synchronized (this) {
                 if (mColor == 0 && !mFlashing) {
                     setLightLocked(color, LIGHT_FLASH_HARDWARE, onMS, 1000, BRIGHTNESS_MODE_USER);
+                    mColor = 0;
                     mH.sendMessageDelayed(Message.obtain(mH, 1, this), onMS);
                 }
             }
diff --git a/services/java/com/android/server/pm/PackageManagerService.java b/services/java/com/android/server/pm/PackageManagerService.java
index 7e244b9..7ea1fce 100755
--- a/services/java/com/android/server/pm/PackageManagerService.java
+++ b/services/java/com/android/server/pm/PackageManagerService.java
@@ -1301,6 +1301,11 @@
 
             // Collect all vendor packages.
             File vendorAppDir = new File("/vendor/app");
+            try {
+                vendorAppDir = vendorAppDir.getCanonicalFile();
+            } catch (IOException e) {
+                // failed to look up canonical path, continue with original one
+            }
             mVendorInstallObserver = new AppDirObserver(
                 vendorAppDir.getPath(), OBSERVER_EVENTS, true, false);
             mVendorInstallObserver.startWatching();
diff --git a/tests/SystemUIDemoModeController/Android.mk b/tests/SystemUIDemoModeController/Android.mk
new file mode 100644
index 0000000..64ea63c
--- /dev/null
+++ b/tests/SystemUIDemoModeController/Android.mk
@@ -0,0 +1,10 @@
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+
+LOCAL_SRC_FILES := $(call all-subdir-java-files)
+
+LOCAL_PACKAGE_NAME := DemoModeController
+
+include $(BUILD_PACKAGE)
diff --git a/tests/SystemUIDemoModeController/AndroidManifest.xml b/tests/SystemUIDemoModeController/AndroidManifest.xml
new file mode 100644
index 0000000..2e97932
--- /dev/null
+++ b/tests/SystemUIDemoModeController/AndroidManifest.xml
@@ -0,0 +1,39 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- 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.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.example.android.demomodecontroller"
+    android:versionCode="1"
+    android:versionName="0.1" >
+
+    <uses-sdk
+        android:minSdkVersion="19"
+        android:targetSdkVersion="19" />
+
+    <application
+        android:allowBackup="false"
+        android:label="@string/app_name" >
+        <activity
+            android:name=".DemoModeController" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.DEFAULT" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest>
diff --git a/tests/SystemUIDemoModeController/res/values/strings.xml b/tests/SystemUIDemoModeController/res/values/strings.xml
new file mode 100644
index 0000000..257a353
--- /dev/null
+++ b/tests/SystemUIDemoModeController/res/values/strings.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- 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.
+-->
+
+<resources>
+
+    <string name="app_name">Demo Mode Controller</string>
+    <string name="help_text">"Drag: control icon states\nLong-press + drag: control background color\nDouble-tap: toggle bar mode</string>
+
+</resources>
diff --git a/tests/SystemUIDemoModeController/src/com/example/android/demomodecontroller/DemoModeController.java b/tests/SystemUIDemoModeController/src/com/example/android/demomodecontroller/DemoModeController.java
new file mode 100644
index 0000000..b177d7e
--- /dev/null
+++ b/tests/SystemUIDemoModeController/src/com/example/android/demomodecontroller/DemoModeController.java
@@ -0,0 +1,340 @@
+/*
+ * 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 com.example.android.demomodecontroller;
+
+import android.app.Activity;
+import android.content.Context;
+import android.content.Intent;
+import android.graphics.Color;
+import android.graphics.PointF;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.HandlerThread;
+import android.os.SystemClock;
+import android.util.Log;
+import android.view.MotionEvent;
+import android.view.View;
+import android.view.View.OnTouchListener;
+import android.view.ViewConfiguration;
+import android.view.WindowManager;
+import android.widget.Toast;
+
+public class DemoModeController extends Activity implements OnTouchListener {
+    private static final String TAG = DemoModeController.class.getSimpleName();
+    private static final boolean DEBUG = false;
+
+    private final Context mContext = this;
+    private final Handler mHandler = new Handler();
+    private final PointF mLastDown = new PointF();
+
+    private View mContent;
+    private Handler mBackground;
+    private int mTouchSlop;
+    private long mLastDownTime;
+    private boolean mControllingColor;
+    private Toast mToast;
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
+                | WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS  // so WM gives us enough room
+                | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
+        getActionBar().hide();
+        mContent = new View(mContext);
+        mContent.setBackgroundColor(0xff33b5e5);
+        mContent.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
+                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
+                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
+        mContent.setOnTouchListener(this);
+        setContentView(mContent);
+        mTouchSlop = ViewConfiguration.get(mContext).getScaledTouchSlop();
+
+        final HandlerThread background = new HandlerThread("background");
+        background.start();
+        mBackground = new Handler(background.getLooper());
+        updateMode();
+    }
+
+    @Override
+    protected void onPause() {
+        super.onPause();
+        exitDemoMode();
+    }
+
+    @Override
+    protected void onResume() {
+        super.onResume();
+        exitDemoMode();
+        mToast = Toast.makeText(mContext, R.string.help_text, Toast.LENGTH_LONG);
+        mToast.show();
+    }
+
+    @Override
+    public boolean onTouch(View v, MotionEvent event) {
+        if (mToast != null) {
+            mToast.cancel();
+            mToast = null;
+        }
+        final int action = event.getAction();
+        if (action == MotionEvent.ACTION_DOWN) {
+            if (DEBUG) Log.d(TAG, "down");
+            mHandler.postDelayed(mLongPressCheck, 500);
+            final long now = SystemClock.uptimeMillis();
+            if (now - mLastDownTime < 200) {
+                toggleMode();
+            }
+            mLastDownTime = now;
+            mLastDown.x = event.getX();
+            mLastDown.y = event.getY();
+            return true;
+        }
+        if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
+            if (DEBUG) Log.d(TAG, "upOrCancel");
+            mControllingColor = false;
+            mHandler.removeCallbacks(mLongPressCheck);
+        }
+        if (action != MotionEvent.ACTION_MOVE) return false;
+
+        float x = event.getX();
+        float y = event.getY();
+        if (Math.abs(mLastDown.x - x) > mTouchSlop || Math.abs(mLastDown.y - y) > mTouchSlop) {
+            mHandler.removeCallbacks(mLongPressCheck);
+        }
+        x = Math.max(x, 0);
+        y = Math.max(y, 0);
+        final int h = mContent.getMeasuredHeight();
+        final int w = mContent.getMeasuredWidth();
+        x = Math.min(x, w);
+        y = Math.min(y, h);
+
+        y = h - y;
+        x = w - x;
+
+        if (mControllingColor) {
+            final float hue = y / (h / 360);
+            final float sat = 1 - (x / (float)w);
+            final float val = x / (float)w;
+            final int color = Color.HSVToColor(new float[]{hue, sat, val});
+            if (DEBUG) Log.d(TAG, String.format("hsv=(%s,%s,%s) argb=#%08x", hue, sat, val, color));
+            mContent.setBackgroundColor(color);
+            return true;
+        }
+
+        final int hh = (int)x / (w / 12);
+        if (hh != mHH) {
+            mHH = hh;
+            mBackground.removeCallbacks(mUpdateClock);
+            mBackground.post(mUpdateClock);
+        }
+
+        final int mm = (int)y / (h / 60);
+        if (mm != mMM) {
+            mMM = mm;
+            mBackground.removeCallbacks(mUpdateClock);
+            mBackground.post(mUpdateClock);
+        }
+
+        final int batteryLevel = (int)y / (h / 101);
+        if (batteryLevel != mBatteryLevel) {
+            mBatteryLevel = batteryLevel;
+            mBackground.removeCallbacks(mUpdateBattery);
+            mBackground.post(mUpdateBattery);
+        }
+
+        final boolean batteryPlugged = x >= w / 2;
+        if (batteryPlugged != mBatteryPlugged) {
+            mBatteryPlugged = batteryPlugged;
+            mBackground.removeCallbacks(mUpdateBattery);
+            mBackground.post(mUpdateBattery);
+        }
+
+        final int mobileLevel = (int)y / (h / 10);
+        if (mobileLevel != mMobileLevel) {
+            mMobileLevel = mobileLevel;
+            mBackground.removeCallbacks(mUpdateMobile);
+            mBackground.post(mUpdateMobile);
+        }
+
+        final int wifiLevel = (int)y / (h / 10);
+        if (wifiLevel != mWifiLevel) {
+            mWifiLevel = wifiLevel;
+            mBackground.removeCallbacks(mUpdateWifi);
+            mBackground.post(mUpdateWifi);
+        }
+
+        final int statusSlots = (int)x / (w / 13);
+        if (statusSlots != mStatusSlots) {
+            mStatusSlots = statusSlots;
+            mBackground.removeCallbacks(mUpdateStatus);
+            mBackground.post(mUpdateStatus);
+        }
+
+        final int networkIcons = (int)x / (w / 4);
+        if (networkIcons != mNetworkIcons) {
+            mNetworkIcons = networkIcons;
+            mBackground.removeCallbacks(mUpdateNetwork);
+            mBackground.post(mUpdateNetwork);
+        }
+
+        final int mobileDataType = (int)y / (h / 9);
+        if (mobileDataType != mMobileDataType) {
+            mMobileDataType = mobileDataType;
+            mBackground.removeCallbacks(mUpdateMobile);
+            mBackground.post(mUpdateMobile);
+        }
+        return true;
+    }
+
+    private void toggleMode() {
+        if (DEBUG) Log.d(TAG, "toggleMode");
+        mBarMode = (mBarMode + 1) % 3;
+        updateMode();
+    }
+
+    private void updateMode() {
+        mBackground.removeCallbacks(mUpdateBarMode);
+        mBackground.post(mUpdateBarMode);
+    }
+
+    private final Runnable mLongPressCheck = new Runnable() {
+        @Override
+        public void run() {
+            if (DEBUG) Log.d(TAG, "mControllingColor = true");
+            mControllingColor = true;
+
+        }
+    };
+
+    private void exitDemoMode() {
+        if (DEBUG) Log.d(TAG, "exitDemoMode");
+        final Intent intent = new Intent("com.android.systemui.demo");
+        intent.putExtra("command", "exit");
+        mContext.sendBroadcast(intent);
+    }
+
+    private int mStatusSlots; // 0 - 12
+    private final Runnable mUpdateStatus = new Runnable() {
+        @Override
+        public void run() {
+            final Intent intent = new Intent("com.android.systemui.demo");
+            intent.putExtra("command", "status");
+            intent.putExtra("volume", mStatusSlots < 1 ? "hide"
+                    : mStatusSlots < 2 ? "silent" : "vibrate");
+            intent.putExtra("bluetooth", mStatusSlots < 3 ? "hide"
+                    : mStatusSlots < 4 ? "disconnected" : "connected");
+            intent.putExtra("location", mStatusSlots < 5 ? "hide" : "show");
+            intent.putExtra("alarm", mStatusSlots < 6 ? "hide" : "show");
+            intent.putExtra("sync", mStatusSlots < 7 ? "hide" : "show");
+            intent.putExtra("tty", mStatusSlots < 8 ? "hide" : "show");
+            intent.putExtra("eri", mStatusSlots < 9 ? "hide" : "show");
+            intent.putExtra("secure", mStatusSlots < 10 ? "hide" : "show");
+            intent.putExtra("mute", mStatusSlots < 11 ? "hide" : "show");
+            intent.putExtra("speakerphone", mStatusSlots < 12 ? "hide" : "show");
+            mContext.sendBroadcast(intent);
+        }
+    };
+
+    private int mNetworkIcons;  // 0:airplane  1:mobile  2:airplane+wifi  3:mobile+wifi
+    private final Runnable mUpdateNetwork = new Runnable() {
+        @Override
+        public void run() {
+            final Intent intent = new Intent("com.android.systemui.demo");
+            intent.putExtra("command", "network");
+            intent.putExtra("airplane", mNetworkIcons % 2 == 0 ? "show" : "hide");
+            intent.putExtra("wifi", mNetworkIcons >= 2 ? "show" : "hide");
+            intent.putExtra("mobile", mNetworkIcons % 2 == 1 ? "show" : "hide");
+            mContext.sendBroadcast(intent);
+        }
+    };
+
+    private int mWifiLevel; // 0 - 4, 5 - 9, fully
+    private final Runnable mUpdateWifi = new Runnable() {
+        @Override
+        public void run() {
+            final Intent intent = new Intent("com.android.systemui.demo");
+            intent.putExtra("command", "network");
+            intent.putExtra("wifi", mNetworkIcons >= 2 ? "show" : "hide");
+            intent.putExtra("level", Integer.toString(mWifiLevel % 5));
+            intent.putExtra("fully", Boolean.toString(mWifiLevel > 4));
+            mContext.sendBroadcast(intent);
+        }
+    };
+
+    private int mMobileLevel; // 0 - 4, 5 - 9, fully
+    private int mMobileDataType; // 0 - 8
+    private static final String getDataType(int dataType) {
+        if (dataType == 1) return "1x";
+        if (dataType == 2) return "3g";
+        if (dataType == 3) return "4g";
+        if (dataType == 4) return "e";
+        if (dataType == 5) return "g";
+        if (dataType == 6) return "h";
+        if (dataType == 7) return "lte";
+        if (dataType == 8) return "roam";
+        return "";
+    }
+    private final Runnable mUpdateMobile = new Runnable() {
+        @Override
+        public void run() {
+            final Intent intent = new Intent("com.android.systemui.demo");
+            intent.putExtra("command", "network");
+            intent.putExtra("mobile", mNetworkIcons % 2 == 1 ? "show" : "hide");
+            intent.putExtra("level", Integer.toString(mMobileLevel % 5));
+            intent.putExtra("fully", Boolean.toString(mMobileLevel > 4));
+            intent.putExtra("datatype", getDataType(mMobileDataType));
+            mContext.sendBroadcast(intent);
+        }
+    };
+
+    private boolean mBatteryPlugged;
+    private int mBatteryLevel; // 0 - 100
+    private final Runnable mUpdateBattery = new Runnable() {
+        @Override
+        public void run() {
+            final Intent intent = new Intent("com.android.systemui.demo");
+            intent.putExtra("command", "battery");
+            intent.putExtra("level", Integer.toString(mBatteryLevel));
+            intent.putExtra("plugged", Boolean.toString(mBatteryPlugged));
+            mContext.sendBroadcast(intent);
+        }
+    };
+
+    private int mHH; // 0 - 11
+    private int mMM; // 0 - 59
+    private final Runnable mUpdateClock = new Runnable() {
+        @Override
+        public void run() {
+            final Intent intent = new Intent("com.android.systemui.demo");
+            intent.putExtra("command", "clock");
+            intent.putExtra("hhmm", String.format("%02d%02d", mHH + 1, mMM));
+            mContext.sendBroadcast(intent);
+        }
+    };
+
+    private int mBarMode; // 0 - 2  (opaque, semi-transparent, translucent)
+    private final Runnable mUpdateBarMode = new Runnable() {
+        @Override
+        public void run() {
+            final Intent intent = new Intent("com.android.systemui.demo");
+            intent.putExtra("command", "bars");
+            intent.putExtra("mode", mBarMode == 1 ? "semi-transparent"
+                    : mBarMode == 2 ? "translucent" : "opaque");
+            mContext.sendBroadcast(intent);
+        }
+    };
+}
diff --git a/tools/aapt/AaptAssets.cpp b/tools/aapt/AaptAssets.cpp
index d8e113a..ebf4538 100644
--- a/tools/aapt/AaptAssets.cpp
+++ b/tools/aapt/AaptAssets.cpp
@@ -2651,7 +2651,7 @@
 {
     const ResTable& res = getIncludedResources();
     // XXX dirty!
-    return const_cast<ResTable&>(res).add(file->getData(), file->getSize(), NULL);
+    return const_cast<ResTable&>(res).add(file->getData(), file->getSize());
 }
 
 const ResTable& AaptAssets::getIncludedResources() const
diff --git a/tools/aapt/Resource.cpp b/tools/aapt/Resource.cpp
index 386888b..57d44f2 100644
--- a/tools/aapt/Resource.cpp
+++ b/tools/aapt/Resource.cpp
@@ -1320,8 +1320,7 @@
         }
 
         // Read resources back in,
-        finalResTable.add(resFile->getData(), resFile->getSize(), NULL);
-
+        finalResTable.add(resFile->getData(), resFile->getSize());
 #if 0
         NOISY(
               printf("Generated resources:\n");