Fix ref counting for globals when set from java code.

Change-Id: I415b6ddeaab277e60233e905a6bae357cd5193eb
diff --git a/rs.spec b/rs.spec
index ac9abe0..76db14f 100644
--- a/rs.spec
+++ b/rs.spec
@@ -280,6 +280,12 @@
 	param int value
 	}
 
+ScriptSetVarObj {
+	param RsScript s
+	param uint32_t slot
+	param RsObjectBase value
+	}
+
 ScriptSetVarJ {
 	param RsScript s
 	param uint32_t slot
diff --git a/rsScript.cpp b/rsScript.cpp
index 4ffdbfd..efdc626 100644
--- a/rsScript.cpp
+++ b/rsScript.cpp
@@ -67,6 +67,22 @@
     }
 }
 
+void Script::setVarObj(uint32_t slot, ObjectBase *val) {
+    ObjectBase **destPtr = ((ObjectBase ***)mEnviroment.mFieldAddress)[slot];
+
+    if (destPtr) {
+        if (val != NULL) {
+            val->incSysRef();
+        }
+        if (*destPtr) {
+            (*destPtr)->decSysRef();
+        }
+        *destPtr = val;
+    } else {
+        LOGV("Calling setVarObj on slot = %i which is null.  This is dangerous because the script will not hold a ref count on the object.", slot);
+    }
+}
+
 namespace android {
 namespace renderscript {
 
@@ -103,6 +119,12 @@
     s->setVar(slot, &value, sizeof(value));
 }
 
+void rsi_ScriptSetVarObj(Context *rsc, RsScript vs, uint32_t slot, RsObjectBase value) {
+    Script *s = static_cast<Script *>(vs);
+    ObjectBase *o = static_cast<ObjectBase *>(value);
+    s->setVarObj(slot, o);
+}
+
 void rsi_ScriptSetVarJ(Context *rsc, RsScript vs, uint32_t slot, long long value) {
     Script *s = static_cast<Script *>(vs);
     s->setVar(slot, &value, sizeof(value));
diff --git a/rsScript.h b/rsScript.h
index 9b6d8a9..bad095b 100644
--- a/rsScript.h
+++ b/rsScript.h
@@ -61,6 +61,7 @@
     void initSlots();
     void setSlot(uint32_t slot, Allocation *a);
     void setVar(uint32_t slot, const void *val, uint32_t len);
+    void setVarObj(uint32_t slot, ObjectBase *val);
 
     virtual void runForEach(Context *rsc,
                             const Allocation * ain,