back port gles fix to api 18

Following CLs are backported:

    5a50ac8819525f851c677be88a466b14737dbb18 guest system gles fix: Enable screen capture with gpu on
    717e625415c4398431b84851ba1b76d8c59ae9cf Add shader version to glGetString
    32c30975ea654b9654ad9dade0d25b9856e63f1b Add parameters validation to glShaderSource() API
    b0c7cce25bf9323a359800a86c0c7609db2acea4 Fix eglDestroyContext and glTexImage2D
    2fc65202c214640c55b52c29bbc9213170d0b533 handles glGetBooleanv when value is nonboolean
    beda8027439b9c20475b8a3d379823d09fca3abb Properly initialize GLClientState's m_states
    84684ec571a1db94e32a67cb7d154ab562dd0d7f Unbind buffer when buffer is deleted
    89b7aac84f8babab93ff5326ad492164d971c421 Handle empty data parameter in glTexSubImage2D_enc
    adb0f74f792ba7bca20257b9c0ea41ebda9bb229 Allow glGetProgramInfoLog_enc to have empty length
    b31166704ddb7751619cf0bbc4f2f4575c0ad3c4 Guard against negative buffer size
    641f35af08a0a4c46586a592ff4e703e866d581a Guard against negative width and height
    9d18698dd8da15937f80e5476d73400a011934be Handle empty buffer in QemuPipeStream::writeFully
    40a674e0d0acac87aa25eb9de720dc2fb07d9e4f Fix emulator crashes on glDrawElements command
    7fa2b92de2058a3556e5f38a135de415bb3d5e45 Merge "Use more appropriate type in cb_handle_t::validate."
    fe2c5beb964d2e2aecedb02b9cca592e0811d90b Use more appropriate type in cb_handle_t::validate.
    376688e76694bf5b8672379c540b1bda059da682 Merge "ranchu: Fix goldfish_pipe definitions."
    e3e686593cc8bdaf3ca4f6fa0b33b62a6951d1d6 ranchu: Fix goldfish_pipe definitions.
    7d3d0c99d2c82319e001289d1b9e091e5ff8f7aa Merge "ranchu: Add ARM64-specific root/ramdisk config files."
    d0fead3c53d6e450deb69aad72651e132b6cc072 ranchu: Add ARM64-specific root/ramdisk config files.
    638ee524f83053613c47ddea22c4bf98a0175c2f Merge "Remove display initialization from eglGetProcAddress API"
    7a2929cd6548693b581c17ba69308a49e03c56be Remove display initialization from eglGetProcAddress API
    9b1e6c5a3ccd943b7158dce83387fbfcc1162d69 Merge "Make the size of "cb_handle_t" same for 32/64-bit"
    7ea757df0311bfb7310a7a765dcec1b79f39f25d Merge "goldfish: camera: fix 64-bit warnings"
    3725c7c982eac52ec64a625e82f306822452941c goldfish: camera: fix 64-bit warnings
    eed789f036cbcedf2fa96ae3e273c2234102d340 Merge "goldfish: Fix /cache partition type."
    f55ac4fc027ae3d97f4faaa6ccd65480f493dea7 goldfish: Fix /cache partition type.
    690792a66c7fca6bf0aa17c2d5043ab86d145965 Merge "Revert "Revert "goldfish: cache image is not ext4. yet."""
    8853df9503e0edec6cac0e1e0840fa111d57a79a Revert "Revert "goldfish: cache image is not ext4. yet.""
    d8a6e67044ddcac7c53adbe6b871c33447110905 Merge "Revert "goldfish: cache image is not ext4. yet.""
    5e2caf7883279113d6f5f4777122dc88262c34c6 Revert "goldfish: cache image is not ext4. yet."
    3f62b50d45441ae077c958423e9e301acd5dcc11 Make the size of "cb_handle_t" same for 32/64-bit
    aec15d91ee48797f2b3c3fe61cca977900ebcd47 am 646f0b25: Merge "opengl: rcOpenColorBuffer must be synchronous"
    646f0b25e63164950d1d99b9b8021be74c2321c6 Merge "opengl: rcOpenColorBuffer must be synchronous"
    c542f3d8fc89678574b2fa650395f3dfac991a20 opengl: rcOpenColorBuffer must be synchronous
    6ccaeebd78dcb5e20e2c0e81cdc571fb74f9cfb7 am 2c6c08a2: Merge "Move goldfish from fdprintf to POSIX dprintf."
    2c6c08a23d2f5f760753745be5b67fe5759dcc91 Merge "Move goldfish from fdprintf to POSIX dprintf."
    0228f8a1cdf5b2391201333de73fabab6d2ca72f Move goldfish from fdprintf to POSIX dprintf.
    dbda557d4dcf022850ea4ab4f89e1c154e2aea04 am 5cb5779a: Merge "gralloc: don\'t initialize reserved_proc"
    5cb5779ad0ad75a59bfb8ce42317a4ee18300281 Merge "gralloc: don't initialize reserved_proc"
    e46eea0b5bdef28f5c42e4d7764b030679479354 gralloc: don't initialize reserved_proc
    67334d0b9d0da7595daf07a3e9bea6a55436e296 Merge commit 'd9dc763708823aa865983bb8dc37b5ecc5669620' into HEAD
    7076e4647af737393baf020c13e81a090f4a9f26 Merge "Add 64-bit software GLES/EGL support in gralloc.goldfish module"
    3f92be74c1e9b2314d4c0f8feaacf7bafce7dedc Add 64-bit software GLES/EGL support in gralloc.goldfish module
    61a8f0bbc146a4050a885e1e7c314dfc4ab72779 Merge "Fix the Chrome app crash in emulator issue"
    bd93fee73b02d0b223b441c34a4f8e04eb57291d Merge "Support GLES acceleration in 64bit emulator on device side"
    a1de8e2f5e4c29341be01bae364a54d92d14c742 Fix the Chrome app crash in emulator issue
    4f94a5f8b13a5fdd80988e77dd5d468b958b0117 Merge "Remove the useless folder and files in emulator GLES/EGL drivers"
    31aad5c0a0de056114b6bb843a5c37d8de6e46e4 Remove the useless folder and files in emulator GLES/EGL drivers
    aedc716648071a1403f4ac92a380d1d4a5377052 Support GLES acceleration in 64bit emulator on device side
    d9dc763708823aa865983bb8dc37b5ecc5669620 am aedf829a: Merge "goldfish: cache image is not ext4. yet."
    aedf829a920c3100de5caa49b0dec02d66eed96b Merge "goldfish: cache image is not ext4. yet."
    a2543be45f35ab7ace3ecd92c99a3c72150622ec goldfish: cache image is not ext4. yet.
    9dba558f4621d3d70a05c0a3d8e2c34b3883f866 am 48a76778: Merge "Remove #include <asm/page.h>."
    644f53c8705586705c27b799e5b5f303118e8b3c am 155ca91c: Merge topic \'emu64\'
    48a76778937abadf5cbd260696a29d737134d0d9 Merge "Remove #include <asm/page.h>."
    1daf365476f888a5d9534607c8299a3b5160b4a7 Remove #include <asm/page.h>.
    155ca91c1253bcb85a0eeec93ded6da07122d4ff Merge topic 'emu64'
    324a0c43835b935721c938a2684874e0b5bf8311 Disable echo on all tty lines
    8bb5f92dcd48dbbaa69ab15f97aca13d49b08599 ueventd.goldfish.rc: set system permissions for /dev/goldfish_pipe
    5b31b113176dec8d7fcfb5650f3dd7b01baf605c am 48107fa1: Merge "device/generic/goldfish: convert LOCAL_MODULE_PATH to LOCAL_MODULE_RELATIVE_PATH"
    48107fa1dd354f8667b74f335c3f82f472b7d112 Merge "device/generic/goldfish: convert LOCAL_MODULE_PATH to LOCAL_MODULE_RELATIVE_PATH"
    5212e4a903d2654572b8bdde0bda3bdd6ecbee6e device/generic/goldfish: convert LOCAL_MODULE_PATH to LOCAL_MODULE_RELATIVE_PATH
    2061519f3e55ba1dac643cac34a4aa6f0f0dfeee am 44c72ca0: Merge "Vibra: Add the vibrator module for goldfish"
    44c72ca0b92c75ffef5e691a24d5d06d6a3e7baa Merge "Vibra: Add the vibrator module for goldfish"
    0f41b57f2aa2ffa8fd90ebd50c13c2dd0249ee0f Vibra: Add the vibrator module for goldfish
    ac534df6c39944a91f157819628db3d6f63b75f1 am 59922432: Merge commit \'f09bc5256e48a44eec9ca47ba838c12d0e89a198\' into HEAD
    59922432be859a46eeb76650b24308505625da36 Merge commit 'f09bc5256e48a44eec9ca47ba838c12d0e89a198' into HEAD
    144d2d5d683928f393a9567c443c8f5af13dfdd0 am b9a62053: Merge commit \'828bd482a1aeacf96d5f3a3e0701029d9f890c5f\' into HEAD
    b9a62053cf74025a43c8baa118d52729e38cc176 Merge commit '828bd482a1aeacf96d5f3a3e0701029d9f890c5f' into HEAD
    a648b35cca58d3d1608e1beb21028f91bd0b9df7 am 2befc3ed: Merge "Modify the build targets for goldfish from to include aosp*."
    2befc3edc583afb43a4f6740f0af0534eac8e9d5 Merge "Modify the build targets for goldfish from to include aosp*."
    bc233492e3ce3af8cc23496ee58cd3dc1b74d0f0 Modify the build targets for goldfish from to include aosp*.
    f09bc5256e48a44eec9ca47ba838c12d0e89a198 am b9a7de1a: Merge "Delete buffer data when removing it from the SharedGroup namespace"
    b9a7de1a690bc638496e0550e6a9ebe859fc0315 Merge "Delete buffer data when removing it from the SharedGroup namespace"
    8562d1b6e089254837da3ab2d272c65c3bb5d8c7 Delete buffer data when removing it from the SharedGroup namespace
    f8b99f123467cd6164d071237f5dbe703f9ea2d7 am 6b151ca8: Merge "Catch divide by zero case in drawCheckerBoard() function."
    6b151ca8833aa7271e311436dad97588b71b7a38 Merge "Catch divide by zero case in drawCheckerBoard() function."
    d7cc5da79d828ec6cb21926be13265fc52715e2f am 84309165: Merge "Drop setting of in_qemu boolean and restorecon /sys/qemu_trace."
    84309165ca52b7446e388c13127fd6e305833f24 Merge "Drop setting of in_qemu boolean and restorecon /sys/qemu_trace."
    46bcb5f7a64ccd440d5a292c7afd2e2b5c2bee4f Drop setting of in_qemu boolean and restorecon /sys/qemu_trace.
    b0b6afb44269263afa080ecc643f2c4866adfb38 Catch divide by zero case in drawCheckerBoard() function.
    828bd482a1aeacf96d5f3a3e0701029d9f890c5f am 2524d396: Update emulator to FUSE-wrap its SD card.
    2524d39681566f4eca7afb7950e05ab642978263 Update emulator to FUSE-wrap its SD card.
    e8122dff1ef2de4d41835265a59d8960e7800fae camera3: Fix stream id types
    3ad13188d4e7e873947040ec22a35d73efb76812 Camera2/3: Implement full-color NV21 output.
    07da94023283a7be99fdde9b05e54d9204f7deff get rid of HAL pixelformats 5551 and 4444
    a4c19be9274d8bb993f88a6a1cbd2ad92f4a48fa Merge "Added net.dns1 prop for emulator, as Android emulator ignores it by default."
    ccb835ba267e927f7df759290bd46ac78712a3b2 Merge "Camera2/3: Update static metadata"
    0049ee8925212a3a5ff095a8a66cab184adf8f1b Camera2/3: Update static metadata
    8ff1e5f1e3e24baf311e6263b48f389c206f14ac am 8f9288ea: goldfish: use fstab.goldfish
    8f9288eaf10b50d19038f5c7024616e147c64735 goldfish: use fstab.goldfish
    e96a7c7da79939c509a7517f2b2de37e840a6390 Added net.dns1 prop for emulator, as Android emulator ignores it by default.
    ff3a362fb9aca15285a95cad6baa08e961330e8e am bf34d172: (-s ours) Reconcile with jb-mr2-zeroday-release - do not merge
    bf34d1722ea1ebdf779837611220b5269bd35968 Reconcile with jb-mr2-zeroday-release - do not merge
    d9fcbd08b0413fedc8219237534ce31d6b7fd2f5 merge in jb-mr2-zeroday-release history after reset to jb-mr2-dev
    ad9dd4bfdfa9ab6ccfc4be14305b6ed8b9a0ab5a am 2c84e47e: am 07a4c8b4: Camera3: Fix default AE mode
    2c84e47e3d0085b1222de94013c75c0328b02492 am 07a4c8b4: Camera3: Fix default AE mode

Change-Id: Iadb2d609051a33595ce915e638e0e40f9a4841a4
diff --git a/opengl/shared/OpenglCodecCommon/GLClientState.cpp b/opengl/shared/OpenglCodecCommon/GLClientState.cpp
index 9795490..0826a14 100644
--- a/opengl/shared/OpenglCodecCommon/GLClientState.cpp
+++ b/opengl/shared/OpenglCodecCommon/GLClientState.cpp
@@ -35,6 +35,7 @@
     for (int i = 0; i < m_nLocations; i++) {
         m_states[i].enabled = 0;
         m_states[i].enableDirty = false;
+        m_states[i].data = 0;
     }
     m_currentArrayVbo = 0;
     m_currentIndexVbo = 0;
@@ -224,6 +225,8 @@
 
 size_t GLClientState::pixelDataSize(GLsizei width, GLsizei height, GLenum format, GLenum type, int pack) const
 {
+    if (width <= 0 || height <= 0) return 0;
+
     int pixelsize = glUtilsPixelBitSize(format, type) >> 3;
 
     int alignment = pack ? m_pixelStore.pack_alignment : m_pixelStore.unpack_alignment;
diff --git a/opengl/shared/OpenglCodecCommon/GLClientState.h b/opengl/shared/OpenglCodecCommon/GLClientState.h
index c86329b..09ee571 100644
--- a/opengl/shared/OpenglCodecCommon/GLClientState.h
+++ b/opengl/shared/OpenglCodecCommon/GLClientState.h
@@ -91,6 +91,12 @@
     void setActiveTexture(int texUnit) {m_activeTexture = texUnit; };
     int getActiveTexture() const { return m_activeTexture; }
 
+    void unBindBuffer(GLuint id)
+    {
+        if (m_currentArrayVbo == id) m_currentArrayVbo = 0;
+        else if (m_currentIndexVbo == id) m_currentIndexVbo = 0;
+    }
+
     int bindBuffer(GLenum target, GLuint id)
     {
         int err = 0;
diff --git a/opengl/shared/OpenglCodecCommon/GLSharedGroup.cpp b/opengl/shared/OpenglCodecCommon/GLSharedGroup.cpp
old mode 100644
new mode 100755
index 8504f7f..b079b6d
--- a/opengl/shared/OpenglCodecCommon/GLSharedGroup.cpp
+++ b/opengl/shared/OpenglCodecCommon/GLSharedGroup.cpp
@@ -16,10 +16,19 @@
 
 #include "GLSharedGroup.h"
 
+/**** KeyedVector utilities ****/
+
+template <typename T>
+static void clearObjectMap(android::DefaultKeyedVector<GLuint, T>& v) {
+    for (size_t i = 0; i < v.size(); i++)
+        delete v.valueAt(i);
+    v.clear();
+}
+
 /**** BufferData ****/
 
 BufferData::BufferData() : m_size(0) {};
-BufferData::BufferData(GLsizeiptr size, void * data) : m_size(size) 
+BufferData::BufferData(GLsizeiptr size, void * data) : m_size(size)
 {
     void * buffer = NULL;
     if (size>0) buffer = m_fixedBuffer.alloc(size);
@@ -55,7 +64,7 @@
 }
 
 void ProgramData::setIndexInfo(GLuint index, GLint base, GLint size, GLenum type)
-{   
+{
     if (index>=m_numIndexes)
         return;
     m_Indexes[index].base = base;
@@ -87,7 +96,7 @@
     for (GLuint i=0;i<m_numIndexes;++i)
     {
         GLint dist = location - m_Indexes[i].base;
-        if (dist >= 0 && 
+        if (dist >= 0 &&
             (minDist < 0 || dist < minDist)) {
             index = i;
             minDist = dist;
@@ -126,7 +135,7 @@
     GLuint index = getIndexForLocation(hostLoc);
     if (index<m_numIndexes) {
         if (arrIndex > 0) {
-            m_Indexes[index].hostLocsPerElement = 
+            m_Indexes[index].hostLocsPerElement =
                               (hostLoc - m_Indexes[index].base) / arrIndex;
         }
         return m_Indexes[index].appBase + arrIndex;
@@ -226,12 +235,21 @@
 {
     m_buffers.clear();
     m_programs.clear();
+    clearObjectMap(m_buffers);
+    clearObjectMap(m_programs);
+    clearObjectMap(m_shaders);
+}
+
+bool GLSharedGroup::isObject(GLuint obj)
+{
+    android::AutoMutex _lock(m_lock);
+    return ((m_shaders.valueFor(obj)!=NULL) || (m_programs.valueFor(obj)!=NULL));
 }
 
 BufferData * GLSharedGroup::getBufferData(GLuint bufferId)
 {
     android::AutoMutex _lock(m_lock);
-    return m_buffers.valueFor(bufferId);    
+    return m_buffers.valueFor(bufferId);
 }
 
 void GLSharedGroup::addBufferData(GLuint bufferId, GLsizeiptr size, void * data)
@@ -243,32 +261,42 @@
 void GLSharedGroup::updateBufferData(GLuint bufferId, GLsizeiptr size, void * data)
 {
     android::AutoMutex _lock(m_lock);
-    m_buffers.replaceValueFor(bufferId, new BufferData(size, data));
+    ssize_t idx = m_buffers.indexOfKey(bufferId);
+    if (idx >= 0) {
+        delete m_buffers.valueAt(idx);
+        m_buffers.editValueAt(idx) = new BufferData(size, data);
+    } else {
+        m_buffers.add(bufferId, new BufferData(size, data));
+    }
 }
 
 GLenum GLSharedGroup::subUpdateBufferData(GLuint bufferId, GLintptr offset, GLsizeiptr size, void * data)
 {
     android::AutoMutex _lock(m_lock);
     BufferData * buf = m_buffers.valueFor(bufferId);
-    if ((!buf) || (buf->m_size < offset+size) || (offset < 0) || (size<0)) return GL_INVALID_VALUE; 
+    if ((!buf) || (buf->m_size < offset+size) || (offset < 0) || (size<0)) return GL_INVALID_VALUE;
 
     //it's safe to update now
     memcpy((char*)buf->m_fixedBuffer.ptr() + offset, data, size);
-    return GL_NO_ERROR; 
+    return GL_NO_ERROR;
 }
 
 void GLSharedGroup::deleteBufferData(GLuint bufferId)
 {
     android::AutoMutex _lock(m_lock);
-    m_buffers.removeItem(bufferId);
+    ssize_t idx = m_buffers.indexOfKey(bufferId);
+    if (idx >= 0) {
+        delete m_buffers.valueAt(idx);
+        m_buffers.removeItemsAt(idx);
+    }
 }
 
 void GLSharedGroup::addProgramData(GLuint program)
 {
     android::AutoMutex _lock(m_lock);
     ProgramData *pData = m_programs.valueFor(program);
-    if (pData) 
-    {   
+    if (pData)
+    {
         m_programs.removeItem(program);
         delete pData;
     }
@@ -290,7 +318,7 @@
 {
     android::AutoMutex _lock(m_lock);
     ProgramData* pData = m_programs.valueFor(program);
-    if (pData) 
+    if (pData)
     {
         return pData->isInitialized();
     }
@@ -303,7 +331,7 @@
     ProgramData *pData = m_programs.valueFor(program);
     if (pData)
         delete pData;
-    m_programs.removeItem(program); 
+    m_programs.removeItem(program);
 }
 
 void GLSharedGroup::attachShader(GLuint program, GLuint shader)
@@ -363,7 +391,7 @@
     android::AutoMutex _lock(m_lock);
     ProgramData* pData = m_programs.valueFor(program);
     GLenum type=0;
-    if (pData) 
+    if (pData)
     {
         type = pData->getTypeForLocation(location);
     }
diff --git a/opengl/shared/OpenglCodecCommon/GLSharedGroup.h b/opengl/shared/OpenglCodecCommon/GLSharedGroup.h
old mode 100644
new mode 100755
index 61b8f00..6dfcd8f
--- a/opengl/shared/OpenglCodecCommon/GLSharedGroup.h
+++ b/opengl/shared/OpenglCodecCommon/GLSharedGroup.h
@@ -110,6 +110,7 @@
 public:
     GLSharedGroup();
     ~GLSharedGroup();
+    bool isObject(GLuint obj);
     BufferData * getBufferData(GLuint bufferId);
     void    addBufferData(GLuint bufferId, GLsizeiptr size, void * data);
     void    updateBufferData(GLuint bufferId, GLsizeiptr size, void * data);
diff --git a/opengl/system/GLESv1_enc/GLEncoder.cpp b/opengl/system/GLESv1_enc/GLEncoder.cpp
index 4414f24..989c26f 100644
--- a/opengl/system/GLESv1_enc/GLEncoder.cpp
+++ b/opengl/system/GLESv1_enc/GLEncoder.cpp
@@ -464,19 +464,19 @@
                 switch(i) {
                 case GLClientState::VERTEX_LOCATION:
                     this->glVertexPointerOffset(this, state->size, state->type, state->stride,
-                                                (GLuint)state->data + firstIndex);
+                                                (uintptr_t)state->data + firstIndex);
                     break;
                 case GLClientState::NORMAL_LOCATION:
                     this->glNormalPointerOffset(this, state->type, state->stride,
-                                                (GLuint) state->data + firstIndex);
+                                                (uintptr_t)state->data + firstIndex);
                     break;
                 case GLClientState::POINTSIZE_LOCATION:
                     this->glPointSizePointerOffset(this, state->type, state->stride,
-                                                   (GLuint) state->data + firstIndex);
+                                                   (uintptr_t)state->data + firstIndex);
                     break;
                 case GLClientState::COLOR_LOCATION:
                     this->glColorPointerOffset(this, state->size, state->type, state->stride,
-                                               (GLuint) state->data + firstIndex);
+                                               (uintptr_t)state->data + firstIndex);
                     break;
                 case GLClientState::TEXCOORD0_LOCATION:
                 case GLClientState::TEXCOORD1_LOCATION:
@@ -487,17 +487,17 @@
                 case GLClientState::TEXCOORD6_LOCATION:
                 case GLClientState::TEXCOORD7_LOCATION:
                     this->glTexCoordPointerOffset(this, state->size, state->type, state->stride,
-                                                  (GLuint) state->data + firstIndex);
+                                                  (uintptr_t)state->data + firstIndex);
                     break;
                 case GLClientState::WEIGHT_LOCATION:
                     this->glWeightPointerOffset(this,state->size,state->type,state->stride,
-                                                (GLuint)state->data+firstIndex);
+                                                (uintptr_t)state->data+firstIndex);
                     break;
                 case GLClientState::MATRIXINDEX_LOCATION:
                     this->glMatrixIndexPointerOffset(this,state->size,state->type,state->stride,
-                                              (GLuint)state->data+firstIndex);
+                                              (uintptr_t)state->data+firstIndex);
                     break;
-                }                
+                }
                 this->m_glBindBuffer_enc(this, GL_ARRAY_BUFFER, m_state->currentArrayVbo());
             }
         } else {
@@ -545,14 +545,14 @@
         if (!has_immediate_arrays) {
             ctx->sendVertexData(0, count);
             ctx->m_glBindBuffer_enc(self, GL_ELEMENT_ARRAY_BUFFER, ctx->m_state->currentIndexVbo());
-            ctx->glDrawElementsOffset(ctx, mode, count, type, (GLuint)indices);
+            ctx->glDrawElementsOffset(ctx, mode, count, type, (uintptr_t)indices);
             adjustIndices = false;
         } else {
             BufferData * buf = ctx->m_shared->getBufferData(ctx->m_state->currentIndexVbo());
             ctx->m_glBindBuffer_enc(self, GL_ELEMENT_ARRAY_BUFFER, 0);
             indices = (void*)((GLintptr)buf->m_fixedBuffer.ptr() + (GLintptr)indices);
         }
-    } 
+    }
     if (adjustIndices) {
         void *adjustedIndices = (void*)indices;
         int minIndex = 0, maxIndex = 0;
diff --git a/opengl/system/GLESv2_enc/GL2Encoder.cpp b/opengl/system/GLESv2_enc/GL2Encoder.cpp
old mode 100644
new mode 100755
index 7fc32b5..db0e270
--- a/opengl/system/GLESv2_enc/GL2Encoder.cpp
+++ b/opengl/system/GLESv2_enc/GL2Encoder.cpp
@@ -79,6 +79,11 @@
     m_glDeleteShader_enc = set_glDeleteShader(s_glDeleteShader);
     m_glAttachShader_enc = set_glAttachShader(s_glAttachShader);
     m_glDetachShader_enc = set_glDetachShader(s_glDetachShader);
+    m_glGetAttachedShaders_enc = set_glGetAttachedShaders(s_glGetAttachedShaders);
+    m_glGetShaderSource_enc = set_glGetShaderSource(s_glGetShaderSource);
+    m_glGetShaderInfoLog_enc = set_glGetShaderInfoLog(s_glGetShaderInfoLog);
+    m_glGetProgramInfoLog_enc = set_glGetProgramInfoLog(s_glGetProgramInfoLog);
+
     m_glGetUniformLocation_enc = set_glGetUniformLocation(s_glGetUniformLocation);
     m_glUseProgram_enc = set_glUseProgram(s_glUseProgram);
 
@@ -111,6 +116,7 @@
     m_glTexParameterfv_enc = set_glTexParameterfv(s_glTexParameterfv);
     m_glTexParameteri_enc = set_glTexParameteri(s_glTexParameteri);
     m_glTexParameteriv_enc = set_glTexParameteriv(s_glTexParameteriv);
+    m_glTexImage2D_enc = set_glTexImage2D(s_glTexImage2D);
 }
 
 GL2Encoder::~GL2Encoder()
@@ -179,6 +185,7 @@
 void GL2Encoder::s_glBufferData(void * self, GLenum target, GLsizeiptr size, const GLvoid * data, GLenum usage)
 {
     GL2Encoder *ctx = (GL2Encoder *) self;
+    SET_ERROR_IF(!(target == GL_ARRAY_BUFFER || target == GL_ELEMENT_ARRAY_BUFFER), GL_INVALID_ENUM);
     GLuint bufferId = ctx->m_state->getBuffer(target);
     SET_ERROR_IF(bufferId==0, GL_INVALID_OPERATION);
     SET_ERROR_IF(size<0, GL_INVALID_VALUE);
@@ -190,6 +197,7 @@
 void GL2Encoder::s_glBufferSubData(void * self, GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid * data)
 {
     GL2Encoder *ctx = (GL2Encoder *) self;
+    SET_ERROR_IF(!(target == GL_ARRAY_BUFFER || target == GL_ELEMENT_ARRAY_BUFFER), GL_INVALID_ENUM);
     GLuint bufferId = ctx->m_state->getBuffer(target);
     SET_ERROR_IF(bufferId==0, GL_INVALID_OPERATION);
 
@@ -205,6 +213,7 @@
     SET_ERROR_IF(n<0, GL_INVALID_VALUE);
     for (int i=0; i<n; i++) {
         ctx->m_shared->deleteBufferData(buffers[i]);
+        ctx->m_state->unBindBuffer(buffers[i]);
         ctx->m_glDeleteBuffers_enc(self,1,&buffers[i]);
     }
 }
@@ -348,6 +357,7 @@
         if (!ctx->m_state->getClientStateParameter<GLboolean>(param, ptr)) {
             ctx->m_glGetBooleanv_enc(self, param, ptr);
         }
+        *ptr = (*ptr != 0) ? GL_TRUE : GL_FALSE;
         break;
     }
 }
@@ -424,15 +434,15 @@
             int stride = state->stride == 0 ? state->elementSize : state->stride;
             int firstIndex = stride * first;
 
+            this->m_glBindBuffer_enc(this, GL_ARRAY_BUFFER, state->bufferObject);
             if (state->bufferObject == 0) {
                 this->glVertexAttribPointerData(this, i, state->size, state->type, state->normalized, state->stride,
                                                 (unsigned char *)state->data + firstIndex, datalen);
             } else {
-                this->m_glBindBuffer_enc(this, GL_ARRAY_BUFFER, state->bufferObject);
                 this->glVertexAttribPointerOffset(this, i, state->size, state->type, state->normalized, state->stride,
-                                                  (GLuint) state->data + firstIndex);
-                this->m_glBindBuffer_enc(this, GL_ARRAY_BUFFER, m_state->currentArrayVbo());
+                                                  (uintptr_t) state->data + firstIndex);
             }
+            this->m_glBindBuffer_enc(this, GL_ARRAY_BUFFER, m_state->currentArrayVbo());
         } else {
             this->m_glDisableVertexAttribArray_enc(this, i);
         }
@@ -479,7 +489,7 @@
         if (!has_immediate_arrays) {
             ctx->sendVertexAttributes(0, count);
             ctx->m_glBindBuffer_enc(self, GL_ELEMENT_ARRAY_BUFFER, ctx->m_state->currentIndexVbo());
-            ctx->glDrawElementsOffset(ctx, mode, count, type, (GLuint)indices);
+            ctx->glDrawElementsOffset(ctx, mode, count, type, (uintptr_t)indices);
             adjustIndices = false;
         } else {
             BufferData * buf = ctx->m_shared->getBufferData(ctx->m_state->currentIndexVbo());
@@ -637,7 +647,9 @@
 {
     GL2Encoder* ctx = (GL2Encoder*)self;
     ShaderData* shaderData = ctx->m_shared->getShaderData(shader);
-    SET_ERROR_IF(!shaderData, GL_INVALID_VALUE);
+    SET_ERROR_IF(!ctx->m_shared->isObject(shader), GL_INVALID_VALUE);
+    SET_ERROR_IF(!shaderData, GL_INVALID_OPERATION);
+    SET_ERROR_IF((count<0), GL_INVALID_VALUE);
 
     int len = glUtilsCalcShaderSourceLen((char**)string, (GLint*)length, count);
     char *str = new char[len + 1];
@@ -746,6 +758,38 @@
     return shader;
 }
 
+void GL2Encoder::s_glGetAttachedShaders(void *self, GLuint program, GLsizei maxCount,
+        GLsizei* count, GLuint* shaders)
+{
+    GL2Encoder *ctx = (GL2Encoder*)self;
+    SET_ERROR_IF(maxCount < 0, GL_INVALID_VALUE);
+    ctx->m_glGetAttachedShaders_enc(self, program, maxCount, count, shaders);
+}
+
+void GL2Encoder::s_glGetShaderSource(void *self, GLuint shader, GLsizei bufsize,
+            GLsizei* length, GLchar* source)
+{
+    GL2Encoder *ctx = (GL2Encoder*)self;
+    SET_ERROR_IF(bufsize < 0, GL_INVALID_VALUE);
+    ctx->m_glGetShaderSource_enc(self, shader, bufsize, length, source);
+}
+
+void GL2Encoder::s_glGetShaderInfoLog(void *self, GLuint shader, GLsizei bufsize,
+        GLsizei* length, GLchar* infolog)
+{
+    GL2Encoder *ctx = (GL2Encoder*)self;
+    SET_ERROR_IF(bufsize < 0, GL_INVALID_VALUE);
+    ctx->m_glGetShaderInfoLog_enc(self, shader, bufsize, length, infolog);
+}
+
+void GL2Encoder::s_glGetProgramInfoLog(void *self, GLuint program, GLsizei bufsize,
+        GLsizei* length, GLchar* infolog)
+{
+    GL2Encoder *ctx = (GL2Encoder*)self;
+    SET_ERROR_IF(bufsize < 0, GL_INVALID_VALUE);
+    ctx->m_glGetProgramInfoLog_enc(self, program, bufsize, length, infolog);
+}
+
 void GL2Encoder::s_glDeleteShader(void *self, GLenum shader)
 {
     GL2Encoder *ctx = (GL2Encoder*)self;
@@ -1161,6 +1205,23 @@
     }
 }
 
+void GL2Encoder::s_glTexImage2D(void* self, GLenum target, GLint level,
+        GLint internalformat, GLsizei width, GLsizei height, GLint border,
+        GLenum format, GLenum type, const GLvoid* pixels)
+{
+    GL2Encoder* ctx = (GL2Encoder*)self;
+    if (target == GL_TEXTURE_2D || target == GL_TEXTURE_EXTERNAL_OES) {
+        ctx->override2DTextureTarget(target);
+        ctx->m_glTexImage2D_enc(ctx, target, level, internalformat, width,
+                height, border, format, type, pixels);
+        ctx->restore2DTextureTarget();
+    } else {
+        ctx->m_glTexImage2D_enc(ctx, target, level, internalformat, width,
+                height, border, format, type, pixels);
+    }
+}
+
+
 void GL2Encoder::s_glTexParameteriv(void* self,
         GLenum target, GLenum pname, const GLint* params)
 {
diff --git a/opengl/system/GLESv2_enc/GL2Encoder.h b/opengl/system/GLESv2_enc/GL2Encoder.h
index c6506a9..927bd66 100644
--- a/opengl/system/GLESv2_enc/GL2Encoder.h
+++ b/opengl/system/GLESv2_enc/GL2Encoder.h
@@ -148,6 +148,22 @@
     glDetachShader_client_proc_t m_glDetachShader_enc;
     static void s_glDetachShader(void *self, GLuint program, GLuint shader);
 
+    glGetAttachedShaders_client_proc_t m_glGetAttachedShaders_enc;
+    static void s_glGetAttachedShaders(void *self, GLuint program, GLsizei maxCount,
+            GLsizei* count, GLuint* shaders);
+
+    glGetShaderSource_client_proc_t m_glGetShaderSource_enc;
+    static void s_glGetShaderSource(void *self, GLuint shader, GLsizei bufsize,
+            GLsizei* length, GLchar* source);
+
+    glGetShaderInfoLog_client_proc_t m_glGetShaderInfoLog_enc;
+    static void s_glGetShaderInfoLog(void *self,GLuint shader,
+            GLsizei bufsize, GLsizei* length, GLchar* infolog);
+
+    glGetProgramInfoLog_client_proc_t m_glGetProgramInfoLog_enc;
+    static void s_glGetProgramInfoLog(void *self,GLuint program,
+            GLsizei bufsize, GLsizei* length, GLchar* infolog);
+
     glGetUniformLocation_client_proc_t m_glGetUniformLocation_enc;
     static int s_glGetUniformLocation(void *self, GLuint program, const GLchar *name);
     glUseProgram_client_proc_t m_glUseProgram_enc;
@@ -202,6 +218,7 @@
     glTexParameterfv_client_proc_t m_glTexParameterfv_enc;
     glTexParameteri_client_proc_t m_glTexParameteri_enc;
     glTexParameteriv_client_proc_t m_glTexParameteriv_enc;
+    glTexImage2D_client_proc_t m_glTexImage2D_enc;
 
     static void s_glActiveTexture(void* self, GLenum texture);
     static void s_glBindTexture(void* self, GLenum target, GLuint texture);
@@ -212,5 +229,9 @@
     static void s_glTexParameterfv(void* self, GLenum target, GLenum pname, const GLfloat* params);
     static void s_glTexParameteri(void* self, GLenum target, GLenum pname, GLint param);
     static void s_glTexParameteriv(void* self, GLenum target, GLenum pname, const GLint* params);
+    static void s_glTexImage2D(void* self, GLenum target, GLint level, GLint internalformat,
+            GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type,
+            const GLvoid* pixels);
+
 };
 #endif
diff --git a/opengl/system/GLESv2_enc/gl2_enc.cpp b/opengl/system/GLESv2_enc/gl2_enc.cpp
index 46684e9..5929697 100644
--- a/opengl/system/GLESv2_enc/gl2_enc.cpp
+++ b/opengl/system/GLESv2_enc/gl2_enc.cpp
@@ -1162,7 +1162,7 @@
 	gl2_encoder_context_t *ctx = (gl2_encoder_context_t *)self;
 	IOStream *stream = ctx->m_stream;
 
-	const unsigned int __size_length =  sizeof(GLsizei);
+	const unsigned int __size_length = ((length != NULL) ?  (sizeof(GLsizei)) : 0);
 	const unsigned int __size_infolog =  bufsize;
 	 unsigned char *ptr;
 	 const size_t packetSize = 8 + 4 + 4 + __size_length + __size_infolog + 2*4;
@@ -1174,7 +1174,7 @@
 		memcpy(ptr, &bufsize, 4); ptr += 4;
 	*(unsigned int *)(ptr) = __size_length; ptr += 4;
 	*(unsigned int *)(ptr) = __size_infolog; ptr += 4;
-	stream->readback(length, __size_length);
+	if (length != NULL) stream->readback(length, __size_length);
 	stream->readback(infolog, __size_infolog);
 }
 
@@ -1923,7 +1923,7 @@
 	gl2_encoder_context_t *ctx = (gl2_encoder_context_t *)self;
 	IOStream *stream = ctx->m_stream;
 
-	const unsigned int __size_pixels =  pixelDataSize(self, width, height, format, type, 0);
+	const unsigned int __size_pixels = ((pixels != NULL) ?  pixelDataSize(self, width, height, format, type, 0) : 0);
 	 unsigned char *ptr;
 	 const size_t packetSize = 8 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + __size_pixels + 1*4;
 	ptr = stream->alloc(8 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4);
@@ -1940,7 +1940,7 @@
 		memcpy(ptr, &type, 4); ptr += 4;
 	stream->flush();
 	stream->writeFully(&__size_pixels,4);
-	stream->writeFully(pixels, __size_pixels);
+	if (pixels != NULL) stream->writeFully(pixels, __size_pixels);
 }
 
 void glUniform1f_enc(void *self , GLint location, GLfloat x)
diff --git a/opengl/system/OpenglSystemCommon/QemuPipeStream.cpp b/opengl/system/OpenglSystemCommon/QemuPipeStream.cpp
index a55dca0..5798370 100644
--- a/opengl/system/OpenglSystemCommon/QemuPipeStream.cpp
+++ b/opengl/system/OpenglSystemCommon/QemuPipeStream.cpp
@@ -87,6 +87,10 @@
 {
     //DBG(">> QemuPipeStream::writeFully %d\n", len);
     if (!valid()) return -1;
+    if (!buf) {
+        if (len>0) ERR("QemuPipeStream::writeFully failed, buf=NULL, len %d", len);
+        return 0;
+    }
 
     size_t res = len;
     int retval = 0;
diff --git a/opengl/system/OpenglSystemCommon/ThreadInfo.cpp b/opengl/system/OpenglSystemCommon/ThreadInfo.cpp
index 75da8f2..f9c8521 100644
--- a/opengl/system/OpenglSystemCommon/ThreadInfo.cpp
+++ b/opengl/system/OpenglSystemCommon/ThreadInfo.cpp
@@ -24,6 +24,7 @@
         EGLThreadInfo *ti = (EGLThreadInfo *)ptr;
         delete ti->hostConn;
         delete ti;
+        ((intptr_t *)__get_tls())[TLS_SLOT_OPENGL] = NULL;
     }
 }
 
diff --git a/opengl/system/OpenglSystemCommon/ThreadInfo.h b/opengl/system/OpenglSystemCommon/ThreadInfo.h
index 0328733..f59ce2a 100644
--- a/opengl/system/OpenglSystemCommon/ThreadInfo.h
+++ b/opengl/system/OpenglSystemCommon/ThreadInfo.h
@@ -40,10 +40,10 @@
     // We have a dedicated TLS slot in bionic
     inline EGLThreadInfo* getEGLThreadInfo() {
         EGLThreadInfo *tInfo =
-             (EGLThreadInfo *)(((unsigned *)__get_tls())[TLS_SLOT_OPENGL]);
+             (EGLThreadInfo *)(((uintptr_t *)__get_tls())[TLS_SLOT_OPENGL]);
         if (!tInfo) {
             tInfo = slow_getEGLThreadInfo();
-            ((uint32_t *)__get_tls())[TLS_SLOT_OPENGL] = (uint32_t)tInfo;
+            ((uintptr_t *)__get_tls())[TLS_SLOT_OPENGL] = (uintptr_t)tInfo;
         }
         return tInfo;
     }
diff --git a/opengl/system/OpenglSystemCommon/gralloc_cb.h b/opengl/system/OpenglSystemCommon/gralloc_cb.h
index fd35473..d2d6f35 100644
--- a/opengl/system/OpenglSystemCommon/gralloc_cb.h
+++ b/opengl/system/OpenglSystemCommon/gralloc_cb.h
@@ -71,8 +71,8 @@
         numInts = CB_HANDLE_NUM_INTS(numFds);
     }
 
-    static bool validate(cb_handle_t * hnd) {
-        return (hnd && 
+    static bool validate(const cb_handle_t* hnd) {
+        return (hnd &&
                 hnd->version == sizeof(native_handle) &&
                 hnd->magic == BUFFER_HANDLE_MAGIC &&
                 hnd->numInts == CB_HANDLE_NUM_INTS(hnd->numFds));
@@ -96,7 +96,11 @@
     int glType;             // OpenGL type enum used when uploading to host
     int ashmemSize;         // ashmem region size for the buffer (0 unless is HW_FB buffer or
                             //                                    s/w access is needed)
-    int ashmemBase;         // CPU address of the mapped ashmem region
+    union {
+        intptr_t ashmemBase;    // CPU address of the mapped ashmem region
+        uint64_t padding;       // enforce same size on 32-bit/64-bit
+    } __attribute__((aligned(8)));
+
     int ashmemBasePid;      // process id which mapped the ashmem region
     int mappedPid;          // process id which succeeded gralloc_register call
     int lockedLeft;         // region of buffer locked for s/w write
diff --git a/opengl/system/egl/egl.cpp b/opengl/system/egl/egl.cpp
index da89c4d..65ff39e 100644
--- a/opengl/system/egl/egl.cpp
+++ b/opengl/system/egl/egl.cpp
@@ -86,7 +86,7 @@
 #endif //LOG_EGL_ERRORS
 
 #define VALIDATE_CONFIG(cfg,ret) \
-    if(((int)cfg<0)||((int)cfg>s_display.getNumConfigs())) { \
+    if(((intptr_t)cfg<0)||((intptr_t)cfg>s_display.getNumConfigs())) { \
         RETURN_ERROR(ret,EGL_BAD_CONFIG); \
     }
 
@@ -140,7 +140,9 @@
     versionString(NULL),
     vendorString(NULL),
     rendererString(NULL),
-    extensionString(NULL)
+    shaderVersionString(NULL),
+    extensionString(NULL),
+    deletePending(0)
 {
     flags = 0;
     version = 1;
@@ -157,6 +159,7 @@
     delete [] versionString;
     delete [] vendorString;
     delete [] rendererString;
+    delete [] shaderVersionString;
     delete [] extensionString;
 }
 
@@ -268,7 +271,7 @@
     }
 
     DEFINE_AND_VALIDATE_HOST_CONNECTION(EGL_FALSE);
-    rcSurface = rcEnc->rcCreateWindowSurface(rcEnc, (uint32_t)config,
+    rcSurface = rcEnc->rcCreateWindowSurface(rcEnc, (uintptr_t)config,
             getWidth(), getHeight());
     if (!rcSurface) {
         ALOGE("rcCreateWindowSurface returned 0");
@@ -371,7 +374,7 @@
 {
     DEFINE_AND_VALIDATE_HOST_CONNECTION(EGL_FALSE);
 
-    rcSurface = rcEnc->rcCreateWindowSurface(rcEnc, (uint32_t)config,
+    rcSurface = rcEnc->rcCreateWindowSurface(rcEnc, (uintptr_t)config,
             getWidth(), getHeight());
     if (!rcSurface) {
         ALOGE("rcCreateWindowSurface returned 0");
@@ -415,6 +418,7 @@
 #define GL_VENDOR                         0x1F00
 #define GL_RENDERER                       0x1F01
 #define GL_VERSION                        0x1F02
+#define GL_SHADING_LANGUAGE_VERSION       0x8B8C
 #define GL_EXTENSIONS                     0x1F03
 
     switch(glEnum) {
@@ -427,6 +431,9 @@
         case GL_RENDERER:
             strPtr = &tInfo->currentContext->rendererString;
             break;
+        case GL_SHADING_LANGUAGE_VERSION:
+            strPtr = &tInfo->currentContext->shaderVersionString;
+            break;
         case GL_EXTENSIONS:
             strPtr = &tInfo->currentContext->extensionString;
             break;
@@ -526,15 +533,6 @@
         }
     }
 
-    //
-    // Make sure display is initialized before searching in client APIs
-    //
-    if (!s_display.initialized()) {
-        if (!s_display.initialize(&s_eglIface)) {
-            return NULL;
-        }
-    }
-
     // look in gles client api's extensions table
     return (__eglMustCastToProperFunctionPointerType)ClientAPIExts::getProcAddress(procname);
 
@@ -563,7 +561,7 @@
         return EGL_TRUE;
     }
 
-    int i=0;
+    uintptr_t i=0;
     for (i=0 ; i<numConfigs && i<config_size ; i++) {
         *configs++ = (EGLConfig)i;
     }
@@ -585,9 +583,18 @@
         attribs_size++; //for the terminating EGL_NONE
     }
 
+    uint32_t* tempConfigs[config_size];
     DEFINE_AND_VALIDATE_HOST_CONNECTION(EGL_FALSE);
-    *num_config = rcEnc->rcChooseConfig(rcEnc, (EGLint*)attrib_list, attribs_size * sizeof(EGLint), (uint32_t*)configs, config_size);
+    *num_config = rcEnc->rcChooseConfig(rcEnc, (EGLint*)attrib_list, attribs_size * sizeof(EGLint), (uint32_t*)tempConfigs, config_size);
+    if (configs!=NULL) {
+        EGLint i=0;
+        for (i=0;i<(*num_config);i++) {
+             *((uintptr_t*)configs+i) = *((uint32_t*)tempConfigs+i);
+        }
+    }
 
+    if (*num_config <= 0)
+        return EGL_FALSE;
     return EGL_TRUE;
 }
 
@@ -873,7 +880,7 @@
     }
 
     DEFINE_AND_VALIDATE_HOST_CONNECTION(EGL_NO_CONTEXT);
-    uint32_t rcContext = rcEnc->rcCreateContext(rcEnc, (uint32_t)config, rcShareCtx, version);
+    uint32_t rcContext = rcEnc->rcCreateContext(rcEnc, (uintptr_t)config, rcShareCtx, version);
     if (!rcContext) {
         ALOGE("rcCreateContext returned 0");
         setErrorReturn(EGL_BAD_ALLOC, EGL_NO_CONTEXT);
@@ -897,9 +904,11 @@
 
     EGLContext_t * context = static_cast<EGLContext_t*>(ctx);
 
-    if (getEGLThreadInfo()->currentContext == context)
-    {
-        eglMakeCurrent(dpy, EGL_NO_CONTEXT, EGL_NO_SURFACE, EGL_NO_SURFACE);
+    if (!context) return EGL_TRUE;
+
+    if (getEGLThreadInfo()->currentContext == context) {
+        getEGLThreadInfo()->currentContext->deletePending = 1;
+        return EGL_TRUE;
     }
 
     if (context->rcContext) {
@@ -934,12 +943,21 @@
     // Nothing to do if no binding change has made
     //
     EGLThreadInfo *tInfo = getEGLThreadInfo();
+
     if (tInfo->currentContext == context &&
         (context == NULL ||
         (context && context->draw == draw && context->read == read))) {
         return EGL_TRUE;
     }
 
+    if (tInfo->currentContext && tInfo->currentContext->deletePending) {
+        if (tInfo->currentContext != context) {
+            EGLContext_t * contextToDelete = tInfo->currentContext;
+            tInfo->currentContext = 0;
+            eglDestroyContext(dpy, contextToDelete);
+        }
+    }
+
     if (context && (context->flags & EGLContext_t::IS_CURRENT) && (context != tInfo->currentContext)) {
         //context is current to another thread
         setErrorReturn(EGL_BAD_ACCESS, EGL_FALSE);
@@ -966,7 +984,7 @@
             hostCon->glEncoder()->setSharedGroup(context->getSharedGroup());
         }
     } 
-    else {
+    else if (tInfo->currentContext) {
         //release ClientState & SharedGroup
         if (tInfo->currentContext->version == 2) {
             hostCon->gl2Encoder()->setClientState(NULL);
diff --git a/opengl/system/egl/eglContext.h b/opengl/system/egl/eglContext.h
index 2ca6d0c..5b6a428 100644
--- a/opengl/system/egl/eglContext.h
+++ b/opengl/system/egl/eglContext.h
@@ -39,8 +39,9 @@
     const char*         versionString;
     const char*         vendorString;
     const char*         rendererString;
+    const char*         shaderVersionString;
     const char*         extensionString;
-
+    EGLint              deletePending;
     GLClientState * getClientState(){ return clientState; }
     GLSharedGroupPtr getSharedGroup(){ return sharedGroup; }
 private:
diff --git a/opengl/system/egl/eglDisplay.cpp b/opengl/system/egl/eglDisplay.cpp
index bcb0d4b..96540aa 100644
--- a/opengl/system/egl/eglDisplay.cpp
+++ b/opengl/system/egl/eglDisplay.cpp
@@ -84,9 +84,15 @@
         //
         // load GLES client API
         //
+#if __LP64__
+        m_gles_iface = loadGLESClientAPI("/system/lib64/egl/libGLESv1_CM_emulation.so",
+                                         eglIface,
+                                         &s_gles_lib);
+#else
         m_gles_iface = loadGLESClientAPI("/system/lib/egl/libGLESv1_CM_emulation.so",
                                          eglIface,
                                          &s_gles_lib);
+#endif
         if (!m_gles_iface) {
             pthread_mutex_unlock(&m_lock);
             ALOGE("Failed to load gles1 iface");
@@ -94,9 +100,15 @@
         }
 
 #ifdef WITH_GLES2
+#if __LP64__
+        m_gles2_iface = loadGLESClientAPI("/system/lib64/egl/libGLESv2_emulation.so",
+                                          eglIface,
+                                          &s_gles2_lib);
+#else
         m_gles2_iface = loadGLESClientAPI("/system/lib/egl/libGLESv2_emulation.so",
                                           eglIface,
                                           &s_gles2_lib);
+#endif
         // Note that if loading gles2 failed, we can still run with no
         // GLES2 support, having GLES2 is not mandatory.
 #endif
@@ -189,7 +201,7 @@
 
 void eglDisplay::processConfigs()
 {
-    for (int i=0; i<m_numConfigs; i++) {
+    for (intptr_t i=0; i<m_numConfigs; i++) {
         EGLConfig config = (EGLConfig)i;
         //Setup the EGL_NATIVE_VISUAL_ID attribute
         PixelFormat format;
@@ -401,7 +413,7 @@
         ALOGE("[%s] Bad attribute idx\n", __FUNCTION__);
         return EGL_FALSE;
     }
-    *value = *(m_configs + (int)config*m_numConfigAttribs + attribIdx);
+    *value = *(m_configs + (intptr_t)config*m_numConfigAttribs + attribIdx);
     return EGL_TRUE;
 }
 
@@ -434,7 +446,7 @@
         ALOGE("[%s] Bad attribute idx\n", __FUNCTION__);
         return EGL_FALSE;
     }
-    *(m_configs + (int)config*m_numConfigAttribs + attribIdx) = value;
+    *(m_configs + (intptr_t)config*m_numConfigAttribs + attribIdx) = value;
     return EGL_TRUE;
 }
 
diff --git a/opengl/system/gralloc/gralloc.cpp b/opengl/system/gralloc/gralloc.cpp
index ed5d05f..8fd1584 100644
--- a/opengl/system/gralloc/gralloc.cpp
+++ b/opengl/system/gralloc/gralloc.cpp
@@ -15,11 +15,7 @@
 */
 #include <string.h>
 #include <pthread.h>
-#ifdef HAVE_ANDROID_OS      // just want PAGE_SIZE define
-# include <asm/page.h>
-#else
-# include <sys/user.h>
-#endif
+#include <limits.h>
 #include <cutils/ashmem.h>
 #include <unistd.h>
 #include <errno.h>
@@ -332,6 +328,7 @@
     //
     if (usage & (GRALLOC_USAGE_HW_TEXTURE | GRALLOC_USAGE_HW_RENDER |
                     GRALLOC_USAGE_HW_2D | GRALLOC_USAGE_HW_COMPOSER |
+                    GRALLOC_USAGE_SW_READ_OFTEN |
                     GRALLOC_USAGE_HW_FB) ) {
         DEFINE_HOST_CONNECTION;
         if (hostCon && rcEnc) {
@@ -460,7 +457,7 @@
     DEFINE_AND_VALIDATE_HOST_CONNECTION;
 
     // increment the post count of the buffer
-    uint32_t *postCountPtr = (uint32_t *)cb->ashmemBase;
+    intptr_t *postCountPtr = (intptr_t *)cb->ashmemBase;
     if (!postCountPtr) {
         // This should not happen
         return -EINVAL;
@@ -545,7 +542,7 @@
     if (cb->hostHandle != 0) {
         DEFINE_AND_VALIDATE_HOST_CONNECTION;
         D("Opening host ColorBuffer 0x%x\n", cb->hostHandle);
-        rcEnc->rcOpenColorBuffer(rcEnc, cb->hostHandle);
+        rcEnc->rcOpenColorBuffer2(rcEnc, cb->hostHandle);
     }
 
     //
@@ -652,7 +649,7 @@
         return -EINVAL;
     }
 
-    EGLint postCount = 0;
+    intptr_t postCount = 0;
     void *cpu_addr = NULL;
 
     //
@@ -666,8 +663,8 @@
         }
 
         if (cb->canBePosted()) {
-            postCount = *((int *)cb->ashmemBase);
-            cpu_addr = (void *)(cb->ashmemBase + sizeof(int));
+            postCount = *((intptr_t *)cb->ashmemBase);
+            cpu_addr = (void *)(cb->ashmemBase + sizeof(intptr_t));
         }
         else {
             cpu_addr = (void *)(cb->ashmemBase);
@@ -692,6 +689,14 @@
             return -EBUSY;
         }
 
+        const bool sw_read = (cb->usage & GRALLOC_USAGE_SW_READ_OFTEN);
+        const bool screen_capture_mode = (sw_read);
+        if (screen_capture_mode) {
+            D("gralloc_lock read back color buffer %d %d\n", cb->width, cb->height);
+            DEFINE_AND_VALIDATE_HOST_CONNECTION;
+            rcEnc->rcReadColorBuffer(rcEnc, cb->hostHandle,
+                    0, 0, cb->width, cb->height, GL_RGBA, GL_UNSIGNED_BYTE, cpu_addr);
+        }
     }
 
     //
@@ -1021,7 +1026,6 @@
         unlock: gralloc_unlock,
         perform: NULL,
         lock_ycbcr: gralloc_lock_ycbcr,
-        reserved_proc: {0, }
     }
 };
 
@@ -1042,7 +1046,11 @@
         return;
     }
     ALOGD("Emulator without GPU emulation detected.");
+#if __LP64__
+    module = dlopen("/system/lib64/hw/gralloc.default.so", RTLD_LAZY|RTLD_LOCAL);
+#else
     module = dlopen("/system/lib/hw/gralloc.default.so", RTLD_LAZY|RTLD_LOCAL);
+#endif
     if (module != NULL) {
         sFallback = reinterpret_cast<gralloc_module_t*>(dlsym(module, HAL_MODULE_INFO_SYM_AS_STR));
         if (sFallback == NULL) {
diff --git a/opengl/system/renderControl_enc/renderControl_client_context.cpp b/opengl/system/renderControl_enc/renderControl_client_context.cpp
index 9488248..a4bdb25 100644
--- a/opengl/system/renderControl_enc/renderControl_client_context.cpp
+++ b/opengl/system/renderControl_enc/renderControl_client_context.cpp
@@ -37,6 +37,7 @@
 	ptr = getProc("rcColorBufferCacheFlush", userData); set_rcColorBufferCacheFlush((rcColorBufferCacheFlush_client_proc_t)ptr);
 	ptr = getProc("rcReadColorBuffer", userData); set_rcReadColorBuffer((rcReadColorBuffer_client_proc_t)ptr);
 	ptr = getProc("rcUpdateColorBuffer", userData); set_rcUpdateColorBuffer((rcUpdateColorBuffer_client_proc_t)ptr);
+	ptr = getProc("rcOpenColorBuffer2", userData); set_rcOpenColorBuffer2((rcOpenColorBuffer2_client_proc_t)ptr);
 	return 0;
 }
 
diff --git a/opengl/system/renderControl_enc/renderControl_client_context.h b/opengl/system/renderControl_enc/renderControl_client_context.h
index ed2b1fb..46a007f 100644
--- a/opengl/system/renderControl_enc/renderControl_client_context.h
+++ b/opengl/system/renderControl_enc/renderControl_client_context.h
@@ -33,6 +33,7 @@
 	rcColorBufferCacheFlush_client_proc_t rcColorBufferCacheFlush;
 	rcReadColorBuffer_client_proc_t rcReadColorBuffer;
 	rcUpdateColorBuffer_client_proc_t rcUpdateColorBuffer;
+	rcOpenColorBuffer2_client_proc_t rcOpenColorBuffer2;
 	//Accessors 
 	virtual rcGetRendererVersion_client_proc_t set_rcGetRendererVersion(rcGetRendererVersion_client_proc_t f) { rcGetRendererVersion_client_proc_t retval = rcGetRendererVersion; rcGetRendererVersion = f; return retval;}
 	virtual rcGetEGLVersion_client_proc_t set_rcGetEGLVersion(rcGetEGLVersion_client_proc_t f) { rcGetEGLVersion_client_proc_t retval = rcGetEGLVersion; rcGetEGLVersion = f; return retval;}
@@ -59,6 +60,7 @@
 	virtual rcColorBufferCacheFlush_client_proc_t set_rcColorBufferCacheFlush(rcColorBufferCacheFlush_client_proc_t f) { rcColorBufferCacheFlush_client_proc_t retval = rcColorBufferCacheFlush; rcColorBufferCacheFlush = f; return retval;}
 	virtual rcReadColorBuffer_client_proc_t set_rcReadColorBuffer(rcReadColorBuffer_client_proc_t f) { rcReadColorBuffer_client_proc_t retval = rcReadColorBuffer; rcReadColorBuffer = f; return retval;}
 	virtual rcUpdateColorBuffer_client_proc_t set_rcUpdateColorBuffer(rcUpdateColorBuffer_client_proc_t f) { rcUpdateColorBuffer_client_proc_t retval = rcUpdateColorBuffer; rcUpdateColorBuffer = f; return retval;}
+	virtual rcOpenColorBuffer2_client_proc_t set_rcOpenColorBuffer2(rcOpenColorBuffer2_client_proc_t f) { rcOpenColorBuffer2_client_proc_t retval = rcOpenColorBuffer2; rcOpenColorBuffer2 = f; return retval;}
 	 virtual ~renderControl_client_context_t() {}
 
 	typedef renderControl_client_context_t *CONTEXT_ACCESSOR_TYPE(void);
diff --git a/opengl/system/renderControl_enc/renderControl_client_proc.h b/opengl/system/renderControl_enc/renderControl_client_proc.h
index 3e00290..85200cf 100644
--- a/opengl/system/renderControl_enc/renderControl_client_proc.h
+++ b/opengl/system/renderControl_enc/renderControl_client_proc.h
@@ -34,6 +34,7 @@
 typedef EGLint (renderControl_APIENTRY *rcColorBufferCacheFlush_client_proc_t) (void * ctx, uint32_t, EGLint, int);
 typedef void (renderControl_APIENTRY *rcReadColorBuffer_client_proc_t) (void * ctx, uint32_t, GLint, GLint, GLint, GLint, GLenum, GLenum, void*);
 typedef int (renderControl_APIENTRY *rcUpdateColorBuffer_client_proc_t) (void * ctx, uint32_t, GLint, GLint, GLint, GLint, GLenum, GLenum, void*);
+typedef int (renderControl_APIENTRY *rcOpenColorBuffer2_client_proc_t) (void * ctx, uint32_t);
 
 
 #endif
diff --git a/opengl/system/renderControl_enc/renderControl_enc.cpp b/opengl/system/renderControl_enc/renderControl_enc.cpp
index 41f59d0..a40a501 100644
--- a/opengl/system/renderControl_enc/renderControl_enc.cpp
+++ b/opengl/system/renderControl_enc/renderControl_enc.cpp
@@ -505,6 +505,25 @@
 	return retval;
 }
 
+int rcOpenColorBuffer2_enc(void *self , uint32_t colorbuffer)
+{
+
+	renderControl_encoder_context_t *ctx = (renderControl_encoder_context_t *)self;
+	IOStream *stream = ctx->m_stream;
+
+	 unsigned char *ptr;
+	 const size_t packetSize = 8 + 4;
+	ptr = stream->alloc(packetSize);
+	int tmp = OP_rcOpenColorBuffer2;memcpy(ptr, &tmp, 4); ptr += 4;
+	memcpy(ptr, &packetSize, 4);  ptr += 4;
+
+		memcpy(ptr, &colorbuffer, 4); ptr += 4;
+
+	int retval;
+	stream->readback(&retval, 4);
+	return retval;
+}
+
 renderControl_encoder_context_t::renderControl_encoder_context_t(IOStream *stream)
 {
 	m_stream = stream;
@@ -534,5 +553,6 @@
 	set_rcColorBufferCacheFlush(rcColorBufferCacheFlush_enc);
 	set_rcReadColorBuffer(rcReadColorBuffer_enc);
 	set_rcUpdateColorBuffer(rcUpdateColorBuffer_enc);
+	set_rcOpenColorBuffer2(rcOpenColorBuffer2_enc);
 }
 
diff --git a/opengl/system/renderControl_enc/renderControl_enc.h b/opengl/system/renderControl_enc/renderControl_enc.h
index 712eeb9..92ef76e 100644
--- a/opengl/system/renderControl_enc/renderControl_enc.h
+++ b/opengl/system/renderControl_enc/renderControl_enc.h
@@ -47,5 +47,6 @@
 	EGLint rcColorBufferCacheFlush_enc(void *self , uint32_t colorbuffer, EGLint postCount, int forRead);
 	void rcReadColorBuffer_enc(void *self , uint32_t colorbuffer, GLint x, GLint y, GLint width, GLint height, GLenum format, GLenum type, void* pixels);
 	int rcUpdateColorBuffer_enc(void *self , uint32_t colorbuffer, GLint x, GLint y, GLint width, GLint height, GLenum format, GLenum type, void* pixels);
+	int rcOpenColorBuffer2_enc(void *self , uint32_t colorbuffer);
 };
 #endif
\ No newline at end of file
diff --git a/opengl/system/renderControl_enc/renderControl_entry.cpp b/opengl/system/renderControl_enc/renderControl_entry.cpp
index 9a0bba9..a15fd14 100644
--- a/opengl/system/renderControl_enc/renderControl_entry.cpp
+++ b/opengl/system/renderControl_enc/renderControl_entry.cpp
@@ -31,6 +31,7 @@
 	EGLint rcColorBufferCacheFlush(uint32_t colorbuffer, EGLint postCount, int forRead);
 	void rcReadColorBuffer(uint32_t colorbuffer, GLint x, GLint y, GLint width, GLint height, GLenum format, GLenum type, void* pixels);
 	int rcUpdateColorBuffer(uint32_t colorbuffer, GLint x, GLint y, GLint width, GLint height, GLenum format, GLenum type, void* pixels);
+	int rcOpenColorBuffer2(uint32_t colorbuffer);
 };
 
 #endif
@@ -190,3 +191,9 @@
 	 return ctx->rcUpdateColorBuffer(ctx, colorbuffer, x, y, width, height, format, type, pixels);
 }
 
+int rcOpenColorBuffer2(uint32_t colorbuffer)
+{
+	GET_CONTEXT; 
+	 return ctx->rcOpenColorBuffer2(ctx, colorbuffer);
+}
+
diff --git a/opengl/system/renderControl_enc/renderControl_ftable.h b/opengl/system/renderControl_enc/renderControl_ftable.h
index 1e9e2f9..a43fe5b 100644
--- a/opengl/system/renderControl_enc/renderControl_ftable.h
+++ b/opengl/system/renderControl_enc/renderControl_ftable.h
@@ -33,6 +33,7 @@
 	{"rcColorBufferCacheFlush", (void*)rcColorBufferCacheFlush},
 	{"rcReadColorBuffer", (void*)rcReadColorBuffer},
 	{"rcUpdateColorBuffer", (void*)rcUpdateColorBuffer},
+	{"rcOpenColorBuffer2", (void*)rcOpenColorBuffer2},
 };
 static int renderControl_num_funcs = sizeof(renderControl_funcs_by_name) / sizeof(struct _renderControl_funcs_by_name);
 
diff --git a/opengl/system/renderControl_enc/renderControl_opcodes.h b/opengl/system/renderControl_enc/renderControl_opcodes.h
index b44f5d0..a00dc77 100644
--- a/opengl/system/renderControl_enc/renderControl_opcodes.h
+++ b/opengl/system/renderControl_enc/renderControl_opcodes.h
@@ -28,7 +28,8 @@
 #define OP_rcColorBufferCacheFlush 					10022
 #define OP_rcReadColorBuffer 					10023
 #define OP_rcUpdateColorBuffer 					10024
-#define OP_last 					10025
+#define OP_rcOpenColorBuffer2 					10025
+#define OP_last 					10026
 
 
 #endif